xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision 4a6822d07d6d3f9ffe6907ef5f10d11dcadd75c6)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <net/if.h>
60 #include <net/if_arp.h>
61 #include <net/route.h>
62 #include <sys/sockio.h>
63 #include <netinet/in.h>
64 #include <net/if_dl.h>
65 
66 #include <inet/common.h>
67 #include <inet/mi.h>
68 #include <inet/mib2.h>
69 #include <inet/nd.h>
70 #include <inet/arp.h>
71 #include <inet/snmpcom.h>
72 #include <inet/kstatcom.h>
73 
74 #include <netinet/igmp_var.h>
75 #include <netinet/ip6.h>
76 #include <netinet/icmp6.h>
77 #include <netinet/sctp.h>
78 
79 #include <inet/ip.h>
80 #include <inet/ip_impl.h>
81 #include <inet/ip6.h>
82 #include <inet/ip6_asp.h>
83 #include <inet/tcp.h>
84 #include <inet/tcp_impl.h>
85 #include <inet/ip_multi.h>
86 #include <inet/ip_if.h>
87 #include <inet/ip_ire.h>
88 #include <inet/ip_ftable.h>
89 #include <inet/ip_rts.h>
90 #include <inet/optcom.h>
91 #include <inet/ip_ndp.h>
92 #include <inet/ip_listutils.h>
93 #include <netinet/igmp.h>
94 #include <netinet/ip_mroute.h>
95 #include <inet/ipp_common.h>
96 
97 #include <net/pfkeyv2.h>
98 #include <inet/ipsec_info.h>
99 #include <inet/sadb.h>
100 #include <inet/ipsec_impl.h>
101 #include <sys/iphada.h>
102 #include <inet/tun.h>
103 #include <inet/ipdrop.h>
104 #include <inet/ip_netinfo.h>
105 
106 #include <sys/ethernet.h>
107 #include <net/if_types.h>
108 #include <sys/cpuvar.h>
109 
110 #include <ipp/ipp.h>
111 #include <ipp/ipp_impl.h>
112 #include <ipp/ipgpc/ipgpc.h>
113 
114 #include <sys/multidata.h>
115 #include <sys/pattr.h>
116 
117 #include <inet/ipclassifier.h>
118 #include <inet/sctp_ip.h>
119 #include <inet/sctp/sctp_impl.h>
120 #include <inet/udp_impl.h>
121 #include <sys/sunddi.h>
122 
123 #include <sys/tsol/label.h>
124 #include <sys/tsol/tnet.h>
125 
126 #include <rpc/pmap_prot.h>
127 
128 /*
129  * Values for squeue switch:
130  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
131  * IP_SQUEUE_ENTER: squeue_enter
132  * IP_SQUEUE_FILL: squeue_fill
133  */
134 int ip_squeue_enter = 2;	/* Setable in /etc/system */
135 
136 squeue_func_t ip_input_proc;
137 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
138 
139 #define	TCP6 "tcp6"
140 #define	TCP "tcp"
141 #define	SCTP "sctp"
142 #define	SCTP6 "sctp6"
143 
144 major_t TCP6_MAJ;
145 major_t TCP_MAJ;
146 major_t SCTP_MAJ;
147 major_t SCTP6_MAJ;
148 
149 /*
150  * Setable in /etc/system
151  */
152 int ip_poll_normal_ms = 100;
153 int ip_poll_normal_ticks = 0;
154 int ip_modclose_ackwait_ms = 3000;
155 
156 /*
157  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
158  */
159 
160 struct listptr_s {
161 	mblk_t	*lp_head;	/* pointer to the head of the list */
162 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
163 };
164 
165 typedef struct listptr_s listptr_t;
166 
167 /*
168  * This is used by ip_snmp_get_mib2_ip_route_media and
169  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
170  */
171 typedef struct iproutedata_s {
172 	uint_t		ird_idx;
173 	listptr_t	ird_route;	/* ipRouteEntryTable */
174 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
175 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
176 } iproutedata_t;
177 
178 /*
179  * Cluster specific hooks. These should be NULL when booted as a non-cluster
180  */
181 
182 /*
183  * Hook functions to enable cluster networking
184  * On non-clustered systems these vectors must always be NULL.
185  *
186  * Hook function to Check ip specified ip address is a shared ip address
187  * in the cluster
188  *
189  */
190 int (*cl_inet_isclusterwide)(uint8_t protocol,
191     sa_family_t addr_family, uint8_t *laddrp) = NULL;
192 
193 /*
194  * Hook function to generate cluster wide ip fragment identifier
195  */
196 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
197     uint8_t *laddrp, uint8_t *faddrp) = NULL;
198 
199 /*
200  * Synchronization notes:
201  *
202  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
203  * MT level protection given by STREAMS. IP uses a combination of its own
204  * internal serialization mechanism and standard Solaris locking techniques.
205  * The internal serialization is per phyint (no IPMP) or per IPMP group.
206  * This is used to serialize plumbing operations, IPMP operations, certain
207  * multicast operations, most set ioctls, igmp/mld timers etc.
208  *
209  * Plumbing is a long sequence of operations involving message
210  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
211  * involved in plumbing operations. A natural model is to serialize these
212  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
213  * parallel without any interference. But various set ioctls on hme0 are best
214  * serialized. However if the system uses IPMP, the operations are easier if
215  * they are serialized on a per IPMP group basis since IPMP operations
216  * happen across ill's of a group. Thus the lowest common denominator is to
217  * serialize most set ioctls, multicast join/leave operations, IPMP operations
218  * igmp/mld timer operations, and processing of DLPI control messages received
219  * from drivers on a per IPMP group basis. If the system does not employ
220  * IPMP the serialization is on a per phyint basis. This serialization is
221  * provided by the ipsq_t and primitives operating on this. Details can
222  * be found in ip_if.c above the core primitives operating on ipsq_t.
223  *
224  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
225  * Simiarly lookup of an ire by a thread also returns a refheld ire.
226  * In addition ipif's and ill's referenced by the ire are also indirectly
227  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
228  * the ipif's address or netmask change as long as an ipif is refheld
229  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
230  * address of an ipif has to go through the ipsq_t. This ensures that only
231  * 1 such exclusive operation proceeds at any time on the ipif. It then
232  * deletes all ires associated with this ipif, and waits for all refcnts
233  * associated with this ipif to come down to zero. The address is changed
234  * only after the ipif has been quiesced. Then the ipif is brought up again.
235  * More details are described above the comment in ip_sioctl_flags.
236  *
237  * Packet processing is based mostly on IREs and are fully multi-threaded
238  * using standard Solaris MT techniques.
239  *
240  * There are explicit locks in IP to handle:
241  * - The ip_g_head list maintained by mi_open_link() and friends.
242  *
243  * - The reassembly data structures (one lock per hash bucket)
244  *
245  * - conn_lock is meant to protect conn_t fields. The fields actually
246  *   protected by conn_lock are documented in the conn_t definition.
247  *
248  * - ire_lock to protect some of the fields of the ire, IRE tables
249  *   (one lock per hash bucket). Refer to ip_ire.c for details.
250  *
251  * - ndp_g_lock and nce_lock for protecting NCEs.
252  *
253  * - ill_lock protects fields of the ill and ipif. Details in ip.h
254  *
255  * - ill_g_lock: This is a global reader/writer lock. Protects the following
256  *	* The AVL tree based global multi list of all ills.
257  *	* The linked list of all ipifs of an ill
258  *	* The <ill-ipsq> mapping
259  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
260  *	* The illgroup list threaded by ill_group_next.
261  *	* <ill-phyint> association
262  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
263  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
264  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
265  *   will all have to hold the ill_g_lock as writer for the actual duration
266  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
267  *   may be found in the IPMP section.
268  *
269  * - ill_lock:  This is a per ill mutex.
270  *   It protects some members of the ill and is documented below.
271  *   It also protects the <ill-ipsq> mapping
272  *   It also protects the illgroup list threaded by ill_group_next.
273  *   It also protects the <ill-phyint> assoc.
274  *   It also protects the list of ipifs hanging off the ill.
275  *
276  * - ipsq_lock: This is a per ipsq_t mutex lock.
277  *   This protects all the other members of the ipsq struct except
278  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
279  *
280  * - illgrp_lock: This is a per ill_group mutex lock.
281  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
282  *   which dictates which is the next ill in an ill_group that is to be chosen
283  *   for sending outgoing packets, through creation of an IRE_CACHE that
284  *   references this ill.
285  *
286  * - phyint_lock: This is a per phyint mutex lock. Protects just the
287  *   phyint_flags
288  *
289  * - ip_g_nd_lock: This is a global reader/writer lock.
290  *   Any call to nd_load to load a new parameter to the ND table must hold the
291  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
292  *   as reader.
293  *
294  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
295  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
296  *   uniqueness check also done atomically.
297  *
298  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
299  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
300  *   as a writer when adding or deleting elements from these lists, and
301  *   as a reader when walking these lists to send a SADB update to the
302  *   IPsec capable ills.
303  *
304  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
305  *   group list linked by ill_usesrc_grp_next. It also protects the
306  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
307  *   group is being added or deleted.  This lock is taken as a reader when
308  *   walking the list/group(eg: to get the number of members in a usesrc group).
309  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
310  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
311  *   example, it is not necessary to take this lock in the initial portion
312  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
313  *   ip_sioctl_flags since the these operations are executed exclusively and
314  *   that ensures that the "usesrc group state" cannot change. The "usesrc
315  *   group state" change can happen only in the latter part of
316  *   ip_sioctl_slifusesrc and in ill_delete.
317  *
318  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
319  *
320  * To change the <ill-phyint> association, the ill_g_lock must be held
321  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
322  * must be held.
323  *
324  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
325  * and the ill_lock of the ill in question must be held.
326  *
327  * To change the <ill-illgroup> association the ill_g_lock must be held as
328  * writer and the ill_lock of the ill in question must be held.
329  *
330  * To add or delete an ipif from the list of ipifs hanging off the ill,
331  * ill_g_lock (writer) and ill_lock must be held and the thread must be
332  * a writer on the associated ipsq,.
333  *
334  * To add or delete an ill to the system, the ill_g_lock must be held as
335  * writer and the thread must be a writer on the associated ipsq.
336  *
337  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
338  * must be a writer on the associated ipsq.
339  *
340  * Lock hierarchy
341  *
342  * Some lock hierarchy scenarios are listed below.
343  *
344  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
345  * ill_g_lock -> illgrp_lock -> ill_lock
346  * ill_g_lock -> ill_lock(s) -> phyint_lock
347  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
348  * ill_g_lock -> ip_addr_avail_lock
349  * conn_lock -> irb_lock -> ill_lock -> ire_lock
350  * ill_g_lock -> ip_g_nd_lock
351  *
352  * When more than 1 ill lock is needed to be held, all ill lock addresses
353  * are sorted on address and locked starting from highest addressed lock
354  * downward.
355  *
356  * IPsec scenarios
357  *
358  * ipsa_lock -> ill_g_lock -> ill_lock
359  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
360  * ipsec_capab_ills_lock -> ipsa_lock
361  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
362  *
363  * Trusted Solaris scenarios
364  *
365  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
366  * igsa_lock -> gcdb_lock
367  * gcgrp_rwlock -> ire_lock
368  * gcgrp_rwlock -> gcdb_lock
369  *
370  *
371  * Routing/forwarding table locking notes:
372  *
373  * Lock acquisition order: Radix tree lock, irb_lock.
374  * Requirements:
375  * i.  Walker must not hold any locks during the walker callback.
376  * ii  Walker must not see a truncated tree during the walk because of any node
377  *     deletion.
378  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
379  *     in many places in the code to walk the irb list. Thus even if all the
380  *     ires in a bucket have been deleted, we still can't free the radix node
381  *     until the ires have actually been inactive'd (freed).
382  *
383  * Tree traversal - Need to hold the global tree lock in read mode.
384  * Before dropping the global tree lock, need to either increment the ire_refcnt
385  * to ensure that the radix node can't be deleted.
386  *
387  * Tree add - Need to hold the global tree lock in write mode to add a
388  * radix node. To prevent the node from being deleted, increment the
389  * irb_refcnt, after the node is added to the tree. The ire itself is
390  * added later while holding the irb_lock, but not the tree lock.
391  *
392  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
393  * All associated ires must be inactive (i.e. freed), and irb_refcnt
394  * must be zero.
395  *
396  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
397  * global tree lock (read mode) for traversal.
398  *
399  * IPSEC notes :
400  *
401  * IP interacts with the IPSEC code (AH/ESP) by tagging a M_CTL message
402  * in front of the actual packet. For outbound datagrams, the M_CTL
403  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
404  * information used by the IPSEC code for applying the right level of
405  * protection. The information initialized by IP in the ipsec_out_t
406  * is determined by the per-socket policy or global policy in the system.
407  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
408  * ipsec_info.h) which starts out with nothing in it. It gets filled
409  * with the right information if it goes through the AH/ESP code, which
410  * happens if the incoming packet is secure. The information initialized
411  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
412  * the policy requirements needed by per-socket policy or global policy
413  * is met or not.
414  *
415  * If there is both per-socket policy (set using setsockopt) and there
416  * is also global policy match for the 5 tuples of the socket,
417  * ipsec_override_policy() makes the decision of which one to use.
418  *
419  * For fully connected sockets i.e dst, src [addr, port] is known,
420  * conn_policy_cached is set indicating that policy has been cached.
421  * conn_in_enforce_policy may or may not be set depending on whether
422  * there is a global policy match or per-socket policy match.
423  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
424  * Once the right policy is set on the conn_t, policy cannot change for
425  * this socket. This makes life simpler for TCP (UDP ?) where
426  * re-transmissions go out with the same policy. For symmetry, policy
427  * is cached for fully connected UDP sockets also. Thus if policy is cached,
428  * it also implies that policy is latched i.e policy cannot change
429  * on these sockets. As we have the right policy on the conn, we don't
430  * have to lookup global policy for every outbound and inbound datagram
431  * and thus serving as an optimization. Note that a global policy change
432  * does not affect fully connected sockets if they have policy. If fully
433  * connected sockets did not have any policy associated with it, global
434  * policy change may affect them.
435  *
436  * IP Flow control notes:
437  *
438  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
439  * cannot be sent down to the driver by IP, because of a canput failure, IP
440  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
441  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
442  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
443  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
444  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
445  * the queued messages, and removes the conn from the drain list, if all
446  * messages were drained. It also qenables the next conn in the drain list to
447  * continue the drain process.
448  *
449  * In reality the drain list is not a single list, but a configurable number
450  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
451  * list. If the ip_wsrv of the next qenabled conn does not run, because the
452  * stream closes, ip_close takes responsibility to qenable the next conn in
453  * the drain list. The directly called ip_wput path always does a putq, if
454  * it cannot putnext. Thus synchronization problems are handled between
455  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
456  * functions that manipulate this drain list. Furthermore conn_drain_insert
457  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
458  * running on a queue at any time. conn_drain_tail can be simultaneously called
459  * from both ip_wsrv and ip_close.
460  *
461  * IPQOS notes:
462  *
463  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
464  * and IPQoS modules. IPPF includes hooks in IP at different control points
465  * (callout positions) which direct packets to IPQoS modules for policy
466  * processing. Policies, if present, are global.
467  *
468  * The callout positions are located in the following paths:
469  *		o local_in (packets destined for this host)
470  *		o local_out (packets orginating from this host )
471  *		o fwd_in  (packets forwarded by this m/c - inbound)
472  *		o fwd_out (packets forwarded by this m/c - outbound)
473  * Hooks at these callout points can be enabled/disabled using the ndd variable
474  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
475  * By default all the callout positions are enabled.
476  *
477  * Outbound (local_out)
478  * Hooks are placed in ip_wput_ire and ipsec_out_process.
479  *
480  * Inbound (local_in)
481  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
482  * TCP and UDP fanout routines.
483  *
484  * Forwarding (in and out)
485  * Hooks are placed in ip_rput_forward.
486  *
487  * IP Policy Framework processing (IPPF processing)
488  * Policy processing for a packet is initiated by ip_process, which ascertains
489  * that the classifier (ipgpc) is loaded and configured, failing which the
490  * packet resumes normal processing in IP. If the clasifier is present, the
491  * packet is acted upon by one or more IPQoS modules (action instances), per
492  * filters configured in ipgpc and resumes normal IP processing thereafter.
493  * An action instance can drop a packet in course of its processing.
494  *
495  * A boolean variable, ip_policy, is used in all the fanout routines that can
496  * invoke ip_process for a packet. This variable indicates if the packet should
497  * to be sent for policy processing. The variable is set to B_TRUE by default,
498  * i.e. when the routines are invoked in the normal ip procesing path for a
499  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
500  * ip_policy is set to B_FALSE for all the routines called in these two
501  * functions because, in the former case,  we don't process loopback traffic
502  * currently while in the latter, the packets have already been processed in
503  * icmp_inbound.
504  *
505  * Zones notes:
506  *
507  * The partitioning rules for networking are as follows:
508  * 1) Packets coming from a zone must have a source address belonging to that
509  * zone.
510  * 2) Packets coming from a zone can only be sent on a physical interface on
511  * which the zone has an IP address.
512  * 3) Between two zones on the same machine, packet delivery is only allowed if
513  * there's a matching route for the destination and zone in the forwarding
514  * table.
515  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
516  * different zones can bind to the same port with the wildcard address
517  * (INADDR_ANY).
518  *
519  * The granularity of interface partitioning is at the logical interface level.
520  * Therefore, every zone has its own IP addresses, and incoming packets can be
521  * attributed to a zone unambiguously. A logical interface is placed into a zone
522  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
523  * structure. Rule (1) is implemented by modifying the source address selection
524  * algorithm so that the list of eligible addresses is filtered based on the
525  * sending process zone.
526  *
527  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
528  * across all zones, depending on their type. Here is the break-up:
529  *
530  * IRE type				Shared/exclusive
531  * --------				----------------
532  * IRE_BROADCAST			Exclusive
533  * IRE_DEFAULT (default routes)		Shared (*)
534  * IRE_LOCAL				Exclusive (x)
535  * IRE_LOOPBACK				Exclusive
536  * IRE_PREFIX (net routes)		Shared (*)
537  * IRE_CACHE				Exclusive
538  * IRE_IF_NORESOLVER (interface routes)	Exclusive
539  * IRE_IF_RESOLVER (interface routes)	Exclusive
540  * IRE_HOST (host routes)		Shared (*)
541  *
542  * (*) A zone can only use a default or off-subnet route if the gateway is
543  * directly reachable from the zone, that is, if the gateway's address matches
544  * one of the zone's logical interfaces.
545  *
546  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
547  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
548  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
549  * address of the zone itself (the destination). Since IRE_LOCAL is used
550  * for communication between zones, ip_wput_ire has special logic to set
551  * the right source address when sending using an IRE_LOCAL.
552  *
553  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
554  * ire_cache_lookup restricts loopback using an IRE_LOCAL
555  * between zone to the case when L2 would have conceptually looped the packet
556  * back, i.e. the loopback which is required since neither Ethernet drivers
557  * nor Ethernet hardware loops them back. This is the case when the normal
558  * routes (ignoring IREs with different zoneids) would send out the packet on
559  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
560  * associated.
561  *
562  * Multiple zones can share a common broadcast address; typically all zones
563  * share the 255.255.255.255 address. Incoming as well as locally originated
564  * broadcast packets must be dispatched to all the zones on the broadcast
565  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
566  * since some zones may not be on the 10.16.72/24 network. To handle this, each
567  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
568  * sent to every zone that has an IRE_BROADCAST entry for the destination
569  * address on the input ill, see conn_wantpacket().
570  *
571  * Applications in different zones can join the same multicast group address.
572  * For IPv4, group memberships are per-logical interface, so they're already
573  * inherently part of a zone. For IPv6, group memberships are per-physical
574  * interface, so we distinguish IPv6 group memberships based on group address,
575  * interface and zoneid. In both cases, received multicast packets are sent to
576  * every zone for which a group membership entry exists. On IPv6 we need to
577  * check that the target zone still has an address on the receiving physical
578  * interface; it could have been removed since the application issued the
579  * IPV6_JOIN_GROUP.
580  */
581 
582 /*
583  * Squeue Fanout flags:
584  *	0: No fanout.
585  *	1: Fanout across all squeues
586  */
587 boolean_t	ip_squeue_fanout = 0;
588 
589 /*
590  * Maximum dups allowed per packet.
591  */
592 uint_t ip_max_frag_dups = 10;
593 
594 #define	IS_SIMPLE_IPH(ipha)						\
595 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
596 
597 /* RFC1122 Conformance */
598 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
599 
600 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
601 
602 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
603 
604 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
605 
606 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
607 		    ip_stack_t *);
608 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
609 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
610 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
611 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
612 		    mblk_t *, int, ip_stack_t *);
613 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
614 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
615 		    ill_t *, zoneid_t);
616 static void	icmp_options_update(ipha_t *);
617 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
618 		    ip_stack_t *);
619 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
620 		    zoneid_t zoneid, ip_stack_t *);
621 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
622 static void	icmp_redirect(ill_t *, mblk_t *);
623 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
624 		    ip_stack_t *);
625 
626 static void	ip_arp_news(queue_t *, mblk_t *);
627 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
628 		    ip_stack_t *);
629 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
630 char		*ip_dot_addr(ipaddr_t, char *);
631 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
632 int		ip_close(queue_t *, int);
633 static char	*ip_dot_saddr(uchar_t *, char *);
634 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
635 		    boolean_t, boolean_t, ill_t *, zoneid_t);
636 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
637 		    boolean_t, boolean_t, zoneid_t);
638 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
639 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
640 static void	ip_lrput(queue_t *, mblk_t *);
641 ipaddr_t	ip_net_mask(ipaddr_t);
642 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
643 		    ip_stack_t *);
644 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
645 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
646 char		*ip_nv_lookup(nv_t *, int);
647 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
648 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
649 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
650 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
651     ipndp_t *, size_t);
652 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
653 void	ip_rput(queue_t *, mblk_t *);
654 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
655 		    void *dummy_arg);
656 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
657 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
658     ip_stack_t *);
659 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
660 			    ire_t *, ip_stack_t *);
661 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
662 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
663 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
664     ip_stack_t *);
665 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
666 		    uint16_t *);
667 int		ip_snmp_get(queue_t *, mblk_t *);
668 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
669 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
670 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
671 		    ip_stack_t *);
672 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
673 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
674 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
675 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
676 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
677 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
678 		    ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
680 		    ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
682 		    ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
684 		    ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
698 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
699 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
700 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
701 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
702 static boolean_t	ip_source_route_included(ipha_t *);
703 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
704 
705 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
706 		    zoneid_t, ip_stack_t *);
707 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
708 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
709 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
710 		    zoneid_t, ip_stack_t *);
711 
712 static void	conn_drain_init(ip_stack_t *);
713 static void	conn_drain_fini(ip_stack_t *);
714 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
715 
716 static void	conn_walk_drain(ip_stack_t *);
717 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
718     zoneid_t);
719 
720 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
721 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
722 static void	ip_stack_fini(netstackid_t stackid, void *arg);
723 
724 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
725     zoneid_t);
726 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
727     void *dummy_arg);
728 
729 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
730 
731 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
732     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
733     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
734 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
735 
736 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
737 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
738     caddr_t, cred_t *);
739 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
740     caddr_t cp, cred_t *cr);
741 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
742     cred_t *);
743 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
748     cred_t *);
749 static squeue_func_t ip_squeue_switch(int);
750 
751 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
752 static void	ip_kstat_fini(netstackid_t, kstat_t *);
753 static int	ip_kstat_update(kstat_t *kp, int rw);
754 static void	*icmp_kstat_init(netstackid_t);
755 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
756 static int	icmp_kstat_update(kstat_t *kp, int rw);
757 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
758 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
759 
760 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
761 
762 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
763     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
764 
765 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
766     ipha_t *, ill_t *, boolean_t);
767 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
768 
769 /* How long, in seconds, we allow frags to hang around. */
770 #define	IP_FRAG_TIMEOUT	60
771 
772 /*
773  * Threshold which determines whether MDT should be used when
774  * generating IP fragments; payload size must be greater than
775  * this threshold for MDT to take place.
776  */
777 #define	IP_WPUT_FRAG_MDT_MIN	32768
778 
779 /* Setable in /etc/system only */
780 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
781 
782 static long ip_rput_pullups;
783 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
784 
785 vmem_t *ip_minor_arena;
786 
787 int	ip_debug;
788 
789 #ifdef DEBUG
790 uint32_t ipsechw_debug = 0;
791 #endif
792 
793 /*
794  * Multirouting/CGTP stuff
795  */
796 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
797 
798 /*
799  * XXX following really should only be in a header. Would need more
800  * header and .c clean up first.
801  */
802 extern optdb_obj_t	ip_opt_obj;
803 
804 ulong_t ip_squeue_enter_unbound = 0;
805 
806 /*
807  * Named Dispatch Parameter Table.
808  * All of these are alterable, within the min/max values given, at run time.
809  */
810 static ipparam_t	lcl_param_arr[] = {
811 	/* min	max	value	name */
812 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
813 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
814 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
815 	{  0,	1,	0,	"ip_respond_to_timestamp"},
816 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
817 	{  0,	1,	1,	"ip_send_redirects"},
818 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
819 	{  0,	10,	0,	"ip_debug"},
820 	{  0,	10,	0,	"ip_mrtdebug"},
821 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
822 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
823 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
824 	{  1,	255,	255,	"ip_def_ttl" },
825 	{  0,	1,	0,	"ip_forward_src_routed"},
826 	{  0,	256,	32,	"ip_wroff_extra" },
827 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
828 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
829 	{  0,	1,	1,	"ip_path_mtu_discovery" },
830 	{  0,	240,	30,	"ip_ignore_delete_time" },
831 	{  0,	1,	0,	"ip_ignore_redirect" },
832 	{  0,	1,	1,	"ip_output_queue" },
833 	{  1,	254,	1,	"ip_broadcast_ttl" },
834 	{  0,	99999,	100,	"ip_icmp_err_interval" },
835 	{  1,	99999,	10,	"ip_icmp_err_burst" },
836 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
837 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
838 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
839 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
840 	{  0,	1,	1,	"icmp_accept_clear_messages" },
841 	{  0,	1,	1,	"igmp_accept_clear_messages" },
842 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
843 				"ip_ndp_delay_first_probe_time"},
844 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
845 				"ip_ndp_max_unicast_solicit"},
846 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
847 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
848 	{  0,	1,	0,	"ip6_forward_src_routed"},
849 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
850 	{  0,	1,	1,	"ip6_send_redirects"},
851 	{  0,	1,	0,	"ip6_ignore_redirect" },
852 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
853 
854 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
855 
856 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
857 
858 	{  0,	1,	1,	"pim_accept_clear_messages" },
859 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
860 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
861 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
862 	{  0,	15,	0,	"ip_policy_mask" },
863 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
864 	{  0,	255,	1,	"ip_multirt_ttl" },
865 	{  0,	1,	1,	"ip_multidata_outbound" },
866 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
867 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
868 	{  0,	1000,	1,	"ip_max_temp_defend" },
869 	{  0,	1000,	3,	"ip_max_defend" },
870 	{  0,	999999,	30,	"ip_defend_interval" },
871 	{  0,	3600000, 300000, "ip_dup_recovery" },
872 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
873 	{  0,	1,	1,	"ip_lso_outbound" },
874 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
875 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
876 #ifdef DEBUG
877 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
878 #else
879 	{  0,	0,	0,	"" },
880 #endif
881 };
882 
883 /*
884  * Extended NDP table
885  * The addresses for the first two are filled in to be ips_ip_g_forward
886  * and ips_ipv6_forward at init time.
887  */
888 static ipndp_t	lcl_ndp_arr[] = {
889 	/* getf			setf		data			name */
890 #define	IPNDP_IP_FORWARDING_OFFSET	0
891 	{  ip_param_generic_get,	ip_forward_set,	NULL,
892 	    "ip_forwarding" },
893 #define	IPNDP_IP6_FORWARDING_OFFSET	1
894 	{  ip_param_generic_get,	ip_forward_set,	NULL,
895 	    "ip6_forwarding" },
896 	{  ip_ill_report,	NULL,		NULL,
897 	    "ip_ill_status" },
898 	{  ip_ipif_report,	NULL,		NULL,
899 	    "ip_ipif_status" },
900 	{  ip_ire_report,	NULL,		NULL,
901 	    "ipv4_ire_status" },
902 	{  ip_ire_report_v6,	NULL,		NULL,
903 	    "ipv6_ire_status" },
904 	{  ip_conn_report,	NULL,		NULL,
905 	    "ip_conn_status" },
906 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
907 	    "ip_rput_pullups" },
908 	{  ndp_report,		NULL,		NULL,
909 	    "ip_ndp_cache_report" },
910 	{  ip_srcid_report,	NULL,		NULL,
911 	    "ip_srcid_status" },
912 	{ ip_param_generic_get, ip_squeue_profile_set,
913 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
914 	{ ip_param_generic_get, ip_squeue_bind_set,
915 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
916 	{ ip_param_generic_get, ip_input_proc_set,
917 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
918 	{ ip_param_generic_get, ip_int_set,
919 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
920 #define	IPNDP_CGTP_FILTER_OFFSET	14
921 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
922 	    "ip_cgtp_filter" },
923 	{ ip_param_generic_get, ip_int_set,
924 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
925 #define	IPNDP_IPMP_HOOK_OFFSET	16
926 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
927 	    "ipmp_hook_emulation" },
928 };
929 
930 /*
931  * Table of IP ioctls encoding the various properties of the ioctl and
932  * indexed based on the last byte of the ioctl command. Occasionally there
933  * is a clash, and there is more than 1 ioctl with the same last byte.
934  * In such a case 1 ioctl is encoded in the ndx table and the remaining
935  * ioctls are encoded in the misc table. An entry in the ndx table is
936  * retrieved by indexing on the last byte of the ioctl command and comparing
937  * the ioctl command with the value in the ndx table. In the event of a
938  * mismatch the misc table is then searched sequentially for the desired
939  * ioctl command.
940  *
941  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
942  */
943 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
944 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
945 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 
955 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
956 			MISC_CMD, ip_siocaddrt, NULL },
957 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
958 			MISC_CMD, ip_siocdelrt, NULL },
959 
960 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
961 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
962 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
963 			IF_CMD, ip_sioctl_get_addr, NULL },
964 
965 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
966 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
967 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
968 			IPI_GET_CMD | IPI_REPL,
969 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
970 
971 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
972 			IPI_PRIV | IPI_WR | IPI_REPL,
973 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
974 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
975 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
976 			IF_CMD, ip_sioctl_get_flags, NULL },
977 
978 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 
981 	/* copyin size cannot be coded for SIOCGIFCONF */
982 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
983 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
984 
985 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
986 			IF_CMD, ip_sioctl_mtu, NULL },
987 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
988 			IF_CMD, ip_sioctl_get_mtu, NULL },
989 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
990 			IPI_GET_CMD | IPI_REPL,
991 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
992 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
993 			IF_CMD, ip_sioctl_brdaddr, NULL },
994 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
995 			IPI_GET_CMD | IPI_REPL,
996 			IF_CMD, ip_sioctl_get_netmask, NULL },
997 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
998 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
999 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1000 			IPI_GET_CMD | IPI_REPL,
1001 			IF_CMD, ip_sioctl_get_metric, NULL },
1002 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1003 			IF_CMD, ip_sioctl_metric, NULL },
1004 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1005 
1006 	/* See 166-168 below for extended SIOC*XARP ioctls */
1007 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1008 			ARP_CMD, ip_sioctl_arp, NULL },
1009 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1010 			ARP_CMD, ip_sioctl_arp, NULL },
1011 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 
1014 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1015 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1037 			MISC_CMD, if_unitsel, if_unitsel_restart },
1038 
1039 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 
1058 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1059 			IPI_PRIV | IPI_WR | IPI_MODOK,
1060 			IF_CMD, ip_sioctl_sifname, NULL },
1061 
1062 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 
1076 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1077 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1078 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1079 			IF_CMD, ip_sioctl_get_muxid, NULL },
1080 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1081 			IPI_PRIV | IPI_WR | IPI_REPL,
1082 			IF_CMD, ip_sioctl_muxid, NULL },
1083 
1084 	/* Both if and lif variants share same func */
1085 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1086 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1087 	/* Both if and lif variants share same func */
1088 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1089 			IPI_PRIV | IPI_WR | IPI_REPL,
1090 			IF_CMD, ip_sioctl_slifindex, NULL },
1091 
1092 	/* copyin size cannot be coded for SIOCGIFCONF */
1093 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1094 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1095 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1114 			IPI_PRIV | IPI_WR | IPI_REPL,
1115 			LIF_CMD, ip_sioctl_removeif,
1116 			ip_sioctl_removeif_restart },
1117 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1118 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1119 			LIF_CMD, ip_sioctl_addif, NULL },
1120 #define	SIOCLIFADDR_NDX 112
1121 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1122 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1123 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1124 			IPI_GET_CMD | IPI_REPL,
1125 			LIF_CMD, ip_sioctl_get_addr, NULL },
1126 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1127 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1128 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1131 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1132 			IPI_PRIV | IPI_WR | IPI_REPL,
1133 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1134 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_flags, NULL },
1137 
1138 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 
1141 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1142 			ip_sioctl_get_lifconf, NULL },
1143 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1144 			LIF_CMD, ip_sioctl_mtu, NULL },
1145 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1146 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1147 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1148 			IPI_GET_CMD | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1150 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1151 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1152 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1153 			IPI_GET_CMD | IPI_REPL,
1154 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1155 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1156 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1157 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1158 			IPI_GET_CMD | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_get_metric, NULL },
1160 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1161 			LIF_CMD, ip_sioctl_metric, NULL },
1162 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1163 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1164 			LIF_CMD, ip_sioctl_slifname,
1165 			ip_sioctl_slifname_restart },
1166 
1167 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1168 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1169 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1170 			IPI_GET_CMD | IPI_REPL,
1171 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1172 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1173 			IPI_PRIV | IPI_WR | IPI_REPL,
1174 			LIF_CMD, ip_sioctl_muxid, NULL },
1175 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1176 			IPI_GET_CMD | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1178 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1179 			IPI_PRIV | IPI_WR | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_slifindex, 0 },
1181 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1182 			LIF_CMD, ip_sioctl_token, NULL },
1183 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1184 			IPI_GET_CMD | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_get_token, NULL },
1186 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1187 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1188 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1189 			IPI_GET_CMD | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1191 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1192 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1193 
1194 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1197 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1198 			LIF_CMD, ip_siocdelndp_v6, NULL },
1199 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1200 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1201 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1202 			LIF_CMD, ip_siocsetndp_v6, NULL },
1203 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1204 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1205 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1206 			MISC_CMD, ip_sioctl_tonlink, NULL },
1207 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1208 			MISC_CMD, ip_sioctl_tmysite, NULL },
1209 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1210 			TUN_CMD, ip_sioctl_tunparam, NULL },
1211 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1212 			IPI_PRIV | IPI_WR,
1213 			TUN_CMD, ip_sioctl_tunparam, NULL },
1214 
1215 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1216 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1217 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1218 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 
1221 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1222 			IPI_PRIV | IPI_WR | IPI_REPL,
1223 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1224 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1225 			IPI_PRIV | IPI_WR | IPI_REPL,
1226 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1227 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1230 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1231 			IPI_GET_CMD | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1233 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1234 			IPI_GET_CMD | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1236 
1237 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1238 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 
1242 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1244 
1245 	/* These are handled in ip_sioctl_copyin_setup itself */
1246 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1247 			MISC_CMD, NULL, NULL },
1248 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1249 			MISC_CMD, NULL, NULL },
1250 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1251 
1252 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1253 			ip_sioctl_get_lifconf, NULL },
1254 
1255 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1256 			XARP_CMD, ip_sioctl_arp, NULL },
1257 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1258 			XARP_CMD, ip_sioctl_arp, NULL },
1259 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1260 			XARP_CMD, ip_sioctl_arp, NULL },
1261 
1262 	/* SIOCPOPSOCKFS is not handled by IP */
1263 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1264 
1265 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1266 			IPI_GET_CMD | IPI_REPL,
1267 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1268 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1269 			IPI_PRIV | IPI_WR | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_slifzone,
1271 			ip_sioctl_slifzone_restart },
1272 	/* 172-174 are SCTP ioctls and not handled by IP */
1273 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1274 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1275 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1276 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1277 			IPI_GET_CMD, LIF_CMD,
1278 			ip_sioctl_get_lifusesrc, 0 },
1279 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR,
1281 			LIF_CMD, ip_sioctl_slifusesrc,
1282 			NULL },
1283 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1284 			ip_sioctl_get_lifsrcof, NULL },
1285 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1286 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1287 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1288 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1289 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1290 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1294 			ip_sioctl_set_ipmpfailback, NULL }
1295 };
1296 
1297 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1298 
1299 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1300 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1301 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1302 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1303 		TUN_CMD, ip_sioctl_tunparam, NULL },
1304 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1305 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1306 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1307 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1311 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1312 		MISC_CMD, mrt_ioctl},
1313 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1314 		MISC_CMD, mrt_ioctl},
1315 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1316 		MISC_CMD, mrt_ioctl}
1317 };
1318 
1319 int ip_misc_ioctl_count =
1320     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1321 
1322 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1323 					/* Settable in /etc/system */
1324 /* Defined in ip_ire.c */
1325 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1326 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1327 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1328 
1329 static nv_t	ire_nv_arr[] = {
1330 	{ IRE_BROADCAST, "BROADCAST" },
1331 	{ IRE_LOCAL, "LOCAL" },
1332 	{ IRE_LOOPBACK, "LOOPBACK" },
1333 	{ IRE_CACHE, "CACHE" },
1334 	{ IRE_DEFAULT, "DEFAULT" },
1335 	{ IRE_PREFIX, "PREFIX" },
1336 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1337 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1338 	{ IRE_HOST, "HOST" },
1339 	{ 0 }
1340 };
1341 
1342 nv_t	*ire_nv_tbl = ire_nv_arr;
1343 
1344 /* Defined in ip_netinfo.c */
1345 extern ddi_taskq_t	*eventq_queue_nic;
1346 
1347 /* Simple ICMP IP Header Template */
1348 static ipha_t icmp_ipha = {
1349 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1350 };
1351 
1352 struct module_info ip_mod_info = {
1353 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1354 };
1355 
1356 /*
1357  * Duplicate static symbols within a module confuses mdb; so we avoid the
1358  * problem by making the symbols here distinct from those in udp.c.
1359  */
1360 
1361 static struct qinit iprinit = {
1362 	(pfi_t)ip_rput, NULL, ip_open, ip_close, NULL,
1363 	&ip_mod_info
1364 };
1365 
1366 static struct qinit ipwinit = {
1367 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, ip_open, ip_close, NULL,
1368 	&ip_mod_info
1369 };
1370 
1371 static struct qinit iplrinit = {
1372 	(pfi_t)ip_lrput, NULL, ip_open, ip_close, NULL,
1373 	&ip_mod_info
1374 };
1375 
1376 static struct qinit iplwinit = {
1377 	(pfi_t)ip_lwput, NULL, ip_open, ip_close, NULL,
1378 	&ip_mod_info
1379 };
1380 
1381 struct streamtab ipinfo = {
1382 	&iprinit, &ipwinit, &iplrinit, &iplwinit
1383 };
1384 
1385 #ifdef	DEBUG
1386 static boolean_t skip_sctp_cksum = B_FALSE;
1387 #endif
1388 
1389 /*
1390  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1391  * ip_rput_v6(), ip_output(), etc.  If the message
1392  * block already has a M_CTL at the front of it, then simply set the zoneid
1393  * appropriately.
1394  */
1395 mblk_t *
1396 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1397 {
1398 	mblk_t		*first_mp;
1399 	ipsec_out_t	*io;
1400 
1401 	ASSERT(zoneid != ALL_ZONES);
1402 	if (mp->b_datap->db_type == M_CTL) {
1403 		io = (ipsec_out_t *)mp->b_rptr;
1404 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1405 		io->ipsec_out_zoneid = zoneid;
1406 		return (mp);
1407 	}
1408 
1409 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1410 	if (first_mp == NULL)
1411 		return (NULL);
1412 	io = (ipsec_out_t *)first_mp->b_rptr;
1413 	/* This is not a secure packet */
1414 	io->ipsec_out_secure = B_FALSE;
1415 	io->ipsec_out_zoneid = zoneid;
1416 	first_mp->b_cont = mp;
1417 	return (first_mp);
1418 }
1419 
1420 /*
1421  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1422  */
1423 mblk_t *
1424 ip_copymsg(mblk_t *mp)
1425 {
1426 	mblk_t *nmp;
1427 	ipsec_info_t *in;
1428 
1429 	if (mp->b_datap->db_type != M_CTL)
1430 		return (copymsg(mp));
1431 
1432 	in = (ipsec_info_t *)mp->b_rptr;
1433 
1434 	/*
1435 	 * Note that M_CTL is also used for delivering ICMP error messages
1436 	 * upstream to transport layers.
1437 	 */
1438 	if (in->ipsec_info_type != IPSEC_OUT &&
1439 	    in->ipsec_info_type != IPSEC_IN)
1440 		return (copymsg(mp));
1441 
1442 	nmp = copymsg(mp->b_cont);
1443 
1444 	if (in->ipsec_info_type == IPSEC_OUT) {
1445 		return (ipsec_out_tag(mp, nmp,
1446 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1447 	} else {
1448 		return (ipsec_in_tag(mp, nmp,
1449 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1450 	}
1451 }
1452 
1453 /* Generate an ICMP fragmentation needed message. */
1454 static void
1455 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1456     ip_stack_t *ipst)
1457 {
1458 	icmph_t	icmph;
1459 	mblk_t *first_mp;
1460 	boolean_t mctl_present;
1461 
1462 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1463 
1464 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1465 		if (mctl_present)
1466 			freeb(first_mp);
1467 		return;
1468 	}
1469 
1470 	bzero(&icmph, sizeof (icmph_t));
1471 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1472 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1473 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1474 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1475 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1476 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1477 	    ipst);
1478 }
1479 
1480 /*
1481  * icmp_inbound deals with ICMP messages in the following ways.
1482  *
1483  * 1) It needs to send a reply back and possibly delivering it
1484  *    to the "interested" upper clients.
1485  * 2) It needs to send it to the upper clients only.
1486  * 3) It needs to change some values in IP only.
1487  * 4) It needs to change some values in IP and upper layers e.g TCP.
1488  *
1489  * We need to accomodate icmp messages coming in clear until we get
1490  * everything secure from the wire. If icmp_accept_clear_messages
1491  * is zero we check with the global policy and act accordingly. If
1492  * it is non-zero, we accept the message without any checks. But
1493  * *this does not mean* that this will be delivered to the upper
1494  * clients. By accepting we might send replies back, change our MTU
1495  * value etc. but delivery to the ULP/clients depends on their policy
1496  * dispositions.
1497  *
1498  * We handle the above 4 cases in the context of IPSEC in the
1499  * following way :
1500  *
1501  * 1) Send the reply back in the same way as the request came in.
1502  *    If it came in encrypted, it goes out encrypted. If it came in
1503  *    clear, it goes out in clear. Thus, this will prevent chosen
1504  *    plain text attack.
1505  * 2) The client may or may not expect things to come in secure.
1506  *    If it comes in secure, the policy constraints are checked
1507  *    before delivering it to the upper layers. If it comes in
1508  *    clear, ipsec_inbound_accept_clear will decide whether to
1509  *    accept this in clear or not. In both the cases, if the returned
1510  *    message (IP header + 8 bytes) that caused the icmp message has
1511  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1512  *    sending up. If there are only 8 bytes of returned message, then
1513  *    upper client will not be notified.
1514  * 3) Check with global policy to see whether it matches the constaints.
1515  *    But this will be done only if icmp_accept_messages_in_clear is
1516  *    zero.
1517  * 4) If we need to change both in IP and ULP, then the decision taken
1518  *    while affecting the values in IP and while delivering up to TCP
1519  *    should be the same.
1520  *
1521  * 	There are two cases.
1522  *
1523  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1524  *	   failed), we will not deliver it to the ULP, even though they
1525  *	   are *willing* to accept in *clear*. This is fine as our global
1526  *	   disposition to icmp messages asks us reject the datagram.
1527  *
1528  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1529  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1530  *	   to deliver it to ULP (policy failed), it can lead to
1531  *	   consistency problems. The cases known at this time are
1532  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1533  *	   values :
1534  *
1535  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1536  *	     and Upper layer rejects. Then the communication will
1537  *	     come to a stop. This is solved by making similar decisions
1538  *	     at both levels. Currently, when we are unable to deliver
1539  *	     to the Upper Layer (due to policy failures) while IP has
1540  *	     adjusted ire_max_frag, the next outbound datagram would
1541  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1542  *	     will be with the right level of protection. Thus the right
1543  *	     value will be communicated even if we are not able to
1544  *	     communicate when we get from the wire initially. But this
1545  *	     assumes there would be at least one outbound datagram after
1546  *	     IP has adjusted its ire_max_frag value. To make things
1547  *	     simpler, we accept in clear after the validation of
1548  *	     AH/ESP headers.
1549  *
1550  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1551  *	     upper layer depending on the level of protection the upper
1552  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1553  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1554  *	     should be accepted in clear when the Upper layer expects secure.
1555  *	     Thus the communication may get aborted by some bad ICMP
1556  *	     packets.
1557  *
1558  * IPQoS Notes:
1559  * The only instance when a packet is sent for processing is when there
1560  * isn't an ICMP client and if we are interested in it.
1561  * If there is a client, IPPF processing will take place in the
1562  * ip_fanout_proto routine.
1563  *
1564  * Zones notes:
1565  * The packet is only processed in the context of the specified zone: typically
1566  * only this zone will reply to an echo request, and only interested clients in
1567  * this zone will receive a copy of the packet. This means that the caller must
1568  * call icmp_inbound() for each relevant zone.
1569  */
1570 static void
1571 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1572     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1573     ill_t *recv_ill, zoneid_t zoneid)
1574 {
1575 	icmph_t	*icmph;
1576 	ipha_t	*ipha;
1577 	int	iph_hdr_length;
1578 	int	hdr_length;
1579 	boolean_t	interested;
1580 	uint32_t	ts;
1581 	uchar_t	*wptr;
1582 	ipif_t	*ipif;
1583 	mblk_t *first_mp;
1584 	ipsec_in_t *ii;
1585 	ire_t *src_ire;
1586 	boolean_t onlink;
1587 	timestruc_t now;
1588 	uint32_t ill_index;
1589 	ip_stack_t *ipst;
1590 
1591 	ASSERT(ill != NULL);
1592 	ipst = ill->ill_ipst;
1593 
1594 	first_mp = mp;
1595 	if (mctl_present) {
1596 		mp = first_mp->b_cont;
1597 		ASSERT(mp != NULL);
1598 	}
1599 
1600 	ipha = (ipha_t *)mp->b_rptr;
1601 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1602 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1603 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1604 		if (first_mp == NULL)
1605 			return;
1606 	}
1607 
1608 	/*
1609 	 * On a labeled system, we have to check whether the zone itself is
1610 	 * permitted to receive raw traffic.
1611 	 */
1612 	if (is_system_labeled()) {
1613 		if (zoneid == ALL_ZONES)
1614 			zoneid = tsol_packet_to_zoneid(mp);
1615 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1616 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1617 			    zoneid));
1618 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1619 			freemsg(first_mp);
1620 			return;
1621 		}
1622 	}
1623 
1624 	/*
1625 	 * We have accepted the ICMP message. It means that we will
1626 	 * respond to the packet if needed. It may not be delivered
1627 	 * to the upper client depending on the policy constraints
1628 	 * and the disposition in ipsec_inbound_accept_clear.
1629 	 */
1630 
1631 	ASSERT(ill != NULL);
1632 
1633 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1634 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1635 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1636 		/* Last chance to get real. */
1637 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1638 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1639 			freemsg(first_mp);
1640 			return;
1641 		}
1642 		/* Refresh iph following the pullup. */
1643 		ipha = (ipha_t *)mp->b_rptr;
1644 	}
1645 	/* ICMP header checksum, including checksum field, should be zero. */
1646 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1647 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1648 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1649 		freemsg(first_mp);
1650 		return;
1651 	}
1652 	/* The IP header will always be a multiple of four bytes */
1653 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1654 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1655 	    icmph->icmph_code));
1656 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1657 	/* We will set "interested" to "true" if we want a copy */
1658 	interested = B_FALSE;
1659 	switch (icmph->icmph_type) {
1660 	case ICMP_ECHO_REPLY:
1661 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1662 		break;
1663 	case ICMP_DEST_UNREACHABLE:
1664 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1665 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1666 		interested = B_TRUE;	/* Pass up to transport */
1667 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1668 		break;
1669 	case ICMP_SOURCE_QUENCH:
1670 		interested = B_TRUE;	/* Pass up to transport */
1671 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1672 		break;
1673 	case ICMP_REDIRECT:
1674 		if (!ipst->ips_ip_ignore_redirect)
1675 			interested = B_TRUE;
1676 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1677 		break;
1678 	case ICMP_ECHO_REQUEST:
1679 		/*
1680 		 * Whether to respond to echo requests that come in as IP
1681 		 * broadcasts or as IP multicast is subject to debate
1682 		 * (what isn't?).  We aim to please, you pick it.
1683 		 * Default is do it.
1684 		 */
1685 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1686 			/* unicast: always respond */
1687 			interested = B_TRUE;
1688 		} else if (CLASSD(ipha->ipha_dst)) {
1689 			/* multicast: respond based on tunable */
1690 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1691 		} else if (broadcast) {
1692 			/* broadcast: respond based on tunable */
1693 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1694 		}
1695 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1696 		break;
1697 	case ICMP_ROUTER_ADVERTISEMENT:
1698 	case ICMP_ROUTER_SOLICITATION:
1699 		break;
1700 	case ICMP_TIME_EXCEEDED:
1701 		interested = B_TRUE;	/* Pass up to transport */
1702 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1703 		break;
1704 	case ICMP_PARAM_PROBLEM:
1705 		interested = B_TRUE;	/* Pass up to transport */
1706 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1707 		break;
1708 	case ICMP_TIME_STAMP_REQUEST:
1709 		/* Response to Time Stamp Requests is local policy. */
1710 		if (ipst->ips_ip_g_resp_to_timestamp &&
1711 		    /* So is whether to respond if it was an IP broadcast. */
1712 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1713 			int tstamp_len = 3 * sizeof (uint32_t);
1714 
1715 			if (wptr +  tstamp_len > mp->b_wptr) {
1716 				if (!pullupmsg(mp, wptr + tstamp_len -
1717 				    mp->b_rptr)) {
1718 					BUMP_MIB(ill->ill_ip_mib,
1719 					    ipIfStatsInDiscards);
1720 					freemsg(first_mp);
1721 					return;
1722 				}
1723 				/* Refresh ipha following the pullup. */
1724 				ipha = (ipha_t *)mp->b_rptr;
1725 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1726 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1727 			}
1728 			interested = B_TRUE;
1729 		}
1730 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1731 		break;
1732 	case ICMP_TIME_STAMP_REPLY:
1733 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1734 		break;
1735 	case ICMP_INFO_REQUEST:
1736 		/* Per RFC 1122 3.2.2.7, ignore this. */
1737 	case ICMP_INFO_REPLY:
1738 		break;
1739 	case ICMP_ADDRESS_MASK_REQUEST:
1740 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1741 		    !broadcast) &&
1742 		    /* TODO m_pullup of complete header? */
1743 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1744 			interested = B_TRUE;
1745 		}
1746 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1747 		break;
1748 	case ICMP_ADDRESS_MASK_REPLY:
1749 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1750 		break;
1751 	default:
1752 		interested = B_TRUE;	/* Pass up to transport */
1753 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1754 		break;
1755 	}
1756 	/* See if there is an ICMP client. */
1757 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1758 		/* If there is an ICMP client and we want one too, copy it. */
1759 		mblk_t *first_mp1;
1760 
1761 		if (!interested) {
1762 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1763 			    ip_policy, recv_ill, zoneid);
1764 			return;
1765 		}
1766 		first_mp1 = ip_copymsg(first_mp);
1767 		if (first_mp1 != NULL) {
1768 			ip_fanout_proto(q, first_mp1, ill, ipha,
1769 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1770 		}
1771 	} else if (!interested) {
1772 		freemsg(first_mp);
1773 		return;
1774 	} else {
1775 		/*
1776 		 * Initiate policy processing for this packet if ip_policy
1777 		 * is true.
1778 		 */
1779 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1780 			ill_index = ill->ill_phyint->phyint_ifindex;
1781 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1782 			if (mp == NULL) {
1783 				if (mctl_present) {
1784 					freeb(first_mp);
1785 				}
1786 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1787 				return;
1788 			}
1789 		}
1790 	}
1791 	/* We want to do something with it. */
1792 	/* Check db_ref to make sure we can modify the packet. */
1793 	if (mp->b_datap->db_ref > 1) {
1794 		mblk_t	*first_mp1;
1795 
1796 		first_mp1 = ip_copymsg(first_mp);
1797 		freemsg(first_mp);
1798 		if (!first_mp1) {
1799 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1800 			return;
1801 		}
1802 		first_mp = first_mp1;
1803 		if (mctl_present) {
1804 			mp = first_mp->b_cont;
1805 			ASSERT(mp != NULL);
1806 		} else {
1807 			mp = first_mp;
1808 		}
1809 		ipha = (ipha_t *)mp->b_rptr;
1810 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1811 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1812 	}
1813 	switch (icmph->icmph_type) {
1814 	case ICMP_ADDRESS_MASK_REQUEST:
1815 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1816 		if (ipif == NULL) {
1817 			freemsg(first_mp);
1818 			return;
1819 		}
1820 		/*
1821 		 * outging interface must be IPv4
1822 		 */
1823 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1824 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1825 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1826 		ipif_refrele(ipif);
1827 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1828 		break;
1829 	case ICMP_ECHO_REQUEST:
1830 		icmph->icmph_type = ICMP_ECHO_REPLY;
1831 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1832 		break;
1833 	case ICMP_TIME_STAMP_REQUEST: {
1834 		uint32_t *tsp;
1835 
1836 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1837 		tsp = (uint32_t *)wptr;
1838 		tsp++;		/* Skip past 'originate time' */
1839 		/* Compute # of milliseconds since midnight */
1840 		gethrestime(&now);
1841 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1842 		    now.tv_nsec / (NANOSEC / MILLISEC);
1843 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1844 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1845 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1846 		break;
1847 	}
1848 	default:
1849 		ipha = (ipha_t *)&icmph[1];
1850 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1851 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1852 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1853 				freemsg(first_mp);
1854 				return;
1855 			}
1856 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1857 			ipha = (ipha_t *)&icmph[1];
1858 		}
1859 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1860 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1861 			freemsg(first_mp);
1862 			return;
1863 		}
1864 		hdr_length = IPH_HDR_LENGTH(ipha);
1865 		if (hdr_length < sizeof (ipha_t)) {
1866 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1867 			freemsg(first_mp);
1868 			return;
1869 		}
1870 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1871 			if (!pullupmsg(mp,
1872 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1873 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1874 				freemsg(first_mp);
1875 				return;
1876 			}
1877 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1878 			ipha = (ipha_t *)&icmph[1];
1879 		}
1880 		switch (icmph->icmph_type) {
1881 		case ICMP_REDIRECT:
1882 			/*
1883 			 * As there is no upper client to deliver, we don't
1884 			 * need the first_mp any more.
1885 			 */
1886 			if (mctl_present) {
1887 				freeb(first_mp);
1888 			}
1889 			icmp_redirect(ill, mp);
1890 			return;
1891 		case ICMP_DEST_UNREACHABLE:
1892 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1893 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1894 				    zoneid, mp, iph_hdr_length, ipst)) {
1895 					freemsg(first_mp);
1896 					return;
1897 				}
1898 				/*
1899 				 * icmp_inbound_too_big() may alter mp.
1900 				 * Resynch ipha and icmph accordingly.
1901 				 */
1902 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1903 				ipha = (ipha_t *)&icmph[1];
1904 			}
1905 			/* FALLTHRU */
1906 		default :
1907 			/*
1908 			 * IPQoS notes: Since we have already done IPQoS
1909 			 * processing we don't want to do it again in
1910 			 * the fanout routines called by
1911 			 * icmp_inbound_error_fanout, hence the last
1912 			 * argument, ip_policy, is B_FALSE.
1913 			 */
1914 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1915 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1916 			    B_FALSE, recv_ill, zoneid);
1917 		}
1918 		return;
1919 	}
1920 	/* Send out an ICMP packet */
1921 	icmph->icmph_checksum = 0;
1922 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1923 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1924 		ipif_t	*ipif_chosen;
1925 		/*
1926 		 * Make it look like it was directed to us, so we don't look
1927 		 * like a fool with a broadcast or multicast source address.
1928 		 */
1929 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1930 		/*
1931 		 * Make sure that we haven't grabbed an interface that's DOWN.
1932 		 */
1933 		if (ipif != NULL) {
1934 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1935 			    ipha->ipha_src, zoneid);
1936 			if (ipif_chosen != NULL) {
1937 				ipif_refrele(ipif);
1938 				ipif = ipif_chosen;
1939 			}
1940 		}
1941 		if (ipif == NULL) {
1942 			ip0dbg(("icmp_inbound: "
1943 			    "No source for broadcast/multicast:\n"
1944 			    "\tsrc 0x%x dst 0x%x ill %p "
1945 			    "ipif_lcl_addr 0x%x\n",
1946 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1947 			    (void *)ill,
1948 			    ill->ill_ipif->ipif_lcl_addr));
1949 			freemsg(first_mp);
1950 			return;
1951 		}
1952 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1953 		ipha->ipha_dst = ipif->ipif_src_addr;
1954 		ipif_refrele(ipif);
1955 	}
1956 	/* Reset time to live. */
1957 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1958 	{
1959 		/* Swap source and destination addresses */
1960 		ipaddr_t tmp;
1961 
1962 		tmp = ipha->ipha_src;
1963 		ipha->ipha_src = ipha->ipha_dst;
1964 		ipha->ipha_dst = tmp;
1965 	}
1966 	ipha->ipha_ident = 0;
1967 	if (!IS_SIMPLE_IPH(ipha))
1968 		icmp_options_update(ipha);
1969 
1970 	/*
1971 	 * ICMP echo replies should go out on the same interface
1972 	 * the request came on as probes used by in.mpathd for detecting
1973 	 * NIC failures are ECHO packets. We turn-off load spreading
1974 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1975 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1976 	 * function. This is in turn handled by ip_wput and ip_newroute
1977 	 * to make sure that the packet goes out on the interface it came
1978 	 * in on. If we don't turnoff load spreading, the packets might get
1979 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
1980 	 * to go out and in.mpathd would wrongly detect a failure or
1981 	 * mis-detect a NIC failure for link failure. As load spreading
1982 	 * can happen only if ill_group is not NULL, we do only for
1983 	 * that case and this does not affect the normal case.
1984 	 *
1985 	 * We turn off load spreading only on echo packets that came from
1986 	 * on-link hosts. If the interface route has been deleted, this will
1987 	 * not be enforced as we can't do much. For off-link hosts, as the
1988 	 * default routes in IPv4 does not typically have an ire_ipif
1989 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
1990 	 * Moreover, expecting a default route through this interface may
1991 	 * not be correct. We use ipha_dst because of the swap above.
1992 	 */
1993 	onlink = B_FALSE;
1994 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
1995 		/*
1996 		 * First, we need to make sure that it is not one of our
1997 		 * local addresses. If we set onlink when it is one of
1998 		 * our local addresses, we will end up creating IRE_CACHES
1999 		 * for one of our local addresses. Then, we will never
2000 		 * accept packets for them afterwards.
2001 		 */
2002 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2003 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2004 		if (src_ire == NULL) {
2005 			ipif = ipif_get_next_ipif(NULL, ill);
2006 			if (ipif == NULL) {
2007 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2008 				freemsg(mp);
2009 				return;
2010 			}
2011 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2012 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2013 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2014 			ipif_refrele(ipif);
2015 			if (src_ire != NULL) {
2016 				onlink = B_TRUE;
2017 				ire_refrele(src_ire);
2018 			}
2019 		} else {
2020 			ire_refrele(src_ire);
2021 		}
2022 	}
2023 	if (!mctl_present) {
2024 		/*
2025 		 * This packet should go out the same way as it
2026 		 * came in i.e in clear. To make sure that global
2027 		 * policy will not be applied to this in ip_wput_ire,
2028 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2029 		 */
2030 		ASSERT(first_mp == mp);
2031 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2032 		if (first_mp == NULL) {
2033 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2034 			freemsg(mp);
2035 			return;
2036 		}
2037 		ii = (ipsec_in_t *)first_mp->b_rptr;
2038 
2039 		/* This is not a secure packet */
2040 		ii->ipsec_in_secure = B_FALSE;
2041 		if (onlink) {
2042 			ii->ipsec_in_attach_if = B_TRUE;
2043 			ii->ipsec_in_ill_index =
2044 			    ill->ill_phyint->phyint_ifindex;
2045 			ii->ipsec_in_rill_index =
2046 			    recv_ill->ill_phyint->phyint_ifindex;
2047 		}
2048 		first_mp->b_cont = mp;
2049 	} else if (onlink) {
2050 		ii = (ipsec_in_t *)first_mp->b_rptr;
2051 		ii->ipsec_in_attach_if = B_TRUE;
2052 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2053 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2054 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2055 	} else {
2056 		ii = (ipsec_in_t *)first_mp->b_rptr;
2057 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2058 	}
2059 	ii->ipsec_in_zoneid = zoneid;
2060 	ASSERT(zoneid != ALL_ZONES);
2061 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2062 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2063 		return;
2064 	}
2065 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2066 	put(WR(q), first_mp);
2067 }
2068 
2069 static ipaddr_t
2070 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2071 {
2072 	conn_t *connp;
2073 	connf_t *connfp;
2074 	ipaddr_t nexthop_addr = INADDR_ANY;
2075 	int hdr_length = IPH_HDR_LENGTH(ipha);
2076 	uint16_t *up;
2077 	uint32_t ports;
2078 	ip_stack_t *ipst = ill->ill_ipst;
2079 
2080 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2081 	switch (ipha->ipha_protocol) {
2082 		case IPPROTO_TCP:
2083 		{
2084 			tcph_t *tcph;
2085 
2086 			/* do a reverse lookup */
2087 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2088 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2089 			    TCPS_LISTEN, ipst);
2090 			break;
2091 		}
2092 		case IPPROTO_UDP:
2093 		{
2094 			uint32_t dstport, srcport;
2095 
2096 			((uint16_t *)&ports)[0] = up[1];
2097 			((uint16_t *)&ports)[1] = up[0];
2098 
2099 			/* Extract ports in net byte order */
2100 			dstport = htons(ntohl(ports) & 0xFFFF);
2101 			srcport = htons(ntohl(ports) >> 16);
2102 
2103 			connfp = &ipst->ips_ipcl_udp_fanout[
2104 			    IPCL_UDP_HASH(dstport, ipst)];
2105 			mutex_enter(&connfp->connf_lock);
2106 			connp = connfp->connf_head;
2107 
2108 			/* do a reverse lookup */
2109 			while ((connp != NULL) &&
2110 			    (!IPCL_UDP_MATCH(connp, dstport,
2111 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2112 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2113 				connp = connp->conn_next;
2114 			}
2115 			if (connp != NULL)
2116 				CONN_INC_REF(connp);
2117 			mutex_exit(&connfp->connf_lock);
2118 			break;
2119 		}
2120 		case IPPROTO_SCTP:
2121 		{
2122 			in6_addr_t map_src, map_dst;
2123 
2124 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2125 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2126 			((uint16_t *)&ports)[0] = up[1];
2127 			((uint16_t *)&ports)[1] = up[0];
2128 
2129 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2130 			    zoneid, ipst->ips_netstack->netstack_sctp);
2131 			if (connp == NULL) {
2132 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2133 				    zoneid, ports, ipha, ipst);
2134 			} else {
2135 				CONN_INC_REF(connp);
2136 				SCTP_REFRELE(CONN2SCTP(connp));
2137 			}
2138 			break;
2139 		}
2140 		default:
2141 		{
2142 			ipha_t ripha;
2143 
2144 			ripha.ipha_src = ipha->ipha_dst;
2145 			ripha.ipha_dst = ipha->ipha_src;
2146 			ripha.ipha_protocol = ipha->ipha_protocol;
2147 
2148 			connfp = &ipst->ips_ipcl_proto_fanout[
2149 			    ipha->ipha_protocol];
2150 			mutex_enter(&connfp->connf_lock);
2151 			connp = connfp->connf_head;
2152 			for (connp = connfp->connf_head; connp != NULL;
2153 			    connp = connp->conn_next) {
2154 				if (IPCL_PROTO_MATCH(connp,
2155 				    ipha->ipha_protocol, &ripha, ill,
2156 				    0, zoneid)) {
2157 					CONN_INC_REF(connp);
2158 					break;
2159 				}
2160 			}
2161 			mutex_exit(&connfp->connf_lock);
2162 		}
2163 	}
2164 	if (connp != NULL) {
2165 		if (connp->conn_nexthop_set)
2166 			nexthop_addr = connp->conn_nexthop_v4;
2167 		CONN_DEC_REF(connp);
2168 	}
2169 	return (nexthop_addr);
2170 }
2171 
2172 /* Table from RFC 1191 */
2173 static int icmp_frag_size_table[] =
2174 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2175 
2176 /*
2177  * Process received ICMP Packet too big.
2178  * After updating any IRE it does the fanout to any matching transport streams.
2179  * Assumes the message has been pulled up till the IP header that caused
2180  * the error.
2181  *
2182  * Returns B_FALSE on failure and B_TRUE on success.
2183  */
2184 static boolean_t
2185 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2186     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2187     ip_stack_t *ipst)
2188 {
2189 	ire_t	*ire, *first_ire;
2190 	int	mtu;
2191 	int	hdr_length;
2192 	ipaddr_t nexthop_addr;
2193 
2194 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2195 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2196 	ASSERT(ill != NULL);
2197 
2198 	hdr_length = IPH_HDR_LENGTH(ipha);
2199 
2200 	/* Drop if the original packet contained a source route */
2201 	if (ip_source_route_included(ipha)) {
2202 		return (B_FALSE);
2203 	}
2204 	/*
2205 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2206 	 * header.
2207 	 */
2208 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2209 	    mp->b_wptr) {
2210 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2211 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2212 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2213 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2214 			return (B_FALSE);
2215 		}
2216 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2217 		ipha = (ipha_t *)&icmph[1];
2218 	}
2219 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2220 	if (nexthop_addr != INADDR_ANY) {
2221 		/* nexthop set */
2222 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2223 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2224 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2225 	} else {
2226 		/* nexthop not set */
2227 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2228 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2229 	}
2230 
2231 	if (!first_ire) {
2232 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2233 		    ntohl(ipha->ipha_dst)));
2234 		return (B_FALSE);
2235 	}
2236 	/* Check for MTU discovery advice as described in RFC 1191 */
2237 	mtu = ntohs(icmph->icmph_du_mtu);
2238 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2239 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2240 	    ire = ire->ire_next) {
2241 		/*
2242 		 * Look for the connection to which this ICMP message is
2243 		 * directed. If it has the IP_NEXTHOP option set, then the
2244 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2245 		 * option. Else the search is limited to regular IREs.
2246 		 */
2247 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2248 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2249 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2250 		    (nexthop_addr != INADDR_ANY)))
2251 			continue;
2252 
2253 		mutex_enter(&ire->ire_lock);
2254 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2255 			/* Reduce the IRE max frag value as advised. */
2256 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2257 			    mtu, ire->ire_max_frag));
2258 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2259 		} else {
2260 			uint32_t length;
2261 			int	i;
2262 
2263 			/*
2264 			 * Use the table from RFC 1191 to figure out
2265 			 * the next "plateau" based on the length in
2266 			 * the original IP packet.
2267 			 */
2268 			length = ntohs(ipha->ipha_length);
2269 			if (ire->ire_max_frag <= length &&
2270 			    ire->ire_max_frag >= length - hdr_length) {
2271 				/*
2272 				 * Handle broken BSD 4.2 systems that
2273 				 * return the wrong iph_length in ICMP
2274 				 * errors.
2275 				 */
2276 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2277 				    length, ire->ire_max_frag));
2278 				length -= hdr_length;
2279 			}
2280 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2281 				if (length > icmp_frag_size_table[i])
2282 					break;
2283 			}
2284 			if (i == A_CNT(icmp_frag_size_table)) {
2285 				/* Smaller than 68! */
2286 				ip1dbg(("Too big for packet size %d\n",
2287 				    length));
2288 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2289 				ire->ire_frag_flag = 0;
2290 			} else {
2291 				mtu = icmp_frag_size_table[i];
2292 				ip1dbg(("Calculated mtu %d, packet size %d, "
2293 				    "before %d", mtu, length,
2294 				    ire->ire_max_frag));
2295 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2296 				ip1dbg((", after %d\n", ire->ire_max_frag));
2297 			}
2298 			/* Record the new max frag size for the ULP. */
2299 			icmph->icmph_du_zero = 0;
2300 			icmph->icmph_du_mtu =
2301 			    htons((uint16_t)ire->ire_max_frag);
2302 		}
2303 		mutex_exit(&ire->ire_lock);
2304 	}
2305 	rw_exit(&first_ire->ire_bucket->irb_lock);
2306 	ire_refrele(first_ire);
2307 	return (B_TRUE);
2308 }
2309 
2310 /*
2311  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2312  * calls this function.
2313  */
2314 static mblk_t *
2315 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2316 {
2317 	ipha_t *ipha;
2318 	icmph_t *icmph;
2319 	ipha_t *in_ipha;
2320 	int length;
2321 
2322 	ASSERT(mp->b_datap->db_type == M_DATA);
2323 
2324 	/*
2325 	 * For Self-encapsulated packets, we added an extra IP header
2326 	 * without the options. Inner IP header is the one from which
2327 	 * the outer IP header was formed. Thus, we need to remove the
2328 	 * outer IP header. To do this, we pullup the whole message
2329 	 * and overlay whatever follows the outer IP header over the
2330 	 * outer IP header.
2331 	 */
2332 
2333 	if (!pullupmsg(mp, -1))
2334 		return (NULL);
2335 
2336 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2337 	ipha = (ipha_t *)&icmph[1];
2338 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2339 
2340 	/*
2341 	 * The length that we want to overlay is following the inner
2342 	 * IP header. Subtracting the IP header + icmp header + outer
2343 	 * IP header's length should give us the length that we want to
2344 	 * overlay.
2345 	 */
2346 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2347 	    hdr_length;
2348 	/*
2349 	 * Overlay whatever follows the inner header over the
2350 	 * outer header.
2351 	 */
2352 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2353 
2354 	/* Set the wptr to account for the outer header */
2355 	mp->b_wptr -= hdr_length;
2356 	return (mp);
2357 }
2358 
2359 /*
2360  * Try to pass the ICMP message upstream in case the ULP cares.
2361  *
2362  * If the packet that caused the ICMP error is secure, we send
2363  * it to AH/ESP to make sure that the attached packet has a
2364  * valid association. ipha in the code below points to the
2365  * IP header of the packet that caused the error.
2366  *
2367  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2368  * in the context of IPSEC. Normally we tell the upper layer
2369  * whenever we send the ire (including ip_bind), the IPSEC header
2370  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2371  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2372  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2373  * same thing. As TCP has the IPSEC options size that needs to be
2374  * adjusted, we just pass the MTU unchanged.
2375  *
2376  * IFN could have been generated locally or by some router.
2377  *
2378  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2379  *	    This happens because IP adjusted its value of MTU on an
2380  *	    earlier IFN message and could not tell the upper layer,
2381  *	    the new adjusted value of MTU e.g. Packet was encrypted
2382  *	    or there was not enough information to fanout to upper
2383  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2384  *	    generates the IFN, where IPSEC processing has *not* been
2385  *	    done.
2386  *
2387  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2388  *	    could have generated this. This happens because ire_max_frag
2389  *	    value in IP was set to a new value, while the IPSEC processing
2390  *	    was being done and after we made the fragmentation check in
2391  *	    ip_wput_ire. Thus on return from IPSEC processing,
2392  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2393  *	    and generates the IFN. As IPSEC processing is over, we fanout
2394  *	    to AH/ESP to remove the header.
2395  *
2396  *	    In both these cases, ipsec_in_loopback will be set indicating
2397  *	    that IFN was generated locally.
2398  *
2399  * ROUTER : IFN could be secure or non-secure.
2400  *
2401  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2402  *	      packet in error has AH/ESP headers to validate the AH/ESP
2403  *	      headers. AH/ESP will verify whether there is a valid SA or
2404  *	      not and send it back. We will fanout again if we have more
2405  *	      data in the packet.
2406  *
2407  *	      If the packet in error does not have AH/ESP, we handle it
2408  *	      like any other case.
2409  *
2410  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2411  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2412  *	      for validation. AH/ESP will verify whether there is a
2413  *	      valid SA or not and send it back. We will fanout again if
2414  *	      we have more data in the packet.
2415  *
2416  *	      If the packet in error does not have AH/ESP, we handle it
2417  *	      like any other case.
2418  */
2419 static void
2420 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2421     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2422     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2423     zoneid_t zoneid)
2424 {
2425 	uint16_t *up;	/* Pointer to ports in ULP header */
2426 	uint32_t ports;	/* reversed ports for fanout */
2427 	ipha_t ripha;	/* With reversed addresses */
2428 	mblk_t *first_mp;
2429 	ipsec_in_t *ii;
2430 	tcph_t	*tcph;
2431 	conn_t	*connp;
2432 	ip_stack_t *ipst;
2433 
2434 	ASSERT(ill != NULL);
2435 
2436 	ASSERT(recv_ill != NULL);
2437 	ipst = recv_ill->ill_ipst;
2438 
2439 	first_mp = mp;
2440 	if (mctl_present) {
2441 		mp = first_mp->b_cont;
2442 		ASSERT(mp != NULL);
2443 
2444 		ii = (ipsec_in_t *)first_mp->b_rptr;
2445 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2446 	} else {
2447 		ii = NULL;
2448 	}
2449 
2450 	switch (ipha->ipha_protocol) {
2451 	case IPPROTO_UDP:
2452 		/*
2453 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2454 		 * transport header.
2455 		 */
2456 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2457 		    mp->b_wptr) {
2458 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2459 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2460 				goto discard_pkt;
2461 			}
2462 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2463 			ipha = (ipha_t *)&icmph[1];
2464 		}
2465 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2466 
2467 		/*
2468 		 * Attempt to find a client stream based on port.
2469 		 * Note that we do a reverse lookup since the header is
2470 		 * in the form we sent it out.
2471 		 * The ripha header is only used for the IP_UDP_MATCH and we
2472 		 * only set the src and dst addresses and protocol.
2473 		 */
2474 		ripha.ipha_src = ipha->ipha_dst;
2475 		ripha.ipha_dst = ipha->ipha_src;
2476 		ripha.ipha_protocol = ipha->ipha_protocol;
2477 		((uint16_t *)&ports)[0] = up[1];
2478 		((uint16_t *)&ports)[1] = up[0];
2479 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2480 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2481 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2482 		    icmph->icmph_type, icmph->icmph_code));
2483 
2484 		/* Have to change db_type after any pullupmsg */
2485 		DB_TYPE(mp) = M_CTL;
2486 
2487 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2488 		    mctl_present, ip_policy, recv_ill, zoneid);
2489 		return;
2490 
2491 	case IPPROTO_TCP:
2492 		/*
2493 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2494 		 * transport header.
2495 		 */
2496 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2497 		    mp->b_wptr) {
2498 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2499 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2500 				goto discard_pkt;
2501 			}
2502 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2503 			ipha = (ipha_t *)&icmph[1];
2504 		}
2505 		/*
2506 		 * Find a TCP client stream for this packet.
2507 		 * Note that we do a reverse lookup since the header is
2508 		 * in the form we sent it out.
2509 		 */
2510 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2511 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2512 		    ipst);
2513 		if (connp == NULL)
2514 			goto discard_pkt;
2515 
2516 		/* Have to change db_type after any pullupmsg */
2517 		DB_TYPE(mp) = M_CTL;
2518 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2519 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2520 		return;
2521 
2522 	case IPPROTO_SCTP:
2523 		/*
2524 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2525 		 * transport header.
2526 		 */
2527 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2528 		    mp->b_wptr) {
2529 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2530 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2531 				goto discard_pkt;
2532 			}
2533 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2534 			ipha = (ipha_t *)&icmph[1];
2535 		}
2536 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2537 		/*
2538 		 * Find a SCTP client stream for this packet.
2539 		 * Note that we do a reverse lookup since the header is
2540 		 * in the form we sent it out.
2541 		 * The ripha header is only used for the matching and we
2542 		 * only set the src and dst addresses, protocol, and version.
2543 		 */
2544 		ripha.ipha_src = ipha->ipha_dst;
2545 		ripha.ipha_dst = ipha->ipha_src;
2546 		ripha.ipha_protocol = ipha->ipha_protocol;
2547 		ripha.ipha_version_and_hdr_length =
2548 		    ipha->ipha_version_and_hdr_length;
2549 		((uint16_t *)&ports)[0] = up[1];
2550 		((uint16_t *)&ports)[1] = up[0];
2551 
2552 		/* Have to change db_type after any pullupmsg */
2553 		DB_TYPE(mp) = M_CTL;
2554 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2555 		    mctl_present, ip_policy, zoneid);
2556 		return;
2557 
2558 	case IPPROTO_ESP:
2559 	case IPPROTO_AH: {
2560 		int ipsec_rc;
2561 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2562 
2563 		/*
2564 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2565 		 * We will re-use the IPSEC_IN if it is already present as
2566 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2567 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2568 		 * one and attach it in the front.
2569 		 */
2570 		if (ii != NULL) {
2571 			/*
2572 			 * ip_fanout_proto_again converts the ICMP errors
2573 			 * that come back from AH/ESP to M_DATA so that
2574 			 * if it is non-AH/ESP and we do a pullupmsg in
2575 			 * this function, it would work. Convert it back
2576 			 * to M_CTL before we send up as this is a ICMP
2577 			 * error. This could have been generated locally or
2578 			 * by some router. Validate the inner IPSEC
2579 			 * headers.
2580 			 *
2581 			 * NOTE : ill_index is used by ip_fanout_proto_again
2582 			 * to locate the ill.
2583 			 */
2584 			ASSERT(ill != NULL);
2585 			ii->ipsec_in_ill_index =
2586 			    ill->ill_phyint->phyint_ifindex;
2587 			ii->ipsec_in_rill_index =
2588 			    recv_ill->ill_phyint->phyint_ifindex;
2589 			DB_TYPE(first_mp->b_cont) = M_CTL;
2590 		} else {
2591 			/*
2592 			 * IPSEC_IN is not present. We attach a ipsec_in
2593 			 * message and send up to IPSEC for validating
2594 			 * and removing the IPSEC headers. Clear
2595 			 * ipsec_in_secure so that when we return
2596 			 * from IPSEC, we don't mistakenly think that this
2597 			 * is a secure packet came from the network.
2598 			 *
2599 			 * NOTE : ill_index is used by ip_fanout_proto_again
2600 			 * to locate the ill.
2601 			 */
2602 			ASSERT(first_mp == mp);
2603 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2604 			if (first_mp == NULL) {
2605 				freemsg(mp);
2606 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2607 				return;
2608 			}
2609 			ii = (ipsec_in_t *)first_mp->b_rptr;
2610 
2611 			/* This is not a secure packet */
2612 			ii->ipsec_in_secure = B_FALSE;
2613 			first_mp->b_cont = mp;
2614 			DB_TYPE(mp) = M_CTL;
2615 			ASSERT(ill != NULL);
2616 			ii->ipsec_in_ill_index =
2617 			    ill->ill_phyint->phyint_ifindex;
2618 			ii->ipsec_in_rill_index =
2619 			    recv_ill->ill_phyint->phyint_ifindex;
2620 		}
2621 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2622 
2623 		if (!ipsec_loaded(ipss)) {
2624 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2625 			return;
2626 		}
2627 
2628 		if (ipha->ipha_protocol == IPPROTO_ESP)
2629 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2630 		else
2631 			ipsec_rc = ipsecah_icmp_error(first_mp);
2632 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2633 			return;
2634 
2635 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2636 		return;
2637 	}
2638 	default:
2639 		/*
2640 		 * The ripha header is only used for the lookup and we
2641 		 * only set the src and dst addresses and protocol.
2642 		 */
2643 		ripha.ipha_src = ipha->ipha_dst;
2644 		ripha.ipha_dst = ipha->ipha_src;
2645 		ripha.ipha_protocol = ipha->ipha_protocol;
2646 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2647 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2648 		    ntohl(ipha->ipha_dst),
2649 		    icmph->icmph_type, icmph->icmph_code));
2650 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2651 			ipha_t *in_ipha;
2652 
2653 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2654 			    mp->b_wptr) {
2655 				if (!pullupmsg(mp, (uchar_t *)ipha +
2656 				    hdr_length + sizeof (ipha_t) -
2657 				    mp->b_rptr)) {
2658 					goto discard_pkt;
2659 				}
2660 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2661 				ipha = (ipha_t *)&icmph[1];
2662 			}
2663 			/*
2664 			 * Caller has verified that length has to be
2665 			 * at least the size of IP header.
2666 			 */
2667 			ASSERT(hdr_length >= sizeof (ipha_t));
2668 			/*
2669 			 * Check the sanity of the inner IP header like
2670 			 * we did for the outer header.
2671 			 */
2672 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2673 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2674 				goto discard_pkt;
2675 			}
2676 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2677 				goto discard_pkt;
2678 			}
2679 			/* Check for Self-encapsulated tunnels */
2680 			if (in_ipha->ipha_src == ipha->ipha_src &&
2681 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2682 
2683 				mp = icmp_inbound_self_encap_error(mp,
2684 				    iph_hdr_length, hdr_length);
2685 				if (mp == NULL)
2686 					goto discard_pkt;
2687 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2688 				ipha = (ipha_t *)&icmph[1];
2689 				hdr_length = IPH_HDR_LENGTH(ipha);
2690 				/*
2691 				 * The packet in error is self-encapsualted.
2692 				 * And we are finding it further encapsulated
2693 				 * which we could not have possibly generated.
2694 				 */
2695 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2696 					goto discard_pkt;
2697 				}
2698 				icmp_inbound_error_fanout(q, ill, first_mp,
2699 				    icmph, ipha, iph_hdr_length, hdr_length,
2700 				    mctl_present, ip_policy, recv_ill, zoneid);
2701 				return;
2702 			}
2703 		}
2704 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2705 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2706 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2707 		    ii != NULL &&
2708 		    ii->ipsec_in_loopback &&
2709 		    ii->ipsec_in_secure) {
2710 			/*
2711 			 * For IP tunnels that get a looped-back
2712 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2713 			 * reported new MTU to take into account the IPsec
2714 			 * headers protecting this configured tunnel.
2715 			 *
2716 			 * This allows the tunnel module (tun.c) to blindly
2717 			 * accept the MTU reported in an ICMP "too big"
2718 			 * message.
2719 			 *
2720 			 * Non-looped back ICMP messages will just be
2721 			 * handled by the security protocols (if needed),
2722 			 * and the first subsequent packet will hit this
2723 			 * path.
2724 			 */
2725 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2726 			    ipsec_in_extra_length(first_mp));
2727 		}
2728 		/* Have to change db_type after any pullupmsg */
2729 		DB_TYPE(mp) = M_CTL;
2730 
2731 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2732 		    ip_policy, recv_ill, zoneid);
2733 		return;
2734 	}
2735 	/* NOTREACHED */
2736 discard_pkt:
2737 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2738 drop_pkt:;
2739 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2740 	freemsg(first_mp);
2741 }
2742 
2743 /*
2744  * Common IP options parser.
2745  *
2746  * Setup routine: fill in *optp with options-parsing state, then
2747  * tail-call ipoptp_next to return the first option.
2748  */
2749 uint8_t
2750 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2751 {
2752 	uint32_t totallen; /* total length of all options */
2753 
2754 	totallen = ipha->ipha_version_and_hdr_length -
2755 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2756 	totallen <<= 2;
2757 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2758 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2759 	optp->ipoptp_flags = 0;
2760 	return (ipoptp_next(optp));
2761 }
2762 
2763 /*
2764  * Common IP options parser: extract next option.
2765  */
2766 uint8_t
2767 ipoptp_next(ipoptp_t *optp)
2768 {
2769 	uint8_t *end = optp->ipoptp_end;
2770 	uint8_t *cur = optp->ipoptp_next;
2771 	uint8_t opt, len, pointer;
2772 
2773 	/*
2774 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2775 	 * has been corrupted.
2776 	 */
2777 	ASSERT(cur <= end);
2778 
2779 	if (cur == end)
2780 		return (IPOPT_EOL);
2781 
2782 	opt = cur[IPOPT_OPTVAL];
2783 
2784 	/*
2785 	 * Skip any NOP options.
2786 	 */
2787 	while (opt == IPOPT_NOP) {
2788 		cur++;
2789 		if (cur == end)
2790 			return (IPOPT_EOL);
2791 		opt = cur[IPOPT_OPTVAL];
2792 	}
2793 
2794 	if (opt == IPOPT_EOL)
2795 		return (IPOPT_EOL);
2796 
2797 	/*
2798 	 * Option requiring a length.
2799 	 */
2800 	if ((cur + 1) >= end) {
2801 		optp->ipoptp_flags |= IPOPTP_ERROR;
2802 		return (IPOPT_EOL);
2803 	}
2804 	len = cur[IPOPT_OLEN];
2805 	if (len < 2) {
2806 		optp->ipoptp_flags |= IPOPTP_ERROR;
2807 		return (IPOPT_EOL);
2808 	}
2809 	optp->ipoptp_cur = cur;
2810 	optp->ipoptp_len = len;
2811 	optp->ipoptp_next = cur + len;
2812 	if (cur + len > end) {
2813 		optp->ipoptp_flags |= IPOPTP_ERROR;
2814 		return (IPOPT_EOL);
2815 	}
2816 
2817 	/*
2818 	 * For the options which require a pointer field, make sure
2819 	 * its there, and make sure it points to either something
2820 	 * inside this option, or the end of the option.
2821 	 */
2822 	switch (opt) {
2823 	case IPOPT_RR:
2824 	case IPOPT_TS:
2825 	case IPOPT_LSRR:
2826 	case IPOPT_SSRR:
2827 		if (len <= IPOPT_OFFSET) {
2828 			optp->ipoptp_flags |= IPOPTP_ERROR;
2829 			return (opt);
2830 		}
2831 		pointer = cur[IPOPT_OFFSET];
2832 		if (pointer - 1 > len) {
2833 			optp->ipoptp_flags |= IPOPTP_ERROR;
2834 			return (opt);
2835 		}
2836 		break;
2837 	}
2838 
2839 	/*
2840 	 * Sanity check the pointer field based on the type of the
2841 	 * option.
2842 	 */
2843 	switch (opt) {
2844 	case IPOPT_RR:
2845 	case IPOPT_SSRR:
2846 	case IPOPT_LSRR:
2847 		if (pointer < IPOPT_MINOFF_SR)
2848 			optp->ipoptp_flags |= IPOPTP_ERROR;
2849 		break;
2850 	case IPOPT_TS:
2851 		if (pointer < IPOPT_MINOFF_IT)
2852 			optp->ipoptp_flags |= IPOPTP_ERROR;
2853 		/*
2854 		 * Note that the Internet Timestamp option also
2855 		 * contains two four bit fields (the Overflow field,
2856 		 * and the Flag field), which follow the pointer
2857 		 * field.  We don't need to check that these fields
2858 		 * fall within the length of the option because this
2859 		 * was implicitely done above.  We've checked that the
2860 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2861 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2862 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2863 		 */
2864 		ASSERT(len > IPOPT_POS_OV_FLG);
2865 		break;
2866 	}
2867 
2868 	return (opt);
2869 }
2870 
2871 /*
2872  * Use the outgoing IP header to create an IP_OPTIONS option the way
2873  * it was passed down from the application.
2874  */
2875 int
2876 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2877 {
2878 	ipoptp_t	opts;
2879 	const uchar_t	*opt;
2880 	uint8_t		optval;
2881 	uint8_t		optlen;
2882 	uint32_t	len = 0;
2883 	uchar_t	*buf1 = buf;
2884 
2885 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2886 	len += IP_ADDR_LEN;
2887 	bzero(buf1, IP_ADDR_LEN);
2888 
2889 	/*
2890 	 * OK to cast away const here, as we don't store through the returned
2891 	 * opts.ipoptp_cur pointer.
2892 	 */
2893 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2894 	    optval != IPOPT_EOL;
2895 	    optval = ipoptp_next(&opts)) {
2896 		int	off;
2897 
2898 		opt = opts.ipoptp_cur;
2899 		optlen = opts.ipoptp_len;
2900 		switch (optval) {
2901 		case IPOPT_SSRR:
2902 		case IPOPT_LSRR:
2903 
2904 			/*
2905 			 * Insert ipha_dst as the first entry in the source
2906 			 * route and move down the entries on step.
2907 			 * The last entry gets placed at buf1.
2908 			 */
2909 			buf[IPOPT_OPTVAL] = optval;
2910 			buf[IPOPT_OLEN] = optlen;
2911 			buf[IPOPT_OFFSET] = optlen;
2912 
2913 			off = optlen - IP_ADDR_LEN;
2914 			if (off < 0) {
2915 				/* No entries in source route */
2916 				break;
2917 			}
2918 			/* Last entry in source route */
2919 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2920 			off -= IP_ADDR_LEN;
2921 
2922 			while (off > 0) {
2923 				bcopy(opt + off,
2924 				    buf + off + IP_ADDR_LEN,
2925 				    IP_ADDR_LEN);
2926 				off -= IP_ADDR_LEN;
2927 			}
2928 			/* ipha_dst into first slot */
2929 			bcopy(&ipha->ipha_dst,
2930 			    buf + off + IP_ADDR_LEN,
2931 			    IP_ADDR_LEN);
2932 			buf += optlen;
2933 			len += optlen;
2934 			break;
2935 
2936 		case IPOPT_COMSEC:
2937 		case IPOPT_SECURITY:
2938 			/* if passing up a label is not ok, then remove */
2939 			if (is_system_labeled())
2940 				break;
2941 			/* FALLTHROUGH */
2942 		default:
2943 			bcopy(opt, buf, optlen);
2944 			buf += optlen;
2945 			len += optlen;
2946 			break;
2947 		}
2948 	}
2949 done:
2950 	/* Pad the resulting options */
2951 	while (len & 0x3) {
2952 		*buf++ = IPOPT_EOL;
2953 		len++;
2954 	}
2955 	return (len);
2956 }
2957 
2958 /*
2959  * Update any record route or timestamp options to include this host.
2960  * Reverse any source route option.
2961  * This routine assumes that the options are well formed i.e. that they
2962  * have already been checked.
2963  */
2964 static void
2965 icmp_options_update(ipha_t *ipha)
2966 {
2967 	ipoptp_t	opts;
2968 	uchar_t		*opt;
2969 	uint8_t		optval;
2970 	ipaddr_t	src;		/* Our local address */
2971 	ipaddr_t	dst;
2972 
2973 	ip2dbg(("icmp_options_update\n"));
2974 	src = ipha->ipha_src;
2975 	dst = ipha->ipha_dst;
2976 
2977 	for (optval = ipoptp_first(&opts, ipha);
2978 	    optval != IPOPT_EOL;
2979 	    optval = ipoptp_next(&opts)) {
2980 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
2981 		opt = opts.ipoptp_cur;
2982 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
2983 		    optval, opts.ipoptp_len));
2984 		switch (optval) {
2985 			int off1, off2;
2986 		case IPOPT_SSRR:
2987 		case IPOPT_LSRR:
2988 			/*
2989 			 * Reverse the source route.  The first entry
2990 			 * should be the next to last one in the current
2991 			 * source route (the last entry is our address).
2992 			 * The last entry should be the final destination.
2993 			 */
2994 			off1 = IPOPT_MINOFF_SR - 1;
2995 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
2996 			if (off2 < 0) {
2997 				/* No entries in source route */
2998 				ip1dbg((
2999 				    "icmp_options_update: bad src route\n"));
3000 				break;
3001 			}
3002 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3003 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3004 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3005 			off2 -= IP_ADDR_LEN;
3006 
3007 			while (off1 < off2) {
3008 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3009 				bcopy((char *)opt + off2, (char *)opt + off1,
3010 				    IP_ADDR_LEN);
3011 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3012 				off1 += IP_ADDR_LEN;
3013 				off2 -= IP_ADDR_LEN;
3014 			}
3015 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3016 			break;
3017 		}
3018 	}
3019 }
3020 
3021 /*
3022  * Process received ICMP Redirect messages.
3023  */
3024 static void
3025 icmp_redirect(ill_t *ill, mblk_t *mp)
3026 {
3027 	ipha_t	*ipha;
3028 	int	iph_hdr_length;
3029 	icmph_t	*icmph;
3030 	ipha_t	*ipha_err;
3031 	ire_t	*ire;
3032 	ire_t	*prev_ire;
3033 	ire_t	*save_ire;
3034 	ipaddr_t  src, dst, gateway;
3035 	iulp_t	ulp_info = { 0 };
3036 	int	error;
3037 	ip_stack_t *ipst;
3038 
3039 	ASSERT(ill != NULL);
3040 	ipst = ill->ill_ipst;
3041 
3042 	ipha = (ipha_t *)mp->b_rptr;
3043 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3044 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3045 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3046 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3047 		freemsg(mp);
3048 		return;
3049 	}
3050 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3051 	ipha_err = (ipha_t *)&icmph[1];
3052 	src = ipha->ipha_src;
3053 	dst = ipha_err->ipha_dst;
3054 	gateway = icmph->icmph_rd_gateway;
3055 	/* Make sure the new gateway is reachable somehow. */
3056 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3057 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3058 	/*
3059 	 * Make sure we had a route for the dest in question and that
3060 	 * that route was pointing to the old gateway (the source of the
3061 	 * redirect packet.)
3062 	 */
3063 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3064 	    NULL, MATCH_IRE_GW, ipst);
3065 	/*
3066 	 * Check that
3067 	 *	the redirect was not from ourselves
3068 	 *	the new gateway and the old gateway are directly reachable
3069 	 */
3070 	if (!prev_ire ||
3071 	    !ire ||
3072 	    ire->ire_type == IRE_LOCAL) {
3073 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3074 		freemsg(mp);
3075 		if (ire != NULL)
3076 			ire_refrele(ire);
3077 		if (prev_ire != NULL)
3078 			ire_refrele(prev_ire);
3079 		return;
3080 	}
3081 
3082 	/*
3083 	 * Should we use the old ULP info to create the new gateway?  From
3084 	 * a user's perspective, we should inherit the info so that it
3085 	 * is a "smooth" transition.  If we do not do that, then new
3086 	 * connections going thru the new gateway will have no route metrics,
3087 	 * which is counter-intuitive to user.  From a network point of
3088 	 * view, this may or may not make sense even though the new gateway
3089 	 * is still directly connected to us so the route metrics should not
3090 	 * change much.
3091 	 *
3092 	 * But if the old ire_uinfo is not initialized, we do another
3093 	 * recursive lookup on the dest using the new gateway.  There may
3094 	 * be a route to that.  If so, use it to initialize the redirect
3095 	 * route.
3096 	 */
3097 	if (prev_ire->ire_uinfo.iulp_set) {
3098 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3099 	} else {
3100 		ire_t *tmp_ire;
3101 		ire_t *sire;
3102 
3103 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3104 		    ALL_ZONES, 0, NULL,
3105 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3106 		    ipst);
3107 		if (sire != NULL) {
3108 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3109 			/*
3110 			 * If sire != NULL, ire_ftable_lookup() should not
3111 			 * return a NULL value.
3112 			 */
3113 			ASSERT(tmp_ire != NULL);
3114 			ire_refrele(tmp_ire);
3115 			ire_refrele(sire);
3116 		} else if (tmp_ire != NULL) {
3117 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3118 			    sizeof (iulp_t));
3119 			ire_refrele(tmp_ire);
3120 		}
3121 	}
3122 	if (prev_ire->ire_type == IRE_CACHE)
3123 		ire_delete(prev_ire);
3124 	ire_refrele(prev_ire);
3125 	/*
3126 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3127 	 * require TOS routing
3128 	 */
3129 	switch (icmph->icmph_code) {
3130 	case 0:
3131 	case 1:
3132 		/* TODO: TOS specificity for cases 2 and 3 */
3133 	case 2:
3134 	case 3:
3135 		break;
3136 	default:
3137 		freemsg(mp);
3138 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3139 		ire_refrele(ire);
3140 		return;
3141 	}
3142 	/*
3143 	 * Create a Route Association.  This will allow us to remember that
3144 	 * someone we believe told us to use the particular gateway.
3145 	 */
3146 	save_ire = ire;
3147 	ire = ire_create(
3148 	    (uchar_t *)&dst,			/* dest addr */
3149 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3150 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3151 	    (uchar_t *)&gateway,		/* gateway addr */
3152 	    &save_ire->ire_max_frag,		/* max frag */
3153 	    NULL,				/* no src nce */
3154 	    NULL,				/* no rfq */
3155 	    NULL,				/* no stq */
3156 	    IRE_HOST,
3157 	    NULL,				/* ipif */
3158 	    0,					/* cmask */
3159 	    0,					/* phandle */
3160 	    0,					/* ihandle */
3161 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3162 	    &ulp_info,
3163 	    NULL,				/* tsol_gc_t */
3164 	    NULL,				/* gcgrp */
3165 	    ipst);
3166 
3167 	if (ire == NULL) {
3168 		freemsg(mp);
3169 		ire_refrele(save_ire);
3170 		return;
3171 	}
3172 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3173 	ire_refrele(save_ire);
3174 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3175 
3176 	if (error == 0) {
3177 		ire_refrele(ire);		/* Held in ire_add_v4 */
3178 		/* tell routing sockets that we received a redirect */
3179 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3180 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3181 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3182 	}
3183 
3184 	/*
3185 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3186 	 * This together with the added IRE has the effect of
3187 	 * modifying an existing redirect.
3188 	 */
3189 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3190 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3191 	if (prev_ire != NULL) {
3192 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3193 			ire_delete(prev_ire);
3194 		ire_refrele(prev_ire);
3195 	}
3196 
3197 	freemsg(mp);
3198 }
3199 
3200 /*
3201  * Generate an ICMP parameter problem message.
3202  */
3203 static void
3204 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3205 	ip_stack_t *ipst)
3206 {
3207 	icmph_t	icmph;
3208 	boolean_t mctl_present;
3209 	mblk_t *first_mp;
3210 
3211 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3212 
3213 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3214 		if (mctl_present)
3215 			freeb(first_mp);
3216 		return;
3217 	}
3218 
3219 	bzero(&icmph, sizeof (icmph_t));
3220 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3221 	icmph.icmph_pp_ptr = ptr;
3222 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3223 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3224 	    ipst);
3225 }
3226 
3227 /*
3228  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3229  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3230  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3231  * an icmp error packet can be sent.
3232  * Assigns an appropriate source address to the packet. If ipha_dst is
3233  * one of our addresses use it for source. Otherwise pick a source based
3234  * on a route lookup back to ipha_src.
3235  * Note that ipha_src must be set here since the
3236  * packet is likely to arrive on an ill queue in ip_wput() which will
3237  * not set a source address.
3238  */
3239 static void
3240 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3241     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3242 {
3243 	ipaddr_t dst;
3244 	icmph_t	*icmph;
3245 	ipha_t	*ipha;
3246 	uint_t	len_needed;
3247 	size_t	msg_len;
3248 	mblk_t	*mp1;
3249 	ipaddr_t src;
3250 	ire_t	*ire;
3251 	mblk_t *ipsec_mp;
3252 	ipsec_out_t	*io = NULL;
3253 
3254 	if (mctl_present) {
3255 		/*
3256 		 * If it is :
3257 		 *
3258 		 * 1) a IPSEC_OUT, then this is caused by outbound
3259 		 *    datagram originating on this host. IPSEC processing
3260 		 *    may or may not have been done. Refer to comments above
3261 		 *    icmp_inbound_error_fanout for details.
3262 		 *
3263 		 * 2) a IPSEC_IN if we are generating a icmp_message
3264 		 *    for an incoming datagram destined for us i.e called
3265 		 *    from ip_fanout_send_icmp.
3266 		 */
3267 		ipsec_info_t *in;
3268 		ipsec_mp = mp;
3269 		mp = ipsec_mp->b_cont;
3270 
3271 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3272 		ipha = (ipha_t *)mp->b_rptr;
3273 
3274 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3275 		    in->ipsec_info_type == IPSEC_IN);
3276 
3277 		if (in->ipsec_info_type == IPSEC_IN) {
3278 			/*
3279 			 * Convert the IPSEC_IN to IPSEC_OUT.
3280 			 */
3281 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3282 				BUMP_MIB(&ipst->ips_ip_mib,
3283 				    ipIfStatsOutDiscards);
3284 				return;
3285 			}
3286 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3287 		} else {
3288 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3289 			io = (ipsec_out_t *)in;
3290 			/*
3291 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3292 			 * ire lookup.
3293 			 */
3294 			io->ipsec_out_proc_begin = B_FALSE;
3295 		}
3296 		ASSERT(zoneid == io->ipsec_out_zoneid);
3297 		ASSERT(zoneid != ALL_ZONES);
3298 	} else {
3299 		/*
3300 		 * This is in clear. The icmp message we are building
3301 		 * here should go out in clear.
3302 		 *
3303 		 * Pardon the convolution of it all, but it's easier to
3304 		 * allocate a "use cleartext" IPSEC_IN message and convert
3305 		 * it than it is to allocate a new one.
3306 		 */
3307 		ipsec_in_t *ii;
3308 		ASSERT(DB_TYPE(mp) == M_DATA);
3309 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3310 		if (ipsec_mp == NULL) {
3311 			freemsg(mp);
3312 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3313 			return;
3314 		}
3315 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3316 
3317 		/* This is not a secure packet */
3318 		ii->ipsec_in_secure = B_FALSE;
3319 		/*
3320 		 * For trusted extensions using a shared IP address we can
3321 		 * send using any zoneid.
3322 		 */
3323 		if (zoneid == ALL_ZONES)
3324 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3325 		else
3326 			ii->ipsec_in_zoneid = zoneid;
3327 		ipsec_mp->b_cont = mp;
3328 		ipha = (ipha_t *)mp->b_rptr;
3329 		/*
3330 		 * Convert the IPSEC_IN to IPSEC_OUT.
3331 		 */
3332 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3333 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3334 			return;
3335 		}
3336 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3337 	}
3338 
3339 	/* Remember our eventual destination */
3340 	dst = ipha->ipha_src;
3341 
3342 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3343 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3344 	if (ire != NULL &&
3345 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3346 		src = ipha->ipha_dst;
3347 	} else {
3348 		if (ire != NULL)
3349 			ire_refrele(ire);
3350 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3351 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3352 		    ipst);
3353 		if (ire == NULL) {
3354 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3355 			freemsg(ipsec_mp);
3356 			return;
3357 		}
3358 		src = ire->ire_src_addr;
3359 	}
3360 
3361 	if (ire != NULL)
3362 		ire_refrele(ire);
3363 
3364 	/*
3365 	 * Check if we can send back more then 8 bytes in addition to
3366 	 * the IP header.  We try to send 64 bytes of data and the internal
3367 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3368 	 */
3369 	len_needed = IPH_HDR_LENGTH(ipha);
3370 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3371 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3372 
3373 		if (!pullupmsg(mp, -1)) {
3374 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3375 			freemsg(ipsec_mp);
3376 			return;
3377 		}
3378 		ipha = (ipha_t *)mp->b_rptr;
3379 
3380 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3381 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3382 			    len_needed));
3383 		} else {
3384 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3385 
3386 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3387 			len_needed += ip_hdr_length_v6(mp, ip6h);
3388 		}
3389 	}
3390 	len_needed += ipst->ips_ip_icmp_return;
3391 	msg_len = msgdsize(mp);
3392 	if (msg_len > len_needed) {
3393 		(void) adjmsg(mp, len_needed - msg_len);
3394 		msg_len = len_needed;
3395 	}
3396 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3397 	if (mp1 == NULL) {
3398 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3399 		freemsg(ipsec_mp);
3400 		return;
3401 	}
3402 	mp1->b_cont = mp;
3403 	mp = mp1;
3404 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3405 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3406 	    io->ipsec_out_type == IPSEC_OUT);
3407 	ipsec_mp->b_cont = mp;
3408 
3409 	/*
3410 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3411 	 * node generates be accepted in peace by all on-host destinations.
3412 	 * If we do NOT assume that all on-host destinations trust
3413 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3414 	 * (Look for ipsec_out_icmp_loopback).
3415 	 */
3416 	io->ipsec_out_icmp_loopback = B_TRUE;
3417 
3418 	ipha = (ipha_t *)mp->b_rptr;
3419 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3420 	*ipha = icmp_ipha;
3421 	ipha->ipha_src = src;
3422 	ipha->ipha_dst = dst;
3423 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3424 	msg_len += sizeof (icmp_ipha) + len;
3425 	if (msg_len > IP_MAXPACKET) {
3426 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3427 		msg_len = IP_MAXPACKET;
3428 	}
3429 	ipha->ipha_length = htons((uint16_t)msg_len);
3430 	icmph = (icmph_t *)&ipha[1];
3431 	bcopy(stuff, icmph, len);
3432 	icmph->icmph_checksum = 0;
3433 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3434 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3435 	put(q, ipsec_mp);
3436 }
3437 
3438 /*
3439  * Determine if an ICMP error packet can be sent given the rate limit.
3440  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3441  * in milliseconds) and a burst size. Burst size number of packets can
3442  * be sent arbitrarely closely spaced.
3443  * The state is tracked using two variables to implement an approximate
3444  * token bucket filter:
3445  *	icmp_pkt_err_last - lbolt value when the last burst started
3446  *	icmp_pkt_err_sent - number of packets sent in current burst
3447  */
3448 boolean_t
3449 icmp_err_rate_limit(ip_stack_t *ipst)
3450 {
3451 	clock_t now = TICK_TO_MSEC(lbolt);
3452 	uint_t refilled; /* Number of packets refilled in tbf since last */
3453 	/* Guard against changes by loading into local variable */
3454 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3455 
3456 	if (err_interval == 0)
3457 		return (B_FALSE);
3458 
3459 	if (ipst->ips_icmp_pkt_err_last > now) {
3460 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3461 		ipst->ips_icmp_pkt_err_last = 0;
3462 		ipst->ips_icmp_pkt_err_sent = 0;
3463 	}
3464 	/*
3465 	 * If we are in a burst update the token bucket filter.
3466 	 * Update the "last" time to be close to "now" but make sure
3467 	 * we don't loose precision.
3468 	 */
3469 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3470 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3471 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3472 			ipst->ips_icmp_pkt_err_sent = 0;
3473 		} else {
3474 			ipst->ips_icmp_pkt_err_sent -= refilled;
3475 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3476 		}
3477 	}
3478 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3479 		/* Start of new burst */
3480 		ipst->ips_icmp_pkt_err_last = now;
3481 	}
3482 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3483 		ipst->ips_icmp_pkt_err_sent++;
3484 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3485 		    ipst->ips_icmp_pkt_err_sent));
3486 		return (B_FALSE);
3487 	}
3488 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3489 	return (B_TRUE);
3490 }
3491 
3492 /*
3493  * Check if it is ok to send an IPv4 ICMP error packet in
3494  * response to the IPv4 packet in mp.
3495  * Free the message and return null if no
3496  * ICMP error packet should be sent.
3497  */
3498 static mblk_t *
3499 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3500 {
3501 	icmph_t	*icmph;
3502 	ipha_t	*ipha;
3503 	uint_t	len_needed;
3504 	ire_t	*src_ire;
3505 	ire_t	*dst_ire;
3506 
3507 	if (!mp)
3508 		return (NULL);
3509 	ipha = (ipha_t *)mp->b_rptr;
3510 	if (ip_csum_hdr(ipha)) {
3511 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3512 		freemsg(mp);
3513 		return (NULL);
3514 	}
3515 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3516 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3517 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3518 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3519 	if (src_ire != NULL || dst_ire != NULL ||
3520 	    CLASSD(ipha->ipha_dst) ||
3521 	    CLASSD(ipha->ipha_src) ||
3522 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3523 		/* Note: only errors to the fragment with offset 0 */
3524 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3525 		freemsg(mp);
3526 		if (src_ire != NULL)
3527 			ire_refrele(src_ire);
3528 		if (dst_ire != NULL)
3529 			ire_refrele(dst_ire);
3530 		return (NULL);
3531 	}
3532 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3533 		/*
3534 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3535 		 * errors in response to any ICMP errors.
3536 		 */
3537 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3538 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3539 			if (!pullupmsg(mp, len_needed)) {
3540 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3541 				freemsg(mp);
3542 				return (NULL);
3543 			}
3544 			ipha = (ipha_t *)mp->b_rptr;
3545 		}
3546 		icmph = (icmph_t *)
3547 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3548 		switch (icmph->icmph_type) {
3549 		case ICMP_DEST_UNREACHABLE:
3550 		case ICMP_SOURCE_QUENCH:
3551 		case ICMP_TIME_EXCEEDED:
3552 		case ICMP_PARAM_PROBLEM:
3553 		case ICMP_REDIRECT:
3554 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3555 			freemsg(mp);
3556 			return (NULL);
3557 		default:
3558 			break;
3559 		}
3560 	}
3561 	/*
3562 	 * If this is a labeled system, then check to see if we're allowed to
3563 	 * send a response to this particular sender.  If not, then just drop.
3564 	 */
3565 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3566 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3567 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3568 		freemsg(mp);
3569 		return (NULL);
3570 	}
3571 	if (icmp_err_rate_limit(ipst)) {
3572 		/*
3573 		 * Only send ICMP error packets every so often.
3574 		 * This should be done on a per port/source basis,
3575 		 * but for now this will suffice.
3576 		 */
3577 		freemsg(mp);
3578 		return (NULL);
3579 	}
3580 	return (mp);
3581 }
3582 
3583 /*
3584  * Generate an ICMP redirect message.
3585  */
3586 static void
3587 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3588 {
3589 	icmph_t	icmph;
3590 
3591 	/*
3592 	 * We are called from ip_rput where we could
3593 	 * not have attached an IPSEC_IN.
3594 	 */
3595 	ASSERT(mp->b_datap->db_type == M_DATA);
3596 
3597 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3598 		return;
3599 	}
3600 
3601 	bzero(&icmph, sizeof (icmph_t));
3602 	icmph.icmph_type = ICMP_REDIRECT;
3603 	icmph.icmph_code = 1;
3604 	icmph.icmph_rd_gateway = gateway;
3605 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3606 	/* Redirects sent by router, and router is global zone */
3607 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3608 }
3609 
3610 /*
3611  * Generate an ICMP time exceeded message.
3612  */
3613 void
3614 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3615     ip_stack_t *ipst)
3616 {
3617 	icmph_t	icmph;
3618 	boolean_t mctl_present;
3619 	mblk_t *first_mp;
3620 
3621 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3622 
3623 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3624 		if (mctl_present)
3625 			freeb(first_mp);
3626 		return;
3627 	}
3628 
3629 	bzero(&icmph, sizeof (icmph_t));
3630 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3631 	icmph.icmph_code = code;
3632 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3633 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3634 	    ipst);
3635 }
3636 
3637 /*
3638  * Generate an ICMP unreachable message.
3639  */
3640 void
3641 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3642     ip_stack_t *ipst)
3643 {
3644 	icmph_t	icmph;
3645 	mblk_t *first_mp;
3646 	boolean_t mctl_present;
3647 
3648 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3649 
3650 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3651 		if (mctl_present)
3652 			freeb(first_mp);
3653 		return;
3654 	}
3655 
3656 	bzero(&icmph, sizeof (icmph_t));
3657 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3658 	icmph.icmph_code = code;
3659 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3660 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3661 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3662 	    zoneid, ipst);
3663 }
3664 
3665 /*
3666  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3667  * duplicate.  As long as someone else holds the address, the interface will
3668  * stay down.  When that conflict goes away, the interface is brought back up.
3669  * This is done so that accidental shutdowns of addresses aren't made
3670  * permanent.  Your server will recover from a failure.
3671  *
3672  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3673  * user space process (dhcpagent).
3674  *
3675  * Recovery completes if ARP reports that the address is now ours (via
3676  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3677  *
3678  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3679  */
3680 static void
3681 ipif_dup_recovery(void *arg)
3682 {
3683 	ipif_t *ipif = arg;
3684 	ill_t *ill = ipif->ipif_ill;
3685 	mblk_t *arp_add_mp;
3686 	mblk_t *arp_del_mp;
3687 	area_t *area;
3688 	ip_stack_t *ipst = ill->ill_ipst;
3689 
3690 	ipif->ipif_recovery_id = 0;
3691 
3692 	/*
3693 	 * No lock needed for moving or condemned check, as this is just an
3694 	 * optimization.
3695 	 */
3696 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3697 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3698 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3699 		/* No reason to try to bring this address back. */
3700 		return;
3701 	}
3702 
3703 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3704 		goto alloc_fail;
3705 
3706 	if (ipif->ipif_arp_del_mp == NULL) {
3707 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3708 			goto alloc_fail;
3709 		ipif->ipif_arp_del_mp = arp_del_mp;
3710 	}
3711 
3712 	/* Setting the 'unverified' flag restarts DAD */
3713 	area = (area_t *)arp_add_mp->b_rptr;
3714 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3715 	    ACE_F_UNVERIFIED;
3716 	putnext(ill->ill_rq, arp_add_mp);
3717 	return;
3718 
3719 alloc_fail:
3720 	/*
3721 	 * On allocation failure, just restart the timer.  Note that the ipif
3722 	 * is down here, so no other thread could be trying to start a recovery
3723 	 * timer.  The ill_lock protects the condemned flag and the recovery
3724 	 * timer ID.
3725 	 */
3726 	freemsg(arp_add_mp);
3727 	mutex_enter(&ill->ill_lock);
3728 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3729 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3730 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3731 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3732 	}
3733 	mutex_exit(&ill->ill_lock);
3734 }
3735 
3736 /*
3737  * This is for exclusive changes due to ARP.  Either tear down an interface due
3738  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3739  */
3740 /* ARGSUSED */
3741 static void
3742 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3743 {
3744 	ill_t	*ill = rq->q_ptr;
3745 	arh_t *arh;
3746 	ipaddr_t src;
3747 	ipif_t	*ipif;
3748 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3749 	char hbuf[MAC_STR_LEN];
3750 	char sbuf[INET_ADDRSTRLEN];
3751 	const char *failtype;
3752 	boolean_t bring_up;
3753 	ip_stack_t *ipst = ill->ill_ipst;
3754 
3755 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3756 	case AR_CN_READY:
3757 		failtype = NULL;
3758 		bring_up = B_TRUE;
3759 		break;
3760 	case AR_CN_FAILED:
3761 		failtype = "in use";
3762 		bring_up = B_FALSE;
3763 		break;
3764 	default:
3765 		failtype = "claimed";
3766 		bring_up = B_FALSE;
3767 		break;
3768 	}
3769 
3770 	arh = (arh_t *)mp->b_cont->b_rptr;
3771 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3772 
3773 	/* Handle failures due to probes */
3774 	if (src == 0) {
3775 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3776 		    IP_ADDR_LEN);
3777 	}
3778 
3779 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3780 	    sizeof (hbuf));
3781 	(void) ip_dot_addr(src, sbuf);
3782 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3783 
3784 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3785 		    ipif->ipif_lcl_addr != src) {
3786 			continue;
3787 		}
3788 
3789 		/*
3790 		 * If we failed on a recovery probe, then restart the timer to
3791 		 * try again later.
3792 		 */
3793 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3794 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3795 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3796 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3797 		    ipst->ips_ip_dup_recovery > 0 &&
3798 		    ipif->ipif_recovery_id == 0) {
3799 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3800 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3801 			continue;
3802 		}
3803 
3804 		/*
3805 		 * If what we're trying to do has already been done, then do
3806 		 * nothing.
3807 		 */
3808 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3809 			continue;
3810 
3811 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3812 
3813 		if (failtype == NULL) {
3814 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3815 			    ibuf);
3816 		} else {
3817 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3818 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3819 		}
3820 
3821 		if (bring_up) {
3822 			ASSERT(ill->ill_dl_up);
3823 			/*
3824 			 * Free up the ARP delete message so we can allocate
3825 			 * a fresh one through the normal path.
3826 			 */
3827 			freemsg(ipif->ipif_arp_del_mp);
3828 			ipif->ipif_arp_del_mp = NULL;
3829 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3830 			    EINPROGRESS) {
3831 				ipif->ipif_addr_ready = 1;
3832 				(void) ipif_up_done(ipif);
3833 			}
3834 			continue;
3835 		}
3836 
3837 		mutex_enter(&ill->ill_lock);
3838 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3839 		ipif->ipif_flags |= IPIF_DUPLICATE;
3840 		ill->ill_ipif_dup_count++;
3841 		mutex_exit(&ill->ill_lock);
3842 		/*
3843 		 * Already exclusive on the ill; no need to handle deferred
3844 		 * processing here.
3845 		 */
3846 		(void) ipif_down(ipif, NULL, NULL);
3847 		ipif_down_tail(ipif);
3848 		mutex_enter(&ill->ill_lock);
3849 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3850 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3851 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3852 		    ipst->ips_ip_dup_recovery > 0) {
3853 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3854 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3855 		}
3856 		mutex_exit(&ill->ill_lock);
3857 	}
3858 	freemsg(mp);
3859 }
3860 
3861 /* ARGSUSED */
3862 static void
3863 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3864 {
3865 	ill_t	*ill = rq->q_ptr;
3866 	arh_t *arh;
3867 	ipaddr_t src;
3868 	ipif_t	*ipif;
3869 
3870 	arh = (arh_t *)mp->b_cont->b_rptr;
3871 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3872 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3873 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3874 			(void) ipif_resolver_up(ipif, Res_act_defend);
3875 	}
3876 	freemsg(mp);
3877 }
3878 
3879 /*
3880  * News from ARP.  ARP sends notification of interesting events down
3881  * to its clients using M_CTL messages with the interesting ARP packet
3882  * attached via b_cont.
3883  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3884  * queue as opposed to ARP sending the message to all the clients, i.e. all
3885  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3886  * table if a cache IRE is found to delete all the entries for the address in
3887  * the packet.
3888  */
3889 static void
3890 ip_arp_news(queue_t *q, mblk_t *mp)
3891 {
3892 	arcn_t		*arcn;
3893 	arh_t		*arh;
3894 	ire_t		*ire = NULL;
3895 	char		hbuf[MAC_STR_LEN];
3896 	char		sbuf[INET_ADDRSTRLEN];
3897 	ipaddr_t	src;
3898 	in6_addr_t	v6src;
3899 	boolean_t	isv6 = B_FALSE;
3900 	ipif_t		*ipif;
3901 	ill_t		*ill;
3902 	ip_stack_t	*ipst;
3903 
3904 	if (CONN_Q(q)) {
3905 		conn_t *connp = Q_TO_CONN(q);
3906 
3907 		ipst = connp->conn_netstack->netstack_ip;
3908 	} else {
3909 		ill_t *ill = (ill_t *)q->q_ptr;
3910 
3911 		ipst = ill->ill_ipst;
3912 	}
3913 
3914 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3915 		if (q->q_next) {
3916 			putnext(q, mp);
3917 		} else
3918 			freemsg(mp);
3919 		return;
3920 	}
3921 	arh = (arh_t *)mp->b_cont->b_rptr;
3922 	/* Is it one we are interested in? */
3923 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3924 		isv6 = B_TRUE;
3925 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3926 		    IPV6_ADDR_LEN);
3927 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3928 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3929 		    IP_ADDR_LEN);
3930 	} else {
3931 		freemsg(mp);
3932 		return;
3933 	}
3934 
3935 	ill = q->q_ptr;
3936 
3937 	arcn = (arcn_t *)mp->b_rptr;
3938 	switch (arcn->arcn_code) {
3939 	case AR_CN_BOGON:
3940 		/*
3941 		 * Someone is sending ARP packets with a source protocol
3942 		 * address that we have published and for which we believe our
3943 		 * entry is authoritative and (when ill_arp_extend is set)
3944 		 * verified to be unique on the network.
3945 		 *
3946 		 * The ARP module internally handles the cases where the sender
3947 		 * is just probing (for DAD) and where the hardware address of
3948 		 * a non-authoritative entry has changed.  Thus, these are the
3949 		 * real conflicts, and we have to do resolution.
3950 		 *
3951 		 * We back away quickly from the address if it's from DHCP or
3952 		 * otherwise temporary and hasn't been used recently (or at
3953 		 * all).  We'd like to include "deprecated" addresses here as
3954 		 * well (as there's no real reason to defend something we're
3955 		 * discarding), but IPMP "reuses" this flag to mean something
3956 		 * other than the standard meaning.
3957 		 *
3958 		 * If the ARP module above is not extended (meaning that it
3959 		 * doesn't know how to defend the address), then we just log
3960 		 * the problem as we always did and continue on.  It's not
3961 		 * right, but there's little else we can do, and those old ATM
3962 		 * users are going away anyway.
3963 		 */
3964 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3965 		    hbuf, sizeof (hbuf));
3966 		(void) ip_dot_addr(src, sbuf);
3967 		if (isv6) {
3968 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3969 			    ipst);
3970 		} else {
3971 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3972 		}
3973 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3974 			uint32_t now;
3975 			uint32_t maxage;
3976 			clock_t lused;
3977 			uint_t maxdefense;
3978 			uint_t defs;
3979 
3980 			/*
3981 			 * First, figure out if this address hasn't been used
3982 			 * in a while.  If it hasn't, then it's a better
3983 			 * candidate for abandoning.
3984 			 */
3985 			ipif = ire->ire_ipif;
3986 			ASSERT(ipif != NULL);
3987 			now = gethrestime_sec();
3988 			maxage = now - ire->ire_create_time;
3989 			if (maxage > ipst->ips_ip_max_temp_idle)
3990 				maxage = ipst->ips_ip_max_temp_idle;
3991 			lused = drv_hztousec(ddi_get_lbolt() -
3992 			    ire->ire_last_used_time) / MICROSEC + 1;
3993 			if (lused >= maxage && (ipif->ipif_flags &
3994 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
3995 				maxdefense = ipst->ips_ip_max_temp_defend;
3996 			else
3997 				maxdefense = ipst->ips_ip_max_defend;
3998 
3999 			/*
4000 			 * Now figure out how many times we've defended
4001 			 * ourselves.  Ignore defenses that happened long in
4002 			 * the past.
4003 			 */
4004 			mutex_enter(&ire->ire_lock);
4005 			if ((defs = ire->ire_defense_count) > 0 &&
4006 			    now - ire->ire_defense_time >
4007 			    ipst->ips_ip_defend_interval) {
4008 				ire->ire_defense_count = defs = 0;
4009 			}
4010 			ire->ire_defense_count++;
4011 			ire->ire_defense_time = now;
4012 			mutex_exit(&ire->ire_lock);
4013 			ill_refhold(ill);
4014 			ire_refrele(ire);
4015 
4016 			/*
4017 			 * If we've defended ourselves too many times already,
4018 			 * then give up and tear down the interface(s) using
4019 			 * this address.  Otherwise, defend by sending out a
4020 			 * gratuitous ARP.
4021 			 */
4022 			if (defs >= maxdefense && ill->ill_arp_extend) {
4023 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4024 				    B_FALSE);
4025 			} else {
4026 				cmn_err(CE_WARN,
4027 				    "node %s is using our IP address %s on %s",
4028 				    hbuf, sbuf, ill->ill_name);
4029 				/*
4030 				 * If this is an old (ATM) ARP module, then
4031 				 * don't try to defend the address.  Remain
4032 				 * compatible with the old behavior.  Defend
4033 				 * only with new ARP.
4034 				 */
4035 				if (ill->ill_arp_extend) {
4036 					qwriter_ip(ill, q, mp, ip_arp_defend,
4037 					    NEW_OP, B_FALSE);
4038 				} else {
4039 					ill_refrele(ill);
4040 				}
4041 			}
4042 			return;
4043 		}
4044 		cmn_err(CE_WARN,
4045 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4046 		    hbuf, sbuf, ill->ill_name);
4047 		if (ire != NULL)
4048 			ire_refrele(ire);
4049 		break;
4050 	case AR_CN_ANNOUNCE:
4051 		if (isv6) {
4052 			/*
4053 			 * For XRESOLV interfaces.
4054 			 * Delete the IRE cache entry and NCE for this
4055 			 * v6 address
4056 			 */
4057 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4058 			/*
4059 			 * If v6src is a non-zero, it's a router address
4060 			 * as below. Do the same sort of thing to clean
4061 			 * out off-net IRE_CACHE entries that go through
4062 			 * the router.
4063 			 */
4064 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4065 				ire_walk_v6(ire_delete_cache_gw_v6,
4066 				    (char *)&v6src, ALL_ZONES, ipst);
4067 			}
4068 		} else {
4069 			nce_hw_map_t hwm;
4070 
4071 			/*
4072 			 * ARP gives us a copy of any packet where it thinks
4073 			 * the address has changed, so that we can update our
4074 			 * caches.  We're responsible for caching known answers
4075 			 * in the current design.  We check whether the
4076 			 * hardware address really has changed in all of our
4077 			 * entries that have cached this mapping, and if so, we
4078 			 * blow them away.  This way we will immediately pick
4079 			 * up the rare case of a host changing hardware
4080 			 * address.
4081 			 */
4082 			if (src == 0)
4083 				break;
4084 			hwm.hwm_addr = src;
4085 			hwm.hwm_hwlen = arh->arh_hlen;
4086 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4087 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4088 			ndp_walk_common(ipst->ips_ndp4, NULL,
4089 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4090 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4091 		}
4092 		break;
4093 	case AR_CN_READY:
4094 		/* No external v6 resolver has a contract to use this */
4095 		if (isv6)
4096 			break;
4097 		/* If the link is down, we'll retry this later */
4098 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4099 			break;
4100 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4101 		    NULL, NULL, ipst);
4102 		if (ipif != NULL) {
4103 			/*
4104 			 * If this is a duplicate recovery, then we now need to
4105 			 * go exclusive to bring this thing back up.
4106 			 */
4107 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4108 			    IPIF_DUPLICATE) {
4109 				ipif_refrele(ipif);
4110 				ill_refhold(ill);
4111 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4112 				    B_FALSE);
4113 				return;
4114 			}
4115 			/*
4116 			 * If this is the first notice that this address is
4117 			 * ready, then let the user know now.
4118 			 */
4119 			if ((ipif->ipif_flags & IPIF_UP) &&
4120 			    !ipif->ipif_addr_ready) {
4121 				ipif_mask_reply(ipif);
4122 				ip_rts_ifmsg(ipif);
4123 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4124 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4125 			}
4126 			ipif->ipif_addr_ready = 1;
4127 			ipif_refrele(ipif);
4128 		}
4129 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4130 		if (ire != NULL) {
4131 			ire->ire_defense_count = 0;
4132 			ire_refrele(ire);
4133 		}
4134 		break;
4135 	case AR_CN_FAILED:
4136 		/* No external v6 resolver has a contract to use this */
4137 		if (isv6)
4138 			break;
4139 		ill_refhold(ill);
4140 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4141 		return;
4142 	}
4143 	freemsg(mp);
4144 }
4145 
4146 /*
4147  * Create a mblk suitable for carrying the interface index and/or source link
4148  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4149  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4150  * application.
4151  */
4152 mblk_t *
4153 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4154     ip_stack_t *ipst)
4155 {
4156 	mblk_t		*mp;
4157 	ip_pktinfo_t	*pinfo;
4158 	ipha_t *ipha;
4159 	struct ether_header *pether;
4160 
4161 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4162 	if (mp == NULL) {
4163 		ip1dbg(("ip_add_info: allocation failure.\n"));
4164 		return (data_mp);
4165 	}
4166 
4167 	ipha	= (ipha_t *)data_mp->b_rptr;
4168 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4169 	bzero(pinfo, sizeof (ip_pktinfo_t));
4170 	pinfo->ip_pkt_flags = (uchar_t)flags;
4171 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4172 
4173 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4174 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4175 	if (flags & IPF_RECVADDR) {
4176 		ipif_t	*ipif;
4177 		ire_t	*ire;
4178 
4179 		/*
4180 		 * Only valid for V4
4181 		 */
4182 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4183 		    (IPV4_VERSION << 4));
4184 
4185 		ipif = ipif_get_next_ipif(NULL, ill);
4186 		if (ipif != NULL) {
4187 			/*
4188 			 * Since a decision has already been made to deliver the
4189 			 * packet, there is no need to test for SECATTR and
4190 			 * ZONEONLY.
4191 			 * When a multicast packet is transmitted
4192 			 * a cache entry is created for the multicast address.
4193 			 * When delivering a copy of the packet or when new
4194 			 * packets are received we do not want to match on the
4195 			 * cached entry so explicitly match on
4196 			 * IRE_LOCAL and IRE_LOOPBACK
4197 			 */
4198 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4199 			    IRE_LOCAL | IRE_LOOPBACK,
4200 			    ipif, zoneid, NULL,
4201 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4202 			if (ire == NULL) {
4203 				/*
4204 				 * packet must have come on a different
4205 				 * interface.
4206 				 * Since a decision has already been made to
4207 				 * deliver the packet, there is no need to test
4208 				 * for SECATTR and ZONEONLY.
4209 				 * Only match on local and broadcast ire's.
4210 				 * See detailed comment above.
4211 				 */
4212 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4213 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4214 				    NULL, MATCH_IRE_TYPE, ipst);
4215 			}
4216 
4217 			if (ire == NULL) {
4218 				/*
4219 				 * This is either a multicast packet or
4220 				 * the address has been removed since
4221 				 * the packet was received.
4222 				 * Return INADDR_ANY so that normal source
4223 				 * selection occurs for the response.
4224 				 */
4225 
4226 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4227 			} else {
4228 				pinfo->ip_pkt_match_addr.s_addr =
4229 				    ire->ire_src_addr;
4230 				ire_refrele(ire);
4231 			}
4232 			ipif_refrele(ipif);
4233 		} else {
4234 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4235 		}
4236 	}
4237 
4238 	pether = (struct ether_header *)((char *)ipha
4239 	    - sizeof (struct ether_header));
4240 	/*
4241 	 * Make sure the interface is an ethernet type, since this option
4242 	 * is currently supported only on this type of interface. Also make
4243 	 * sure we are pointing correctly above db_base.
4244 	 */
4245 
4246 	if ((flags & IPF_RECVSLLA) &&
4247 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4248 	    (ill->ill_type == IFT_ETHER) &&
4249 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4250 
4251 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4252 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4253 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4254 	} else {
4255 		/*
4256 		 * Clear the bit. Indicate to upper layer that IP is not
4257 		 * sending this ancillary info.
4258 		 */
4259 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4260 	}
4261 
4262 	mp->b_datap->db_type = M_CTL;
4263 	mp->b_wptr += sizeof (ip_pktinfo_t);
4264 	mp->b_cont = data_mp;
4265 
4266 	return (mp);
4267 }
4268 
4269 /*
4270  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4271  * part of the bind request.
4272  */
4273 
4274 boolean_t
4275 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4276 {
4277 	ipsec_in_t *ii;
4278 
4279 	ASSERT(policy_mp != NULL);
4280 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4281 
4282 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4283 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4284 
4285 	connp->conn_policy = ii->ipsec_in_policy;
4286 	ii->ipsec_in_policy = NULL;
4287 
4288 	if (ii->ipsec_in_action != NULL) {
4289 		if (connp->conn_latch == NULL) {
4290 			connp->conn_latch = iplatch_create();
4291 			if (connp->conn_latch == NULL)
4292 				return (B_FALSE);
4293 		}
4294 		ipsec_latch_inbound(connp->conn_latch, ii);
4295 	}
4296 	return (B_TRUE);
4297 }
4298 
4299 /*
4300  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4301  * and to arrange for power-fanout assist.  The ULP is identified by
4302  * adding a single byte at the end of the original bind message.
4303  * A ULP other than UDP or TCP that wishes to be recognized passes
4304  * down a bind with a zero length address.
4305  *
4306  * The binding works as follows:
4307  * - A zero byte address means just bind to the protocol.
4308  * - A four byte address is treated as a request to validate
4309  *   that the address is a valid local address, appropriate for
4310  *   an application to bind to. This does not affect any fanout
4311  *   information in IP.
4312  * - A sizeof sin_t byte address is used to bind to only the local address
4313  *   and port.
4314  * - A sizeof ipa_conn_t byte address contains complete fanout information
4315  *   consisting of local and remote addresses and ports.  In
4316  *   this case, the addresses are both validated as appropriate
4317  *   for this operation, and, if so, the information is retained
4318  *   for use in the inbound fanout.
4319  *
4320  * The ULP (except in the zero-length bind) can append an
4321  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4322  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4323  * a copy of the source or destination IRE (source for local bind;
4324  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4325  * policy information contained should be copied on to the conn.
4326  *
4327  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4328  */
4329 mblk_t *
4330 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4331 {
4332 	ssize_t		len;
4333 	struct T_bind_req	*tbr;
4334 	sin_t		*sin;
4335 	ipa_conn_t	*ac;
4336 	uchar_t		*ucp;
4337 	mblk_t		*mp1;
4338 	boolean_t	ire_requested;
4339 	boolean_t	ipsec_policy_set = B_FALSE;
4340 	int		error = 0;
4341 	int		protocol;
4342 	ipa_conn_x_t	*acx;
4343 
4344 	ASSERT(!connp->conn_af_isv6);
4345 	connp->conn_pkt_isv6 = B_FALSE;
4346 
4347 	len = MBLKL(mp);
4348 	if (len < (sizeof (*tbr) + 1)) {
4349 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4350 		    "ip_bind: bogus msg, len %ld", len);
4351 		/* XXX: Need to return something better */
4352 		goto bad_addr;
4353 	}
4354 	/* Back up and extract the protocol identifier. */
4355 	mp->b_wptr--;
4356 	protocol = *mp->b_wptr & 0xFF;
4357 	tbr = (struct T_bind_req *)mp->b_rptr;
4358 	/* Reset the message type in preparation for shipping it back. */
4359 	DB_TYPE(mp) = M_PCPROTO;
4360 
4361 	connp->conn_ulp = (uint8_t)protocol;
4362 
4363 	/*
4364 	 * Check for a zero length address.  This is from a protocol that
4365 	 * wants to register to receive all packets of its type.
4366 	 */
4367 	if (tbr->ADDR_length == 0) {
4368 		/*
4369 		 * These protocols are now intercepted in ip_bind_v6().
4370 		 * Reject protocol-level binds here for now.
4371 		 *
4372 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4373 		 * so that the protocol type cannot be SCTP.
4374 		 */
4375 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4376 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4377 			goto bad_addr;
4378 		}
4379 
4380 		/*
4381 		 *
4382 		 * The udp module never sends down a zero-length address,
4383 		 * and allowing this on a labeled system will break MLP
4384 		 * functionality.
4385 		 */
4386 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4387 			goto bad_addr;
4388 
4389 		if (connp->conn_mac_exempt)
4390 			goto bad_addr;
4391 
4392 		/* No hash here really.  The table is big enough. */
4393 		connp->conn_srcv6 = ipv6_all_zeros;
4394 
4395 		ipcl_proto_insert(connp, protocol);
4396 
4397 		tbr->PRIM_type = T_BIND_ACK;
4398 		return (mp);
4399 	}
4400 
4401 	/* Extract the address pointer from the message. */
4402 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4403 	    tbr->ADDR_length);
4404 	if (ucp == NULL) {
4405 		ip1dbg(("ip_bind: no address\n"));
4406 		goto bad_addr;
4407 	}
4408 	if (!OK_32PTR(ucp)) {
4409 		ip1dbg(("ip_bind: unaligned address\n"));
4410 		goto bad_addr;
4411 	}
4412 	/*
4413 	 * Check for trailing mps.
4414 	 */
4415 
4416 	mp1 = mp->b_cont;
4417 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4418 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4419 
4420 	switch (tbr->ADDR_length) {
4421 	default:
4422 		ip1dbg(("ip_bind: bad address length %d\n",
4423 		    (int)tbr->ADDR_length));
4424 		goto bad_addr;
4425 
4426 	case IP_ADDR_LEN:
4427 		/* Verification of local address only */
4428 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4429 		    ire_requested, ipsec_policy_set, B_FALSE);
4430 		break;
4431 
4432 	case sizeof (sin_t):
4433 		sin = (sin_t *)ucp;
4434 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4435 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4436 		break;
4437 
4438 	case sizeof (ipa_conn_t):
4439 		ac = (ipa_conn_t *)ucp;
4440 		/* For raw socket, the local port is not set. */
4441 		if (ac->ac_lport == 0)
4442 			ac->ac_lport = connp->conn_lport;
4443 		/* Always verify destination reachability. */
4444 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4445 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4446 		    ipsec_policy_set, B_TRUE, B_TRUE);
4447 		break;
4448 
4449 	case sizeof (ipa_conn_x_t):
4450 		acx = (ipa_conn_x_t *)ucp;
4451 		/*
4452 		 * Whether or not to verify destination reachability depends
4453 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4454 		 */
4455 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4456 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4457 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4458 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4459 		break;
4460 	}
4461 	if (error == EINPROGRESS)
4462 		return (NULL);
4463 	else if (error != 0)
4464 		goto bad_addr;
4465 	/*
4466 	 * Pass the IPSEC headers size in ire_ipsec_overhead.
4467 	 * We can't do this in ip_bind_insert_ire because the policy
4468 	 * may not have been inherited at that point in time and hence
4469 	 * conn_out_enforce_policy may not be set.
4470 	 */
4471 	mp1 = mp->b_cont;
4472 	if (ire_requested && connp->conn_out_enforce_policy &&
4473 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4474 		ire_t *ire = (ire_t *)mp1->b_rptr;
4475 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4476 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4477 	}
4478 
4479 	/* Send it home. */
4480 	mp->b_datap->db_type = M_PCPROTO;
4481 	tbr->PRIM_type = T_BIND_ACK;
4482 	return (mp);
4483 
4484 bad_addr:
4485 	/*
4486 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4487 	 * a unix errno.
4488 	 */
4489 	if (error > 0)
4490 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4491 	else
4492 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4493 	return (mp);
4494 }
4495 
4496 /*
4497  * Here address is verified to be a valid local address.
4498  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4499  * address is also considered a valid local address.
4500  * In the case of a broadcast/multicast address, however, the
4501  * upper protocol is expected to reset the src address
4502  * to 0 if it sees a IRE_BROADCAST type returned so that
4503  * no packets are emitted with broadcast/multicast address as
4504  * source address (that violates hosts requirements RFC1122)
4505  * The addresses valid for bind are:
4506  *	(1) - INADDR_ANY (0)
4507  *	(2) - IP address of an UP interface
4508  *	(3) - IP address of a DOWN interface
4509  *	(4) - valid local IP broadcast addresses. In this case
4510  *	the conn will only receive packets destined to
4511  *	the specified broadcast address.
4512  *	(5) - a multicast address. In this case
4513  *	the conn will only receive packets destined to
4514  *	the specified multicast address. Note: the
4515  *	application still has to issue an
4516  *	IP_ADD_MEMBERSHIP socket option.
4517  *
4518  * On error, return -1 for TBADADDR otherwise pass the
4519  * errno with TSYSERR reply.
4520  *
4521  * In all the above cases, the bound address must be valid in the current zone.
4522  * When the address is loopback, multicast or broadcast, there might be many
4523  * matching IREs so bind has to look up based on the zone.
4524  *
4525  * Note: lport is in network byte order.
4526  */
4527 int
4528 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4529     boolean_t ire_requested, boolean_t ipsec_policy_set,
4530     boolean_t fanout_insert)
4531 {
4532 	int		error = 0;
4533 	ire_t		*src_ire;
4534 	mblk_t		*policy_mp;
4535 	ipif_t		*ipif;
4536 	zoneid_t	zoneid;
4537 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4538 
4539 	if (ipsec_policy_set) {
4540 		policy_mp = mp->b_cont;
4541 	}
4542 
4543 	/*
4544 	 * If it was previously connected, conn_fully_bound would have
4545 	 * been set.
4546 	 */
4547 	connp->conn_fully_bound = B_FALSE;
4548 
4549 	src_ire = NULL;
4550 	ipif = NULL;
4551 
4552 	zoneid = IPCL_ZONEID(connp);
4553 
4554 	if (src_addr) {
4555 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4556 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4557 		/*
4558 		 * If an address other than 0.0.0.0 is requested,
4559 		 * we verify that it is a valid address for bind
4560 		 * Note: Following code is in if-else-if form for
4561 		 * readability compared to a condition check.
4562 		 */
4563 		/* LINTED - statement has no consequent */
4564 		if (IRE_IS_LOCAL(src_ire)) {
4565 			/*
4566 			 * (2) Bind to address of local UP interface
4567 			 */
4568 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4569 			/*
4570 			 * (4) Bind to broadcast address
4571 			 * Note: permitted only from transports that
4572 			 * request IRE
4573 			 */
4574 			if (!ire_requested)
4575 				error = EADDRNOTAVAIL;
4576 		} else {
4577 			/*
4578 			 * (3) Bind to address of local DOWN interface
4579 			 * (ipif_lookup_addr() looks up all interfaces
4580 			 * but we do not get here for UP interfaces
4581 			 * - case (2) above)
4582 			 * We put the protocol byte back into the mblk
4583 			 * since we may come back via ip_wput_nondata()
4584 			 * later with this mblk if ipif_lookup_addr chooses
4585 			 * to defer processing.
4586 			 */
4587 			*mp->b_wptr++ = (char)connp->conn_ulp;
4588 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4589 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4590 			    &error, ipst)) != NULL) {
4591 				ipif_refrele(ipif);
4592 			} else if (error == EINPROGRESS) {
4593 				if (src_ire != NULL)
4594 					ire_refrele(src_ire);
4595 				return (EINPROGRESS);
4596 			} else if (CLASSD(src_addr)) {
4597 				error = 0;
4598 				if (src_ire != NULL)
4599 					ire_refrele(src_ire);
4600 				/*
4601 				 * (5) bind to multicast address.
4602 				 * Fake out the IRE returned to upper
4603 				 * layer to be a broadcast IRE.
4604 				 */
4605 				src_ire = ire_ctable_lookup(
4606 				    INADDR_BROADCAST, INADDR_ANY,
4607 				    IRE_BROADCAST, NULL, zoneid, NULL,
4608 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4609 				    ipst);
4610 				if (src_ire == NULL || !ire_requested)
4611 					error = EADDRNOTAVAIL;
4612 			} else {
4613 				/*
4614 				 * Not a valid address for bind
4615 				 */
4616 				error = EADDRNOTAVAIL;
4617 			}
4618 			/*
4619 			 * Just to keep it consistent with the processing in
4620 			 * ip_bind_v4()
4621 			 */
4622 			mp->b_wptr--;
4623 		}
4624 		if (error) {
4625 			/* Red Alert!  Attempting to be a bogon! */
4626 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4627 			    ntohl(src_addr)));
4628 			goto bad_addr;
4629 		}
4630 	}
4631 
4632 	/*
4633 	 * Allow setting new policies. For example, disconnects come
4634 	 * down as ipa_t bind. As we would have set conn_policy_cached
4635 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4636 	 * can change after the disconnect.
4637 	 */
4638 	connp->conn_policy_cached = B_FALSE;
4639 
4640 	/*
4641 	 * If not fanout_insert this was just an address verification
4642 	 */
4643 	if (fanout_insert) {
4644 		/*
4645 		 * The addresses have been verified. Time to insert in
4646 		 * the correct fanout list.
4647 		 */
4648 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4649 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4650 		connp->conn_lport = lport;
4651 		connp->conn_fport = 0;
4652 		/*
4653 		 * Do we need to add a check to reject Multicast packets
4654 		 *
4655 		 * We need to make sure that the conn_recv is set to a non-null
4656 		 * value before we insert the conn into the classifier table.
4657 		 * This is to avoid a race with an incoming packet which does an
4658 		 * ipcl_classify().
4659 		 */
4660 		if (*mp->b_wptr == IPPROTO_TCP)
4661 			connp->conn_recv = tcp_conn_request;
4662 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4663 	}
4664 
4665 	if (error == 0) {
4666 		if (ire_requested) {
4667 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4668 				error = -1;
4669 				/* Falls through to bad_addr */
4670 			}
4671 		} else if (ipsec_policy_set) {
4672 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4673 				error = -1;
4674 				/* Falls through to bad_addr */
4675 			}
4676 		}
4677 	} else if (connp->conn_ulp == IPPROTO_TCP) {
4678 		connp->conn_recv = tcp_input;
4679 	}
4680 bad_addr:
4681 	if (error != 0) {
4682 		if (connp->conn_anon_port) {
4683 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4684 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4685 			    B_FALSE);
4686 		}
4687 		connp->conn_mlp_type = mlptSingle;
4688 	}
4689 	if (src_ire != NULL)
4690 		IRE_REFRELE(src_ire);
4691 	if (ipsec_policy_set) {
4692 		ASSERT(policy_mp == mp->b_cont);
4693 		ASSERT(policy_mp != NULL);
4694 		freeb(policy_mp);
4695 		/*
4696 		 * As of now assume that nothing else accompanies
4697 		 * IPSEC_POLICY_SET.
4698 		 */
4699 		mp->b_cont = NULL;
4700 	}
4701 	return (error);
4702 }
4703 
4704 /*
4705  * Verify that both the source and destination addresses
4706  * are valid.  If verify_dst is false, then the destination address may be
4707  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4708  * destination reachability, while tunnels do not.
4709  * Note that we allow connect to broadcast and multicast
4710  * addresses when ire_requested is set. Thus the ULP
4711  * has to check for IRE_BROADCAST and multicast.
4712  *
4713  * Returns zero if ok.
4714  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4715  * (for use with TSYSERR reply).
4716  *
4717  * Note: lport and fport are in network byte order.
4718  */
4719 int
4720 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4721     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4722     boolean_t ire_requested, boolean_t ipsec_policy_set,
4723     boolean_t fanout_insert, boolean_t verify_dst)
4724 {
4725 	ire_t		*src_ire;
4726 	ire_t		*dst_ire;
4727 	int		error = 0;
4728 	int 		protocol;
4729 	mblk_t		*policy_mp;
4730 	ire_t		*sire = NULL;
4731 	ire_t		*md_dst_ire = NULL;
4732 	ire_t		*lso_dst_ire = NULL;
4733 	ill_t		*ill = NULL;
4734 	zoneid_t	zoneid;
4735 	ipaddr_t	src_addr = *src_addrp;
4736 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4737 
4738 	src_ire = dst_ire = NULL;
4739 	protocol = *mp->b_wptr & 0xFF;
4740 
4741 	/*
4742 	 * If we never got a disconnect before, clear it now.
4743 	 */
4744 	connp->conn_fully_bound = B_FALSE;
4745 
4746 	if (ipsec_policy_set) {
4747 		policy_mp = mp->b_cont;
4748 	}
4749 
4750 	zoneid = IPCL_ZONEID(connp);
4751 
4752 	if (CLASSD(dst_addr)) {
4753 		/* Pick up an IRE_BROADCAST */
4754 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4755 		    NULL, zoneid, MBLK_GETLABEL(mp),
4756 		    (MATCH_IRE_RECURSIVE |
4757 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4758 		    MATCH_IRE_SECATTR), ipst);
4759 	} else {
4760 		/*
4761 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4762 		 * and onlink ipif is not found set ENETUNREACH error.
4763 		 */
4764 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4765 			ipif_t *ipif;
4766 
4767 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4768 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4769 			if (ipif == NULL) {
4770 				error = ENETUNREACH;
4771 				goto bad_addr;
4772 			}
4773 			ipif_refrele(ipif);
4774 		}
4775 
4776 		if (connp->conn_nexthop_set) {
4777 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4778 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4779 			    MATCH_IRE_SECATTR, ipst);
4780 		} else {
4781 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4782 			    &sire, zoneid, MBLK_GETLABEL(mp),
4783 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4784 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4785 			    MATCH_IRE_SECATTR), ipst);
4786 		}
4787 	}
4788 	/*
4789 	 * dst_ire can't be a broadcast when not ire_requested.
4790 	 * We also prevent ire's with src address INADDR_ANY to
4791 	 * be used, which are created temporarily for
4792 	 * sending out packets from endpoints that have
4793 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4794 	 * reachable.  If verify_dst is false, the destination needn't be
4795 	 * reachable.
4796 	 *
4797 	 * If we match on a reject or black hole, then we've got a
4798 	 * local failure.  May as well fail out the connect() attempt,
4799 	 * since it's never going to succeed.
4800 	 */
4801 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4802 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4803 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4804 		/*
4805 		 * If we're verifying destination reachability, we always want
4806 		 * to complain here.
4807 		 *
4808 		 * If we're not verifying destination reachability but the
4809 		 * destination has a route, we still want to fail on the
4810 		 * temporary address and broadcast address tests.
4811 		 */
4812 		if (verify_dst || (dst_ire != NULL)) {
4813 			if (ip_debug > 2) {
4814 				pr_addr_dbg("ip_bind_connected: bad connected "
4815 				    "dst %s\n", AF_INET, &dst_addr);
4816 			}
4817 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4818 				error = ENETUNREACH;
4819 			else
4820 				error = EHOSTUNREACH;
4821 			goto bad_addr;
4822 		}
4823 	}
4824 
4825 	/*
4826 	 * We now know that routing will allow us to reach the destination.
4827 	 * Check whether Trusted Solaris policy allows communication with this
4828 	 * host, and pretend that the destination is unreachable if not.
4829 	 *
4830 	 * This is never a problem for TCP, since that transport is known to
4831 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4832 	 * handling.  If the remote is unreachable, it will be detected at that
4833 	 * point, so there's no reason to check it here.
4834 	 *
4835 	 * Note that for sendto (and other datagram-oriented friends), this
4836 	 * check is done as part of the data path label computation instead.
4837 	 * The check here is just to make non-TCP connect() report the right
4838 	 * error.
4839 	 */
4840 	if (dst_ire != NULL && is_system_labeled() &&
4841 	    !IPCL_IS_TCP(connp) &&
4842 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4843 	    connp->conn_mac_exempt, ipst) != 0) {
4844 		error = EHOSTUNREACH;
4845 		if (ip_debug > 2) {
4846 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4847 			    AF_INET, &dst_addr);
4848 		}
4849 		goto bad_addr;
4850 	}
4851 
4852 	/*
4853 	 * If the app does a connect(), it means that it will most likely
4854 	 * send more than 1 packet to the destination.  It makes sense
4855 	 * to clear the temporary flag.
4856 	 */
4857 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4858 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4859 		irb_t *irb = dst_ire->ire_bucket;
4860 
4861 		rw_enter(&irb->irb_lock, RW_WRITER);
4862 		dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4863 		irb->irb_tmp_ire_cnt--;
4864 		rw_exit(&irb->irb_lock);
4865 	}
4866 
4867 	/*
4868 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4869 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4870 	 * eligibility tests for passive connects are handled separately
4871 	 * through tcp_adapt_ire().  We do this before the source address
4872 	 * selection, because dst_ire may change after a call to
4873 	 * ipif_select_source().  This is a best-effort check, as the
4874 	 * packet for this connection may not actually go through
4875 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4876 	 * calling ip_newroute().  This is why we further check on the
4877 	 * IRE during LSO/Multidata packet transmission in
4878 	 * tcp_lsosend()/tcp_multisend().
4879 	 */
4880 	if (!ipsec_policy_set && dst_ire != NULL &&
4881 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4882 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4883 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4884 			lso_dst_ire = dst_ire;
4885 			IRE_REFHOLD(lso_dst_ire);
4886 		} else if (ipst->ips_ip_multidata_outbound &&
4887 		    ILL_MDT_CAPABLE(ill)) {
4888 			md_dst_ire = dst_ire;
4889 			IRE_REFHOLD(md_dst_ire);
4890 		}
4891 	}
4892 
4893 	if (dst_ire != NULL &&
4894 	    dst_ire->ire_type == IRE_LOCAL &&
4895 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4896 		/*
4897 		 * If the IRE belongs to a different zone, look for a matching
4898 		 * route in the forwarding table and use the source address from
4899 		 * that route.
4900 		 */
4901 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4902 		    zoneid, 0, NULL,
4903 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4904 		    MATCH_IRE_RJ_BHOLE, ipst);
4905 		if (src_ire == NULL) {
4906 			error = EHOSTUNREACH;
4907 			goto bad_addr;
4908 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4909 			if (!(src_ire->ire_type & IRE_HOST))
4910 				error = ENETUNREACH;
4911 			else
4912 				error = EHOSTUNREACH;
4913 			goto bad_addr;
4914 		}
4915 		if (src_addr == INADDR_ANY)
4916 			src_addr = src_ire->ire_src_addr;
4917 		ire_refrele(src_ire);
4918 		src_ire = NULL;
4919 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4920 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4921 			src_addr = sire->ire_src_addr;
4922 			ire_refrele(dst_ire);
4923 			dst_ire = sire;
4924 			sire = NULL;
4925 		} else {
4926 			/*
4927 			 * Pick a source address so that a proper inbound
4928 			 * load spreading would happen.
4929 			 */
4930 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4931 			ipif_t *src_ipif = NULL;
4932 			ire_t *ipif_ire;
4933 
4934 			/*
4935 			 * Supply a local source address such that inbound
4936 			 * load spreading happens.
4937 			 *
4938 			 * Determine the best source address on this ill for
4939 			 * the destination.
4940 			 *
4941 			 * 1) For broadcast, we should return a broadcast ire
4942 			 *    found above so that upper layers know that the
4943 			 *    destination address is a broadcast address.
4944 			 *
4945 			 * 2) If this is part of a group, select a better
4946 			 *    source address so that better inbound load
4947 			 *    balancing happens. Do the same if the ipif
4948 			 *    is DEPRECATED.
4949 			 *
4950 			 * 3) If the outgoing interface is part of a usesrc
4951 			 *    group, then try selecting a source address from
4952 			 *    the usesrc ILL.
4953 			 */
4954 			if ((dst_ire->ire_zoneid != zoneid &&
4955 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4956 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4957 			    ((dst_ill->ill_group != NULL) ||
4958 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4959 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4960 				/*
4961 				 * If the destination is reachable via a
4962 				 * given gateway, the selected source address
4963 				 * should be in the same subnet as the gateway.
4964 				 * Otherwise, the destination is not reachable.
4965 				 *
4966 				 * If there are no interfaces on the same subnet
4967 				 * as the destination, ipif_select_source gives
4968 				 * first non-deprecated interface which might be
4969 				 * on a different subnet than the gateway.
4970 				 * This is not desirable. Hence pass the dst_ire
4971 				 * source address to ipif_select_source.
4972 				 * It is sure that the destination is reachable
4973 				 * with the dst_ire source address subnet.
4974 				 * So passing dst_ire source address to
4975 				 * ipif_select_source will make sure that the
4976 				 * selected source will be on the same subnet
4977 				 * as dst_ire source address.
4978 				 */
4979 				ipaddr_t saddr =
4980 				    dst_ire->ire_ipif->ipif_src_addr;
4981 				src_ipif = ipif_select_source(dst_ill,
4982 				    saddr, zoneid);
4983 				if (src_ipif != NULL) {
4984 					if (IS_VNI(src_ipif->ipif_ill)) {
4985 						/*
4986 						 * For VNI there is no
4987 						 * interface route
4988 						 */
4989 						src_addr =
4990 						    src_ipif->ipif_src_addr;
4991 					} else {
4992 						ipif_ire =
4993 						    ipif_to_ire(src_ipif);
4994 						if (ipif_ire != NULL) {
4995 							IRE_REFRELE(dst_ire);
4996 							dst_ire = ipif_ire;
4997 						}
4998 						src_addr =
4999 						    dst_ire->ire_src_addr;
5000 					}
5001 					ipif_refrele(src_ipif);
5002 				} else {
5003 					src_addr = dst_ire->ire_src_addr;
5004 				}
5005 			} else {
5006 				src_addr = dst_ire->ire_src_addr;
5007 			}
5008 		}
5009 	}
5010 
5011 	/*
5012 	 * We do ire_route_lookup() here (and not
5013 	 * interface lookup as we assert that
5014 	 * src_addr should only come from an
5015 	 * UP interface for hard binding.
5016 	 */
5017 	ASSERT(src_ire == NULL);
5018 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5019 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5020 	/* src_ire must be a local|loopback */
5021 	if (!IRE_IS_LOCAL(src_ire)) {
5022 		if (ip_debug > 2) {
5023 			pr_addr_dbg("ip_bind_connected: bad connected "
5024 			    "src %s\n", AF_INET, &src_addr);
5025 		}
5026 		error = EADDRNOTAVAIL;
5027 		goto bad_addr;
5028 	}
5029 
5030 	/*
5031 	 * If the source address is a loopback address, the
5032 	 * destination had best be local or multicast.
5033 	 * The transports that can't handle multicast will reject
5034 	 * those addresses.
5035 	 */
5036 	if (src_ire->ire_type == IRE_LOOPBACK &&
5037 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5038 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5039 		error = -1;
5040 		goto bad_addr;
5041 	}
5042 
5043 	/*
5044 	 * Allow setting new policies. For example, disconnects come
5045 	 * down as ipa_t bind. As we would have set conn_policy_cached
5046 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5047 	 * can change after the disconnect.
5048 	 */
5049 	connp->conn_policy_cached = B_FALSE;
5050 
5051 	/*
5052 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5053 	 * can handle their passed-in conn's.
5054 	 */
5055 
5056 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5057 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5058 	connp->conn_lport = lport;
5059 	connp->conn_fport = fport;
5060 	*src_addrp = src_addr;
5061 
5062 	ASSERT(!(ipsec_policy_set && ire_requested));
5063 	if (ire_requested) {
5064 		iulp_t *ulp_info = NULL;
5065 
5066 		/*
5067 		 * Note that sire will not be NULL if this is an off-link
5068 		 * connection and there is not cache for that dest yet.
5069 		 *
5070 		 * XXX Because of an existing bug, if there are multiple
5071 		 * default routes, the IRE returned now may not be the actual
5072 		 * default route used (default routes are chosen in a
5073 		 * round robin fashion).  So if the metrics for different
5074 		 * default routes are different, we may return the wrong
5075 		 * metrics.  This will not be a problem if the existing
5076 		 * bug is fixed.
5077 		 */
5078 		if (sire != NULL) {
5079 			ulp_info = &(sire->ire_uinfo);
5080 		}
5081 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5082 			error = -1;
5083 			goto bad_addr;
5084 		}
5085 	} else if (ipsec_policy_set) {
5086 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5087 			error = -1;
5088 			goto bad_addr;
5089 		}
5090 	}
5091 
5092 	/*
5093 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5094 	 * we'll cache that.  If we don't, we'll inherit global policy.
5095 	 *
5096 	 * We can't insert until the conn reflects the policy. Note that
5097 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5098 	 * connections where we don't have a policy. This is to prevent
5099 	 * global policy lookups in the inbound path.
5100 	 *
5101 	 * If we insert before we set conn_policy_cached,
5102 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5103 	 * because global policy cound be non-empty. We normally call
5104 	 * ipsec_check_policy() for conn_policy_cached connections only if
5105 	 * ipc_in_enforce_policy is set. But in this case,
5106 	 * conn_policy_cached can get set anytime since we made the
5107 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5108 	 * called, which will make the above assumption false.  Thus, we
5109 	 * need to insert after we set conn_policy_cached.
5110 	 */
5111 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5112 		goto bad_addr;
5113 
5114 	if (fanout_insert) {
5115 		/*
5116 		 * The addresses have been verified. Time to insert in
5117 		 * the correct fanout list.
5118 		 * We need to make sure that the conn_recv is set to a non-null
5119 		 * value before we insert into the classifier table to avoid a
5120 		 * race with an incoming packet which does an ipcl_classify().
5121 		 */
5122 		if (protocol == IPPROTO_TCP)
5123 			connp->conn_recv = tcp_input;
5124 		error = ipcl_conn_insert(connp, protocol, src_addr,
5125 		    dst_addr, connp->conn_ports);
5126 	}
5127 
5128 	if (error == 0) {
5129 		connp->conn_fully_bound = B_TRUE;
5130 		/*
5131 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5132 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5133 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5134 		 * ip_xxinfo_return(), which performs further checks
5135 		 * against them and upon success, returns the LSO/MDT info
5136 		 * mblk which we will attach to the bind acknowledgment.
5137 		 */
5138 		if (lso_dst_ire != NULL) {
5139 			mblk_t *lsoinfo_mp;
5140 
5141 			ASSERT(ill->ill_lso_capab != NULL);
5142 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5143 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5144 				linkb(mp, lsoinfo_mp);
5145 		} else if (md_dst_ire != NULL) {
5146 			mblk_t *mdinfo_mp;
5147 
5148 			ASSERT(ill->ill_mdt_capab != NULL);
5149 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5150 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5151 				linkb(mp, mdinfo_mp);
5152 		}
5153 	}
5154 bad_addr:
5155 	if (ipsec_policy_set) {
5156 		ASSERT(policy_mp == mp->b_cont);
5157 		ASSERT(policy_mp != NULL);
5158 		freeb(policy_mp);
5159 		/*
5160 		 * As of now assume that nothing else accompanies
5161 		 * IPSEC_POLICY_SET.
5162 		 */
5163 		mp->b_cont = NULL;
5164 	}
5165 	if (src_ire != NULL)
5166 		IRE_REFRELE(src_ire);
5167 	if (dst_ire != NULL)
5168 		IRE_REFRELE(dst_ire);
5169 	if (sire != NULL)
5170 		IRE_REFRELE(sire);
5171 	if (md_dst_ire != NULL)
5172 		IRE_REFRELE(md_dst_ire);
5173 	if (lso_dst_ire != NULL)
5174 		IRE_REFRELE(lso_dst_ire);
5175 	return (error);
5176 }
5177 
5178 /*
5179  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5180  * Prefers dst_ire over src_ire.
5181  */
5182 static boolean_t
5183 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5184 {
5185 	mblk_t	*mp1;
5186 	ire_t *ret_ire = NULL;
5187 
5188 	mp1 = mp->b_cont;
5189 	ASSERT(mp1 != NULL);
5190 
5191 	if (ire != NULL) {
5192 		/*
5193 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5194 		 * appended mblk. Its <upper protocol>'s
5195 		 * job to make sure there is room.
5196 		 */
5197 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5198 			return (0);
5199 
5200 		mp1->b_datap->db_type = IRE_DB_TYPE;
5201 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5202 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5203 		ret_ire = (ire_t *)mp1->b_rptr;
5204 		/*
5205 		 * Pass the latest setting of the ip_path_mtu_discovery and
5206 		 * copy the ulp info if any.
5207 		 */
5208 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5209 		    IPH_DF : 0;
5210 		if (ulp_info != NULL) {
5211 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5212 			    sizeof (iulp_t));
5213 		}
5214 		ret_ire->ire_mp = mp1;
5215 	} else {
5216 		/*
5217 		 * No IRE was found. Remove IRE mblk.
5218 		 */
5219 		mp->b_cont = mp1->b_cont;
5220 		freeb(mp1);
5221 	}
5222 
5223 	return (1);
5224 }
5225 
5226 /*
5227  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5228  * the final piece where we don't.  Return a pointer to the first mblk in the
5229  * result, and update the pointer to the next mblk to chew on.  If anything
5230  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5231  * NULL pointer.
5232  */
5233 mblk_t *
5234 ip_carve_mp(mblk_t **mpp, ssize_t len)
5235 {
5236 	mblk_t	*mp0;
5237 	mblk_t	*mp1;
5238 	mblk_t	*mp2;
5239 
5240 	if (!len || !mpp || !(mp0 = *mpp))
5241 		return (NULL);
5242 	/* If we aren't going to consume the first mblk, we need a dup. */
5243 	if (mp0->b_wptr - mp0->b_rptr > len) {
5244 		mp1 = dupb(mp0);
5245 		if (mp1) {
5246 			/* Partition the data between the two mblks. */
5247 			mp1->b_wptr = mp1->b_rptr + len;
5248 			mp0->b_rptr = mp1->b_wptr;
5249 			/*
5250 			 * after adjustments if mblk not consumed is now
5251 			 * unaligned, try to align it. If this fails free
5252 			 * all messages and let upper layer recover.
5253 			 */
5254 			if (!OK_32PTR(mp0->b_rptr)) {
5255 				if (!pullupmsg(mp0, -1)) {
5256 					freemsg(mp0);
5257 					freemsg(mp1);
5258 					*mpp = NULL;
5259 					return (NULL);
5260 				}
5261 			}
5262 		}
5263 		return (mp1);
5264 	}
5265 	/* Eat through as many mblks as we need to get len bytes. */
5266 	len -= mp0->b_wptr - mp0->b_rptr;
5267 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5268 		if (mp2->b_wptr - mp2->b_rptr > len) {
5269 			/*
5270 			 * We won't consume the entire last mblk.  Like
5271 			 * above, dup and partition it.
5272 			 */
5273 			mp1->b_cont = dupb(mp2);
5274 			mp1 = mp1->b_cont;
5275 			if (!mp1) {
5276 				/*
5277 				 * Trouble.  Rather than go to a lot of
5278 				 * trouble to clean up, we free the messages.
5279 				 * This won't be any worse than losing it on
5280 				 * the wire.
5281 				 */
5282 				freemsg(mp0);
5283 				freemsg(mp2);
5284 				*mpp = NULL;
5285 				return (NULL);
5286 			}
5287 			mp1->b_wptr = mp1->b_rptr + len;
5288 			mp2->b_rptr = mp1->b_wptr;
5289 			/*
5290 			 * after adjustments if mblk not consumed is now
5291 			 * unaligned, try to align it. If this fails free
5292 			 * all messages and let upper layer recover.
5293 			 */
5294 			if (!OK_32PTR(mp2->b_rptr)) {
5295 				if (!pullupmsg(mp2, -1)) {
5296 					freemsg(mp0);
5297 					freemsg(mp2);
5298 					*mpp = NULL;
5299 					return (NULL);
5300 				}
5301 			}
5302 			*mpp = mp2;
5303 			return (mp0);
5304 		}
5305 		/* Decrement len by the amount we just got. */
5306 		len -= mp2->b_wptr - mp2->b_rptr;
5307 	}
5308 	/*
5309 	 * len should be reduced to zero now.  If not our caller has
5310 	 * screwed up.
5311 	 */
5312 	if (len) {
5313 		/* Shouldn't happen! */
5314 		freemsg(mp0);
5315 		*mpp = NULL;
5316 		return (NULL);
5317 	}
5318 	/*
5319 	 * We consumed up to exactly the end of an mblk.  Detach the part
5320 	 * we are returning from the rest of the chain.
5321 	 */
5322 	mp1->b_cont = NULL;
5323 	*mpp = mp2;
5324 	return (mp0);
5325 }
5326 
5327 /* The ill stream is being unplumbed. Called from ip_close */
5328 int
5329 ip_modclose(ill_t *ill)
5330 {
5331 	boolean_t success;
5332 	ipsq_t	*ipsq;
5333 	ipif_t	*ipif;
5334 	queue_t	*q = ill->ill_rq;
5335 	ip_stack_t	*ipst = ill->ill_ipst;
5336 	clock_t timeout;
5337 
5338 	/*
5339 	 * Wait for the ACKs of all deferred control messages to be processed.
5340 	 * In particular, we wait for a potential capability reset initiated
5341 	 * in ip_sioctl_plink() to complete before proceeding.
5342 	 *
5343 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5344 	 * in case the driver never replies.
5345 	 */
5346 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5347 	mutex_enter(&ill->ill_lock);
5348 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5349 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5350 			/* Timeout */
5351 			break;
5352 		}
5353 	}
5354 	mutex_exit(&ill->ill_lock);
5355 
5356 	/*
5357 	 * Forcibly enter the ipsq after some delay. This is to take
5358 	 * care of the case when some ioctl does not complete because
5359 	 * we sent a control message to the driver and it did not
5360 	 * send us a reply. We want to be able to at least unplumb
5361 	 * and replumb rather than force the user to reboot the system.
5362 	 */
5363 	success = ipsq_enter(ill, B_FALSE);
5364 
5365 	/*
5366 	 * Open/close/push/pop is guaranteed to be single threaded
5367 	 * per stream by STREAMS. FS guarantees that all references
5368 	 * from top are gone before close is called. So there can't
5369 	 * be another close thread that has set CONDEMNED on this ill.
5370 	 * and cause ipsq_enter to return failure.
5371 	 */
5372 	ASSERT(success);
5373 	ipsq = ill->ill_phyint->phyint_ipsq;
5374 
5375 	/*
5376 	 * Mark it condemned. No new reference will be made to this ill.
5377 	 * Lookup functions will return an error. Threads that try to
5378 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5379 	 * that the refcnt will drop down to zero.
5380 	 */
5381 	mutex_enter(&ill->ill_lock);
5382 	ill->ill_state_flags |= ILL_CONDEMNED;
5383 	for (ipif = ill->ill_ipif; ipif != NULL;
5384 	    ipif = ipif->ipif_next) {
5385 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5386 	}
5387 	/*
5388 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5389 	 * returns  error if ILL_CONDEMNED is set
5390 	 */
5391 	cv_broadcast(&ill->ill_cv);
5392 	mutex_exit(&ill->ill_lock);
5393 
5394 	/*
5395 	 * Send all the deferred DLPI messages downstream which came in
5396 	 * during the small window right before ipsq_enter(). We do this
5397 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5398 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5399 	 */
5400 	ill_dlpi_send_deferred(ill);
5401 
5402 	/*
5403 	 * Shut down fragmentation reassembly.
5404 	 * ill_frag_timer won't start a timer again.
5405 	 * Now cancel any existing timer
5406 	 */
5407 	(void) untimeout(ill->ill_frag_timer_id);
5408 	(void) ill_frag_timeout(ill, 0);
5409 
5410 	/*
5411 	 * If MOVE was in progress, clear the
5412 	 * move_in_progress fields also.
5413 	 */
5414 	if (ill->ill_move_in_progress) {
5415 		ILL_CLEAR_MOVE(ill);
5416 	}
5417 
5418 	/*
5419 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5420 	 * this ill. Then wait for the refcnts to drop to zero.
5421 	 * ill_is_quiescent checks whether the ill is really quiescent.
5422 	 * Then make sure that threads that are waiting to enter the
5423 	 * ipsq have seen the error returned by ipsq_enter and have
5424 	 * gone away. Then we call ill_delete_tail which does the
5425 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5426 	 */
5427 	ill_delete(ill);
5428 	mutex_enter(&ill->ill_lock);
5429 	while (!ill_is_quiescent(ill))
5430 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5431 	while (ill->ill_waiters)
5432 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5433 
5434 	mutex_exit(&ill->ill_lock);
5435 
5436 	/*
5437 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5438 	 * it held until the end of the function since the cleanup
5439 	 * below needs to be able to use the ip_stack_t.
5440 	 */
5441 	netstack_hold(ipst->ips_netstack);
5442 
5443 	/* qprocsoff is called in ill_delete_tail */
5444 	ill_delete_tail(ill);
5445 	ASSERT(ill->ill_ipst == NULL);
5446 
5447 	/*
5448 	 * Walk through all upper (conn) streams and qenable
5449 	 * those that have queued data.
5450 	 * close synchronization needs this to
5451 	 * be done to ensure that all upper layers blocked
5452 	 * due to flow control to the closing device
5453 	 * get unblocked.
5454 	 */
5455 	ip1dbg(("ip_wsrv: walking\n"));
5456 	conn_walk_drain(ipst);
5457 
5458 	mutex_enter(&ipst->ips_ip_mi_lock);
5459 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5460 	mutex_exit(&ipst->ips_ip_mi_lock);
5461 
5462 	/*
5463 	 * credp could be null if the open didn't succeed and ip_modopen
5464 	 * itself calls ip_close.
5465 	 */
5466 	if (ill->ill_credp != NULL)
5467 		crfree(ill->ill_credp);
5468 
5469 	mutex_enter(&ill->ill_lock);
5470 	ill_nic_info_dispatch(ill);
5471 	mutex_exit(&ill->ill_lock);
5472 
5473 	/*
5474 	 * Now we are done with the module close pieces that
5475 	 * need the netstack_t.
5476 	 */
5477 	netstack_rele(ipst->ips_netstack);
5478 
5479 	mi_close_free((IDP)ill);
5480 	q->q_ptr = WR(q)->q_ptr = NULL;
5481 
5482 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5483 
5484 	return (0);
5485 }
5486 
5487 /*
5488  * This is called as part of close() for both IP and UDP
5489  * in order to quiesce the conn.
5490  */
5491 void
5492 ip_quiesce_conn(conn_t *connp)
5493 {
5494 	boolean_t	drain_cleanup_reqd = B_FALSE;
5495 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5496 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5497 	ip_stack_t	*ipst;
5498 
5499 	ASSERT(!IPCL_IS_TCP(connp));
5500 	ipst = connp->conn_netstack->netstack_ip;
5501 
5502 	/*
5503 	 * Mark the conn as closing, and this conn must not be
5504 	 * inserted in future into any list. Eg. conn_drain_insert(),
5505 	 * won't insert this conn into the conn_drain_list.
5506 	 * Similarly ill_pending_mp_add() will not add any mp to
5507 	 * the pending mp list, after this conn has started closing.
5508 	 *
5509 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5510 	 * cannot get set henceforth.
5511 	 */
5512 	mutex_enter(&connp->conn_lock);
5513 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5514 	connp->conn_state_flags |= CONN_CLOSING;
5515 	if (connp->conn_idl != NULL)
5516 		drain_cleanup_reqd = B_TRUE;
5517 	if (connp->conn_oper_pending_ill != NULL)
5518 		conn_ioctl_cleanup_reqd = B_TRUE;
5519 	if (connp->conn_ilg_inuse != 0)
5520 		ilg_cleanup_reqd = B_TRUE;
5521 	mutex_exit(&connp->conn_lock);
5522 
5523 	if (IPCL_IS_UDP(connp))
5524 		udp_quiesce_conn(connp);
5525 
5526 	if (conn_ioctl_cleanup_reqd)
5527 		conn_ioctl_cleanup(connp);
5528 
5529 	if (is_system_labeled() && connp->conn_anon_port) {
5530 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5531 		    connp->conn_mlp_type, connp->conn_ulp,
5532 		    ntohs(connp->conn_lport), B_FALSE);
5533 		connp->conn_anon_port = 0;
5534 	}
5535 	connp->conn_mlp_type = mlptSingle;
5536 
5537 	/*
5538 	 * Remove this conn from any fanout list it is on.
5539 	 * and then wait for any threads currently operating
5540 	 * on this endpoint to finish
5541 	 */
5542 	ipcl_hash_remove(connp);
5543 
5544 	/*
5545 	 * Remove this conn from the drain list, and do
5546 	 * any other cleanup that may be required.
5547 	 * (Only non-tcp streams may have a non-null conn_idl.
5548 	 * TCP streams are never flow controlled, and
5549 	 * conn_idl will be null)
5550 	 */
5551 	if (drain_cleanup_reqd)
5552 		conn_drain_tail(connp, B_TRUE);
5553 
5554 	if (connp->conn_rq == ipst->ips_ip_g_mrouter ||
5555 	    connp->conn_wq == ipst->ips_ip_g_mrouter)
5556 		(void) ip_mrouter_done(NULL, ipst);
5557 
5558 	if (ilg_cleanup_reqd)
5559 		ilg_delete_all(connp);
5560 
5561 	conn_delete_ire(connp, NULL);
5562 
5563 	/*
5564 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5565 	 * callers from write side can't be there now because close
5566 	 * is in progress. The only other caller is ipcl_walk
5567 	 * which checks for the condemned flag.
5568 	 */
5569 	mutex_enter(&connp->conn_lock);
5570 	connp->conn_state_flags |= CONN_CONDEMNED;
5571 	while (connp->conn_ref != 1)
5572 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5573 	connp->conn_state_flags |= CONN_QUIESCED;
5574 	mutex_exit(&connp->conn_lock);
5575 }
5576 
5577 /* ARGSUSED */
5578 int
5579 ip_close(queue_t *q, int flags)
5580 {
5581 	conn_t		*connp;
5582 
5583 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5584 
5585 	/*
5586 	 * Call the appropriate delete routine depending on whether this is
5587 	 * a module or device.
5588 	 */
5589 	if (WR(q)->q_next != NULL) {
5590 		/* This is a module close */
5591 		return (ip_modclose((ill_t *)q->q_ptr));
5592 	}
5593 
5594 	connp = q->q_ptr;
5595 	ip_quiesce_conn(connp);
5596 
5597 	qprocsoff(q);
5598 
5599 	/*
5600 	 * Now we are truly single threaded on this stream, and can
5601 	 * delete the things hanging off the connp, and finally the connp.
5602 	 * We removed this connp from the fanout list, it cannot be
5603 	 * accessed thru the fanouts, and we already waited for the
5604 	 * conn_ref to drop to 0. We are already in close, so
5605 	 * there cannot be any other thread from the top. qprocsoff
5606 	 * has completed, and service has completed or won't run in
5607 	 * future.
5608 	 */
5609 	ASSERT(connp->conn_ref == 1);
5610 
5611 	/*
5612 	 * A conn which was previously marked as IPCL_UDP cannot
5613 	 * retain the flag because it would have been cleared by
5614 	 * udp_close().
5615 	 */
5616 	ASSERT(!IPCL_IS_UDP(connp));
5617 
5618 	if (connp->conn_latch != NULL) {
5619 		IPLATCH_REFRELE(connp->conn_latch, connp->conn_netstack);
5620 		connp->conn_latch = NULL;
5621 	}
5622 	if (connp->conn_policy != NULL) {
5623 		IPPH_REFRELE(connp->conn_policy, connp->conn_netstack);
5624 		connp->conn_policy = NULL;
5625 	}
5626 	if (connp->conn_ipsec_opt_mp != NULL) {
5627 		freemsg(connp->conn_ipsec_opt_mp);
5628 		connp->conn_ipsec_opt_mp = NULL;
5629 	}
5630 
5631 	inet_minor_free(ip_minor_arena, connp->conn_dev);
5632 
5633 	connp->conn_ref--;
5634 	ipcl_conn_destroy(connp);
5635 
5636 	q->q_ptr = WR(q)->q_ptr = NULL;
5637 	return (0);
5638 }
5639 
5640 int
5641 ip_snmpmod_close(queue_t *q)
5642 {
5643 	conn_t *connp = Q_TO_CONN(q);
5644 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5645 
5646 	qprocsoff(q);
5647 
5648 	if (connp->conn_flags & IPCL_UDPMOD)
5649 		udp_close_free(connp);
5650 
5651 	if (connp->conn_cred != NULL) {
5652 		crfree(connp->conn_cred);
5653 		connp->conn_cred = NULL;
5654 	}
5655 	CONN_DEC_REF(connp);
5656 	q->q_ptr = WR(q)->q_ptr = NULL;
5657 	return (0);
5658 }
5659 
5660 /*
5661  * Write side put procedure for TCP module or UDP module instance.  TCP/UDP
5662  * as a module is only used for MIB browsers that push TCP/UDP over IP or ARP.
5663  * The only supported primitives are T_SVR4_OPTMGMT_REQ and T_OPTMGMT_REQ.
5664  * M_FLUSH messages and ioctls are only passed downstream; we don't flush our
5665  * queues as we never enqueue messages there and we don't handle any ioctls.
5666  * Everything else is freed.
5667  */
5668 void
5669 ip_snmpmod_wput(queue_t *q, mblk_t *mp)
5670 {
5671 	conn_t	*connp = q->q_ptr;
5672 	pfi_t	setfn;
5673 	pfi_t	getfn;
5674 
5675 	ASSERT(connp->conn_flags & (IPCL_TCPMOD | IPCL_UDPMOD));
5676 
5677 	switch (DB_TYPE(mp)) {
5678 	case M_PROTO:
5679 	case M_PCPROTO:
5680 		if ((MBLKL(mp) >= sizeof (t_scalar_t)) &&
5681 		    ((((union T_primitives *)mp->b_rptr)->type ==
5682 		    T_SVR4_OPTMGMT_REQ) ||
5683 		    (((union T_primitives *)mp->b_rptr)->type ==
5684 		    T_OPTMGMT_REQ))) {
5685 			/*
5686 			 * This is the only TPI primitive supported. Its
5687 			 * handling does not require tcp_t, but it does require
5688 			 * conn_t to check permissions.
5689 			 */
5690 			cred_t	*cr = DB_CREDDEF(mp, connp->conn_cred);
5691 
5692 			if (connp->conn_flags & IPCL_TCPMOD) {
5693 				setfn = tcp_snmp_set;
5694 				getfn = tcp_snmp_get;
5695 			} else {
5696 				setfn = udp_snmp_set;
5697 				getfn = udp_snmp_get;
5698 			}
5699 			if (!snmpcom_req(q, mp, setfn, getfn, cr)) {
5700 				freemsg(mp);
5701 				return;
5702 			}
5703 		} else if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, ENOTSUP))
5704 		    != NULL)
5705 			qreply(q, mp);
5706 		break;
5707 	case M_FLUSH:
5708 	case M_IOCTL:
5709 		putnext(q, mp);
5710 		break;
5711 	default:
5712 		freemsg(mp);
5713 		break;
5714 	}
5715 }
5716 
5717 /* Return the IP checksum for the IP header at "iph". */
5718 uint16_t
5719 ip_csum_hdr(ipha_t *ipha)
5720 {
5721 	uint16_t	*uph;
5722 	uint32_t	sum;
5723 	int		opt_len;
5724 
5725 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5726 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5727 	uph = (uint16_t *)ipha;
5728 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5729 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5730 	if (opt_len > 0) {
5731 		do {
5732 			sum += uph[10];
5733 			sum += uph[11];
5734 			uph += 2;
5735 		} while (--opt_len);
5736 	}
5737 	sum = (sum & 0xFFFF) + (sum >> 16);
5738 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5739 	if (sum == 0xffff)
5740 		sum = 0;
5741 	return ((uint16_t)sum);
5742 }
5743 
5744 /*
5745  * Called when the module is about to be unloaded
5746  */
5747 void
5748 ip_ddi_destroy(void)
5749 {
5750 	tnet_fini();
5751 
5752 	sctp_ddi_g_destroy();
5753 	tcp_ddi_g_destroy();
5754 	ipsec_policy_g_destroy();
5755 	ipcl_g_destroy();
5756 	ip_net_g_destroy();
5757 	ip_ire_g_fini();
5758 	inet_minor_destroy(ip_minor_arena);
5759 
5760 	netstack_unregister(NS_IP);
5761 }
5762 
5763 /*
5764  * First step in cleanup.
5765  */
5766 /* ARGSUSED */
5767 static void
5768 ip_stack_shutdown(netstackid_t stackid, void *arg)
5769 {
5770 	ip_stack_t *ipst = (ip_stack_t *)arg;
5771 
5772 #ifdef NS_DEBUG
5773 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5774 #endif
5775 
5776 	/* Get rid of loopback interfaces and their IREs */
5777 	ip_loopback_cleanup(ipst);
5778 }
5779 
5780 /*
5781  * Free the IP stack instance.
5782  */
5783 static void
5784 ip_stack_fini(netstackid_t stackid, void *arg)
5785 {
5786 	ip_stack_t *ipst = (ip_stack_t *)arg;
5787 	int ret;
5788 
5789 #ifdef NS_DEBUG
5790 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5791 #endif
5792 	ipv4_hook_destroy(ipst);
5793 	ipv6_hook_destroy(ipst);
5794 	ip_net_destroy(ipst);
5795 
5796 	rw_destroy(&ipst->ips_srcid_lock);
5797 
5798 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5799 	ipst->ips_ip_mibkp = NULL;
5800 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5801 	ipst->ips_icmp_mibkp = NULL;
5802 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5803 	ipst->ips_ip_kstat = NULL;
5804 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5805 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5806 	ipst->ips_ip6_kstat = NULL;
5807 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5808 
5809 	nd_free(&ipst->ips_ip_g_nd);
5810 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5811 	ipst->ips_param_arr = NULL;
5812 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5813 	ipst->ips_ndp_arr = NULL;
5814 
5815 	ip_mrouter_stack_destroy(ipst);
5816 
5817 	mutex_destroy(&ipst->ips_ip_mi_lock);
5818 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5819 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5820 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5821 
5822 	ret = untimeout(ipst->ips_igmp_timeout_id);
5823 	if (ret == -1) {
5824 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5825 	} else {
5826 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5827 		ipst->ips_igmp_timeout_id = 0;
5828 	}
5829 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5830 	if (ret == -1) {
5831 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5832 	} else {
5833 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5834 		ipst->ips_igmp_slowtimeout_id = 0;
5835 	}
5836 	ret = untimeout(ipst->ips_mld_timeout_id);
5837 	if (ret == -1) {
5838 		ASSERT(ipst->ips_mld_timeout_id == 0);
5839 	} else {
5840 		ASSERT(ipst->ips_mld_timeout_id != 0);
5841 		ipst->ips_mld_timeout_id = 0;
5842 	}
5843 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5844 	if (ret == -1) {
5845 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5846 	} else {
5847 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5848 		ipst->ips_mld_slowtimeout_id = 0;
5849 	}
5850 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5851 	if (ret == -1) {
5852 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5853 	} else {
5854 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5855 		ipst->ips_ip_ire_expire_id = 0;
5856 	}
5857 
5858 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5859 	mutex_destroy(&ipst->ips_mld_timer_lock);
5860 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5861 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5862 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5863 	rw_destroy(&ipst->ips_ill_g_lock);
5864 
5865 	ip_ire_fini(ipst);
5866 	ip6_asp_free(ipst);
5867 	conn_drain_fini(ipst);
5868 	ipcl_destroy(ipst);
5869 
5870 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5871 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5872 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5873 	ipst->ips_ndp4 = NULL;
5874 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5875 	ipst->ips_ndp6 = NULL;
5876 
5877 	if (ipst->ips_loopback_ksp != NULL) {
5878 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5879 		ipst->ips_loopback_ksp = NULL;
5880 	}
5881 
5882 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5883 	ipst->ips_phyint_g_list = NULL;
5884 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5885 	ipst->ips_ill_g_heads = NULL;
5886 
5887 	kmem_free(ipst, sizeof (*ipst));
5888 }
5889 
5890 /*
5891  * Called when the IP kernel module is loaded into the kernel
5892  */
5893 void
5894 ip_ddi_init(void)
5895 {
5896 	TCP6_MAJ = ddi_name_to_major(TCP6);
5897 	TCP_MAJ	= ddi_name_to_major(TCP);
5898 	SCTP_MAJ = ddi_name_to_major(SCTP);
5899 	SCTP6_MAJ = ddi_name_to_major(SCTP6);
5900 
5901 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5902 
5903 	/*
5904 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5905 	 * initial devices: ip, ip6, tcp, tcp6.
5906 	 */
5907 	if ((ip_minor_arena = inet_minor_create("ip_minor_arena",
5908 	    INET_MIN_DEV + 2, KM_SLEEP)) == NULL) {
5909 		cmn_err(CE_PANIC,
5910 		    "ip_ddi_init: ip_minor_arena creation failed\n");
5911 	}
5912 
5913 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5914 
5915 	ipcl_g_init();
5916 	ip_ire_g_init();
5917 	ip_net_g_init();
5918 
5919 #ifdef ILL_DEBUG
5920 	/* Default cleanup function */
5921 	ip_cleanup_func = ip_thread_exit;
5922 #endif
5923 
5924 	/*
5925 	 * We want to be informed each time a stack is created or
5926 	 * destroyed in the kernel, so we can maintain the
5927 	 * set of udp_stack_t's.
5928 	 */
5929 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5930 	    ip_stack_fini);
5931 
5932 	ipsec_policy_g_init();
5933 	tcp_ddi_g_init();
5934 	sctp_ddi_g_init();
5935 
5936 	tnet_init();
5937 }
5938 
5939 /*
5940  * Initialize the IP stack instance.
5941  */
5942 static void *
5943 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5944 {
5945 	ip_stack_t	*ipst;
5946 	ipparam_t	*pa;
5947 	ipndp_t		*na;
5948 
5949 #ifdef NS_DEBUG
5950 	printf("ip_stack_init(stack %d)\n", stackid);
5951 #endif
5952 
5953 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5954 	ipst->ips_netstack = ns;
5955 
5956 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5957 	    KM_SLEEP);
5958 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5959 	    KM_SLEEP);
5960 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5961 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5962 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5963 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5964 
5965 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5966 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5967 	ipst->ips_igmp_deferred_next = INFINITY;
5968 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5969 	ipst->ips_mld_deferred_next = INFINITY;
5970 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5971 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5972 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5973 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5974 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5975 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5976 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5977 
5978 	ipcl_init(ipst);
5979 	ip_ire_init(ipst);
5980 	ip6_asp_init(ipst);
5981 	ipif_init(ipst);
5982 	conn_drain_init(ipst);
5983 	ip_mrouter_stack_init(ipst);
5984 
5985 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5986 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5987 
5988 	ipst->ips_ip_multirt_log_interval = 1000;
5989 
5990 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5991 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5992 	ipst->ips_ill_index = 1;
5993 
5994 	ipst->ips_saved_ip_g_forward = -1;
5995 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5996 
5997 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5998 	ipst->ips_param_arr = pa;
5999 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
6000 
6001 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
6002 	ipst->ips_ndp_arr = na;
6003 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
6004 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
6005 	    (caddr_t)&ipst->ips_ip_g_forward;
6006 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
6007 	    (caddr_t)&ipst->ips_ipv6_forward;
6008 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
6009 	    "ip_cgtp_filter") == 0);
6010 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
6011 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
6012 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6013 	    "ipmp_hook_emulation") == 0);
6014 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6015 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6016 
6017 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6018 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6019 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6020 
6021 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6022 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6023 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6024 	ipst->ips_ip6_kstat =
6025 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6026 
6027 	ipst->ips_ipmp_enable_failback = B_TRUE;
6028 
6029 	ipst->ips_ip_src_id = 1;
6030 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6031 
6032 	ip_net_init(ipst, ns);
6033 	ipv4_hook_init(ipst);
6034 	ipv6_hook_init(ipst);
6035 
6036 	return (ipst);
6037 }
6038 
6039 /*
6040  * Allocate and initialize a DLPI template of the specified length.  (May be
6041  * called as writer.)
6042  */
6043 mblk_t *
6044 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6045 {
6046 	mblk_t	*mp;
6047 
6048 	mp = allocb(len, BPRI_MED);
6049 	if (!mp)
6050 		return (NULL);
6051 
6052 	/*
6053 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6054 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6055 	 * that other DLPI are M_PROTO.
6056 	 */
6057 	if (prim == DL_INFO_REQ) {
6058 		mp->b_datap->db_type = M_PCPROTO;
6059 	} else {
6060 		mp->b_datap->db_type = M_PROTO;
6061 	}
6062 
6063 	mp->b_wptr = mp->b_rptr + len;
6064 	bzero(mp->b_rptr, len);
6065 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6066 	return (mp);
6067 }
6068 
6069 const char *
6070 dlpi_prim_str(int prim)
6071 {
6072 	switch (prim) {
6073 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6074 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6075 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6076 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6077 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6078 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6079 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6080 	case DL_OK_ACK:		return ("DL_OK_ACK");
6081 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6082 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6083 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6084 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6085 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6086 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6087 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6088 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6089 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6090 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6091 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6092 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6093 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6094 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6095 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6096 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6097 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6098 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6099 	default:		return ("<unknown primitive>");
6100 	}
6101 }
6102 
6103 const char *
6104 dlpi_err_str(int err)
6105 {
6106 	switch (err) {
6107 	case DL_ACCESS:		return ("DL_ACCESS");
6108 	case DL_BADADDR:	return ("DL_BADADDR");
6109 	case DL_BADCORR:	return ("DL_BADCORR");
6110 	case DL_BADDATA:	return ("DL_BADDATA");
6111 	case DL_BADPPA:		return ("DL_BADPPA");
6112 	case DL_BADPRIM:	return ("DL_BADPRIM");
6113 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6114 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6115 	case DL_BADSAP:		return ("DL_BADSAP");
6116 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6117 	case DL_BOUND:		return ("DL_BOUND");
6118 	case DL_INITFAILED:	return ("DL_INITFAILED");
6119 	case DL_NOADDR:		return ("DL_NOADDR");
6120 	case DL_NOTINIT:	return ("DL_NOTINIT");
6121 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6122 	case DL_SYSERR:		return ("DL_SYSERR");
6123 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6124 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6125 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6126 	case DL_TOOMANY:	return ("DL_TOOMANY");
6127 	case DL_NOTENAB:	return ("DL_NOTENAB");
6128 	case DL_BUSY:		return ("DL_BUSY");
6129 	case DL_NOAUTO:		return ("DL_NOAUTO");
6130 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6131 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6132 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6133 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6134 	case DL_PENDING:	return ("DL_PENDING");
6135 	default:		return ("<unknown error>");
6136 	}
6137 }
6138 
6139 /*
6140  * Debug formatting routine.  Returns a character string representation of the
6141  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6142  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6143  *
6144  * Once the ndd table-printing interfaces are removed, this can be changed to
6145  * standard dotted-decimal form.
6146  */
6147 char *
6148 ip_dot_addr(ipaddr_t addr, char *buf)
6149 {
6150 	uint8_t *ap = (uint8_t *)&addr;
6151 
6152 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6153 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6154 	return (buf);
6155 }
6156 
6157 /*
6158  * Write the given MAC address as a printable string in the usual colon-
6159  * separated format.
6160  */
6161 const char *
6162 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6163 {
6164 	char *bp;
6165 
6166 	if (alen == 0 || buflen < 4)
6167 		return ("?");
6168 	bp = buf;
6169 	for (;;) {
6170 		/*
6171 		 * If there are more MAC address bytes available, but we won't
6172 		 * have any room to print them, then add "..." to the string
6173 		 * instead.  See below for the 'magic number' explanation.
6174 		 */
6175 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6176 			(void) strcpy(bp, "...");
6177 			break;
6178 		}
6179 		(void) sprintf(bp, "%02x", *addr++);
6180 		bp += 2;
6181 		if (--alen == 0)
6182 			break;
6183 		*bp++ = ':';
6184 		buflen -= 3;
6185 		/*
6186 		 * At this point, based on the first 'if' statement above,
6187 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6188 		 * buflen >= 4.  The first case leaves room for the final "xx"
6189 		 * number and trailing NUL byte.  The second leaves room for at
6190 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6191 		 * that statement.
6192 		 */
6193 	}
6194 	return (buf);
6195 }
6196 
6197 /*
6198  * Send an ICMP error after patching up the packet appropriately.  Returns
6199  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6200  */
6201 static boolean_t
6202 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6203     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6204     zoneid_t zoneid, ip_stack_t *ipst)
6205 {
6206 	ipha_t *ipha;
6207 	mblk_t *first_mp;
6208 	boolean_t secure;
6209 	unsigned char db_type;
6210 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6211 
6212 	first_mp = mp;
6213 	if (mctl_present) {
6214 		mp = mp->b_cont;
6215 		secure = ipsec_in_is_secure(first_mp);
6216 		ASSERT(mp != NULL);
6217 	} else {
6218 		/*
6219 		 * If this is an ICMP error being reported - which goes
6220 		 * up as M_CTLs, we need to convert them to M_DATA till
6221 		 * we finish checking with global policy because
6222 		 * ipsec_check_global_policy() assumes M_DATA as clear
6223 		 * and M_CTL as secure.
6224 		 */
6225 		db_type = DB_TYPE(mp);
6226 		DB_TYPE(mp) = M_DATA;
6227 		secure = B_FALSE;
6228 	}
6229 	/*
6230 	 * We are generating an icmp error for some inbound packet.
6231 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6232 	 * Before we generate an error, check with global policy
6233 	 * to see whether this is allowed to enter the system. As
6234 	 * there is no "conn", we are checking with global policy.
6235 	 */
6236 	ipha = (ipha_t *)mp->b_rptr;
6237 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6238 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6239 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6240 		if (first_mp == NULL)
6241 			return (B_FALSE);
6242 	}
6243 
6244 	if (!mctl_present)
6245 		DB_TYPE(mp) = db_type;
6246 
6247 	if (flags & IP_FF_SEND_ICMP) {
6248 		if (flags & IP_FF_HDR_COMPLETE) {
6249 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6250 				freemsg(first_mp);
6251 				return (B_TRUE);
6252 			}
6253 		}
6254 		if (flags & IP_FF_CKSUM) {
6255 			/*
6256 			 * Have to correct checksum since
6257 			 * the packet might have been
6258 			 * fragmented and the reassembly code in ip_rput
6259 			 * does not restore the IP checksum.
6260 			 */
6261 			ipha->ipha_hdr_checksum = 0;
6262 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6263 		}
6264 		switch (icmp_type) {
6265 		case ICMP_DEST_UNREACHABLE:
6266 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6267 			    ipst);
6268 			break;
6269 		default:
6270 			freemsg(first_mp);
6271 			break;
6272 		}
6273 	} else {
6274 		freemsg(first_mp);
6275 		return (B_FALSE);
6276 	}
6277 
6278 	return (B_TRUE);
6279 }
6280 
6281 /*
6282  * Used to send an ICMP error message when a packet is received for
6283  * a protocol that is not supported. The mblk passed as argument
6284  * is consumed by this function.
6285  */
6286 void
6287 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6288     ip_stack_t *ipst)
6289 {
6290 	mblk_t *mp;
6291 	ipha_t *ipha;
6292 	ill_t *ill;
6293 	ipsec_in_t *ii;
6294 
6295 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6296 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6297 
6298 	mp = ipsec_mp->b_cont;
6299 	ipsec_mp->b_cont = NULL;
6300 	ipha = (ipha_t *)mp->b_rptr;
6301 	/* Get ill from index in ipsec_in_t. */
6302 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6303 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6304 	    ipst);
6305 	if (ill != NULL) {
6306 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6307 			if (ip_fanout_send_icmp(q, mp, flags,
6308 			    ICMP_DEST_UNREACHABLE,
6309 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6310 				BUMP_MIB(ill->ill_ip_mib,
6311 				    ipIfStatsInUnknownProtos);
6312 			}
6313 		} else {
6314 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6315 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6316 			    0, B_FALSE, zoneid, ipst)) {
6317 				BUMP_MIB(ill->ill_ip_mib,
6318 				    ipIfStatsInUnknownProtos);
6319 			}
6320 		}
6321 		ill_refrele(ill);
6322 	} else { /* re-link for the freemsg() below. */
6323 		ipsec_mp->b_cont = mp;
6324 	}
6325 
6326 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6327 	freemsg(ipsec_mp);
6328 }
6329 
6330 /*
6331  * See if the inbound datagram has had IPsec processing applied to it.
6332  */
6333 boolean_t
6334 ipsec_in_is_secure(mblk_t *ipsec_mp)
6335 {
6336 	ipsec_in_t *ii;
6337 
6338 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6339 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6340 
6341 	if (ii->ipsec_in_loopback) {
6342 		return (ii->ipsec_in_secure);
6343 	} else {
6344 		return (ii->ipsec_in_ah_sa != NULL ||
6345 		    ii->ipsec_in_esp_sa != NULL ||
6346 		    ii->ipsec_in_decaps);
6347 	}
6348 }
6349 
6350 /*
6351  * Handle protocols with which IP is less intimate.  There
6352  * can be more than one stream bound to a particular
6353  * protocol.  When this is the case, normally each one gets a copy
6354  * of any incoming packets.
6355  *
6356  * IPSEC NOTE :
6357  *
6358  * Don't allow a secure packet going up a non-secure connection.
6359  * We don't allow this because
6360  *
6361  * 1) Reply might go out in clear which will be dropped at
6362  *    the sending side.
6363  * 2) If the reply goes out in clear it will give the
6364  *    adversary enough information for getting the key in
6365  *    most of the cases.
6366  *
6367  * Moreover getting a secure packet when we expect clear
6368  * implies that SA's were added without checking for
6369  * policy on both ends. This should not happen once ISAKMP
6370  * is used to negotiate SAs as SAs will be added only after
6371  * verifying the policy.
6372  *
6373  * NOTE : If the packet was tunneled and not multicast we only send
6374  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6375  * back to delivering packets to AF_INET6 raw sockets.
6376  *
6377  * IPQoS Notes:
6378  * Once we have determined the client, invoke IPPF processing.
6379  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6380  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6381  * ip_policy will be false.
6382  *
6383  * Zones notes:
6384  * Currently only applications in the global zone can create raw sockets for
6385  * protocols other than ICMP. So unlike the broadcast / multicast case of
6386  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6387  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6388  */
6389 static void
6390 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6391     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6392     zoneid_t zoneid)
6393 {
6394 	queue_t	*rq;
6395 	mblk_t	*mp1, *first_mp1;
6396 	uint_t	protocol = ipha->ipha_protocol;
6397 	ipaddr_t dst;
6398 	boolean_t one_only;
6399 	mblk_t *first_mp = mp;
6400 	boolean_t secure;
6401 	uint32_t ill_index;
6402 	conn_t	*connp, *first_connp, *next_connp;
6403 	connf_t	*connfp;
6404 	boolean_t shared_addr;
6405 	mib2_ipIfStatsEntry_t *mibptr;
6406 	ip_stack_t *ipst = recv_ill->ill_ipst;
6407 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6408 
6409 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6410 	if (mctl_present) {
6411 		mp = first_mp->b_cont;
6412 		secure = ipsec_in_is_secure(first_mp);
6413 		ASSERT(mp != NULL);
6414 	} else {
6415 		secure = B_FALSE;
6416 	}
6417 	dst = ipha->ipha_dst;
6418 	/*
6419 	 * If the packet was tunneled and not multicast we only send to it
6420 	 * the first match.
6421 	 */
6422 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6423 	    !CLASSD(dst));
6424 
6425 	shared_addr = (zoneid == ALL_ZONES);
6426 	if (shared_addr) {
6427 		/*
6428 		 * We don't allow multilevel ports for raw IP, so no need to
6429 		 * check for that here.
6430 		 */
6431 		zoneid = tsol_packet_to_zoneid(mp);
6432 	}
6433 
6434 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6435 	mutex_enter(&connfp->connf_lock);
6436 	connp = connfp->connf_head;
6437 	for (connp = connfp->connf_head; connp != NULL;
6438 	    connp = connp->conn_next) {
6439 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6440 		    zoneid) &&
6441 		    (!is_system_labeled() ||
6442 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6443 		    connp))) {
6444 			break;
6445 		}
6446 	}
6447 
6448 	if (connp == NULL || connp->conn_upq == NULL) {
6449 		/*
6450 		 * No one bound to these addresses.  Is
6451 		 * there a client that wants all
6452 		 * unclaimed datagrams?
6453 		 */
6454 		mutex_exit(&connfp->connf_lock);
6455 		/*
6456 		 * Check for IPPROTO_ENCAP...
6457 		 */
6458 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6459 			/*
6460 			 * If an IPsec mblk is here on a multicast
6461 			 * tunnel (using ip_mroute stuff), check policy here,
6462 			 * THEN ship off to ip_mroute_decap().
6463 			 *
6464 			 * BTW,  If I match a configured IP-in-IP
6465 			 * tunnel, this path will not be reached, and
6466 			 * ip_mroute_decap will never be called.
6467 			 */
6468 			first_mp = ipsec_check_global_policy(first_mp, connp,
6469 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6470 			if (first_mp != NULL) {
6471 				if (mctl_present)
6472 					freeb(first_mp);
6473 				ip_mroute_decap(q, mp, ill);
6474 			} /* Else we already freed everything! */
6475 		} else {
6476 			/*
6477 			 * Otherwise send an ICMP protocol unreachable.
6478 			 */
6479 			if (ip_fanout_send_icmp(q, first_mp, flags,
6480 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6481 			    mctl_present, zoneid, ipst)) {
6482 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6483 			}
6484 		}
6485 		return;
6486 	}
6487 	CONN_INC_REF(connp);
6488 	first_connp = connp;
6489 
6490 	/*
6491 	 * Only send message to one tunnel driver by immediately
6492 	 * terminating the loop.
6493 	 */
6494 	connp = one_only ? NULL : connp->conn_next;
6495 
6496 	for (;;) {
6497 		while (connp != NULL) {
6498 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6499 			    flags, zoneid) &&
6500 			    (!is_system_labeled() ||
6501 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6502 			    shared_addr, connp)))
6503 				break;
6504 			connp = connp->conn_next;
6505 		}
6506 
6507 		/*
6508 		 * Copy the packet.
6509 		 */
6510 		if (connp == NULL || connp->conn_upq == NULL ||
6511 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6512 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6513 			/*
6514 			 * No more interested clients or memory
6515 			 * allocation failed
6516 			 */
6517 			connp = first_connp;
6518 			break;
6519 		}
6520 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6521 		CONN_INC_REF(connp);
6522 		mutex_exit(&connfp->connf_lock);
6523 		rq = connp->conn_rq;
6524 		if (!canputnext(rq)) {
6525 			if (flags & IP_FF_RAWIP) {
6526 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6527 			} else {
6528 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6529 			}
6530 
6531 			freemsg(first_mp1);
6532 		} else {
6533 			/*
6534 			 * Don't enforce here if we're an actual tunnel -
6535 			 * let "tun" do it instead.
6536 			 */
6537 			if (!IPCL_IS_IPTUN(connp) &&
6538 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6539 			    secure)) {
6540 				first_mp1 = ipsec_check_inbound_policy
6541 				    (first_mp1, connp, ipha, NULL,
6542 				    mctl_present);
6543 			}
6544 			if (first_mp1 != NULL) {
6545 				int in_flags = 0;
6546 				/*
6547 				 * ip_fanout_proto also gets called from
6548 				 * icmp_inbound_error_fanout, in which case
6549 				 * the msg type is M_CTL.  Don't add info
6550 				 * in this case for the time being. In future
6551 				 * when there is a need for knowing the
6552 				 * inbound iface index for ICMP error msgs,
6553 				 * then this can be changed.
6554 				 */
6555 				if (connp->conn_recvif)
6556 					in_flags = IPF_RECVIF;
6557 				/*
6558 				 * The ULP may support IP_RECVPKTINFO for both
6559 				 * IP v4 and v6 so pass the appropriate argument
6560 				 * based on conn IP version.
6561 				 */
6562 				if (connp->conn_ip_recvpktinfo) {
6563 					if (connp->conn_af_isv6) {
6564 						/*
6565 						 * V6 only needs index
6566 						 */
6567 						in_flags |= IPF_RECVIF;
6568 					} else {
6569 						/*
6570 						 * V4 needs index +
6571 						 * matching address.
6572 						 */
6573 						in_flags |= IPF_RECVADDR;
6574 					}
6575 				}
6576 				if ((in_flags != 0) &&
6577 				    (mp->b_datap->db_type != M_CTL)) {
6578 					/*
6579 					 * the actual data will be
6580 					 * contained in b_cont upon
6581 					 * successful return of the
6582 					 * following call else
6583 					 * original mblk is returned
6584 					 */
6585 					ASSERT(recv_ill != NULL);
6586 					mp1 = ip_add_info(mp1, recv_ill,
6587 					    in_flags, IPCL_ZONEID(connp), ipst);
6588 				}
6589 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6590 				if (mctl_present)
6591 					freeb(first_mp1);
6592 				putnext(rq, mp1);
6593 			}
6594 		}
6595 		mutex_enter(&connfp->connf_lock);
6596 		/* Follow the next pointer before releasing the conn. */
6597 		next_connp = connp->conn_next;
6598 		CONN_DEC_REF(connp);
6599 		connp = next_connp;
6600 	}
6601 
6602 	/* Last one.  Send it upstream. */
6603 	mutex_exit(&connfp->connf_lock);
6604 
6605 	/*
6606 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6607 	 * will be set to false.
6608 	 */
6609 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6610 		ill_index = ill->ill_phyint->phyint_ifindex;
6611 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6612 		if (mp == NULL) {
6613 			CONN_DEC_REF(connp);
6614 			if (mctl_present) {
6615 				freeb(first_mp);
6616 			}
6617 			return;
6618 		}
6619 	}
6620 
6621 	rq = connp->conn_rq;
6622 	if (!canputnext(rq)) {
6623 		if (flags & IP_FF_RAWIP) {
6624 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6625 		} else {
6626 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6627 		}
6628 
6629 		freemsg(first_mp);
6630 	} else {
6631 		if (IPCL_IS_IPTUN(connp)) {
6632 			/*
6633 			 * Tunneled packet.  We enforce policy in the tunnel
6634 			 * module itself.
6635 			 *
6636 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6637 			 * a policy check.
6638 			 */
6639 			putnext(rq, first_mp);
6640 			CONN_DEC_REF(connp);
6641 			return;
6642 		}
6643 
6644 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6645 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6646 			    ipha, NULL, mctl_present);
6647 		}
6648 
6649 		if (first_mp != NULL) {
6650 			int in_flags = 0;
6651 
6652 			/*
6653 			 * ip_fanout_proto also gets called
6654 			 * from icmp_inbound_error_fanout, in
6655 			 * which case the msg type is M_CTL.
6656 			 * Don't add info in this case for time
6657 			 * being. In future when there is a
6658 			 * need for knowing the inbound iface
6659 			 * index for ICMP error msgs, then this
6660 			 * can be changed
6661 			 */
6662 			if (connp->conn_recvif)
6663 				in_flags = IPF_RECVIF;
6664 			if (connp->conn_ip_recvpktinfo) {
6665 				if (connp->conn_af_isv6) {
6666 					/*
6667 					 * V6 only needs index
6668 					 */
6669 					in_flags |= IPF_RECVIF;
6670 				} else {
6671 					/*
6672 					 * V4 needs index +
6673 					 * matching address.
6674 					 */
6675 					in_flags |= IPF_RECVADDR;
6676 				}
6677 			}
6678 			if ((in_flags != 0) &&
6679 			    (mp->b_datap->db_type != M_CTL)) {
6680 
6681 				/*
6682 				 * the actual data will be contained in
6683 				 * b_cont upon successful return
6684 				 * of the following call else original
6685 				 * mblk is returned
6686 				 */
6687 				ASSERT(recv_ill != NULL);
6688 				mp = ip_add_info(mp, recv_ill,
6689 				    in_flags, IPCL_ZONEID(connp), ipst);
6690 			}
6691 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6692 			putnext(rq, mp);
6693 			if (mctl_present)
6694 				freeb(first_mp);
6695 		}
6696 	}
6697 	CONN_DEC_REF(connp);
6698 }
6699 
6700 /*
6701  * Fanout for TCP packets
6702  * The caller puts <fport, lport> in the ports parameter.
6703  *
6704  * IPQoS Notes
6705  * Before sending it to the client, invoke IPPF processing.
6706  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6707  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6708  * ip_policy is false.
6709  */
6710 static void
6711 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6712     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6713 {
6714 	mblk_t  *first_mp;
6715 	boolean_t secure;
6716 	uint32_t ill_index;
6717 	int	ip_hdr_len;
6718 	tcph_t	*tcph;
6719 	boolean_t syn_present = B_FALSE;
6720 	conn_t	*connp;
6721 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6722 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6723 
6724 	ASSERT(recv_ill != NULL);
6725 
6726 	first_mp = mp;
6727 	if (mctl_present) {
6728 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6729 		mp = first_mp->b_cont;
6730 		secure = ipsec_in_is_secure(first_mp);
6731 		ASSERT(mp != NULL);
6732 	} else {
6733 		secure = B_FALSE;
6734 	}
6735 
6736 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6737 
6738 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6739 	    zoneid, ipst)) == NULL) {
6740 		/*
6741 		 * No connected connection or listener. Send a
6742 		 * TH_RST via tcp_xmit_listeners_reset.
6743 		 */
6744 
6745 		/* Initiate IPPf processing, if needed. */
6746 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6747 			uint32_t ill_index;
6748 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6749 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6750 			if (first_mp == NULL)
6751 				return;
6752 		}
6753 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6754 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6755 		    zoneid));
6756 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6757 		    ipst->ips_netstack->netstack_tcp);
6758 		return;
6759 	}
6760 
6761 	/*
6762 	 * Allocate the SYN for the TCP connection here itself
6763 	 */
6764 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6765 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6766 		if (IPCL_IS_TCP(connp)) {
6767 			squeue_t *sqp;
6768 
6769 			/*
6770 			 * For fused tcp loopback, assign the eager's
6771 			 * squeue to be that of the active connect's.
6772 			 * Note that we don't check for IP_FF_LOOPBACK
6773 			 * here since this routine gets called only
6774 			 * for loopback (unlike the IPv6 counterpart).
6775 			 */
6776 			ASSERT(Q_TO_CONN(q) != NULL);
6777 			if (do_tcp_fusion &&
6778 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6779 			    !secure &&
6780 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6781 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6782 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6783 				sqp = Q_TO_CONN(q)->conn_sqp;
6784 			} else {
6785 				sqp = IP_SQUEUE_GET(lbolt);
6786 			}
6787 
6788 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6789 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6790 			syn_present = B_TRUE;
6791 		}
6792 	}
6793 
6794 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6795 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6796 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6797 		if ((flags & TH_RST) || (flags & TH_URG)) {
6798 			CONN_DEC_REF(connp);
6799 			freemsg(first_mp);
6800 			return;
6801 		}
6802 		if (flags & TH_ACK) {
6803 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6804 			    ipst->ips_netstack->netstack_tcp);
6805 			CONN_DEC_REF(connp);
6806 			return;
6807 		}
6808 
6809 		CONN_DEC_REF(connp);
6810 		freemsg(first_mp);
6811 		return;
6812 	}
6813 
6814 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6815 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6816 		    NULL, mctl_present);
6817 		if (first_mp == NULL) {
6818 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6819 			CONN_DEC_REF(connp);
6820 			return;
6821 		}
6822 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6823 			ASSERT(syn_present);
6824 			if (mctl_present) {
6825 				ASSERT(first_mp != mp);
6826 				first_mp->b_datap->db_struioflag |=
6827 				    STRUIO_POLICY;
6828 			} else {
6829 				ASSERT(first_mp == mp);
6830 				mp->b_datap->db_struioflag &=
6831 				    ~STRUIO_EAGER;
6832 				mp->b_datap->db_struioflag |=
6833 				    STRUIO_POLICY;
6834 			}
6835 		} else {
6836 			/*
6837 			 * Discard first_mp early since we're dealing with a
6838 			 * fully-connected conn_t and tcp doesn't do policy in
6839 			 * this case.
6840 			 */
6841 			if (mctl_present) {
6842 				freeb(first_mp);
6843 				mctl_present = B_FALSE;
6844 			}
6845 			first_mp = mp;
6846 		}
6847 	}
6848 
6849 	/*
6850 	 * Initiate policy processing here if needed. If we get here from
6851 	 * icmp_inbound_error_fanout, ip_policy is false.
6852 	 */
6853 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6854 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6855 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6856 		if (mp == NULL) {
6857 			CONN_DEC_REF(connp);
6858 			if (mctl_present)
6859 				freeb(first_mp);
6860 			return;
6861 		} else if (mctl_present) {
6862 			ASSERT(first_mp != mp);
6863 			first_mp->b_cont = mp;
6864 		} else {
6865 			first_mp = mp;
6866 		}
6867 	}
6868 
6869 
6870 
6871 	/* Handle socket options. */
6872 	if (!syn_present &&
6873 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6874 		/* Add header */
6875 		ASSERT(recv_ill != NULL);
6876 		/*
6877 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6878 		 * IPF_RECVIF.
6879 		 */
6880 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6881 		    ipst);
6882 		if (mp == NULL) {
6883 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6884 			CONN_DEC_REF(connp);
6885 			if (mctl_present)
6886 				freeb(first_mp);
6887 			return;
6888 		} else if (mctl_present) {
6889 			/*
6890 			 * ip_add_info might return a new mp.
6891 			 */
6892 			ASSERT(first_mp != mp);
6893 			first_mp->b_cont = mp;
6894 		} else {
6895 			first_mp = mp;
6896 		}
6897 	}
6898 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6899 	if (IPCL_IS_TCP(connp)) {
6900 		/* do not drain, certain use cases can blow the stack */
6901 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6902 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6903 	} else {
6904 		putnext(connp->conn_rq, first_mp);
6905 		CONN_DEC_REF(connp);
6906 	}
6907 }
6908 
6909 /*
6910  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6911  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6912  * Caller is responsible for dropping references to the conn, and freeing
6913  * first_mp.
6914  *
6915  * IPQoS Notes
6916  * Before sending it to the client, invoke IPPF processing. Policy processing
6917  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6918  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6919  * ip_wput_local, ip_policy is false.
6920  */
6921 static void
6922 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6923     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6924     boolean_t ip_policy)
6925 {
6926 	boolean_t	mctl_present = (first_mp != NULL);
6927 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6928 	uint32_t	ill_index;
6929 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6930 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6931 
6932 	ASSERT(ill != NULL);
6933 
6934 	if (mctl_present)
6935 		first_mp->b_cont = mp;
6936 	else
6937 		first_mp = mp;
6938 
6939 	if (CONN_UDP_FLOWCTLD(connp)) {
6940 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6941 		freemsg(first_mp);
6942 		return;
6943 	}
6944 
6945 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6946 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6947 		    NULL, mctl_present);
6948 		if (first_mp == NULL) {
6949 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6950 			return;	/* Freed by ipsec_check_inbound_policy(). */
6951 		}
6952 	}
6953 	if (mctl_present)
6954 		freeb(first_mp);
6955 
6956 	/* Handle options. */
6957 	if (connp->conn_recvif)
6958 		in_flags = IPF_RECVIF;
6959 	/*
6960 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
6961 	 * passed to ip_add_info is based on IP version of connp.
6962 	 */
6963 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6964 		if (connp->conn_af_isv6) {
6965 			/*
6966 			 * V6 only needs index
6967 			 */
6968 			in_flags |= IPF_RECVIF;
6969 		} else {
6970 			/*
6971 			 * V4 needs index + matching address.
6972 			 */
6973 			in_flags |= IPF_RECVADDR;
6974 		}
6975 	}
6976 
6977 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
6978 		in_flags |= IPF_RECVSLLA;
6979 
6980 	/*
6981 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
6982 	 * freed if the packet is dropped. The caller will do so.
6983 	 */
6984 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6985 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6986 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6987 		if (mp == NULL) {
6988 			return;
6989 		}
6990 	}
6991 	if ((in_flags != 0) &&
6992 	    (mp->b_datap->db_type != M_CTL)) {
6993 		/*
6994 		 * The actual data will be contained in b_cont
6995 		 * upon successful return of the following call
6996 		 * else original mblk is returned
6997 		 */
6998 		ASSERT(recv_ill != NULL);
6999 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7000 		    ipst);
7001 	}
7002 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7003 	/* Send it upstream */
7004 	CONN_UDP_RECV(connp, mp);
7005 }
7006 
7007 /*
7008  * Fanout for UDP packets.
7009  * The caller puts <fport, lport> in the ports parameter.
7010  *
7011  * If SO_REUSEADDR is set all multicast and broadcast packets
7012  * will be delivered to all streams bound to the same port.
7013  *
7014  * Zones notes:
7015  * Multicast and broadcast packets will be distributed to streams in all zones.
7016  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7017  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7018  * packets. To maintain this behavior with multiple zones, the conns are grouped
7019  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7020  * each zone. If unset, all the following conns in the same zone are skipped.
7021  */
7022 static void
7023 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7024     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7025     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7026 {
7027 	uint32_t	dstport, srcport;
7028 	ipaddr_t	dst;
7029 	mblk_t		*first_mp;
7030 	boolean_t	secure;
7031 	in6_addr_t	v6src;
7032 	conn_t		*connp;
7033 	connf_t		*connfp;
7034 	conn_t		*first_connp;
7035 	conn_t		*next_connp;
7036 	mblk_t		*mp1, *first_mp1;
7037 	ipaddr_t	src;
7038 	zoneid_t	last_zoneid;
7039 	boolean_t	reuseaddr;
7040 	boolean_t	shared_addr;
7041 	ip_stack_t	*ipst;
7042 
7043 	ASSERT(recv_ill != NULL);
7044 	ipst = recv_ill->ill_ipst;
7045 
7046 	first_mp = mp;
7047 	if (mctl_present) {
7048 		mp = first_mp->b_cont;
7049 		first_mp->b_cont = NULL;
7050 		secure = ipsec_in_is_secure(first_mp);
7051 		ASSERT(mp != NULL);
7052 	} else {
7053 		first_mp = NULL;
7054 		secure = B_FALSE;
7055 	}
7056 
7057 	/* Extract ports in net byte order */
7058 	dstport = htons(ntohl(ports) & 0xFFFF);
7059 	srcport = htons(ntohl(ports) >> 16);
7060 	dst = ipha->ipha_dst;
7061 	src = ipha->ipha_src;
7062 
7063 	shared_addr = (zoneid == ALL_ZONES);
7064 	if (shared_addr) {
7065 		/*
7066 		 * No need to handle exclusive-stack zones since ALL_ZONES
7067 		 * only applies to the shared stack.
7068 		 */
7069 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7070 		if (zoneid == ALL_ZONES)
7071 			zoneid = tsol_packet_to_zoneid(mp);
7072 	}
7073 
7074 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7075 	mutex_enter(&connfp->connf_lock);
7076 	connp = connfp->connf_head;
7077 	if (!broadcast && !CLASSD(dst)) {
7078 		/*
7079 		 * Not broadcast or multicast. Send to the one (first)
7080 		 * client we find. No need to check conn_wantpacket()
7081 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7082 		 * IPv4 unicast packets.
7083 		 */
7084 		while ((connp != NULL) &&
7085 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7086 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7087 			connp = connp->conn_next;
7088 		}
7089 
7090 		if (connp == NULL || connp->conn_upq == NULL)
7091 			goto notfound;
7092 
7093 		if (is_system_labeled() &&
7094 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7095 		    connp))
7096 			goto notfound;
7097 
7098 		CONN_INC_REF(connp);
7099 		mutex_exit(&connfp->connf_lock);
7100 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7101 		    flags, recv_ill, ip_policy);
7102 		IP_STAT(ipst, ip_udp_fannorm);
7103 		CONN_DEC_REF(connp);
7104 		return;
7105 	}
7106 
7107 	/*
7108 	 * Broadcast and multicast case
7109 	 *
7110 	 * Need to check conn_wantpacket().
7111 	 * If SO_REUSEADDR has been set on the first we send the
7112 	 * packet to all clients that have joined the group and
7113 	 * match the port.
7114 	 */
7115 
7116 	while (connp != NULL) {
7117 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7118 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7119 		    (!is_system_labeled() ||
7120 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7121 		    connp)))
7122 			break;
7123 		connp = connp->conn_next;
7124 	}
7125 
7126 	if (connp == NULL || connp->conn_upq == NULL)
7127 		goto notfound;
7128 
7129 	first_connp = connp;
7130 	/*
7131 	 * When SO_REUSEADDR is not set, send the packet only to the first
7132 	 * matching connection in its zone by keeping track of the zoneid.
7133 	 */
7134 	reuseaddr = first_connp->conn_reuseaddr;
7135 	last_zoneid = first_connp->conn_zoneid;
7136 
7137 	CONN_INC_REF(connp);
7138 	connp = connp->conn_next;
7139 	for (;;) {
7140 		while (connp != NULL) {
7141 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7142 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7143 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7144 			    (!is_system_labeled() ||
7145 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7146 			    shared_addr, connp)))
7147 				break;
7148 			connp = connp->conn_next;
7149 		}
7150 		/*
7151 		 * Just copy the data part alone. The mctl part is
7152 		 * needed just for verifying policy and it is never
7153 		 * sent up.
7154 		 */
7155 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7156 		    ((mp1 = copymsg(mp)) == NULL))) {
7157 			/*
7158 			 * No more interested clients or memory
7159 			 * allocation failed
7160 			 */
7161 			connp = first_connp;
7162 			break;
7163 		}
7164 		if (connp->conn_zoneid != last_zoneid) {
7165 			/*
7166 			 * Update the zoneid so that the packet isn't sent to
7167 			 * any more conns in the same zone unless SO_REUSEADDR
7168 			 * is set.
7169 			 */
7170 			reuseaddr = connp->conn_reuseaddr;
7171 			last_zoneid = connp->conn_zoneid;
7172 		}
7173 		if (first_mp != NULL) {
7174 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7175 			    ipsec_info_type == IPSEC_IN);
7176 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7177 			    ipst->ips_netstack);
7178 			if (first_mp1 == NULL) {
7179 				freemsg(mp1);
7180 				connp = first_connp;
7181 				break;
7182 			}
7183 		} else {
7184 			first_mp1 = NULL;
7185 		}
7186 		CONN_INC_REF(connp);
7187 		mutex_exit(&connfp->connf_lock);
7188 		/*
7189 		 * IPQoS notes: We don't send the packet for policy
7190 		 * processing here, will do it for the last one (below).
7191 		 * i.e. we do it per-packet now, but if we do policy
7192 		 * processing per-conn, then we would need to do it
7193 		 * here too.
7194 		 */
7195 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7196 		    ipha, flags, recv_ill, B_FALSE);
7197 		mutex_enter(&connfp->connf_lock);
7198 		/* Follow the next pointer before releasing the conn. */
7199 		next_connp = connp->conn_next;
7200 		IP_STAT(ipst, ip_udp_fanmb);
7201 		CONN_DEC_REF(connp);
7202 		connp = next_connp;
7203 	}
7204 
7205 	/* Last one.  Send it upstream. */
7206 	mutex_exit(&connfp->connf_lock);
7207 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7208 	    recv_ill, ip_policy);
7209 	IP_STAT(ipst, ip_udp_fanmb);
7210 	CONN_DEC_REF(connp);
7211 	return;
7212 
7213 notfound:
7214 
7215 	mutex_exit(&connfp->connf_lock);
7216 	IP_STAT(ipst, ip_udp_fanothers);
7217 	/*
7218 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7219 	 * have already been matched above, since they live in the IPv4
7220 	 * fanout tables. This implies we only need to
7221 	 * check for IPv6 in6addr_any endpoints here.
7222 	 * Thus we compare using ipv6_all_zeros instead of the destination
7223 	 * address, except for the multicast group membership lookup which
7224 	 * uses the IPv4 destination.
7225 	 */
7226 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7227 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7228 	mutex_enter(&connfp->connf_lock);
7229 	connp = connfp->connf_head;
7230 	if (!broadcast && !CLASSD(dst)) {
7231 		while (connp != NULL) {
7232 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7233 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7234 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7235 			    !connp->conn_ipv6_v6only)
7236 				break;
7237 			connp = connp->conn_next;
7238 		}
7239 
7240 		if (connp != NULL && is_system_labeled() &&
7241 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7242 		    connp))
7243 			connp = NULL;
7244 
7245 		if (connp == NULL || connp->conn_upq == NULL) {
7246 			/*
7247 			 * No one bound to this port.  Is
7248 			 * there a client that wants all
7249 			 * unclaimed datagrams?
7250 			 */
7251 			mutex_exit(&connfp->connf_lock);
7252 
7253 			if (mctl_present)
7254 				first_mp->b_cont = mp;
7255 			else
7256 				first_mp = mp;
7257 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7258 			    connf_head != NULL) {
7259 				ip_fanout_proto(q, first_mp, ill, ipha,
7260 				    flags | IP_FF_RAWIP, mctl_present,
7261 				    ip_policy, recv_ill, zoneid);
7262 			} else {
7263 				if (ip_fanout_send_icmp(q, first_mp, flags,
7264 				    ICMP_DEST_UNREACHABLE,
7265 				    ICMP_PORT_UNREACHABLE,
7266 				    mctl_present, zoneid, ipst)) {
7267 					BUMP_MIB(ill->ill_ip_mib,
7268 					    udpIfStatsNoPorts);
7269 				}
7270 			}
7271 			return;
7272 		}
7273 
7274 		CONN_INC_REF(connp);
7275 		mutex_exit(&connfp->connf_lock);
7276 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7277 		    flags, recv_ill, ip_policy);
7278 		CONN_DEC_REF(connp);
7279 		return;
7280 	}
7281 	/*
7282 	 * IPv4 multicast packet being delivered to an AF_INET6
7283 	 * in6addr_any endpoint.
7284 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7285 	 * and not conn_wantpacket_v6() since any multicast membership is
7286 	 * for an IPv4-mapped multicast address.
7287 	 * The packet is sent to all clients in all zones that have joined the
7288 	 * group and match the port.
7289 	 */
7290 	while (connp != NULL) {
7291 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7292 		    srcport, v6src) &&
7293 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7294 		    (!is_system_labeled() ||
7295 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7296 		    connp)))
7297 			break;
7298 		connp = connp->conn_next;
7299 	}
7300 
7301 	if (connp == NULL || connp->conn_upq == NULL) {
7302 		/*
7303 		 * No one bound to this port.  Is
7304 		 * there a client that wants all
7305 		 * unclaimed datagrams?
7306 		 */
7307 		mutex_exit(&connfp->connf_lock);
7308 
7309 		if (mctl_present)
7310 			first_mp->b_cont = mp;
7311 		else
7312 			first_mp = mp;
7313 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7314 		    NULL) {
7315 			ip_fanout_proto(q, first_mp, ill, ipha,
7316 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7317 			    recv_ill, zoneid);
7318 		} else {
7319 			/*
7320 			 * We used to attempt to send an icmp error here, but
7321 			 * since this is known to be a multicast packet
7322 			 * and we don't send icmp errors in response to
7323 			 * multicast, just drop the packet and give up sooner.
7324 			 */
7325 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7326 			freemsg(first_mp);
7327 		}
7328 		return;
7329 	}
7330 
7331 	first_connp = connp;
7332 
7333 	CONN_INC_REF(connp);
7334 	connp = connp->conn_next;
7335 	for (;;) {
7336 		while (connp != NULL) {
7337 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7338 			    ipv6_all_zeros, srcport, v6src) &&
7339 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7340 			    (!is_system_labeled() ||
7341 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7342 			    shared_addr, connp)))
7343 				break;
7344 			connp = connp->conn_next;
7345 		}
7346 		/*
7347 		 * Just copy the data part alone. The mctl part is
7348 		 * needed just for verifying policy and it is never
7349 		 * sent up.
7350 		 */
7351 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7352 		    ((mp1 = copymsg(mp)) == NULL))) {
7353 			/*
7354 			 * No more intested clients or memory
7355 			 * allocation failed
7356 			 */
7357 			connp = first_connp;
7358 			break;
7359 		}
7360 		if (first_mp != NULL) {
7361 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7362 			    ipsec_info_type == IPSEC_IN);
7363 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7364 			    ipst->ips_netstack);
7365 			if (first_mp1 == NULL) {
7366 				freemsg(mp1);
7367 				connp = first_connp;
7368 				break;
7369 			}
7370 		} else {
7371 			first_mp1 = NULL;
7372 		}
7373 		CONN_INC_REF(connp);
7374 		mutex_exit(&connfp->connf_lock);
7375 		/*
7376 		 * IPQoS notes: We don't send the packet for policy
7377 		 * processing here, will do it for the last one (below).
7378 		 * i.e. we do it per-packet now, but if we do policy
7379 		 * processing per-conn, then we would need to do it
7380 		 * here too.
7381 		 */
7382 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7383 		    ipha, flags, recv_ill, B_FALSE);
7384 		mutex_enter(&connfp->connf_lock);
7385 		/* Follow the next pointer before releasing the conn. */
7386 		next_connp = connp->conn_next;
7387 		CONN_DEC_REF(connp);
7388 		connp = next_connp;
7389 	}
7390 
7391 	/* Last one.  Send it upstream. */
7392 	mutex_exit(&connfp->connf_lock);
7393 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7394 	    recv_ill, ip_policy);
7395 	CONN_DEC_REF(connp);
7396 }
7397 
7398 /*
7399  * Complete the ip_wput header so that it
7400  * is possible to generate ICMP
7401  * errors.
7402  */
7403 int
7404 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7405 {
7406 	ire_t *ire;
7407 
7408 	if (ipha->ipha_src == INADDR_ANY) {
7409 		ire = ire_lookup_local(zoneid, ipst);
7410 		if (ire == NULL) {
7411 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7412 			return (1);
7413 		}
7414 		ipha->ipha_src = ire->ire_addr;
7415 		ire_refrele(ire);
7416 	}
7417 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7418 	ipha->ipha_hdr_checksum = 0;
7419 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7420 	return (0);
7421 }
7422 
7423 /*
7424  * Nobody should be sending
7425  * packets up this stream
7426  */
7427 static void
7428 ip_lrput(queue_t *q, mblk_t *mp)
7429 {
7430 	mblk_t *mp1;
7431 
7432 	switch (mp->b_datap->db_type) {
7433 	case M_FLUSH:
7434 		/* Turn around */
7435 		if (*mp->b_rptr & FLUSHW) {
7436 			*mp->b_rptr &= ~FLUSHR;
7437 			qreply(q, mp);
7438 			return;
7439 		}
7440 		break;
7441 	}
7442 	/* Could receive messages that passed through ar_rput */
7443 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7444 		mp1->b_prev = mp1->b_next = NULL;
7445 	freemsg(mp);
7446 }
7447 
7448 /* Nobody should be sending packets down this stream */
7449 /* ARGSUSED */
7450 void
7451 ip_lwput(queue_t *q, mblk_t *mp)
7452 {
7453 	freemsg(mp);
7454 }
7455 
7456 /*
7457  * Move the first hop in any source route to ipha_dst and remove that part of
7458  * the source route.  Called by other protocols.  Errors in option formatting
7459  * are ignored - will be handled by ip_wput_options Return the final
7460  * destination (either ipha_dst or the last entry in a source route.)
7461  */
7462 ipaddr_t
7463 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7464 {
7465 	ipoptp_t	opts;
7466 	uchar_t		*opt;
7467 	uint8_t		optval;
7468 	uint8_t		optlen;
7469 	ipaddr_t	dst;
7470 	int		i;
7471 	ire_t		*ire;
7472 	ip_stack_t	*ipst = ns->netstack_ip;
7473 
7474 	ip2dbg(("ip_massage_options\n"));
7475 	dst = ipha->ipha_dst;
7476 	for (optval = ipoptp_first(&opts, ipha);
7477 	    optval != IPOPT_EOL;
7478 	    optval = ipoptp_next(&opts)) {
7479 		opt = opts.ipoptp_cur;
7480 		switch (optval) {
7481 			uint8_t off;
7482 		case IPOPT_SSRR:
7483 		case IPOPT_LSRR:
7484 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7485 				ip1dbg(("ip_massage_options: bad src route\n"));
7486 				break;
7487 			}
7488 			optlen = opts.ipoptp_len;
7489 			off = opt[IPOPT_OFFSET];
7490 			off--;
7491 		redo_srr:
7492 			if (optlen < IP_ADDR_LEN ||
7493 			    off > optlen - IP_ADDR_LEN) {
7494 				/* End of source route */
7495 				ip1dbg(("ip_massage_options: end of SR\n"));
7496 				break;
7497 			}
7498 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7499 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7500 			    ntohl(dst)));
7501 			/*
7502 			 * Check if our address is present more than
7503 			 * once as consecutive hops in source route.
7504 			 * XXX verify per-interface ip_forwarding
7505 			 * for source route?
7506 			 */
7507 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7508 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7509 			if (ire != NULL) {
7510 				ire_refrele(ire);
7511 				off += IP_ADDR_LEN;
7512 				goto redo_srr;
7513 			}
7514 			if (dst == htonl(INADDR_LOOPBACK)) {
7515 				ip1dbg(("ip_massage_options: loopback addr in "
7516 				    "source route!\n"));
7517 				break;
7518 			}
7519 			/*
7520 			 * Update ipha_dst to be the first hop and remove the
7521 			 * first hop from the source route (by overwriting
7522 			 * part of the option with NOP options).
7523 			 */
7524 			ipha->ipha_dst = dst;
7525 			/* Put the last entry in dst */
7526 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7527 			    3;
7528 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7529 
7530 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7531 			    ntohl(dst)));
7532 			/* Move down and overwrite */
7533 			opt[IP_ADDR_LEN] = opt[0];
7534 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7535 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7536 			for (i = 0; i < IP_ADDR_LEN; i++)
7537 				opt[i] = IPOPT_NOP;
7538 			break;
7539 		}
7540 	}
7541 	return (dst);
7542 }
7543 
7544 /*
7545  * Return the network mask
7546  * associated with the specified address.
7547  */
7548 ipaddr_t
7549 ip_net_mask(ipaddr_t addr)
7550 {
7551 	uchar_t	*up = (uchar_t *)&addr;
7552 	ipaddr_t mask = 0;
7553 	uchar_t	*maskp = (uchar_t *)&mask;
7554 
7555 #if defined(__i386) || defined(__amd64)
7556 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7557 #endif
7558 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7559 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7560 #endif
7561 	if (CLASSD(addr)) {
7562 		maskp[0] = 0xF0;
7563 		return (mask);
7564 	}
7565 	if (addr == 0)
7566 		return (0);
7567 	maskp[0] = 0xFF;
7568 	if ((up[0] & 0x80) == 0)
7569 		return (mask);
7570 
7571 	maskp[1] = 0xFF;
7572 	if ((up[0] & 0xC0) == 0x80)
7573 		return (mask);
7574 
7575 	maskp[2] = 0xFF;
7576 	if ((up[0] & 0xE0) == 0xC0)
7577 		return (mask);
7578 
7579 	/* Must be experimental or multicast, indicate as much */
7580 	return ((ipaddr_t)0);
7581 }
7582 
7583 /*
7584  * Select an ill for the packet by considering load spreading across
7585  * a different ill in the group if dst_ill is part of some group.
7586  */
7587 ill_t *
7588 ip_newroute_get_dst_ill(ill_t *dst_ill)
7589 {
7590 	ill_t *ill;
7591 
7592 	/*
7593 	 * We schedule irrespective of whether the source address is
7594 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7595 	 */
7596 	ill = illgrp_scheduler(dst_ill);
7597 	if (ill == NULL)
7598 		return (NULL);
7599 
7600 	/*
7601 	 * For groups with names ip_sioctl_groupname ensures that all
7602 	 * ills are of same type. For groups without names, ifgrp_insert
7603 	 * ensures this.
7604 	 */
7605 	ASSERT(dst_ill->ill_type == ill->ill_type);
7606 
7607 	return (ill);
7608 }
7609 
7610 /*
7611  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7612  */
7613 ill_t *
7614 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7615     ip_stack_t *ipst)
7616 {
7617 	ill_t *ret_ill;
7618 
7619 	ASSERT(ifindex != 0);
7620 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7621 	    ipst);
7622 	if (ret_ill == NULL ||
7623 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7624 		if (isv6) {
7625 			if (ill != NULL) {
7626 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7627 			} else {
7628 				BUMP_MIB(&ipst->ips_ip6_mib,
7629 				    ipIfStatsOutDiscards);
7630 			}
7631 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7632 			    "bad ifindex %d.\n", ifindex));
7633 		} else {
7634 			if (ill != NULL) {
7635 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7636 			} else {
7637 				BUMP_MIB(&ipst->ips_ip_mib,
7638 				    ipIfStatsOutDiscards);
7639 			}
7640 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7641 			    "bad ifindex %d.\n", ifindex));
7642 		}
7643 		if (ret_ill != NULL)
7644 			ill_refrele(ret_ill);
7645 		freemsg(first_mp);
7646 		return (NULL);
7647 	}
7648 
7649 	return (ret_ill);
7650 }
7651 
7652 /*
7653  * IPv4 -
7654  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7655  * out a packet to a destination address for which we do not have specific
7656  * (or sufficient) routing information.
7657  *
7658  * NOTE : These are the scopes of some of the variables that point at IRE,
7659  *	  which needs to be followed while making any future modifications
7660  *	  to avoid memory leaks.
7661  *
7662  *	- ire and sire are the entries looked up initially by
7663  *	  ire_ftable_lookup.
7664  *	- ipif_ire is used to hold the interface ire associated with
7665  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7666  *	  it before branching out to error paths.
7667  *	- save_ire is initialized before ire_create, so that ire returned
7668  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7669  *	  before breaking out of the switch.
7670  *
7671  *	Thus on failures, we have to REFRELE only ire and sire, if they
7672  *	are not NULL.
7673  */
7674 void
7675 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7676     zoneid_t zoneid, ip_stack_t *ipst)
7677 {
7678 	areq_t	*areq;
7679 	ipaddr_t gw = 0;
7680 	ire_t	*ire = NULL;
7681 	mblk_t	*res_mp;
7682 	ipaddr_t *addrp;
7683 	ipaddr_t nexthop_addr;
7684 	ipif_t  *src_ipif = NULL;
7685 	ill_t	*dst_ill = NULL;
7686 	ipha_t  *ipha;
7687 	ire_t	*sire = NULL;
7688 	mblk_t	*first_mp;
7689 	ire_t	*save_ire;
7690 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7691 	ushort_t ire_marks = 0;
7692 	boolean_t mctl_present;
7693 	ipsec_out_t *io;
7694 	mblk_t	*saved_mp;
7695 	ire_t	*first_sire = NULL;
7696 	mblk_t	*copy_mp = NULL;
7697 	mblk_t	*xmit_mp = NULL;
7698 	ipaddr_t save_dst;
7699 	uint32_t multirt_flags =
7700 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7701 	boolean_t multirt_is_resolvable;
7702 	boolean_t multirt_resolve_next;
7703 	boolean_t do_attach_ill = B_FALSE;
7704 	boolean_t ip_nexthop = B_FALSE;
7705 	tsol_ire_gw_secattr_t *attrp = NULL;
7706 	tsol_gcgrp_t *gcgrp = NULL;
7707 	tsol_gcgrp_addr_t ga;
7708 
7709 	if (ip_debug > 2) {
7710 		/* ip1dbg */
7711 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7712 	}
7713 
7714 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7715 	if (mctl_present) {
7716 		io = (ipsec_out_t *)first_mp->b_rptr;
7717 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7718 		ASSERT(zoneid == io->ipsec_out_zoneid);
7719 		ASSERT(zoneid != ALL_ZONES);
7720 	}
7721 
7722 	ipha = (ipha_t *)mp->b_rptr;
7723 
7724 	/* All multicast lookups come through ip_newroute_ipif() */
7725 	if (CLASSD(dst)) {
7726 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7727 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7728 		freemsg(first_mp);
7729 		return;
7730 	}
7731 
7732 	if (mctl_present && io->ipsec_out_attach_if) {
7733 		/* ip_grab_attach_ill returns a held ill */
7734 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7735 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7736 
7737 		/* Failure case frees things for us. */
7738 		if (attach_ill == NULL)
7739 			return;
7740 
7741 		/*
7742 		 * Check if we need an ire that will not be
7743 		 * looked up by anybody else i.e. HIDDEN.
7744 		 */
7745 		if (ill_is_probeonly(attach_ill))
7746 			ire_marks = IRE_MARK_HIDDEN;
7747 	}
7748 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7749 		ip_nexthop = B_TRUE;
7750 		nexthop_addr = io->ipsec_out_nexthop_addr;
7751 	}
7752 	/*
7753 	 * If this IRE is created for forwarding or it is not for
7754 	 * traffic for congestion controlled protocols, mark it as temporary.
7755 	 */
7756 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7757 		ire_marks |= IRE_MARK_TEMPORARY;
7758 
7759 	/*
7760 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7761 	 * chain until it gets the most specific information available.
7762 	 * For example, we know that there is no IRE_CACHE for this dest,
7763 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7764 	 * ire_ftable_lookup will look up the gateway, etc.
7765 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7766 	 * to the destination, of equal netmask length in the forward table,
7767 	 * will be recursively explored. If no information is available
7768 	 * for the final gateway of that route, we force the returned ire
7769 	 * to be equal to sire using MATCH_IRE_PARENT.
7770 	 * At least, in this case we have a starting point (in the buckets)
7771 	 * to look for other routes to the destination in the forward table.
7772 	 * This is actually used only for multirouting, where a list
7773 	 * of routes has to be processed in sequence.
7774 	 *
7775 	 * In the process of coming up with the most specific information,
7776 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7777 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7778 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7779 	 * Two caveats when handling incomplete ire's in ip_newroute:
7780 	 * - we should be careful when accessing its ire_nce (specifically
7781 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7782 	 * - not all legacy code path callers are prepared to handle
7783 	 *   incomplete ire's, so we should not create/add incomplete
7784 	 *   ire_cache entries here. (See discussion about temporary solution
7785 	 *   further below).
7786 	 *
7787 	 * In order to minimize packet dropping, and to preserve existing
7788 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7789 	 * gateway, and instead use the IF_RESOLVER ire to send out
7790 	 * another request to ARP (this is achieved by passing the
7791 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7792 	 * arp response comes back in ip_wput_nondata, we will create
7793 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7794 	 *
7795 	 * Note that this is a temporary solution; the correct solution is
7796 	 * to create an incomplete  per-dst ire_cache entry, and send the
7797 	 * packet out when the gw's nce is resolved. In order to achieve this,
7798 	 * all packet processing must have been completed prior to calling
7799 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7800 	 * to be modified to accomodate this solution.
7801 	 */
7802 	if (ip_nexthop) {
7803 		/*
7804 		 * The first time we come here, we look for an IRE_INTERFACE
7805 		 * entry for the specified nexthop, set the dst to be the
7806 		 * nexthop address and create an IRE_CACHE entry for the
7807 		 * nexthop. The next time around, we are able to find an
7808 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7809 		 * nexthop address and create an IRE_CACHE entry for the
7810 		 * destination address via the specified nexthop.
7811 		 */
7812 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7813 		    MBLK_GETLABEL(mp), ipst);
7814 		if (ire != NULL) {
7815 			gw = nexthop_addr;
7816 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7817 		} else {
7818 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7819 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7820 			    MBLK_GETLABEL(mp),
7821 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7822 			    ipst);
7823 			if (ire != NULL) {
7824 				dst = nexthop_addr;
7825 			}
7826 		}
7827 	} else if (attach_ill == NULL) {
7828 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7829 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7830 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7831 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7832 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7833 		    ipst);
7834 	} else {
7835 		/*
7836 		 * attach_ill is set only for communicating with
7837 		 * on-link hosts. So, don't look for DEFAULT.
7838 		 */
7839 		ipif_t	*attach_ipif;
7840 
7841 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7842 		if (attach_ipif == NULL) {
7843 			ill_refrele(attach_ill);
7844 			goto icmp_err_ret;
7845 		}
7846 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7847 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7848 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7849 		    MATCH_IRE_SECATTR, ipst);
7850 		ipif_refrele(attach_ipif);
7851 	}
7852 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7853 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7854 
7855 	/*
7856 	 * This loop is run only once in most cases.
7857 	 * We loop to resolve further routes only when the destination
7858 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7859 	 */
7860 	do {
7861 		/* Clear the previous iteration's values */
7862 		if (src_ipif != NULL) {
7863 			ipif_refrele(src_ipif);
7864 			src_ipif = NULL;
7865 		}
7866 		if (dst_ill != NULL) {
7867 			ill_refrele(dst_ill);
7868 			dst_ill = NULL;
7869 		}
7870 
7871 		multirt_resolve_next = B_FALSE;
7872 		/*
7873 		 * We check if packets have to be multirouted.
7874 		 * In this case, given the current <ire, sire> couple,
7875 		 * we look for the next suitable <ire, sire>.
7876 		 * This check is done in ire_multirt_lookup(),
7877 		 * which applies various criteria to find the next route
7878 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7879 		 * unchanged if it detects it has not been tried yet.
7880 		 */
7881 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7882 			ip3dbg(("ip_newroute: starting next_resolution "
7883 			    "with first_mp %p, tag %d\n",
7884 			    (void *)first_mp,
7885 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7886 
7887 			ASSERT(sire != NULL);
7888 			multirt_is_resolvable =
7889 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7890 			    MBLK_GETLABEL(mp), ipst);
7891 
7892 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7893 			    "ire %p, sire %p\n",
7894 			    multirt_is_resolvable,
7895 			    (void *)ire, (void *)sire));
7896 
7897 			if (!multirt_is_resolvable) {
7898 				/*
7899 				 * No more multirt route to resolve; give up
7900 				 * (all routes resolved or no more
7901 				 * resolvable routes).
7902 				 */
7903 				if (ire != NULL) {
7904 					ire_refrele(ire);
7905 					ire = NULL;
7906 				}
7907 			} else {
7908 				ASSERT(sire != NULL);
7909 				ASSERT(ire != NULL);
7910 				/*
7911 				 * We simply use first_sire as a flag that
7912 				 * indicates if a resolvable multirt route
7913 				 * has already been found.
7914 				 * If it is not the case, we may have to send
7915 				 * an ICMP error to report that the
7916 				 * destination is unreachable.
7917 				 * We do not IRE_REFHOLD first_sire.
7918 				 */
7919 				if (first_sire == NULL) {
7920 					first_sire = sire;
7921 				}
7922 			}
7923 		}
7924 		if (ire == NULL) {
7925 			if (ip_debug > 3) {
7926 				/* ip2dbg */
7927 				pr_addr_dbg("ip_newroute: "
7928 				    "can't resolve %s\n", AF_INET, &dst);
7929 			}
7930 			ip3dbg(("ip_newroute: "
7931 			    "ire %p, sire %p, first_sire %p\n",
7932 			    (void *)ire, (void *)sire, (void *)first_sire));
7933 
7934 			if (sire != NULL) {
7935 				ire_refrele(sire);
7936 				sire = NULL;
7937 			}
7938 
7939 			if (first_sire != NULL) {
7940 				/*
7941 				 * At least one multirt route has been found
7942 				 * in the same call to ip_newroute();
7943 				 * there is no need to report an ICMP error.
7944 				 * first_sire was not IRE_REFHOLDed.
7945 				 */
7946 				MULTIRT_DEBUG_UNTAG(first_mp);
7947 				freemsg(first_mp);
7948 				return;
7949 			}
7950 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
7951 			    RTA_DST, ipst);
7952 			if (attach_ill != NULL)
7953 				ill_refrele(attach_ill);
7954 			goto icmp_err_ret;
7955 		}
7956 
7957 		/*
7958 		 * Verify that the returned IRE does not have either
7959 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
7960 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
7961 		 */
7962 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
7963 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
7964 			if (attach_ill != NULL)
7965 				ill_refrele(attach_ill);
7966 			goto icmp_err_ret;
7967 		}
7968 		/*
7969 		 * Increment the ire_ob_pkt_count field for ire if it is an
7970 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
7971 		 * increment the same for the parent IRE, sire, if it is some
7972 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
7973 		 */
7974 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
7975 			UPDATE_OB_PKT_COUNT(ire);
7976 			ire->ire_last_used_time = lbolt;
7977 		}
7978 
7979 		if (sire != NULL) {
7980 			gw = sire->ire_gateway_addr;
7981 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
7982 			    IRE_INTERFACE)) == 0);
7983 			UPDATE_OB_PKT_COUNT(sire);
7984 			sire->ire_last_used_time = lbolt;
7985 		}
7986 		/*
7987 		 * We have a route to reach the destination.
7988 		 *
7989 		 * 1) If the interface is part of ill group, try to get a new
7990 		 *    ill taking load spreading into account.
7991 		 *
7992 		 * 2) After selecting the ill, get a source address that
7993 		 *    might create good inbound load spreading.
7994 		 *    ipif_select_source does this for us.
7995 		 *
7996 		 * If the application specified the ill (ifindex), we still
7997 		 * load spread. Only if the packets needs to go out
7998 		 * specifically on a given ill e.g. binding to
7999 		 * IPIF_NOFAILOVER address, then we don't try to use a
8000 		 * different ill for load spreading.
8001 		 */
8002 		if (attach_ill == NULL) {
8003 			/*
8004 			 * Don't perform outbound load spreading in the
8005 			 * case of an RTF_MULTIRT route, as we actually
8006 			 * typically want to replicate outgoing packets
8007 			 * through particular interfaces.
8008 			 */
8009 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8010 				dst_ill = ire->ire_ipif->ipif_ill;
8011 				/* for uniformity */
8012 				ill_refhold(dst_ill);
8013 			} else {
8014 				/*
8015 				 * If we are here trying to create an IRE_CACHE
8016 				 * for an offlink destination and have the
8017 				 * IRE_CACHE for the next hop and the latter is
8018 				 * using virtual IP source address selection i.e
8019 				 * it's ire->ire_ipif is pointing to a virtual
8020 				 * network interface (vni) then
8021 				 * ip_newroute_get_dst_ll() will return the vni
8022 				 * interface as the dst_ill. Since the vni is
8023 				 * virtual i.e not associated with any physical
8024 				 * interface, it cannot be the dst_ill, hence
8025 				 * in such a case call ip_newroute_get_dst_ll()
8026 				 * with the stq_ill instead of the ire_ipif ILL.
8027 				 * The function returns a refheld ill.
8028 				 */
8029 				if ((ire->ire_type == IRE_CACHE) &&
8030 				    IS_VNI(ire->ire_ipif->ipif_ill))
8031 					dst_ill = ip_newroute_get_dst_ill(
8032 					    ire->ire_stq->q_ptr);
8033 				else
8034 					dst_ill = ip_newroute_get_dst_ill(
8035 					    ire->ire_ipif->ipif_ill);
8036 			}
8037 			if (dst_ill == NULL) {
8038 				if (ip_debug > 2) {
8039 					pr_addr_dbg("ip_newroute: "
8040 					    "no dst ill for dst"
8041 					    " %s\n", AF_INET, &dst);
8042 				}
8043 				goto icmp_err_ret;
8044 			}
8045 		} else {
8046 			dst_ill = ire->ire_ipif->ipif_ill;
8047 			/* for uniformity */
8048 			ill_refhold(dst_ill);
8049 			/*
8050 			 * We should have found a route matching ill as we
8051 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8052 			 * Rather than asserting, when there is a mismatch,
8053 			 * we just drop the packet.
8054 			 */
8055 			if (dst_ill != attach_ill) {
8056 				ip0dbg(("ip_newroute: Packet dropped as "
8057 				    "IPIF_NOFAILOVER ill is %s, "
8058 				    "ire->ire_ipif->ipif_ill is %s\n",
8059 				    attach_ill->ill_name,
8060 				    dst_ill->ill_name));
8061 				ill_refrele(attach_ill);
8062 				goto icmp_err_ret;
8063 			}
8064 		}
8065 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8066 		if (attach_ill != NULL) {
8067 			ill_refrele(attach_ill);
8068 			attach_ill = NULL;
8069 			do_attach_ill = B_TRUE;
8070 		}
8071 		ASSERT(dst_ill != NULL);
8072 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8073 
8074 		/*
8075 		 * Pick the best source address from dst_ill.
8076 		 *
8077 		 * 1) If it is part of a multipathing group, we would
8078 		 *    like to spread the inbound packets across different
8079 		 *    interfaces. ipif_select_source picks a random source
8080 		 *    across the different ills in the group.
8081 		 *
8082 		 * 2) If it is not part of a multipathing group, we try
8083 		 *    to pick the source address from the destination
8084 		 *    route. Clustering assumes that when we have multiple
8085 		 *    prefixes hosted on an interface, the prefix of the
8086 		 *    source address matches the prefix of the destination
8087 		 *    route. We do this only if the address is not
8088 		 *    DEPRECATED.
8089 		 *
8090 		 * 3) If the conn is in a different zone than the ire, we
8091 		 *    need to pick a source address from the right zone.
8092 		 *
8093 		 * NOTE : If we hit case (1) above, the prefix of the source
8094 		 *	  address picked may not match the prefix of the
8095 		 *	  destination routes prefix as ipif_select_source
8096 		 *	  does not look at "dst" while picking a source
8097 		 *	  address.
8098 		 *	  If we want the same behavior as (2), we will need
8099 		 *	  to change the behavior of ipif_select_source.
8100 		 */
8101 		ASSERT(src_ipif == NULL);
8102 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8103 			/*
8104 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8105 			 * Check that the ipif matching the requested source
8106 			 * address still exists.
8107 			 */
8108 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8109 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8110 		}
8111 		if (src_ipif == NULL) {
8112 			ire_marks |= IRE_MARK_USESRC_CHECK;
8113 			if ((dst_ill->ill_group != NULL) ||
8114 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8115 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8116 			    ire->ire_zoneid != ALL_ZONES) ||
8117 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8118 				/*
8119 				 * If the destination is reachable via a
8120 				 * given gateway, the selected source address
8121 				 * should be in the same subnet as the gateway.
8122 				 * Otherwise, the destination is not reachable.
8123 				 *
8124 				 * If there are no interfaces on the same subnet
8125 				 * as the destination, ipif_select_source gives
8126 				 * first non-deprecated interface which might be
8127 				 * on a different subnet than the gateway.
8128 				 * This is not desirable. Hence pass the dst_ire
8129 				 * source address to ipif_select_source.
8130 				 * It is sure that the destination is reachable
8131 				 * with the dst_ire source address subnet.
8132 				 * So passing dst_ire source address to
8133 				 * ipif_select_source will make sure that the
8134 				 * selected source will be on the same subnet
8135 				 * as dst_ire source address.
8136 				 */
8137 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8138 				src_ipif = ipif_select_source(dst_ill, saddr,
8139 				    zoneid);
8140 				if (src_ipif == NULL) {
8141 					if (ip_debug > 2) {
8142 						pr_addr_dbg("ip_newroute: "
8143 						    "no src for dst %s ",
8144 						    AF_INET, &dst);
8145 						printf("through interface %s\n",
8146 						    dst_ill->ill_name);
8147 					}
8148 					goto icmp_err_ret;
8149 				}
8150 			} else {
8151 				src_ipif = ire->ire_ipif;
8152 				ASSERT(src_ipif != NULL);
8153 				/* hold src_ipif for uniformity */
8154 				ipif_refhold(src_ipif);
8155 			}
8156 		}
8157 
8158 		/*
8159 		 * Assign a source address while we have the conn.
8160 		 * We can't have ip_wput_ire pick a source address when the
8161 		 * packet returns from arp since we need to look at
8162 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8163 		 * going through arp.
8164 		 *
8165 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8166 		 *	  it uses ip6i to store this information.
8167 		 */
8168 		if (ipha->ipha_src == INADDR_ANY &&
8169 		    (connp == NULL || !connp->conn_unspec_src)) {
8170 			ipha->ipha_src = src_ipif->ipif_src_addr;
8171 		}
8172 		if (ip_debug > 3) {
8173 			/* ip2dbg */
8174 			pr_addr_dbg("ip_newroute: first hop %s\n",
8175 			    AF_INET, &gw);
8176 		}
8177 		ip2dbg(("\tire type %s (%d)\n",
8178 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8179 
8180 		/*
8181 		 * The TTL of multirouted packets is bounded by the
8182 		 * ip_multirt_ttl ndd variable.
8183 		 */
8184 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8185 			/* Force TTL of multirouted packets */
8186 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8187 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8188 				ip2dbg(("ip_newroute: forcing multirt TTL "
8189 				    "to %d (was %d), dst 0x%08x\n",
8190 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8191 				    ntohl(sire->ire_addr)));
8192 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8193 			}
8194 		}
8195 		/*
8196 		 * At this point in ip_newroute(), ire is either the
8197 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8198 		 * destination or an IRE_INTERFACE type that should be used
8199 		 * to resolve an on-subnet destination or an on-subnet
8200 		 * next-hop gateway.
8201 		 *
8202 		 * In the IRE_CACHE case, we have the following :
8203 		 *
8204 		 * 1) src_ipif - used for getting a source address.
8205 		 *
8206 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8207 		 *    means packets using this IRE_CACHE will go out on
8208 		 *    dst_ill.
8209 		 *
8210 		 * 3) The IRE sire will point to the prefix that is the
8211 		 *    longest  matching route for the destination. These
8212 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8213 		 *
8214 		 *    The newly created IRE_CACHE entry for the off-subnet
8215 		 *    destination is tied to both the prefix route and the
8216 		 *    interface route used to resolve the next-hop gateway
8217 		 *    via the ire_phandle and ire_ihandle fields,
8218 		 *    respectively.
8219 		 *
8220 		 * In the IRE_INTERFACE case, we have the following :
8221 		 *
8222 		 * 1) src_ipif - used for getting a source address.
8223 		 *
8224 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8225 		 *    means packets using the IRE_CACHE that we will build
8226 		 *    here will go out on dst_ill.
8227 		 *
8228 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8229 		 *    to be created will only be tied to the IRE_INTERFACE
8230 		 *    that was derived from the ire_ihandle field.
8231 		 *
8232 		 *    If sire is non-NULL, it means the destination is
8233 		 *    off-link and we will first create the IRE_CACHE for the
8234 		 *    gateway. Next time through ip_newroute, we will create
8235 		 *    the IRE_CACHE for the final destination as described
8236 		 *    above.
8237 		 *
8238 		 * In both cases, after the current resolution has been
8239 		 * completed (or possibly initialised, in the IRE_INTERFACE
8240 		 * case), the loop may be re-entered to attempt the resolution
8241 		 * of another RTF_MULTIRT route.
8242 		 *
8243 		 * When an IRE_CACHE entry for the off-subnet destination is
8244 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8245 		 * for further processing in emission loops.
8246 		 */
8247 		save_ire = ire;
8248 		switch (ire->ire_type) {
8249 		case IRE_CACHE: {
8250 			ire_t	*ipif_ire;
8251 
8252 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8253 			if (gw == 0)
8254 				gw = ire->ire_gateway_addr;
8255 			/*
8256 			 * We need 3 ire's to create a new cache ire for an
8257 			 * off-link destination from the cache ire of the
8258 			 * gateway.
8259 			 *
8260 			 *	1. The prefix ire 'sire' (Note that this does
8261 			 *	   not apply to the conn_nexthop_set case)
8262 			 *	2. The cache ire of the gateway 'ire'
8263 			 *	3. The interface ire 'ipif_ire'
8264 			 *
8265 			 * We have (1) and (2). We lookup (3) below.
8266 			 *
8267 			 * If there is no interface route to the gateway,
8268 			 * it is a race condition, where we found the cache
8269 			 * but the interface route has been deleted.
8270 			 */
8271 			if (ip_nexthop) {
8272 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8273 			} else {
8274 				ipif_ire =
8275 				    ire_ihandle_lookup_offlink(ire, sire);
8276 			}
8277 			if (ipif_ire == NULL) {
8278 				ip1dbg(("ip_newroute: "
8279 				    "ire_ihandle_lookup_offlink failed\n"));
8280 				goto icmp_err_ret;
8281 			}
8282 
8283 			/*
8284 			 * Check cached gateway IRE for any security
8285 			 * attributes; if found, associate the gateway
8286 			 * credentials group to the destination IRE.
8287 			 */
8288 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8289 				mutex_enter(&attrp->igsa_lock);
8290 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8291 					GCGRP_REFHOLD(gcgrp);
8292 				mutex_exit(&attrp->igsa_lock);
8293 			}
8294 
8295 			/*
8296 			 * XXX For the source of the resolver mp,
8297 			 * we are using the same DL_UNITDATA_REQ
8298 			 * (from save_ire->ire_nce->nce_res_mp)
8299 			 * though the save_ire is not pointing at the same ill.
8300 			 * This is incorrect. We need to send it up to the
8301 			 * resolver to get the right res_mp. For ethernets
8302 			 * this may be okay (ill_type == DL_ETHER).
8303 			 */
8304 
8305 			ire = ire_create(
8306 			    (uchar_t *)&dst,		/* dest address */
8307 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8308 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8309 			    (uchar_t *)&gw,		/* gateway address */
8310 			    &save_ire->ire_max_frag,
8311 			    save_ire->ire_nce,		/* src nce */
8312 			    dst_ill->ill_rq,		/* recv-from queue */
8313 			    dst_ill->ill_wq,		/* send-to queue */
8314 			    IRE_CACHE,			/* IRE type */
8315 			    src_ipif,
8316 			    (sire != NULL) ?
8317 			    sire->ire_mask : 0, 	/* Parent mask */
8318 			    (sire != NULL) ?
8319 			    sire->ire_phandle : 0,	/* Parent handle */
8320 			    ipif_ire->ire_ihandle,	/* Interface handle */
8321 			    (sire != NULL) ? (sire->ire_flags &
8322 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8323 			    (sire != NULL) ?
8324 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8325 			    NULL,
8326 			    gcgrp,
8327 			    ipst);
8328 
8329 			if (ire == NULL) {
8330 				if (gcgrp != NULL) {
8331 					GCGRP_REFRELE(gcgrp);
8332 					gcgrp = NULL;
8333 				}
8334 				ire_refrele(ipif_ire);
8335 				ire_refrele(save_ire);
8336 				break;
8337 			}
8338 
8339 			/* reference now held by IRE */
8340 			gcgrp = NULL;
8341 
8342 			ire->ire_marks |= ire_marks;
8343 
8344 			/*
8345 			 * Prevent sire and ipif_ire from getting deleted.
8346 			 * The newly created ire is tied to both of them via
8347 			 * the phandle and ihandle respectively.
8348 			 */
8349 			if (sire != NULL) {
8350 				IRB_REFHOLD(sire->ire_bucket);
8351 				/* Has it been removed already ? */
8352 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8353 					IRB_REFRELE(sire->ire_bucket);
8354 					ire_refrele(ipif_ire);
8355 					ire_refrele(save_ire);
8356 					break;
8357 				}
8358 			}
8359 
8360 			IRB_REFHOLD(ipif_ire->ire_bucket);
8361 			/* Has it been removed already ? */
8362 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8363 				IRB_REFRELE(ipif_ire->ire_bucket);
8364 				if (sire != NULL)
8365 					IRB_REFRELE(sire->ire_bucket);
8366 				ire_refrele(ipif_ire);
8367 				ire_refrele(save_ire);
8368 				break;
8369 			}
8370 
8371 			xmit_mp = first_mp;
8372 			/*
8373 			 * In the case of multirouting, a copy
8374 			 * of the packet is done before its sending.
8375 			 * The copy is used to attempt another
8376 			 * route resolution, in a next loop.
8377 			 */
8378 			if (ire->ire_flags & RTF_MULTIRT) {
8379 				copy_mp = copymsg(first_mp);
8380 				if (copy_mp != NULL) {
8381 					xmit_mp = copy_mp;
8382 					MULTIRT_DEBUG_TAG(first_mp);
8383 				}
8384 			}
8385 			ire_add_then_send(q, ire, xmit_mp);
8386 			ire_refrele(save_ire);
8387 
8388 			/* Assert that sire is not deleted yet. */
8389 			if (sire != NULL) {
8390 				ASSERT(sire->ire_ptpn != NULL);
8391 				IRB_REFRELE(sire->ire_bucket);
8392 			}
8393 
8394 			/* Assert that ipif_ire is not deleted yet. */
8395 			ASSERT(ipif_ire->ire_ptpn != NULL);
8396 			IRB_REFRELE(ipif_ire->ire_bucket);
8397 			ire_refrele(ipif_ire);
8398 
8399 			/*
8400 			 * If copy_mp is not NULL, multirouting was
8401 			 * requested. We loop to initiate a next
8402 			 * route resolution attempt, starting from sire.
8403 			 */
8404 			if (copy_mp != NULL) {
8405 				/*
8406 				 * Search for the next unresolved
8407 				 * multirt route.
8408 				 */
8409 				copy_mp = NULL;
8410 				ipif_ire = NULL;
8411 				ire = NULL;
8412 				multirt_resolve_next = B_TRUE;
8413 				continue;
8414 			}
8415 			if (sire != NULL)
8416 				ire_refrele(sire);
8417 			ipif_refrele(src_ipif);
8418 			ill_refrele(dst_ill);
8419 			return;
8420 		}
8421 		case IRE_IF_NORESOLVER: {
8422 
8423 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8424 			    dst_ill->ill_resolver_mp == NULL) {
8425 				ip1dbg(("ip_newroute: dst_ill %p "
8426 				    "for IRE_IF_NORESOLVER ire %p has "
8427 				    "no ill_resolver_mp\n",
8428 				    (void *)dst_ill, (void *)ire));
8429 				break;
8430 			}
8431 
8432 			/*
8433 			 * TSol note: We are creating the ire cache for the
8434 			 * destination 'dst'. If 'dst' is offlink, going
8435 			 * through the first hop 'gw', the security attributes
8436 			 * of 'dst' must be set to point to the gateway
8437 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8438 			 * is possible that 'dst' is a potential gateway that is
8439 			 * referenced by some route that has some security
8440 			 * attributes. Thus in the former case, we need to do a
8441 			 * gcgrp_lookup of 'gw' while in the latter case we
8442 			 * need to do gcgrp_lookup of 'dst' itself.
8443 			 */
8444 			ga.ga_af = AF_INET;
8445 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8446 			    &ga.ga_addr);
8447 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8448 
8449 			ire = ire_create(
8450 			    (uchar_t *)&dst,		/* dest address */
8451 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8452 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8453 			    (uchar_t *)&gw,		/* gateway address */
8454 			    &save_ire->ire_max_frag,
8455 			    NULL,			/* no src nce */
8456 			    dst_ill->ill_rq,		/* recv-from queue */
8457 			    dst_ill->ill_wq,		/* send-to queue */
8458 			    IRE_CACHE,
8459 			    src_ipif,
8460 			    save_ire->ire_mask,		/* Parent mask */
8461 			    (sire != NULL) ?		/* Parent handle */
8462 			    sire->ire_phandle : 0,
8463 			    save_ire->ire_ihandle,	/* Interface handle */
8464 			    (sire != NULL) ? sire->ire_flags &
8465 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8466 			    &(save_ire->ire_uinfo),
8467 			    NULL,
8468 			    gcgrp,
8469 			    ipst);
8470 
8471 			if (ire == NULL) {
8472 				if (gcgrp != NULL) {
8473 					GCGRP_REFRELE(gcgrp);
8474 					gcgrp = NULL;
8475 				}
8476 				ire_refrele(save_ire);
8477 				break;
8478 			}
8479 
8480 			/* reference now held by IRE */
8481 			gcgrp = NULL;
8482 
8483 			ire->ire_marks |= ire_marks;
8484 
8485 			/* Prevent save_ire from getting deleted */
8486 			IRB_REFHOLD(save_ire->ire_bucket);
8487 			/* Has it been removed already ? */
8488 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8489 				IRB_REFRELE(save_ire->ire_bucket);
8490 				ire_refrele(save_ire);
8491 				break;
8492 			}
8493 
8494 			/*
8495 			 * In the case of multirouting, a copy
8496 			 * of the packet is made before it is sent.
8497 			 * The copy is used in the next
8498 			 * loop to attempt another resolution.
8499 			 */
8500 			xmit_mp = first_mp;
8501 			if ((sire != NULL) &&
8502 			    (sire->ire_flags & RTF_MULTIRT)) {
8503 				copy_mp = copymsg(first_mp);
8504 				if (copy_mp != NULL) {
8505 					xmit_mp = copy_mp;
8506 					MULTIRT_DEBUG_TAG(first_mp);
8507 				}
8508 			}
8509 			ire_add_then_send(q, ire, xmit_mp);
8510 
8511 			/* Assert that it is not deleted yet. */
8512 			ASSERT(save_ire->ire_ptpn != NULL);
8513 			IRB_REFRELE(save_ire->ire_bucket);
8514 			ire_refrele(save_ire);
8515 
8516 			if (copy_mp != NULL) {
8517 				/*
8518 				 * If we found a (no)resolver, we ignore any
8519 				 * trailing top priority IRE_CACHE in further
8520 				 * loops. This ensures that we do not omit any
8521 				 * (no)resolver.
8522 				 * This IRE_CACHE, if any, will be processed
8523 				 * by another thread entering ip_newroute().
8524 				 * IRE_CACHE entries, if any, will be processed
8525 				 * by another thread entering ip_newroute(),
8526 				 * (upon resolver response, for instance).
8527 				 * This aims to force parallel multirt
8528 				 * resolutions as soon as a packet must be sent.
8529 				 * In the best case, after the tx of only one
8530 				 * packet, all reachable routes are resolved.
8531 				 * Otherwise, the resolution of all RTF_MULTIRT
8532 				 * routes would require several emissions.
8533 				 */
8534 				multirt_flags &= ~MULTIRT_CACHEGW;
8535 
8536 				/*
8537 				 * Search for the next unresolved multirt
8538 				 * route.
8539 				 */
8540 				copy_mp = NULL;
8541 				save_ire = NULL;
8542 				ire = NULL;
8543 				multirt_resolve_next = B_TRUE;
8544 				continue;
8545 			}
8546 
8547 			/*
8548 			 * Don't need sire anymore
8549 			 */
8550 			if (sire != NULL)
8551 				ire_refrele(sire);
8552 
8553 			ipif_refrele(src_ipif);
8554 			ill_refrele(dst_ill);
8555 			return;
8556 		}
8557 		case IRE_IF_RESOLVER:
8558 			/*
8559 			 * We can't build an IRE_CACHE yet, but at least we
8560 			 * found a resolver that can help.
8561 			 */
8562 			res_mp = dst_ill->ill_resolver_mp;
8563 			if (!OK_RESOLVER_MP(res_mp))
8564 				break;
8565 
8566 			/*
8567 			 * To be at this point in the code with a non-zero gw
8568 			 * means that dst is reachable through a gateway that
8569 			 * we have never resolved.  By changing dst to the gw
8570 			 * addr we resolve the gateway first.
8571 			 * When ire_add_then_send() tries to put the IP dg
8572 			 * to dst, it will reenter ip_newroute() at which
8573 			 * time we will find the IRE_CACHE for the gw and
8574 			 * create another IRE_CACHE in case IRE_CACHE above.
8575 			 */
8576 			if (gw != INADDR_ANY) {
8577 				/*
8578 				 * The source ipif that was determined above was
8579 				 * relative to the destination address, not the
8580 				 * gateway's. If src_ipif was not taken out of
8581 				 * the IRE_IF_RESOLVER entry, we'll need to call
8582 				 * ipif_select_source() again.
8583 				 */
8584 				if (src_ipif != ire->ire_ipif) {
8585 					ipif_refrele(src_ipif);
8586 					src_ipif = ipif_select_source(dst_ill,
8587 					    gw, zoneid);
8588 					if (src_ipif == NULL) {
8589 						if (ip_debug > 2) {
8590 							pr_addr_dbg(
8591 							    "ip_newroute: no "
8592 							    "src for gw %s ",
8593 							    AF_INET, &gw);
8594 							printf("through "
8595 							    "interface %s\n",
8596 							    dst_ill->ill_name);
8597 						}
8598 						goto icmp_err_ret;
8599 					}
8600 				}
8601 				save_dst = dst;
8602 				dst = gw;
8603 				gw = INADDR_ANY;
8604 			}
8605 
8606 			/*
8607 			 * We obtain a partial IRE_CACHE which we will pass
8608 			 * along with the resolver query.  When the response
8609 			 * comes back it will be there ready for us to add.
8610 			 * The ire_max_frag is atomically set under the
8611 			 * irebucket lock in ire_add_v[46].
8612 			 */
8613 
8614 			ire = ire_create_mp(
8615 			    (uchar_t *)&dst,		/* dest address */
8616 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8617 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8618 			    (uchar_t *)&gw,		/* gateway address */
8619 			    NULL,			/* ire_max_frag */
8620 			    NULL,			/* no src nce */
8621 			    dst_ill->ill_rq,		/* recv-from queue */
8622 			    dst_ill->ill_wq,		/* send-to queue */
8623 			    IRE_CACHE,
8624 			    src_ipif,			/* Interface ipif */
8625 			    save_ire->ire_mask,		/* Parent mask */
8626 			    0,
8627 			    save_ire->ire_ihandle,	/* Interface handle */
8628 			    0,				/* flags if any */
8629 			    &(save_ire->ire_uinfo),
8630 			    NULL,
8631 			    NULL,
8632 			    ipst);
8633 
8634 			if (ire == NULL) {
8635 				ire_refrele(save_ire);
8636 				break;
8637 			}
8638 
8639 			if ((sire != NULL) &&
8640 			    (sire->ire_flags & RTF_MULTIRT)) {
8641 				copy_mp = copymsg(first_mp);
8642 				if (copy_mp != NULL)
8643 					MULTIRT_DEBUG_TAG(copy_mp);
8644 			}
8645 
8646 			ire->ire_marks |= ire_marks;
8647 
8648 			/*
8649 			 * Construct message chain for the resolver
8650 			 * of the form:
8651 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8652 			 * Packet could contain a IPSEC_OUT mp.
8653 			 *
8654 			 * NOTE : ire will be added later when the response
8655 			 * comes back from ARP. If the response does not
8656 			 * come back, ARP frees the packet. For this reason,
8657 			 * we can't REFHOLD the bucket of save_ire to prevent
8658 			 * deletions. We may not be able to REFRELE the bucket
8659 			 * if the response never comes back. Thus, before
8660 			 * adding the ire, ire_add_v4 will make sure that the
8661 			 * interface route does not get deleted. This is the
8662 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8663 			 * where we can always prevent deletions because of
8664 			 * the synchronous nature of adding IRES i.e
8665 			 * ire_add_then_send is called after creating the IRE.
8666 			 */
8667 			ASSERT(ire->ire_mp != NULL);
8668 			ire->ire_mp->b_cont = first_mp;
8669 			/* Have saved_mp handy, for cleanup if canput fails */
8670 			saved_mp = mp;
8671 			mp = copyb(res_mp);
8672 			if (mp == NULL) {
8673 				/* Prepare for cleanup */
8674 				mp = saved_mp; /* pkt */
8675 				ire_delete(ire); /* ire_mp */
8676 				ire = NULL;
8677 				ire_refrele(save_ire);
8678 				if (copy_mp != NULL) {
8679 					MULTIRT_DEBUG_UNTAG(copy_mp);
8680 					freemsg(copy_mp);
8681 					copy_mp = NULL;
8682 				}
8683 				break;
8684 			}
8685 			linkb(mp, ire->ire_mp);
8686 
8687 			/*
8688 			 * Fill in the source and dest addrs for the resolver.
8689 			 * NOTE: this depends on memory layouts imposed by
8690 			 * ill_init().
8691 			 */
8692 			areq = (areq_t *)mp->b_rptr;
8693 			addrp = (ipaddr_t *)((char *)areq +
8694 			    areq->areq_sender_addr_offset);
8695 			if (do_attach_ill) {
8696 				/*
8697 				 * This is bind to no failover case.
8698 				 * arp packet also must go out on attach_ill.
8699 				 */
8700 				ASSERT(ipha->ipha_src != NULL);
8701 				*addrp = ipha->ipha_src;
8702 			} else {
8703 				*addrp = save_ire->ire_src_addr;
8704 			}
8705 
8706 			ire_refrele(save_ire);
8707 			addrp = (ipaddr_t *)((char *)areq +
8708 			    areq->areq_target_addr_offset);
8709 			*addrp = dst;
8710 			/* Up to the resolver. */
8711 			if (canputnext(dst_ill->ill_rq) &&
8712 			    !(dst_ill->ill_arp_closing)) {
8713 				putnext(dst_ill->ill_rq, mp);
8714 				ire = NULL;
8715 				if (copy_mp != NULL) {
8716 					/*
8717 					 * If we found a resolver, we ignore
8718 					 * any trailing top priority IRE_CACHE
8719 					 * in the further loops. This ensures
8720 					 * that we do not omit any resolver.
8721 					 * IRE_CACHE entries, if any, will be
8722 					 * processed next time we enter
8723 					 * ip_newroute().
8724 					 */
8725 					multirt_flags &= ~MULTIRT_CACHEGW;
8726 					/*
8727 					 * Search for the next unresolved
8728 					 * multirt route.
8729 					 */
8730 					first_mp = copy_mp;
8731 					copy_mp = NULL;
8732 					/* Prepare the next resolution loop. */
8733 					mp = first_mp;
8734 					EXTRACT_PKT_MP(mp, first_mp,
8735 					    mctl_present);
8736 					if (mctl_present)
8737 						io = (ipsec_out_t *)
8738 						    first_mp->b_rptr;
8739 					ipha = (ipha_t *)mp->b_rptr;
8740 
8741 					ASSERT(sire != NULL);
8742 
8743 					dst = save_dst;
8744 					multirt_resolve_next = B_TRUE;
8745 					continue;
8746 				}
8747 
8748 				if (sire != NULL)
8749 					ire_refrele(sire);
8750 
8751 				/*
8752 				 * The response will come back in ip_wput
8753 				 * with db_type IRE_DB_TYPE.
8754 				 */
8755 				ipif_refrele(src_ipif);
8756 				ill_refrele(dst_ill);
8757 				return;
8758 			} else {
8759 				/* Prepare for cleanup */
8760 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8761 				    mp);
8762 				mp->b_cont = NULL;
8763 				freeb(mp); /* areq */
8764 				/*
8765 				 * this is an ire that is not added to the
8766 				 * cache. ire_freemblk will handle the release
8767 				 * of any resources associated with the ire.
8768 				 */
8769 				ire_delete(ire); /* ire_mp */
8770 				mp = saved_mp; /* pkt */
8771 				ire = NULL;
8772 				if (copy_mp != NULL) {
8773 					MULTIRT_DEBUG_UNTAG(copy_mp);
8774 					freemsg(copy_mp);
8775 					copy_mp = NULL;
8776 				}
8777 				break;
8778 			}
8779 		default:
8780 			break;
8781 		}
8782 	} while (multirt_resolve_next);
8783 
8784 	ip1dbg(("ip_newroute: dropped\n"));
8785 	/* Did this packet originate externally? */
8786 	if (mp->b_prev) {
8787 		mp->b_next = NULL;
8788 		mp->b_prev = NULL;
8789 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8790 	} else {
8791 		if (dst_ill != NULL) {
8792 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8793 		} else {
8794 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8795 		}
8796 	}
8797 	ASSERT(copy_mp == NULL);
8798 	MULTIRT_DEBUG_UNTAG(first_mp);
8799 	freemsg(first_mp);
8800 	if (ire != NULL)
8801 		ire_refrele(ire);
8802 	if (sire != NULL)
8803 		ire_refrele(sire);
8804 	if (src_ipif != NULL)
8805 		ipif_refrele(src_ipif);
8806 	if (dst_ill != NULL)
8807 		ill_refrele(dst_ill);
8808 	return;
8809 
8810 icmp_err_ret:
8811 	ip1dbg(("ip_newroute: no route\n"));
8812 	if (src_ipif != NULL)
8813 		ipif_refrele(src_ipif);
8814 	if (dst_ill != NULL)
8815 		ill_refrele(dst_ill);
8816 	if (sire != NULL)
8817 		ire_refrele(sire);
8818 	/* Did this packet originate externally? */
8819 	if (mp->b_prev) {
8820 		mp->b_next = NULL;
8821 		mp->b_prev = NULL;
8822 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8823 		q = WR(q);
8824 	} else {
8825 		/*
8826 		 * There is no outgoing ill, so just increment the
8827 		 * system MIB.
8828 		 */
8829 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8830 		/*
8831 		 * Since ip_wput() isn't close to finished, we fill
8832 		 * in enough of the header for credible error reporting.
8833 		 */
8834 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8835 			/* Failed */
8836 			MULTIRT_DEBUG_UNTAG(first_mp);
8837 			freemsg(first_mp);
8838 			if (ire != NULL)
8839 				ire_refrele(ire);
8840 			return;
8841 		}
8842 	}
8843 
8844 	/*
8845 	 * At this point we will have ire only if RTF_BLACKHOLE
8846 	 * or RTF_REJECT flags are set on the IRE. It will not
8847 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8848 	 */
8849 	if (ire != NULL) {
8850 		if (ire->ire_flags & RTF_BLACKHOLE) {
8851 			ire_refrele(ire);
8852 			MULTIRT_DEBUG_UNTAG(first_mp);
8853 			freemsg(first_mp);
8854 			return;
8855 		}
8856 		ire_refrele(ire);
8857 	}
8858 	if (ip_source_routed(ipha, ipst)) {
8859 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8860 		    zoneid, ipst);
8861 		return;
8862 	}
8863 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8864 }
8865 
8866 ip_opt_info_t zero_info;
8867 
8868 /*
8869  * IPv4 -
8870  * ip_newroute_ipif is called by ip_wput_multicast and
8871  * ip_rput_forward_multicast whenever we need to send
8872  * out a packet to a destination address for which we do not have specific
8873  * routing information. It is used when the packet will be sent out
8874  * on a specific interface. It is also called by ip_wput() when IP_XMIT_IF
8875  * socket option is set or icmp error message wants to go out on a particular
8876  * interface for a unicast packet.
8877  *
8878  * In most cases, the destination address is resolved thanks to the ipif
8879  * intrinsic resolver. However, there are some cases where the call to
8880  * ip_newroute_ipif must take into account the potential presence of
8881  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8882  * that uses the interface. This is specified through flags,
8883  * which can be a combination of:
8884  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8885  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8886  *   and flags. Additionally, the packet source address has to be set to
8887  *   the specified address. The caller is thus expected to set this flag
8888  *   if the packet has no specific source address yet.
8889  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8890  *   flag, the resulting ire will inherit the flag. All unresolved routes
8891  *   to the destination must be explored in the same call to
8892  *   ip_newroute_ipif().
8893  */
8894 static void
8895 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8896     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8897 {
8898 	areq_t	*areq;
8899 	ire_t	*ire = NULL;
8900 	mblk_t	*res_mp;
8901 	ipaddr_t *addrp;
8902 	mblk_t *first_mp;
8903 	ire_t	*save_ire = NULL;
8904 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8905 	ipif_t	*src_ipif = NULL;
8906 	ushort_t ire_marks = 0;
8907 	ill_t	*dst_ill = NULL;
8908 	boolean_t mctl_present;
8909 	ipsec_out_t *io;
8910 	ipha_t *ipha;
8911 	int	ihandle = 0;
8912 	mblk_t	*saved_mp;
8913 	ire_t   *fire = NULL;
8914 	mblk_t  *copy_mp = NULL;
8915 	boolean_t multirt_resolve_next;
8916 	ipaddr_t ipha_dst;
8917 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8918 
8919 	/*
8920 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8921 	 * here for uniformity
8922 	 */
8923 	ipif_refhold(ipif);
8924 
8925 	/*
8926 	 * This loop is run only once in most cases.
8927 	 * We loop to resolve further routes only when the destination
8928 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8929 	 */
8930 	do {
8931 		if (dst_ill != NULL) {
8932 			ill_refrele(dst_ill);
8933 			dst_ill = NULL;
8934 		}
8935 		if (src_ipif != NULL) {
8936 			ipif_refrele(src_ipif);
8937 			src_ipif = NULL;
8938 		}
8939 		multirt_resolve_next = B_FALSE;
8940 
8941 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
8942 		    ipif->ipif_ill->ill_name));
8943 
8944 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
8945 		if (mctl_present)
8946 			io = (ipsec_out_t *)first_mp->b_rptr;
8947 
8948 		ipha = (ipha_t *)mp->b_rptr;
8949 
8950 		/*
8951 		 * Save the packet destination address, we may need it after
8952 		 * the packet has been consumed.
8953 		 */
8954 		ipha_dst = ipha->ipha_dst;
8955 
8956 		/*
8957 		 * If the interface is a pt-pt interface we look for an
8958 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
8959 		 * local_address and the pt-pt destination address. Otherwise
8960 		 * we just match the local address.
8961 		 * NOTE: dst could be different than ipha->ipha_dst in case
8962 		 * of sending igmp multicast packets over a point-to-point
8963 		 * connection.
8964 		 * Thus we must be careful enough to check ipha_dst to be a
8965 		 * multicast address, otherwise it will take xmit_if path for
8966 		 * multicast packets resulting into kernel stack overflow by
8967 		 * repeated calls to ip_newroute_ipif from ire_send().
8968 		 */
8969 		if (CLASSD(ipha_dst) &&
8970 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
8971 			goto err_ret;
8972 		}
8973 
8974 		/*
8975 		 * We check if an IRE_OFFSUBNET for the addr that goes through
8976 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
8977 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
8978 		 * propagate its flags to the new ire.
8979 		 */
8980 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
8981 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
8982 			ip2dbg(("ip_newroute_ipif: "
8983 			    "ipif_lookup_multi_ire("
8984 			    "ipif %p, dst %08x) = fire %p\n",
8985 			    (void *)ipif, ntohl(dst), (void *)fire));
8986 		}
8987 
8988 		if (mctl_present && io->ipsec_out_attach_if) {
8989 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
8990 			    io->ipsec_out_ill_index, B_FALSE, ipst);
8991 
8992 			/* Failure case frees things for us. */
8993 			if (attach_ill == NULL) {
8994 				ipif_refrele(ipif);
8995 				if (fire != NULL)
8996 					ire_refrele(fire);
8997 				return;
8998 			}
8999 
9000 			/*
9001 			 * Check if we need an ire that will not be
9002 			 * looked up by anybody else i.e. HIDDEN.
9003 			 */
9004 			if (ill_is_probeonly(attach_ill)) {
9005 				ire_marks = IRE_MARK_HIDDEN;
9006 			}
9007 			/*
9008 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9009 			 * case.
9010 			 */
9011 			dst_ill = ipif->ipif_ill;
9012 			/* attach_ill has been refheld by ip_grab_attach_ill */
9013 			ASSERT(dst_ill == attach_ill);
9014 		} else {
9015 			/*
9016 			 * If this is set by IP_XMIT_IF, then make sure that
9017 			 * ipif is pointing to the same ill as the IP_XMIT_IF
9018 			 * specified ill.
9019 			 */
9020 			ASSERT((connp == NULL) ||
9021 			    (connp->conn_xmit_if_ill == NULL) ||
9022 			    (connp->conn_xmit_if_ill == ipif->ipif_ill));
9023 			/*
9024 			 * If the interface belongs to an interface group,
9025 			 * make sure the next possible interface in the group
9026 			 * is used.  This encourages load spreading among
9027 			 * peers in an interface group.
9028 			 * Note: load spreading is disabled for RTF_MULTIRT
9029 			 * routes.
9030 			 */
9031 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9032 			    (fire->ire_flags & RTF_MULTIRT)) {
9033 				/*
9034 				 * Don't perform outbound load spreading
9035 				 * in the case of an RTF_MULTIRT issued route,
9036 				 * we actually typically want to replicate
9037 				 * outgoing packets through particular
9038 				 * interfaces.
9039 				 */
9040 				dst_ill = ipif->ipif_ill;
9041 				ill_refhold(dst_ill);
9042 			} else {
9043 				dst_ill = ip_newroute_get_dst_ill(
9044 				    ipif->ipif_ill);
9045 			}
9046 			if (dst_ill == NULL) {
9047 				if (ip_debug > 2) {
9048 					pr_addr_dbg("ip_newroute_ipif: "
9049 					    "no dst ill for dst %s\n",
9050 					    AF_INET, &dst);
9051 				}
9052 				goto err_ret;
9053 			}
9054 		}
9055 
9056 		/*
9057 		 * Pick a source address preferring non-deprecated ones.
9058 		 * Unlike ip_newroute, we don't do any source address
9059 		 * selection here since for multicast it really does not help
9060 		 * in inbound load spreading as in the unicast case.
9061 		 */
9062 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9063 		    (fire->ire_flags & RTF_SETSRC)) {
9064 			/*
9065 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9066 			 * on that interface. This ire has RTF_SETSRC flag, so
9067 			 * the source address of the packet must be changed.
9068 			 * Check that the ipif matching the requested source
9069 			 * address still exists.
9070 			 */
9071 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9072 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9073 		}
9074 		if (((ipif->ipif_flags & IPIF_DEPRECATED) ||
9075 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9076 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9077 		    (src_ipif == NULL)) {
9078 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9079 			if (src_ipif == NULL) {
9080 				if (ip_debug > 2) {
9081 					/* ip1dbg */
9082 					pr_addr_dbg("ip_newroute_ipif: "
9083 					    "no src for dst %s",
9084 					    AF_INET, &dst);
9085 				}
9086 				ip1dbg((" through interface %s\n",
9087 				    dst_ill->ill_name));
9088 				goto err_ret;
9089 			}
9090 			ipif_refrele(ipif);
9091 			ipif = src_ipif;
9092 			ipif_refhold(ipif);
9093 		}
9094 		if (src_ipif == NULL) {
9095 			src_ipif = ipif;
9096 			ipif_refhold(src_ipif);
9097 		}
9098 
9099 		/*
9100 		 * Assign a source address while we have the conn.
9101 		 * We can't have ip_wput_ire pick a source address when the
9102 		 * packet returns from arp since conn_unspec_src might be set
9103 		 * and we loose the conn when going through arp.
9104 		 */
9105 		if (ipha->ipha_src == INADDR_ANY &&
9106 		    (connp == NULL || !connp->conn_unspec_src)) {
9107 			ipha->ipha_src = src_ipif->ipif_src_addr;
9108 		}
9109 
9110 		/*
9111 		 * In the case of IP_XMIT_IF, it is possible that the
9112 		 * outgoing interface does not have an interface ire.
9113 		 */
9114 		if (CLASSD(ipha_dst) && (connp == NULL ||
9115 		    connp->conn_xmit_if_ill == NULL) &&
9116 		    infop->ip_opt_ill_index == 0) {
9117 			/* ipif_to_ire returns an held ire */
9118 			ire = ipif_to_ire(ipif);
9119 			if (ire == NULL)
9120 				goto err_ret;
9121 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9122 				goto err_ret;
9123 			/*
9124 			 * ihandle is needed when the ire is added to
9125 			 * cache table.
9126 			 */
9127 			save_ire = ire;
9128 			ihandle = save_ire->ire_ihandle;
9129 
9130 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9131 			    "flags %04x\n",
9132 			    (void *)ire, (void *)ipif, flags));
9133 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9134 			    (fire->ire_flags & RTF_MULTIRT)) {
9135 				/*
9136 				 * As requested by flags, an IRE_OFFSUBNET was
9137 				 * looked up on that interface. This ire has
9138 				 * RTF_MULTIRT flag, so the resolution loop will
9139 				 * be re-entered to resolve additional routes on
9140 				 * other interfaces. For that purpose, a copy of
9141 				 * the packet is performed at this point.
9142 				 */
9143 				fire->ire_last_used_time = lbolt;
9144 				copy_mp = copymsg(first_mp);
9145 				if (copy_mp) {
9146 					MULTIRT_DEBUG_TAG(copy_mp);
9147 				}
9148 			}
9149 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9150 			    (fire->ire_flags & RTF_SETSRC)) {
9151 				/*
9152 				 * As requested by flags, an IRE_OFFSUBET was
9153 				 * looked up on that interface. This ire has
9154 				 * RTF_SETSRC flag, so the source address of the
9155 				 * packet must be changed.
9156 				 */
9157 				ipha->ipha_src = fire->ire_src_addr;
9158 			}
9159 		} else {
9160 			ASSERT((connp == NULL) ||
9161 			    (connp->conn_xmit_if_ill != NULL) ||
9162 			    (connp->conn_dontroute) ||
9163 			    infop->ip_opt_ill_index != 0);
9164 			/*
9165 			 * The only ways we can come here are:
9166 			 * 1) IP_XMIT_IF socket option is set
9167 			 * 2) SO_DONTROUTE socket option is set
9168 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9169 			 * In all cases, the new ire will not be added
9170 			 * into cache table.
9171 			 */
9172 			ire_marks |= IRE_MARK_NOADD;
9173 		}
9174 
9175 		switch (ipif->ipif_net_type) {
9176 		case IRE_IF_NORESOLVER: {
9177 			/* We have what we need to build an IRE_CACHE. */
9178 
9179 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9180 			    (dst_ill->ill_resolver_mp == NULL)) {
9181 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9182 				    "for IRE_IF_NORESOLVER ire %p has "
9183 				    "no ill_resolver_mp\n",
9184 				    (void *)dst_ill, (void *)ire));
9185 				break;
9186 			}
9187 
9188 			/*
9189 			 * The new ire inherits the IRE_OFFSUBNET flags
9190 			 * and source address, if this was requested.
9191 			 */
9192 			ire = ire_create(
9193 			    (uchar_t *)&dst,		/* dest address */
9194 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9195 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9196 			    NULL,			/* gateway address */
9197 			    &ipif->ipif_mtu,
9198 			    NULL,			/* no src nce */
9199 			    dst_ill->ill_rq,		/* recv-from queue */
9200 			    dst_ill->ill_wq,		/* send-to queue */
9201 			    IRE_CACHE,
9202 			    src_ipif,
9203 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9204 			    (fire != NULL) ?		/* Parent handle */
9205 			    fire->ire_phandle : 0,
9206 			    ihandle,			/* Interface handle */
9207 			    (fire != NULL) ?
9208 			    (fire->ire_flags &
9209 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9210 			    (save_ire == NULL ? &ire_uinfo_null :
9211 			    &save_ire->ire_uinfo),
9212 			    NULL,
9213 			    NULL,
9214 			    ipst);
9215 
9216 			if (ire == NULL) {
9217 				if (save_ire != NULL)
9218 					ire_refrele(save_ire);
9219 				break;
9220 			}
9221 
9222 			ire->ire_marks |= ire_marks;
9223 
9224 			/*
9225 			 * If IRE_MARK_NOADD is set then we need to convert
9226 			 * the max_fragp to a useable value now. This is
9227 			 * normally done in ire_add_v[46]. We also need to
9228 			 * associate the ire with an nce (normally would be
9229 			 * done in ip_wput_nondata()).
9230 			 *
9231 			 * Note that IRE_MARK_NOADD packets created here
9232 			 * do not have a non-null ire_mp pointer. The null
9233 			 * value of ire_bucket indicates that they were
9234 			 * never added.
9235 			 */
9236 			if (ire->ire_marks & IRE_MARK_NOADD) {
9237 				uint_t  max_frag;
9238 
9239 				max_frag = *ire->ire_max_fragp;
9240 				ire->ire_max_fragp = NULL;
9241 				ire->ire_max_frag = max_frag;
9242 
9243 				if ((ire->ire_nce = ndp_lookup_v4(
9244 				    ire_to_ill(ire),
9245 				    (ire->ire_gateway_addr != INADDR_ANY ?
9246 				    &ire->ire_gateway_addr : &ire->ire_addr),
9247 				    B_FALSE)) == NULL) {
9248 					if (save_ire != NULL)
9249 						ire_refrele(save_ire);
9250 					break;
9251 				}
9252 				ASSERT(ire->ire_nce->nce_state ==
9253 				    ND_REACHABLE);
9254 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9255 			}
9256 
9257 			/* Prevent save_ire from getting deleted */
9258 			if (save_ire != NULL) {
9259 				IRB_REFHOLD(save_ire->ire_bucket);
9260 				/* Has it been removed already ? */
9261 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9262 					IRB_REFRELE(save_ire->ire_bucket);
9263 					ire_refrele(save_ire);
9264 					break;
9265 				}
9266 			}
9267 
9268 			ire_add_then_send(q, ire, first_mp);
9269 
9270 			/* Assert that save_ire is not deleted yet. */
9271 			if (save_ire != NULL) {
9272 				ASSERT(save_ire->ire_ptpn != NULL);
9273 				IRB_REFRELE(save_ire->ire_bucket);
9274 				ire_refrele(save_ire);
9275 				save_ire = NULL;
9276 			}
9277 			if (fire != NULL) {
9278 				ire_refrele(fire);
9279 				fire = NULL;
9280 			}
9281 
9282 			/*
9283 			 * the resolution loop is re-entered if this
9284 			 * was requested through flags and if we
9285 			 * actually are in a multirouting case.
9286 			 */
9287 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9288 				boolean_t need_resolve =
9289 				    ire_multirt_need_resolve(ipha_dst,
9290 				    MBLK_GETLABEL(copy_mp), ipst);
9291 				if (!need_resolve) {
9292 					MULTIRT_DEBUG_UNTAG(copy_mp);
9293 					freemsg(copy_mp);
9294 					copy_mp = NULL;
9295 				} else {
9296 					/*
9297 					 * ipif_lookup_group() calls
9298 					 * ire_lookup_multi() that uses
9299 					 * ire_ftable_lookup() to find
9300 					 * an IRE_INTERFACE for the group.
9301 					 * In the multirt case,
9302 					 * ire_lookup_multi() then invokes
9303 					 * ire_multirt_lookup() to find
9304 					 * the next resolvable ire.
9305 					 * As a result, we obtain an new
9306 					 * interface, derived from the
9307 					 * next ire.
9308 					 */
9309 					ipif_refrele(ipif);
9310 					ipif = ipif_lookup_group(ipha_dst,
9311 					    zoneid, ipst);
9312 					ip2dbg(("ip_newroute_ipif: "
9313 					    "multirt dst %08x, ipif %p\n",
9314 					    htonl(dst), (void *)ipif));
9315 					if (ipif != NULL) {
9316 						mp = copy_mp;
9317 						copy_mp = NULL;
9318 						multirt_resolve_next = B_TRUE;
9319 						continue;
9320 					} else {
9321 						freemsg(copy_mp);
9322 					}
9323 				}
9324 			}
9325 			if (ipif != NULL)
9326 				ipif_refrele(ipif);
9327 			ill_refrele(dst_ill);
9328 			ipif_refrele(src_ipif);
9329 			return;
9330 		}
9331 		case IRE_IF_RESOLVER:
9332 			/*
9333 			 * We can't build an IRE_CACHE yet, but at least
9334 			 * we found a resolver that can help.
9335 			 */
9336 			res_mp = dst_ill->ill_resolver_mp;
9337 			if (!OK_RESOLVER_MP(res_mp))
9338 				break;
9339 
9340 			/*
9341 			 * We obtain a partial IRE_CACHE which we will pass
9342 			 * along with the resolver query.  When the response
9343 			 * comes back it will be there ready for us to add.
9344 			 * The new ire inherits the IRE_OFFSUBNET flags
9345 			 * and source address, if this was requested.
9346 			 * The ire_max_frag is atomically set under the
9347 			 * irebucket lock in ire_add_v[46]. Only in the
9348 			 * case of IRE_MARK_NOADD, we set it here itself.
9349 			 */
9350 			ire = ire_create_mp(
9351 			    (uchar_t *)&dst,		/* dest address */
9352 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9353 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9354 			    NULL,			/* gateway address */
9355 			    (ire_marks & IRE_MARK_NOADD) ?
9356 			    ipif->ipif_mtu : 0,		/* max_frag */
9357 			    NULL,			/* no src nce */
9358 			    dst_ill->ill_rq,		/* recv-from queue */
9359 			    dst_ill->ill_wq,		/* send-to queue */
9360 			    IRE_CACHE,
9361 			    src_ipif,
9362 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9363 			    (fire != NULL) ?		/* Parent handle */
9364 			    fire->ire_phandle : 0,
9365 			    ihandle,			/* Interface handle */
9366 			    (fire != NULL) ?		/* flags if any */
9367 			    (fire->ire_flags &
9368 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9369 			    (save_ire == NULL ? &ire_uinfo_null :
9370 			    &save_ire->ire_uinfo),
9371 			    NULL,
9372 			    NULL,
9373 			    ipst);
9374 
9375 			if (save_ire != NULL) {
9376 				ire_refrele(save_ire);
9377 				save_ire = NULL;
9378 			}
9379 			if (ire == NULL)
9380 				break;
9381 
9382 			ire->ire_marks |= ire_marks;
9383 			/*
9384 			 * Construct message chain for the resolver of the
9385 			 * form:
9386 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9387 			 *
9388 			 * NOTE : ire will be added later when the response
9389 			 * comes back from ARP. If the response does not
9390 			 * come back, ARP frees the packet. For this reason,
9391 			 * we can't REFHOLD the bucket of save_ire to prevent
9392 			 * deletions. We may not be able to REFRELE the
9393 			 * bucket if the response never comes back.
9394 			 * Thus, before adding the ire, ire_add_v4 will make
9395 			 * sure that the interface route does not get deleted.
9396 			 * This is the only case unlike ip_newroute_v6,
9397 			 * ip_newroute_ipif_v6 where we can always prevent
9398 			 * deletions because ire_add_then_send is called after
9399 			 * creating the IRE.
9400 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9401 			 * does not add this IRE into the IRE CACHE.
9402 			 */
9403 			ASSERT(ire->ire_mp != NULL);
9404 			ire->ire_mp->b_cont = first_mp;
9405 			/* Have saved_mp handy, for cleanup if canput fails */
9406 			saved_mp = mp;
9407 			mp = copyb(res_mp);
9408 			if (mp == NULL) {
9409 				/* Prepare for cleanup */
9410 				mp = saved_mp; /* pkt */
9411 				ire_delete(ire); /* ire_mp */
9412 				ire = NULL;
9413 				if (copy_mp != NULL) {
9414 					MULTIRT_DEBUG_UNTAG(copy_mp);
9415 					freemsg(copy_mp);
9416 					copy_mp = NULL;
9417 				}
9418 				break;
9419 			}
9420 			linkb(mp, ire->ire_mp);
9421 
9422 			/*
9423 			 * Fill in the source and dest addrs for the resolver.
9424 			 * NOTE: this depends on memory layouts imposed by
9425 			 * ill_init().
9426 			 */
9427 			areq = (areq_t *)mp->b_rptr;
9428 			addrp = (ipaddr_t *)((char *)areq +
9429 			    areq->areq_sender_addr_offset);
9430 			*addrp = ire->ire_src_addr;
9431 			addrp = (ipaddr_t *)((char *)areq +
9432 			    areq->areq_target_addr_offset);
9433 			*addrp = dst;
9434 			/* Up to the resolver. */
9435 			if (canputnext(dst_ill->ill_rq) &&
9436 			    !(dst_ill->ill_arp_closing)) {
9437 				putnext(dst_ill->ill_rq, mp);
9438 				/*
9439 				 * The response will come back in ip_wput
9440 				 * with db_type IRE_DB_TYPE.
9441 				 */
9442 			} else {
9443 				mp->b_cont = NULL;
9444 				freeb(mp); /* areq */
9445 				ire_delete(ire); /* ire_mp */
9446 				saved_mp->b_next = NULL;
9447 				saved_mp->b_prev = NULL;
9448 				freemsg(first_mp); /* pkt */
9449 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9450 			}
9451 
9452 			if (fire != NULL) {
9453 				ire_refrele(fire);
9454 				fire = NULL;
9455 			}
9456 
9457 
9458 			/*
9459 			 * The resolution loop is re-entered if this was
9460 			 * requested through flags and we actually are
9461 			 * in a multirouting case.
9462 			 */
9463 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9464 				boolean_t need_resolve =
9465 				    ire_multirt_need_resolve(ipha_dst,
9466 				    MBLK_GETLABEL(copy_mp), ipst);
9467 				if (!need_resolve) {
9468 					MULTIRT_DEBUG_UNTAG(copy_mp);
9469 					freemsg(copy_mp);
9470 					copy_mp = NULL;
9471 				} else {
9472 					/*
9473 					 * ipif_lookup_group() calls
9474 					 * ire_lookup_multi() that uses
9475 					 * ire_ftable_lookup() to find
9476 					 * an IRE_INTERFACE for the group.
9477 					 * In the multirt case,
9478 					 * ire_lookup_multi() then invokes
9479 					 * ire_multirt_lookup() to find
9480 					 * the next resolvable ire.
9481 					 * As a result, we obtain an new
9482 					 * interface, derived from the
9483 					 * next ire.
9484 					 */
9485 					ipif_refrele(ipif);
9486 					ipif = ipif_lookup_group(ipha_dst,
9487 					    zoneid, ipst);
9488 					if (ipif != NULL) {
9489 						mp = copy_mp;
9490 						copy_mp = NULL;
9491 						multirt_resolve_next = B_TRUE;
9492 						continue;
9493 					} else {
9494 						freemsg(copy_mp);
9495 					}
9496 				}
9497 			}
9498 			if (ipif != NULL)
9499 				ipif_refrele(ipif);
9500 			ill_refrele(dst_ill);
9501 			ipif_refrele(src_ipif);
9502 			return;
9503 		default:
9504 			break;
9505 		}
9506 	} while (multirt_resolve_next);
9507 
9508 err_ret:
9509 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9510 	if (fire != NULL)
9511 		ire_refrele(fire);
9512 	ipif_refrele(ipif);
9513 	/* Did this packet originate externally? */
9514 	if (dst_ill != NULL)
9515 		ill_refrele(dst_ill);
9516 	if (src_ipif != NULL)
9517 		ipif_refrele(src_ipif);
9518 	if (mp->b_prev || mp->b_next) {
9519 		mp->b_next = NULL;
9520 		mp->b_prev = NULL;
9521 	} else {
9522 		/*
9523 		 * Since ip_wput() isn't close to finished, we fill
9524 		 * in enough of the header for credible error reporting.
9525 		 */
9526 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9527 			/* Failed */
9528 			freemsg(first_mp);
9529 			if (ire != NULL)
9530 				ire_refrele(ire);
9531 			return;
9532 		}
9533 	}
9534 	/*
9535 	 * At this point we will have ire only if RTF_BLACKHOLE
9536 	 * or RTF_REJECT flags are set on the IRE. It will not
9537 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9538 	 */
9539 	if (ire != NULL) {
9540 		if (ire->ire_flags & RTF_BLACKHOLE) {
9541 			ire_refrele(ire);
9542 			freemsg(first_mp);
9543 			return;
9544 		}
9545 		ire_refrele(ire);
9546 	}
9547 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9548 }
9549 
9550 /* Name/Value Table Lookup Routine */
9551 char *
9552 ip_nv_lookup(nv_t *nv, int value)
9553 {
9554 	if (!nv)
9555 		return (NULL);
9556 	for (; nv->nv_name; nv++) {
9557 		if (nv->nv_value == value)
9558 			return (nv->nv_name);
9559 	}
9560 	return ("unknown");
9561 }
9562 
9563 /*
9564  * This is a module open, i.e. this is a control stream for access
9565  * to a DLPI device.  We allocate an ill_t as the instance data in
9566  * this case.
9567  */
9568 int
9569 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9570 {
9571 	ill_t	*ill;
9572 	int	err;
9573 	zoneid_t zoneid;
9574 	netstack_t *ns;
9575 	ip_stack_t *ipst;
9576 
9577 	/*
9578 	 * Prevent unprivileged processes from pushing IP so that
9579 	 * they can't send raw IP.
9580 	 */
9581 	if (secpolicy_net_rawaccess(credp) != 0)
9582 		return (EPERM);
9583 
9584 	ns = netstack_find_by_cred(credp);
9585 	ASSERT(ns != NULL);
9586 	ipst = ns->netstack_ip;
9587 	ASSERT(ipst != NULL);
9588 
9589 	/*
9590 	 * For exclusive stacks we set the zoneid to zero
9591 	 * to make IP operate as if in the global zone.
9592 	 */
9593 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9594 		zoneid = GLOBAL_ZONEID;
9595 	else
9596 		zoneid = crgetzoneid(credp);
9597 
9598 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9599 	q->q_ptr = WR(q)->q_ptr = ill;
9600 	ill->ill_ipst = ipst;
9601 	ill->ill_zoneid = zoneid;
9602 
9603 	/*
9604 	 * ill_init initializes the ill fields and then sends down
9605 	 * down a DL_INFO_REQ after calling qprocson.
9606 	 */
9607 	err = ill_init(q, ill);
9608 	if (err != 0) {
9609 		mi_free(ill);
9610 		netstack_rele(ipst->ips_netstack);
9611 		q->q_ptr = NULL;
9612 		WR(q)->q_ptr = NULL;
9613 		return (err);
9614 	}
9615 
9616 	/* ill_init initializes the ipsq marking this thread as writer */
9617 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9618 	/* Wait for the DL_INFO_ACK */
9619 	mutex_enter(&ill->ill_lock);
9620 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9621 		/*
9622 		 * Return value of 0 indicates a pending signal.
9623 		 */
9624 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9625 		if (err == 0) {
9626 			mutex_exit(&ill->ill_lock);
9627 			(void) ip_close(q, 0);
9628 			return (EINTR);
9629 		}
9630 	}
9631 	mutex_exit(&ill->ill_lock);
9632 
9633 	/*
9634 	 * ip_rput_other could have set an error  in ill_error on
9635 	 * receipt of M_ERROR.
9636 	 */
9637 
9638 	err = ill->ill_error;
9639 	if (err != 0) {
9640 		(void) ip_close(q, 0);
9641 		return (err);
9642 	}
9643 
9644 	ill->ill_credp = credp;
9645 	crhold(credp);
9646 
9647 	mutex_enter(&ipst->ips_ip_mi_lock);
9648 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9649 	    credp);
9650 	mutex_exit(&ipst->ips_ip_mi_lock);
9651 	if (err) {
9652 		(void) ip_close(q, 0);
9653 		return (err);
9654 	}
9655 	return (0);
9656 }
9657 
9658 /* IP open routine. */
9659 int
9660 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9661 {
9662 	conn_t 		*connp;
9663 	major_t		maj;
9664 	zoneid_t	zoneid;
9665 	netstack_t	*ns;
9666 	ip_stack_t	*ipst;
9667 
9668 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9669 
9670 	/* Allow reopen. */
9671 	if (q->q_ptr != NULL)
9672 		return (0);
9673 
9674 	if (sflag & MODOPEN) {
9675 		/* This is a module open */
9676 		return (ip_modopen(q, devp, flag, sflag, credp));
9677 	}
9678 
9679 	ns = netstack_find_by_cred(credp);
9680 	ASSERT(ns != NULL);
9681 	ipst = ns->netstack_ip;
9682 	ASSERT(ipst != NULL);
9683 
9684 	/*
9685 	 * For exclusive stacks we set the zoneid to zero
9686 	 * to make IP operate as if in the global zone.
9687 	 */
9688 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9689 		zoneid = GLOBAL_ZONEID;
9690 	else
9691 		zoneid = crgetzoneid(credp);
9692 
9693 	/*
9694 	 * We are opening as a device. This is an IP client stream, and we
9695 	 * allocate an conn_t as the instance data.
9696 	 */
9697 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9698 
9699 	/*
9700 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9701 	 * done by netstack_find_by_cred()
9702 	 */
9703 	netstack_rele(ipst->ips_netstack);
9704 
9705 	connp->conn_zoneid = zoneid;
9706 
9707 	connp->conn_upq = q;
9708 	q->q_ptr = WR(q)->q_ptr = connp;
9709 
9710 	if (flag & SO_SOCKSTR)
9711 		connp->conn_flags |= IPCL_SOCKET;
9712 
9713 	/* Minor tells us which /dev entry was opened */
9714 	if (geteminor(*devp) == IPV6_MINOR) {
9715 		connp->conn_flags |= IPCL_ISV6;
9716 		connp->conn_af_isv6 = B_TRUE;
9717 		ip_setqinfo(q, geteminor(*devp), B_FALSE, ipst);
9718 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9719 	} else {
9720 		connp->conn_af_isv6 = B_FALSE;
9721 		connp->conn_pkt_isv6 = B_FALSE;
9722 	}
9723 
9724 	if ((connp->conn_dev = inet_minor_alloc(ip_minor_arena)) == 0) {
9725 		/* CONN_DEC_REF takes care of netstack_rele() */
9726 		q->q_ptr = WR(q)->q_ptr = NULL;
9727 		CONN_DEC_REF(connp);
9728 		return (EBUSY);
9729 	}
9730 
9731 	maj = getemajor(*devp);
9732 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9733 
9734 	/*
9735 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9736 	 */
9737 	connp->conn_cred = credp;
9738 	crhold(connp->conn_cred);
9739 
9740 	/*
9741 	 * If the caller has the process-wide flag set, then default to MAC
9742 	 * exempt mode.  This allows read-down to unlabeled hosts.
9743 	 */
9744 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9745 		connp->conn_mac_exempt = B_TRUE;
9746 
9747 	/*
9748 	 * This should only happen for ndd, netstat, raw socket or other SCTP
9749 	 * administrative ops.  In these cases, we just need a normal conn_t
9750 	 * with ulp set to IPPROTO_SCTP.  All other ops are trapped and
9751 	 * an error will be returned.
9752 	 */
9753 	if (maj != SCTP_MAJ && maj != SCTP6_MAJ) {
9754 		connp->conn_rq = q;
9755 		connp->conn_wq = WR(q);
9756 	} else {
9757 		connp->conn_ulp = IPPROTO_SCTP;
9758 		connp->conn_rq = connp->conn_wq = NULL;
9759 	}
9760 	/* Non-zero default values */
9761 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9762 
9763 	/*
9764 	 * Make the conn globally visible to walkers
9765 	 */
9766 	ASSERT(connp->conn_ref == 1);
9767 	mutex_enter(&connp->conn_lock);
9768 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9769 	mutex_exit(&connp->conn_lock);
9770 
9771 	qprocson(q);
9772 
9773 	return (0);
9774 }
9775 
9776 /*
9777  * Change q_qinfo based on the value of isv6.
9778  * This can not called on an ill queue.
9779  * Note that there is no race since either q_qinfo works for conn queues - it
9780  * is just an optimization to enter the best wput routine directly.
9781  */
9782 void
9783 ip_setqinfo(queue_t *q, minor_t minor, boolean_t bump_mib, ip_stack_t *ipst)
9784 {
9785 	ASSERT(q->q_flag & QREADR);
9786 	ASSERT(WR(q)->q_next == NULL);
9787 	ASSERT(q->q_ptr != NULL);
9788 
9789 	if (minor == IPV6_MINOR)  {
9790 		if (bump_mib) {
9791 			BUMP_MIB(&ipst->ips_ip6_mib,
9792 			    ipIfStatsOutSwitchIPVersion);
9793 		}
9794 		q->q_qinfo = &rinit_ipv6;
9795 		WR(q)->q_qinfo = &winit_ipv6;
9796 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_TRUE;
9797 	} else {
9798 		if (bump_mib) {
9799 			BUMP_MIB(&ipst->ips_ip_mib,
9800 			    ipIfStatsOutSwitchIPVersion);
9801 		}
9802 		q->q_qinfo = &iprinit;
9803 		WR(q)->q_qinfo = &ipwinit;
9804 		(Q_TO_CONN(q))->conn_pkt_isv6 = B_FALSE;
9805 	}
9806 
9807 }
9808 
9809 /*
9810  * See if IPsec needs loading because of the options in mp.
9811  */
9812 static boolean_t
9813 ipsec_opt_present(mblk_t *mp)
9814 {
9815 	uint8_t *optcp, *next_optcp, *opt_endcp;
9816 	struct opthdr *opt;
9817 	struct T_opthdr *topt;
9818 	int opthdr_len;
9819 	t_uscalar_t optname, optlevel;
9820 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9821 	ipsec_req_t *ipsr;
9822 
9823 	/*
9824 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9825 	 * return TRUE.
9826 	 */
9827 
9828 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9829 	opt_endcp = optcp + tor->OPT_length;
9830 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9831 		opthdr_len = sizeof (struct T_opthdr);
9832 	} else {		/* O_OPTMGMT_REQ */
9833 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9834 		opthdr_len = sizeof (struct opthdr);
9835 	}
9836 	for (; optcp < opt_endcp; optcp = next_optcp) {
9837 		if (optcp + opthdr_len > opt_endcp)
9838 			return (B_FALSE);	/* Not enough option header. */
9839 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9840 			topt = (struct T_opthdr *)optcp;
9841 			optlevel = topt->level;
9842 			optname = topt->name;
9843 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9844 		} else {
9845 			opt = (struct opthdr *)optcp;
9846 			optlevel = opt->level;
9847 			optname = opt->name;
9848 			next_optcp = optcp + opthdr_len +
9849 			    _TPI_ALIGN_OPT(opt->len);
9850 		}
9851 		if ((next_optcp < optcp) || /* wraparound pointer space */
9852 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9853 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9854 			return (B_FALSE); /* bad option buffer */
9855 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9856 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9857 			/*
9858 			 * Check to see if it's an all-bypass or all-zeroes
9859 			 * IPsec request.  Don't bother loading IPsec if
9860 			 * the socket doesn't want to use it.  (A good example
9861 			 * is a bypass request.)
9862 			 *
9863 			 * Basically, if any of the non-NEVER bits are set,
9864 			 * load IPsec.
9865 			 */
9866 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9867 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9868 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9869 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9870 			    != 0)
9871 				return (B_TRUE);
9872 		}
9873 	}
9874 	return (B_FALSE);
9875 }
9876 
9877 /*
9878  * If conn is is waiting for ipsec to finish loading, kick it.
9879  */
9880 /* ARGSUSED */
9881 static void
9882 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9883 {
9884 	t_scalar_t	optreq_prim;
9885 	mblk_t		*mp;
9886 	cred_t		*cr;
9887 	int		err = 0;
9888 
9889 	/*
9890 	 * This function is called, after ipsec loading is complete.
9891 	 * Since IP checks exclusively and atomically (i.e it prevents
9892 	 * ipsec load from completing until ip_optcom_req completes)
9893 	 * whether ipsec load is complete, there cannot be a race with IP
9894 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9895 	 */
9896 	mutex_enter(&connp->conn_lock);
9897 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9898 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9899 		mp = connp->conn_ipsec_opt_mp;
9900 		connp->conn_ipsec_opt_mp = NULL;
9901 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9902 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9903 		mutex_exit(&connp->conn_lock);
9904 
9905 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9906 
9907 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9908 		if (optreq_prim == T_OPTMGMT_REQ) {
9909 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9910 			    &ip_opt_obj);
9911 		} else {
9912 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9913 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9914 			    &ip_opt_obj);
9915 		}
9916 		if (err != EINPROGRESS)
9917 			CONN_OPER_PENDING_DONE(connp);
9918 		return;
9919 	}
9920 	mutex_exit(&connp->conn_lock);
9921 }
9922 
9923 /*
9924  * Called from the ipsec_loader thread, outside any perimeter, to tell
9925  * ip qenable any of the queues waiting for the ipsec loader to
9926  * complete.
9927  */
9928 void
9929 ip_ipsec_load_complete(ipsec_stack_t *ipss)
9930 {
9931 	netstack_t *ns = ipss->ipsec_netstack;
9932 
9933 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
9934 }
9935 
9936 /*
9937  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
9938  * determines the grp on which it has to become exclusive, queues the mp
9939  * and sq draining restarts the optmgmt
9940  */
9941 static boolean_t
9942 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
9943 {
9944 	conn_t *connp = Q_TO_CONN(q);
9945 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
9946 
9947 	/*
9948 	 * Take IPsec requests and treat them special.
9949 	 */
9950 	if (ipsec_opt_present(mp)) {
9951 		/* First check if IPsec is loaded. */
9952 		mutex_enter(&ipss->ipsec_loader_lock);
9953 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
9954 			mutex_exit(&ipss->ipsec_loader_lock);
9955 			return (B_FALSE);
9956 		}
9957 		mutex_enter(&connp->conn_lock);
9958 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
9959 
9960 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
9961 		connp->conn_ipsec_opt_mp = mp;
9962 		mutex_exit(&connp->conn_lock);
9963 		mutex_exit(&ipss->ipsec_loader_lock);
9964 
9965 		ipsec_loader_loadnow(ipss);
9966 		return (B_TRUE);
9967 	}
9968 	return (B_FALSE);
9969 }
9970 
9971 /*
9972  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
9973  * all of them are copied to the conn_t. If the req is "zero", the policy is
9974  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
9975  * fields.
9976  * We keep only the latest setting of the policy and thus policy setting
9977  * is not incremental/cumulative.
9978  *
9979  * Requests to set policies with multiple alternative actions will
9980  * go through a different API.
9981  */
9982 int
9983 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
9984 {
9985 	uint_t ah_req = 0;
9986 	uint_t esp_req = 0;
9987 	uint_t se_req = 0;
9988 	ipsec_selkey_t sel;
9989 	ipsec_act_t *actp = NULL;
9990 	uint_t nact;
9991 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
9992 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
9993 	ipsec_policy_root_t *pr;
9994 	ipsec_policy_head_t *ph;
9995 	int fam;
9996 	boolean_t is_pol_reset;
9997 	int error = 0;
9998 	netstack_t	*ns = connp->conn_netstack;
9999 	ip_stack_t	*ipst = ns->netstack_ip;
10000 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10001 
10002 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10003 
10004 	/*
10005 	 * The IP_SEC_OPT option does not allow variable length parameters,
10006 	 * hence a request cannot be NULL.
10007 	 */
10008 	if (req == NULL)
10009 		return (EINVAL);
10010 
10011 	ah_req = req->ipsr_ah_req;
10012 	esp_req = req->ipsr_esp_req;
10013 	se_req = req->ipsr_self_encap_req;
10014 
10015 	/*
10016 	 * Are we dealing with a request to reset the policy (i.e.
10017 	 * zero requests).
10018 	 */
10019 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10020 	    (esp_req & REQ_MASK) == 0 &&
10021 	    (se_req & REQ_MASK) == 0);
10022 
10023 	if (!is_pol_reset) {
10024 		/*
10025 		 * If we couldn't load IPsec, fail with "protocol
10026 		 * not supported".
10027 		 * IPsec may not have been loaded for a request with zero
10028 		 * policies, so we don't fail in this case.
10029 		 */
10030 		mutex_enter(&ipss->ipsec_loader_lock);
10031 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10032 			mutex_exit(&ipss->ipsec_loader_lock);
10033 			return (EPROTONOSUPPORT);
10034 		}
10035 		mutex_exit(&ipss->ipsec_loader_lock);
10036 
10037 		/*
10038 		 * Test for valid requests. Invalid algorithms
10039 		 * need to be tested by IPSEC code because new
10040 		 * algorithms can be added dynamically.
10041 		 */
10042 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10043 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10044 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10045 			return (EINVAL);
10046 		}
10047 
10048 		/*
10049 		 * Only privileged users can issue these
10050 		 * requests.
10051 		 */
10052 		if (((ah_req & IPSEC_PREF_NEVER) ||
10053 		    (esp_req & IPSEC_PREF_NEVER) ||
10054 		    (se_req & IPSEC_PREF_NEVER)) &&
10055 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10056 			return (EPERM);
10057 		}
10058 
10059 		/*
10060 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10061 		 * are mutually exclusive.
10062 		 */
10063 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10064 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10065 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10066 			/* Both of them are set */
10067 			return (EINVAL);
10068 		}
10069 	}
10070 
10071 	mutex_enter(&connp->conn_lock);
10072 
10073 	/*
10074 	 * If we have already cached policies in ip_bind_connected*(), don't
10075 	 * let them change now. We cache policies for connections
10076 	 * whose src,dst [addr, port] is known.
10077 	 */
10078 	if (connp->conn_policy_cached) {
10079 		mutex_exit(&connp->conn_lock);
10080 		return (EINVAL);
10081 	}
10082 
10083 	/*
10084 	 * We have a zero policies, reset the connection policy if already
10085 	 * set. This will cause the connection to inherit the
10086 	 * global policy, if any.
10087 	 */
10088 	if (is_pol_reset) {
10089 		if (connp->conn_policy != NULL) {
10090 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10091 			connp->conn_policy = NULL;
10092 		}
10093 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10094 		connp->conn_in_enforce_policy = B_FALSE;
10095 		connp->conn_out_enforce_policy = B_FALSE;
10096 		mutex_exit(&connp->conn_lock);
10097 		return (0);
10098 	}
10099 
10100 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10101 	    ipst->ips_netstack);
10102 	if (ph == NULL)
10103 		goto enomem;
10104 
10105 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10106 	if (actp == NULL)
10107 		goto enomem;
10108 
10109 	/*
10110 	 * Always allocate IPv4 policy entries, since they can also
10111 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10112 	 */
10113 	bzero(&sel, sizeof (sel));
10114 	sel.ipsl_valid = IPSL_IPV4;
10115 
10116 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10117 	    ipst->ips_netstack);
10118 	if (pin4 == NULL)
10119 		goto enomem;
10120 
10121 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10122 	    ipst->ips_netstack);
10123 	if (pout4 == NULL)
10124 		goto enomem;
10125 
10126 	if (connp->conn_pkt_isv6) {
10127 		/*
10128 		 * We're looking at a v6 socket, also allocate the
10129 		 * v6-specific entries...
10130 		 */
10131 		sel.ipsl_valid = IPSL_IPV6;
10132 		pin6 = ipsec_policy_create(&sel, actp, nact,
10133 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10134 		if (pin6 == NULL)
10135 			goto enomem;
10136 
10137 		pout6 = ipsec_policy_create(&sel, actp, nact,
10138 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10139 		if (pout6 == NULL)
10140 			goto enomem;
10141 
10142 		/*
10143 		 * .. and file them away in the right place.
10144 		 */
10145 		fam = IPSEC_AF_V6;
10146 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10147 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10148 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10149 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10150 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10151 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10152 	}
10153 
10154 	ipsec_actvec_free(actp, nact);
10155 
10156 	/*
10157 	 * File the v4 policies.
10158 	 */
10159 	fam = IPSEC_AF_V4;
10160 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10161 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10162 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10163 
10164 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10165 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10166 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10167 
10168 	/*
10169 	 * If the requests need security, set enforce_policy.
10170 	 * If the requests are IPSEC_PREF_NEVER, one should
10171 	 * still set conn_out_enforce_policy so that an ipsec_out
10172 	 * gets attached in ip_wput. This is needed so that
10173 	 * for connections that we don't cache policy in ip_bind,
10174 	 * if global policy matches in ip_wput_attach_policy, we
10175 	 * don't wrongly inherit global policy. Similarly, we need
10176 	 * to set conn_in_enforce_policy also so that we don't verify
10177 	 * policy wrongly.
10178 	 */
10179 	if ((ah_req & REQ_MASK) != 0 ||
10180 	    (esp_req & REQ_MASK) != 0 ||
10181 	    (se_req & REQ_MASK) != 0) {
10182 		connp->conn_in_enforce_policy = B_TRUE;
10183 		connp->conn_out_enforce_policy = B_TRUE;
10184 		connp->conn_flags |= IPCL_CHECK_POLICY;
10185 	}
10186 
10187 	mutex_exit(&connp->conn_lock);
10188 	return (error);
10189 #undef REQ_MASK
10190 
10191 	/*
10192 	 * Common memory-allocation-failure exit path.
10193 	 */
10194 enomem:
10195 	mutex_exit(&connp->conn_lock);
10196 	if (actp != NULL)
10197 		ipsec_actvec_free(actp, nact);
10198 	if (pin4 != NULL)
10199 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10200 	if (pout4 != NULL)
10201 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10202 	if (pin6 != NULL)
10203 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10204 	if (pout6 != NULL)
10205 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10206 	return (ENOMEM);
10207 }
10208 
10209 /*
10210  * Only for options that pass in an IP addr. Currently only V4 options
10211  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10212  * So this function assumes level is IPPROTO_IP
10213  */
10214 int
10215 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10216     mblk_t *first_mp)
10217 {
10218 	ipif_t *ipif = NULL;
10219 	int error;
10220 	ill_t *ill;
10221 	int zoneid;
10222 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10223 
10224 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10225 
10226 	if (addr != INADDR_ANY || checkonly) {
10227 		ASSERT(connp != NULL);
10228 		zoneid = IPCL_ZONEID(connp);
10229 		if (option == IP_NEXTHOP) {
10230 			ipif = ipif_lookup_onlink_addr(addr,
10231 			    connp->conn_zoneid, ipst);
10232 		} else {
10233 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10234 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10235 			    &error, ipst);
10236 		}
10237 		if (ipif == NULL) {
10238 			if (error == EINPROGRESS)
10239 				return (error);
10240 			else if ((option == IP_MULTICAST_IF) ||
10241 			    (option == IP_NEXTHOP))
10242 				return (EHOSTUNREACH);
10243 			else
10244 				return (EINVAL);
10245 		} else if (checkonly) {
10246 			if (option == IP_MULTICAST_IF) {
10247 				ill = ipif->ipif_ill;
10248 				/* not supported by the virtual network iface */
10249 				if (IS_VNI(ill)) {
10250 					ipif_refrele(ipif);
10251 					return (EINVAL);
10252 				}
10253 			}
10254 			ipif_refrele(ipif);
10255 			return (0);
10256 		}
10257 		ill = ipif->ipif_ill;
10258 		mutex_enter(&connp->conn_lock);
10259 		mutex_enter(&ill->ill_lock);
10260 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10261 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10262 			mutex_exit(&ill->ill_lock);
10263 			mutex_exit(&connp->conn_lock);
10264 			ipif_refrele(ipif);
10265 			return (option == IP_MULTICAST_IF ?
10266 			    EHOSTUNREACH : EINVAL);
10267 		}
10268 	} else {
10269 		mutex_enter(&connp->conn_lock);
10270 	}
10271 
10272 	/* None of the options below are supported on the VNI */
10273 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10274 		mutex_exit(&ill->ill_lock);
10275 		mutex_exit(&connp->conn_lock);
10276 		ipif_refrele(ipif);
10277 		return (EINVAL);
10278 	}
10279 
10280 	switch (option) {
10281 	case IP_DONTFAILOVER_IF:
10282 		/*
10283 		 * This option is used by in.mpathd to ensure
10284 		 * that IPMP probe packets only go out on the
10285 		 * test interfaces. in.mpathd sets this option
10286 		 * on the non-failover interfaces.
10287 		 * For backward compatibility, this option
10288 		 * implicitly sets IP_MULTICAST_IF, as used
10289 		 * be done in bind(), so that ip_wput gets
10290 		 * this ipif to send mcast packets.
10291 		 */
10292 		if (ipif != NULL) {
10293 			ASSERT(addr != INADDR_ANY);
10294 			connp->conn_nofailover_ill = ipif->ipif_ill;
10295 			connp->conn_multicast_ipif = ipif;
10296 		} else {
10297 			ASSERT(addr == INADDR_ANY);
10298 			connp->conn_nofailover_ill = NULL;
10299 			connp->conn_multicast_ipif = NULL;
10300 		}
10301 		break;
10302 
10303 	case IP_MULTICAST_IF:
10304 		connp->conn_multicast_ipif = ipif;
10305 		break;
10306 	case IP_NEXTHOP:
10307 		connp->conn_nexthop_v4 = addr;
10308 		connp->conn_nexthop_set = B_TRUE;
10309 		break;
10310 	}
10311 
10312 	if (ipif != NULL) {
10313 		mutex_exit(&ill->ill_lock);
10314 		mutex_exit(&connp->conn_lock);
10315 		ipif_refrele(ipif);
10316 		return (0);
10317 	}
10318 	mutex_exit(&connp->conn_lock);
10319 	/* We succeded in cleared the option */
10320 	return (0);
10321 }
10322 
10323 /*
10324  * For options that pass in an ifindex specifying the ill. V6 options always
10325  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10326  */
10327 int
10328 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10329     int level, int option, mblk_t *first_mp)
10330 {
10331 	ill_t *ill = NULL;
10332 	int error = 0;
10333 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10334 
10335 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10336 	if (ifindex != 0) {
10337 		ASSERT(connp != NULL);
10338 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10339 		    first_mp, ip_restart_optmgmt, &error, ipst);
10340 		if (ill != NULL) {
10341 			if (checkonly) {
10342 				/* not supported by the virtual network iface */
10343 				if (IS_VNI(ill)) {
10344 					ill_refrele(ill);
10345 					return (EINVAL);
10346 				}
10347 				ill_refrele(ill);
10348 				return (0);
10349 			}
10350 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10351 			    0, NULL)) {
10352 				ill_refrele(ill);
10353 				ill = NULL;
10354 				mutex_enter(&connp->conn_lock);
10355 				goto setit;
10356 			}
10357 			mutex_enter(&connp->conn_lock);
10358 			mutex_enter(&ill->ill_lock);
10359 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10360 				mutex_exit(&ill->ill_lock);
10361 				mutex_exit(&connp->conn_lock);
10362 				ill_refrele(ill);
10363 				ill = NULL;
10364 				mutex_enter(&connp->conn_lock);
10365 			}
10366 			goto setit;
10367 		} else if (error == EINPROGRESS) {
10368 			return (error);
10369 		} else {
10370 			error = 0;
10371 		}
10372 	}
10373 	mutex_enter(&connp->conn_lock);
10374 setit:
10375 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10376 
10377 	/*
10378 	 * The options below assume that the ILL (if any) transmits and/or
10379 	 * receives traffic. Neither of which is true for the virtual network
10380 	 * interface, so fail setting these on a VNI.
10381 	 */
10382 	if (IS_VNI(ill)) {
10383 		ASSERT(ill != NULL);
10384 		mutex_exit(&ill->ill_lock);
10385 		mutex_exit(&connp->conn_lock);
10386 		ill_refrele(ill);
10387 		return (EINVAL);
10388 	}
10389 
10390 	if (level == IPPROTO_IP) {
10391 		switch (option) {
10392 		case IP_BOUND_IF:
10393 			connp->conn_incoming_ill = ill;
10394 			connp->conn_outgoing_ill = ill;
10395 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10396 			    0 : ifindex;
10397 			break;
10398 
10399 		case IP_XMIT_IF:
10400 			/*
10401 			 * Similar to IP_BOUND_IF, but this only
10402 			 * determines the outgoing interface for
10403 			 * unicast packets. Also no IRE_CACHE entry
10404 			 * is added for the destination of the
10405 			 * outgoing packets.
10406 			 */
10407 			connp->conn_xmit_if_ill = ill;
10408 			connp->conn_orig_xmit_ifindex = (ill == NULL) ?
10409 			    0 : ifindex;
10410 			break;
10411 
10412 		case IP_MULTICAST_IF:
10413 			/*
10414 			 * This option is an internal special. The socket
10415 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10416 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10417 			 * specifies an ifindex and we try first on V6 ill's.
10418 			 * If we don't find one, we they try using on v4 ill's
10419 			 * intenally and we come here.
10420 			 */
10421 			if (!checkonly && ill != NULL) {
10422 				ipif_t	*ipif;
10423 				ipif = ill->ill_ipif;
10424 
10425 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10426 					mutex_exit(&ill->ill_lock);
10427 					mutex_exit(&connp->conn_lock);
10428 					ill_refrele(ill);
10429 					ill = NULL;
10430 					mutex_enter(&connp->conn_lock);
10431 				} else {
10432 					connp->conn_multicast_ipif = ipif;
10433 				}
10434 			}
10435 			break;
10436 		}
10437 	} else {
10438 		switch (option) {
10439 		case IPV6_BOUND_IF:
10440 			connp->conn_incoming_ill = ill;
10441 			connp->conn_outgoing_ill = ill;
10442 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10443 			    0 : ifindex;
10444 			break;
10445 
10446 		case IPV6_BOUND_PIF:
10447 			/*
10448 			 * Limit all transmit to this ill.
10449 			 * Unlike IPV6_BOUND_IF, using this option
10450 			 * prevents load spreading and failover from
10451 			 * happening when the interface is part of the
10452 			 * group. That's why we don't need to remember
10453 			 * the ifindex in orig_bound_ifindex as in
10454 			 * IPV6_BOUND_IF.
10455 			 */
10456 			connp->conn_outgoing_pill = ill;
10457 			break;
10458 
10459 		case IPV6_DONTFAILOVER_IF:
10460 			/*
10461 			 * This option is used by in.mpathd to ensure
10462 			 * that IPMP probe packets only go out on the
10463 			 * test interfaces. in.mpathd sets this option
10464 			 * on the non-failover interfaces.
10465 			 */
10466 			connp->conn_nofailover_ill = ill;
10467 			/*
10468 			 * For backward compatibility, this option
10469 			 * implicitly sets ip_multicast_ill as used in
10470 			 * IP_MULTICAST_IF so that ip_wput gets
10471 			 * this ipif to send mcast packets.
10472 			 */
10473 			connp->conn_multicast_ill = ill;
10474 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10475 			    0 : ifindex;
10476 			break;
10477 
10478 		case IPV6_MULTICAST_IF:
10479 			/*
10480 			 * Set conn_multicast_ill to be the IPv6 ill.
10481 			 * Set conn_multicast_ipif to be an IPv4 ipif
10482 			 * for ifindex to make IPv4 mapped addresses
10483 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10484 			 * Even if no IPv6 ill exists for the ifindex
10485 			 * we need to check for an IPv4 ifindex in order
10486 			 * for this to work with mapped addresses. In that
10487 			 * case only set conn_multicast_ipif.
10488 			 */
10489 			if (!checkonly) {
10490 				if (ifindex == 0) {
10491 					connp->conn_multicast_ill = NULL;
10492 					connp->conn_orig_multicast_ifindex = 0;
10493 					connp->conn_multicast_ipif = NULL;
10494 				} else if (ill != NULL) {
10495 					connp->conn_multicast_ill = ill;
10496 					connp->conn_orig_multicast_ifindex =
10497 					    ifindex;
10498 				}
10499 			}
10500 			break;
10501 		}
10502 	}
10503 
10504 	if (ill != NULL) {
10505 		mutex_exit(&ill->ill_lock);
10506 		mutex_exit(&connp->conn_lock);
10507 		ill_refrele(ill);
10508 		return (0);
10509 	}
10510 	mutex_exit(&connp->conn_lock);
10511 	/*
10512 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10513 	 * locate the ill and could not set the option (ifindex != 0)
10514 	 */
10515 	return (ifindex == 0 ? 0 : EINVAL);
10516 }
10517 
10518 /* This routine sets socket options. */
10519 /* ARGSUSED */
10520 int
10521 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10522     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10523     void *dummy, cred_t *cr, mblk_t *first_mp)
10524 {
10525 	int		*i1 = (int *)invalp;
10526 	conn_t		*connp = Q_TO_CONN(q);
10527 	int		error = 0;
10528 	boolean_t	checkonly;
10529 	ire_t		*ire;
10530 	boolean_t	found;
10531 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10532 
10533 	switch (optset_context) {
10534 
10535 	case SETFN_OPTCOM_CHECKONLY:
10536 		checkonly = B_TRUE;
10537 		/*
10538 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10539 		 * inlen != 0 implies value supplied and
10540 		 * 	we have to "pretend" to set it.
10541 		 * inlen == 0 implies that there is no
10542 		 * 	value part in T_CHECK request and just validation
10543 		 * done elsewhere should be enough, we just return here.
10544 		 */
10545 		if (inlen == 0) {
10546 			*outlenp = 0;
10547 			return (0);
10548 		}
10549 		break;
10550 	case SETFN_OPTCOM_NEGOTIATE:
10551 	case SETFN_UD_NEGOTIATE:
10552 	case SETFN_CONN_NEGOTIATE:
10553 		checkonly = B_FALSE;
10554 		break;
10555 	default:
10556 		/*
10557 		 * We should never get here
10558 		 */
10559 		*outlenp = 0;
10560 		return (EINVAL);
10561 	}
10562 
10563 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10564 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10565 
10566 	/*
10567 	 * For fixed length options, no sanity check
10568 	 * of passed in length is done. It is assumed *_optcom_req()
10569 	 * routines do the right thing.
10570 	 */
10571 
10572 	switch (level) {
10573 	case SOL_SOCKET:
10574 		/*
10575 		 * conn_lock protects the bitfields, and is used to
10576 		 * set the fields atomically.
10577 		 */
10578 		switch (name) {
10579 		case SO_BROADCAST:
10580 			if (!checkonly) {
10581 				/* TODO: use value someplace? */
10582 				mutex_enter(&connp->conn_lock);
10583 				connp->conn_broadcast = *i1 ? 1 : 0;
10584 				mutex_exit(&connp->conn_lock);
10585 			}
10586 			break;	/* goto sizeof (int) option return */
10587 		case SO_USELOOPBACK:
10588 			if (!checkonly) {
10589 				/* TODO: use value someplace? */
10590 				mutex_enter(&connp->conn_lock);
10591 				connp->conn_loopback = *i1 ? 1 : 0;
10592 				mutex_exit(&connp->conn_lock);
10593 			}
10594 			break;	/* goto sizeof (int) option return */
10595 		case SO_DONTROUTE:
10596 			if (!checkonly) {
10597 				mutex_enter(&connp->conn_lock);
10598 				connp->conn_dontroute = *i1 ? 1 : 0;
10599 				mutex_exit(&connp->conn_lock);
10600 			}
10601 			break;	/* goto sizeof (int) option return */
10602 		case SO_REUSEADDR:
10603 			if (!checkonly) {
10604 				mutex_enter(&connp->conn_lock);
10605 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10606 				mutex_exit(&connp->conn_lock);
10607 			}
10608 			break;	/* goto sizeof (int) option return */
10609 		case SO_PROTOTYPE:
10610 			if (!checkonly) {
10611 				mutex_enter(&connp->conn_lock);
10612 				connp->conn_proto = *i1;
10613 				mutex_exit(&connp->conn_lock);
10614 			}
10615 			break;	/* goto sizeof (int) option return */
10616 		case SO_ALLZONES:
10617 			if (!checkonly) {
10618 				mutex_enter(&connp->conn_lock);
10619 				if (IPCL_IS_BOUND(connp)) {
10620 					mutex_exit(&connp->conn_lock);
10621 					return (EINVAL);
10622 				}
10623 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10624 				mutex_exit(&connp->conn_lock);
10625 			}
10626 			break;	/* goto sizeof (int) option return */
10627 		case SO_ANON_MLP:
10628 			if (!checkonly) {
10629 				mutex_enter(&connp->conn_lock);
10630 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10631 				mutex_exit(&connp->conn_lock);
10632 			}
10633 			break;	/* goto sizeof (int) option return */
10634 		case SO_MAC_EXEMPT:
10635 			if (secpolicy_net_mac_aware(cr) != 0 ||
10636 			    IPCL_IS_BOUND(connp))
10637 				return (EACCES);
10638 			if (!checkonly) {
10639 				mutex_enter(&connp->conn_lock);
10640 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10641 				mutex_exit(&connp->conn_lock);
10642 			}
10643 			break;	/* goto sizeof (int) option return */
10644 		default:
10645 			/*
10646 			 * "soft" error (negative)
10647 			 * option not handled at this level
10648 			 * Note: Do not modify *outlenp
10649 			 */
10650 			return (-EINVAL);
10651 		}
10652 		break;
10653 	case IPPROTO_IP:
10654 		switch (name) {
10655 		case IP_NEXTHOP:
10656 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10657 				return (EPERM);
10658 			/* FALLTHRU */
10659 		case IP_MULTICAST_IF:
10660 		case IP_DONTFAILOVER_IF: {
10661 			ipaddr_t addr = *i1;
10662 
10663 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10664 			    first_mp);
10665 			if (error != 0)
10666 				return (error);
10667 			break;	/* goto sizeof (int) option return */
10668 		}
10669 
10670 		case IP_MULTICAST_TTL:
10671 			/* Recorded in transport above IP */
10672 			*outvalp = *invalp;
10673 			*outlenp = sizeof (uchar_t);
10674 			return (0);
10675 		case IP_MULTICAST_LOOP:
10676 			if (!checkonly) {
10677 				mutex_enter(&connp->conn_lock);
10678 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10679 				mutex_exit(&connp->conn_lock);
10680 			}
10681 			*outvalp = *invalp;
10682 			*outlenp = sizeof (uchar_t);
10683 			return (0);
10684 		case IP_ADD_MEMBERSHIP:
10685 		case MCAST_JOIN_GROUP:
10686 		case IP_DROP_MEMBERSHIP:
10687 		case MCAST_LEAVE_GROUP: {
10688 			struct ip_mreq *mreqp;
10689 			struct group_req *greqp;
10690 			ire_t *ire;
10691 			boolean_t done = B_FALSE;
10692 			ipaddr_t group, ifaddr;
10693 			struct sockaddr_in *sin;
10694 			uint32_t *ifindexp;
10695 			boolean_t mcast_opt = B_TRUE;
10696 			mcast_record_t fmode;
10697 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10698 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10699 
10700 			switch (name) {
10701 			case IP_ADD_MEMBERSHIP:
10702 				mcast_opt = B_FALSE;
10703 				/* FALLTHRU */
10704 			case MCAST_JOIN_GROUP:
10705 				fmode = MODE_IS_EXCLUDE;
10706 				optfn = ip_opt_add_group;
10707 				break;
10708 
10709 			case IP_DROP_MEMBERSHIP:
10710 				mcast_opt = B_FALSE;
10711 				/* FALLTHRU */
10712 			case MCAST_LEAVE_GROUP:
10713 				fmode = MODE_IS_INCLUDE;
10714 				optfn = ip_opt_delete_group;
10715 				break;
10716 			}
10717 
10718 			if (mcast_opt) {
10719 				greqp = (struct group_req *)i1;
10720 				sin = (struct sockaddr_in *)&greqp->gr_group;
10721 				if (sin->sin_family != AF_INET) {
10722 					*outlenp = 0;
10723 					return (ENOPROTOOPT);
10724 				}
10725 				group = (ipaddr_t)sin->sin_addr.s_addr;
10726 				ifaddr = INADDR_ANY;
10727 				ifindexp = &greqp->gr_interface;
10728 			} else {
10729 				mreqp = (struct ip_mreq *)i1;
10730 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10731 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10732 				ifindexp = NULL;
10733 			}
10734 
10735 			/*
10736 			 * In the multirouting case, we need to replicate
10737 			 * the request on all interfaces that will take part
10738 			 * in replication.  We do so because multirouting is
10739 			 * reflective, thus we will probably receive multi-
10740 			 * casts on those interfaces.
10741 			 * The ip_multirt_apply_membership() succeeds if the
10742 			 * operation succeeds on at least one interface.
10743 			 */
10744 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10745 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10746 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10747 			if (ire != NULL) {
10748 				if (ire->ire_flags & RTF_MULTIRT) {
10749 					error = ip_multirt_apply_membership(
10750 					    optfn, ire, connp, checkonly, group,
10751 					    fmode, INADDR_ANY, first_mp);
10752 					done = B_TRUE;
10753 				}
10754 				ire_refrele(ire);
10755 			}
10756 			if (!done) {
10757 				error = optfn(connp, checkonly, group, ifaddr,
10758 				    ifindexp, fmode, INADDR_ANY, first_mp);
10759 			}
10760 			if (error) {
10761 				/*
10762 				 * EINPROGRESS is a soft error, needs retry
10763 				 * so don't make *outlenp zero.
10764 				 */
10765 				if (error != EINPROGRESS)
10766 					*outlenp = 0;
10767 				return (error);
10768 			}
10769 			/* OK return - copy input buffer into output buffer */
10770 			if (invalp != outvalp) {
10771 				/* don't trust bcopy for identical src/dst */
10772 				bcopy(invalp, outvalp, inlen);
10773 			}
10774 			*outlenp = inlen;
10775 			return (0);
10776 		}
10777 		case IP_BLOCK_SOURCE:
10778 		case IP_UNBLOCK_SOURCE:
10779 		case IP_ADD_SOURCE_MEMBERSHIP:
10780 		case IP_DROP_SOURCE_MEMBERSHIP:
10781 		case MCAST_BLOCK_SOURCE:
10782 		case MCAST_UNBLOCK_SOURCE:
10783 		case MCAST_JOIN_SOURCE_GROUP:
10784 		case MCAST_LEAVE_SOURCE_GROUP: {
10785 			struct ip_mreq_source *imreqp;
10786 			struct group_source_req *gsreqp;
10787 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10788 			uint32_t ifindex = 0;
10789 			mcast_record_t fmode;
10790 			struct sockaddr_in *sin;
10791 			ire_t *ire;
10792 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10793 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10794 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10795 
10796 			switch (name) {
10797 			case IP_BLOCK_SOURCE:
10798 				mcast_opt = B_FALSE;
10799 				/* FALLTHRU */
10800 			case MCAST_BLOCK_SOURCE:
10801 				fmode = MODE_IS_EXCLUDE;
10802 				optfn = ip_opt_add_group;
10803 				break;
10804 
10805 			case IP_UNBLOCK_SOURCE:
10806 				mcast_opt = B_FALSE;
10807 				/* FALLTHRU */
10808 			case MCAST_UNBLOCK_SOURCE:
10809 				fmode = MODE_IS_EXCLUDE;
10810 				optfn = ip_opt_delete_group;
10811 				break;
10812 
10813 			case IP_ADD_SOURCE_MEMBERSHIP:
10814 				mcast_opt = B_FALSE;
10815 				/* FALLTHRU */
10816 			case MCAST_JOIN_SOURCE_GROUP:
10817 				fmode = MODE_IS_INCLUDE;
10818 				optfn = ip_opt_add_group;
10819 				break;
10820 
10821 			case IP_DROP_SOURCE_MEMBERSHIP:
10822 				mcast_opt = B_FALSE;
10823 				/* FALLTHRU */
10824 			case MCAST_LEAVE_SOURCE_GROUP:
10825 				fmode = MODE_IS_INCLUDE;
10826 				optfn = ip_opt_delete_group;
10827 				break;
10828 			}
10829 
10830 			if (mcast_opt) {
10831 				gsreqp = (struct group_source_req *)i1;
10832 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10833 					*outlenp = 0;
10834 					return (ENOPROTOOPT);
10835 				}
10836 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10837 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10838 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10839 				src = (ipaddr_t)sin->sin_addr.s_addr;
10840 				ifindex = gsreqp->gsr_interface;
10841 			} else {
10842 				imreqp = (struct ip_mreq_source *)i1;
10843 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10844 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10845 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10846 			}
10847 
10848 			/*
10849 			 * In the multirouting case, we need to replicate
10850 			 * the request as noted in the mcast cases above.
10851 			 */
10852 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10853 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10854 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10855 			if (ire != NULL) {
10856 				if (ire->ire_flags & RTF_MULTIRT) {
10857 					error = ip_multirt_apply_membership(
10858 					    optfn, ire, connp, checkonly, grp,
10859 					    fmode, src, first_mp);
10860 					done = B_TRUE;
10861 				}
10862 				ire_refrele(ire);
10863 			}
10864 			if (!done) {
10865 				error = optfn(connp, checkonly, grp, ifaddr,
10866 				    &ifindex, fmode, src, first_mp);
10867 			}
10868 			if (error != 0) {
10869 				/*
10870 				 * EINPROGRESS is a soft error, needs retry
10871 				 * so don't make *outlenp zero.
10872 				 */
10873 				if (error != EINPROGRESS)
10874 					*outlenp = 0;
10875 				return (error);
10876 			}
10877 			/* OK return - copy input buffer into output buffer */
10878 			if (invalp != outvalp) {
10879 				bcopy(invalp, outvalp, inlen);
10880 			}
10881 			*outlenp = inlen;
10882 			return (0);
10883 		}
10884 		case IP_SEC_OPT:
10885 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10886 			if (error != 0) {
10887 				*outlenp = 0;
10888 				return (error);
10889 			}
10890 			break;
10891 		case IP_HDRINCL:
10892 		case IP_OPTIONS:
10893 		case T_IP_OPTIONS:
10894 		case IP_TOS:
10895 		case T_IP_TOS:
10896 		case IP_TTL:
10897 		case IP_RECVDSTADDR:
10898 		case IP_RECVOPTS:
10899 			/* OK return - copy input buffer into output buffer */
10900 			if (invalp != outvalp) {
10901 				/* don't trust bcopy for identical src/dst */
10902 				bcopy(invalp, outvalp, inlen);
10903 			}
10904 			*outlenp = inlen;
10905 			return (0);
10906 		case IP_RECVIF:
10907 			/* Retrieve the inbound interface index */
10908 			if (!checkonly) {
10909 				mutex_enter(&connp->conn_lock);
10910 				connp->conn_recvif = *i1 ? 1 : 0;
10911 				mutex_exit(&connp->conn_lock);
10912 			}
10913 			break;	/* goto sizeof (int) option return */
10914 		case IP_RECVPKTINFO:
10915 			if (!checkonly) {
10916 				mutex_enter(&connp->conn_lock);
10917 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10918 				mutex_exit(&connp->conn_lock);
10919 			}
10920 			break;	/* goto sizeof (int) option return */
10921 		case IP_RECVSLLA:
10922 			/* Retrieve the source link layer address */
10923 			if (!checkonly) {
10924 				mutex_enter(&connp->conn_lock);
10925 				connp->conn_recvslla = *i1 ? 1 : 0;
10926 				mutex_exit(&connp->conn_lock);
10927 			}
10928 			break;	/* goto sizeof (int) option return */
10929 		case MRT_INIT:
10930 		case MRT_DONE:
10931 		case MRT_ADD_VIF:
10932 		case MRT_DEL_VIF:
10933 		case MRT_ADD_MFC:
10934 		case MRT_DEL_MFC:
10935 		case MRT_ASSERT:
10936 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
10937 				*outlenp = 0;
10938 				return (error);
10939 			}
10940 			error = ip_mrouter_set((int)name, q, checkonly,
10941 			    (uchar_t *)invalp, inlen, first_mp);
10942 			if (error) {
10943 				*outlenp = 0;
10944 				return (error);
10945 			}
10946 			/* OK return - copy input buffer into output buffer */
10947 			if (invalp != outvalp) {
10948 				/* don't trust bcopy for identical src/dst */
10949 				bcopy(invalp, outvalp, inlen);
10950 			}
10951 			*outlenp = inlen;
10952 			return (0);
10953 		case IP_BOUND_IF:
10954 		case IP_XMIT_IF:
10955 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
10956 			    level, name, first_mp);
10957 			if (error != 0)
10958 				return (error);
10959 			break; 		/* goto sizeof (int) option return */
10960 
10961 		case IP_UNSPEC_SRC:
10962 			/* Allow sending with a zero source address */
10963 			if (!checkonly) {
10964 				mutex_enter(&connp->conn_lock);
10965 				connp->conn_unspec_src = *i1 ? 1 : 0;
10966 				mutex_exit(&connp->conn_lock);
10967 			}
10968 			break;	/* goto sizeof (int) option return */
10969 		default:
10970 			/*
10971 			 * "soft" error (negative)
10972 			 * option not handled at this level
10973 			 * Note: Do not modify *outlenp
10974 			 */
10975 			return (-EINVAL);
10976 		}
10977 		break;
10978 	case IPPROTO_IPV6:
10979 		switch (name) {
10980 		case IPV6_BOUND_IF:
10981 		case IPV6_BOUND_PIF:
10982 		case IPV6_DONTFAILOVER_IF:
10983 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
10984 			    level, name, first_mp);
10985 			if (error != 0)
10986 				return (error);
10987 			break; 		/* goto sizeof (int) option return */
10988 
10989 		case IPV6_MULTICAST_IF:
10990 			/*
10991 			 * The only possible errors are EINPROGRESS and
10992 			 * EINVAL. EINPROGRESS will be restarted and is not
10993 			 * a hard error. We call this option on both V4 and V6
10994 			 * If both return EINVAL, then this call returns
10995 			 * EINVAL. If at least one of them succeeds we
10996 			 * return success.
10997 			 */
10998 			found = B_FALSE;
10999 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11000 			    level, name, first_mp);
11001 			if (error == EINPROGRESS)
11002 				return (error);
11003 			if (error == 0)
11004 				found = B_TRUE;
11005 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11006 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11007 			if (error == 0)
11008 				found = B_TRUE;
11009 			if (!found)
11010 				return (error);
11011 			break; 		/* goto sizeof (int) option return */
11012 
11013 		case IPV6_MULTICAST_HOPS:
11014 			/* Recorded in transport above IP */
11015 			break;	/* goto sizeof (int) option return */
11016 		case IPV6_MULTICAST_LOOP:
11017 			if (!checkonly) {
11018 				mutex_enter(&connp->conn_lock);
11019 				connp->conn_multicast_loop = *i1;
11020 				mutex_exit(&connp->conn_lock);
11021 			}
11022 			break;	/* goto sizeof (int) option return */
11023 		case IPV6_JOIN_GROUP:
11024 		case MCAST_JOIN_GROUP:
11025 		case IPV6_LEAVE_GROUP:
11026 		case MCAST_LEAVE_GROUP: {
11027 			struct ipv6_mreq *ip_mreqp;
11028 			struct group_req *greqp;
11029 			ire_t *ire;
11030 			boolean_t done = B_FALSE;
11031 			in6_addr_t groupv6;
11032 			uint32_t ifindex;
11033 			boolean_t mcast_opt = B_TRUE;
11034 			mcast_record_t fmode;
11035 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11036 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11037 
11038 			switch (name) {
11039 			case IPV6_JOIN_GROUP:
11040 				mcast_opt = B_FALSE;
11041 				/* FALLTHRU */
11042 			case MCAST_JOIN_GROUP:
11043 				fmode = MODE_IS_EXCLUDE;
11044 				optfn = ip_opt_add_group_v6;
11045 				break;
11046 
11047 			case IPV6_LEAVE_GROUP:
11048 				mcast_opt = B_FALSE;
11049 				/* FALLTHRU */
11050 			case MCAST_LEAVE_GROUP:
11051 				fmode = MODE_IS_INCLUDE;
11052 				optfn = ip_opt_delete_group_v6;
11053 				break;
11054 			}
11055 
11056 			if (mcast_opt) {
11057 				struct sockaddr_in *sin;
11058 				struct sockaddr_in6 *sin6;
11059 				greqp = (struct group_req *)i1;
11060 				if (greqp->gr_group.ss_family == AF_INET) {
11061 					sin = (struct sockaddr_in *)
11062 					    &(greqp->gr_group);
11063 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11064 					    &groupv6);
11065 				} else {
11066 					sin6 = (struct sockaddr_in6 *)
11067 					    &(greqp->gr_group);
11068 					groupv6 = sin6->sin6_addr;
11069 				}
11070 				ifindex = greqp->gr_interface;
11071 			} else {
11072 				ip_mreqp = (struct ipv6_mreq *)i1;
11073 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11074 				ifindex = ip_mreqp->ipv6mr_interface;
11075 			}
11076 			/*
11077 			 * In the multirouting case, we need to replicate
11078 			 * the request on all interfaces that will take part
11079 			 * in replication.  We do so because multirouting is
11080 			 * reflective, thus we will probably receive multi-
11081 			 * casts on those interfaces.
11082 			 * The ip_multirt_apply_membership_v6() succeeds if
11083 			 * the operation succeeds on at least one interface.
11084 			 */
11085 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11086 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11087 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11088 			if (ire != NULL) {
11089 				if (ire->ire_flags & RTF_MULTIRT) {
11090 					error = ip_multirt_apply_membership_v6(
11091 					    optfn, ire, connp, checkonly,
11092 					    &groupv6, fmode, &ipv6_all_zeros,
11093 					    first_mp);
11094 					done = B_TRUE;
11095 				}
11096 				ire_refrele(ire);
11097 			}
11098 			if (!done) {
11099 				error = optfn(connp, checkonly, &groupv6,
11100 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11101 			}
11102 			if (error) {
11103 				/*
11104 				 * EINPROGRESS is a soft error, needs retry
11105 				 * so don't make *outlenp zero.
11106 				 */
11107 				if (error != EINPROGRESS)
11108 					*outlenp = 0;
11109 				return (error);
11110 			}
11111 			/* OK return - copy input buffer into output buffer */
11112 			if (invalp != outvalp) {
11113 				/* don't trust bcopy for identical src/dst */
11114 				bcopy(invalp, outvalp, inlen);
11115 			}
11116 			*outlenp = inlen;
11117 			return (0);
11118 		}
11119 		case MCAST_BLOCK_SOURCE:
11120 		case MCAST_UNBLOCK_SOURCE:
11121 		case MCAST_JOIN_SOURCE_GROUP:
11122 		case MCAST_LEAVE_SOURCE_GROUP: {
11123 			struct group_source_req *gsreqp;
11124 			in6_addr_t v6grp, v6src;
11125 			uint32_t ifindex;
11126 			mcast_record_t fmode;
11127 			ire_t *ire;
11128 			boolean_t done = B_FALSE;
11129 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11130 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11131 
11132 			switch (name) {
11133 			case MCAST_BLOCK_SOURCE:
11134 				fmode = MODE_IS_EXCLUDE;
11135 				optfn = ip_opt_add_group_v6;
11136 				break;
11137 			case MCAST_UNBLOCK_SOURCE:
11138 				fmode = MODE_IS_EXCLUDE;
11139 				optfn = ip_opt_delete_group_v6;
11140 				break;
11141 			case MCAST_JOIN_SOURCE_GROUP:
11142 				fmode = MODE_IS_INCLUDE;
11143 				optfn = ip_opt_add_group_v6;
11144 				break;
11145 			case MCAST_LEAVE_SOURCE_GROUP:
11146 				fmode = MODE_IS_INCLUDE;
11147 				optfn = ip_opt_delete_group_v6;
11148 				break;
11149 			}
11150 
11151 			gsreqp = (struct group_source_req *)i1;
11152 			ifindex = gsreqp->gsr_interface;
11153 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11154 				struct sockaddr_in *s;
11155 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11156 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11157 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11158 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11159 			} else {
11160 				struct sockaddr_in6 *s6;
11161 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11162 				v6grp = s6->sin6_addr;
11163 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11164 				v6src = s6->sin6_addr;
11165 			}
11166 
11167 			/*
11168 			 * In the multirouting case, we need to replicate
11169 			 * the request as noted in the mcast cases above.
11170 			 */
11171 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11172 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11173 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11174 			if (ire != NULL) {
11175 				if (ire->ire_flags & RTF_MULTIRT) {
11176 					error = ip_multirt_apply_membership_v6(
11177 					    optfn, ire, connp, checkonly,
11178 					    &v6grp, fmode, &v6src, first_mp);
11179 					done = B_TRUE;
11180 				}
11181 				ire_refrele(ire);
11182 			}
11183 			if (!done) {
11184 				error = optfn(connp, checkonly, &v6grp,
11185 				    ifindex, fmode, &v6src, first_mp);
11186 			}
11187 			if (error != 0) {
11188 				/*
11189 				 * EINPROGRESS is a soft error, needs retry
11190 				 * so don't make *outlenp zero.
11191 				 */
11192 				if (error != EINPROGRESS)
11193 					*outlenp = 0;
11194 				return (error);
11195 			}
11196 			/* OK return - copy input buffer into output buffer */
11197 			if (invalp != outvalp) {
11198 				bcopy(invalp, outvalp, inlen);
11199 			}
11200 			*outlenp = inlen;
11201 			return (0);
11202 		}
11203 		case IPV6_UNICAST_HOPS:
11204 			/* Recorded in transport above IP */
11205 			break;	/* goto sizeof (int) option return */
11206 		case IPV6_UNSPEC_SRC:
11207 			/* Allow sending with a zero source address */
11208 			if (!checkonly) {
11209 				mutex_enter(&connp->conn_lock);
11210 				connp->conn_unspec_src = *i1 ? 1 : 0;
11211 				mutex_exit(&connp->conn_lock);
11212 			}
11213 			break;	/* goto sizeof (int) option return */
11214 		case IPV6_RECVPKTINFO:
11215 			if (!checkonly) {
11216 				mutex_enter(&connp->conn_lock);
11217 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11218 				mutex_exit(&connp->conn_lock);
11219 			}
11220 			break;	/* goto sizeof (int) option return */
11221 		case IPV6_RECVTCLASS:
11222 			if (!checkonly) {
11223 				if (*i1 < 0 || *i1 > 1) {
11224 					return (EINVAL);
11225 				}
11226 				mutex_enter(&connp->conn_lock);
11227 				connp->conn_ipv6_recvtclass = *i1;
11228 				mutex_exit(&connp->conn_lock);
11229 			}
11230 			break;
11231 		case IPV6_RECVPATHMTU:
11232 			if (!checkonly) {
11233 				if (*i1 < 0 || *i1 > 1) {
11234 					return (EINVAL);
11235 				}
11236 				mutex_enter(&connp->conn_lock);
11237 				connp->conn_ipv6_recvpathmtu = *i1;
11238 				mutex_exit(&connp->conn_lock);
11239 			}
11240 			break;
11241 		case IPV6_RECVHOPLIMIT:
11242 			if (!checkonly) {
11243 				mutex_enter(&connp->conn_lock);
11244 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11245 				mutex_exit(&connp->conn_lock);
11246 			}
11247 			break;	/* goto sizeof (int) option return */
11248 		case IPV6_RECVHOPOPTS:
11249 			if (!checkonly) {
11250 				mutex_enter(&connp->conn_lock);
11251 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11252 				mutex_exit(&connp->conn_lock);
11253 			}
11254 			break;	/* goto sizeof (int) option return */
11255 		case IPV6_RECVDSTOPTS:
11256 			if (!checkonly) {
11257 				mutex_enter(&connp->conn_lock);
11258 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11259 				mutex_exit(&connp->conn_lock);
11260 			}
11261 			break;	/* goto sizeof (int) option return */
11262 		case IPV6_RECVRTHDR:
11263 			if (!checkonly) {
11264 				mutex_enter(&connp->conn_lock);
11265 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11266 				mutex_exit(&connp->conn_lock);
11267 			}
11268 			break;	/* goto sizeof (int) option return */
11269 		case IPV6_RECVRTHDRDSTOPTS:
11270 			if (!checkonly) {
11271 				mutex_enter(&connp->conn_lock);
11272 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11273 				mutex_exit(&connp->conn_lock);
11274 			}
11275 			break;	/* goto sizeof (int) option return */
11276 		case IPV6_PKTINFO:
11277 			if (inlen == 0)
11278 				return (-EINVAL);	/* clearing option */
11279 			error = ip6_set_pktinfo(cr, connp,
11280 			    (struct in6_pktinfo *)invalp, first_mp);
11281 			if (error != 0)
11282 				*outlenp = 0;
11283 			else
11284 				*outlenp = inlen;
11285 			return (error);
11286 		case IPV6_NEXTHOP: {
11287 			struct sockaddr_in6 *sin6;
11288 
11289 			/* Verify that the nexthop is reachable */
11290 			if (inlen == 0)
11291 				return (-EINVAL);	/* clearing option */
11292 
11293 			sin6 = (struct sockaddr_in6 *)invalp;
11294 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11295 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11296 			    NULL, MATCH_IRE_DEFAULT, ipst);
11297 
11298 			if (ire == NULL) {
11299 				*outlenp = 0;
11300 				return (EHOSTUNREACH);
11301 			}
11302 			ire_refrele(ire);
11303 			return (-EINVAL);
11304 		}
11305 		case IPV6_SEC_OPT:
11306 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11307 			if (error != 0) {
11308 				*outlenp = 0;
11309 				return (error);
11310 			}
11311 			break;
11312 		case IPV6_SRC_PREFERENCES: {
11313 			/*
11314 			 * This is implemented strictly in the ip module
11315 			 * (here and in tcp_opt_*() to accomodate tcp
11316 			 * sockets).  Modules above ip pass this option
11317 			 * down here since ip is the only one that needs to
11318 			 * be aware of source address preferences.
11319 			 *
11320 			 * This socket option only affects connected
11321 			 * sockets that haven't already bound to a specific
11322 			 * IPv6 address.  In other words, sockets that
11323 			 * don't call bind() with an address other than the
11324 			 * unspecified address and that call connect().
11325 			 * ip_bind_connected_v6() passes these preferences
11326 			 * to the ipif_select_source_v6() function.
11327 			 */
11328 			if (inlen != sizeof (uint32_t))
11329 				return (EINVAL);
11330 			error = ip6_set_src_preferences(connp,
11331 			    *(uint32_t *)invalp);
11332 			if (error != 0) {
11333 				*outlenp = 0;
11334 				return (error);
11335 			} else {
11336 				*outlenp = sizeof (uint32_t);
11337 			}
11338 			break;
11339 		}
11340 		case IPV6_V6ONLY:
11341 			if (*i1 < 0 || *i1 > 1) {
11342 				return (EINVAL);
11343 			}
11344 			mutex_enter(&connp->conn_lock);
11345 			connp->conn_ipv6_v6only = *i1;
11346 			mutex_exit(&connp->conn_lock);
11347 			break;
11348 		default:
11349 			return (-EINVAL);
11350 		}
11351 		break;
11352 	default:
11353 		/*
11354 		 * "soft" error (negative)
11355 		 * option not handled at this level
11356 		 * Note: Do not modify *outlenp
11357 		 */
11358 		return (-EINVAL);
11359 	}
11360 	/*
11361 	 * Common case of return from an option that is sizeof (int)
11362 	 */
11363 	*(int *)outvalp = *i1;
11364 	*outlenp = sizeof (int);
11365 	return (0);
11366 }
11367 
11368 /*
11369  * This routine gets default values of certain options whose default
11370  * values are maintained by protocol specific code
11371  */
11372 /* ARGSUSED */
11373 int
11374 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11375 {
11376 	int *i1 = (int *)ptr;
11377 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11378 
11379 	switch (level) {
11380 	case IPPROTO_IP:
11381 		switch (name) {
11382 		case IP_MULTICAST_TTL:
11383 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11384 			return (sizeof (uchar_t));
11385 		case IP_MULTICAST_LOOP:
11386 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11387 			return (sizeof (uchar_t));
11388 		default:
11389 			return (-1);
11390 		}
11391 	case IPPROTO_IPV6:
11392 		switch (name) {
11393 		case IPV6_UNICAST_HOPS:
11394 			*i1 = ipst->ips_ipv6_def_hops;
11395 			return (sizeof (int));
11396 		case IPV6_MULTICAST_HOPS:
11397 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11398 			return (sizeof (int));
11399 		case IPV6_MULTICAST_LOOP:
11400 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11401 			return (sizeof (int));
11402 		case IPV6_V6ONLY:
11403 			*i1 = 1;
11404 			return (sizeof (int));
11405 		default:
11406 			return (-1);
11407 		}
11408 	default:
11409 		return (-1);
11410 	}
11411 	/* NOTREACHED */
11412 }
11413 
11414 /*
11415  * Given a destination address and a pointer to where to put the information
11416  * this routine fills in the mtuinfo.
11417  */
11418 int
11419 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11420     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11421 {
11422 	ire_t *ire;
11423 	ip_stack_t	*ipst = ns->netstack_ip;
11424 
11425 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11426 		return (-1);
11427 
11428 	bzero(mtuinfo, sizeof (*mtuinfo));
11429 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11430 	mtuinfo->ip6m_addr.sin6_port = port;
11431 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11432 
11433 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11434 	if (ire != NULL) {
11435 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11436 		ire_refrele(ire);
11437 	} else {
11438 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11439 	}
11440 	return (sizeof (struct ip6_mtuinfo));
11441 }
11442 
11443 /*
11444  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11445  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11446  * isn't.  This doesn't matter as the error checking is done properly for the
11447  * other MRT options coming in through ip_opt_set.
11448  */
11449 int
11450 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11451 {
11452 	conn_t		*connp = Q_TO_CONN(q);
11453 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11454 
11455 	switch (level) {
11456 	case IPPROTO_IP:
11457 		switch (name) {
11458 		case MRT_VERSION:
11459 		case MRT_ASSERT:
11460 			(void) ip_mrouter_get(name, q, ptr);
11461 			return (sizeof (int));
11462 		case IP_SEC_OPT:
11463 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11464 		case IP_NEXTHOP:
11465 			if (connp->conn_nexthop_set) {
11466 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11467 				return (sizeof (ipaddr_t));
11468 			} else
11469 				return (0);
11470 		case IP_RECVPKTINFO:
11471 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11472 			return (sizeof (int));
11473 		default:
11474 			break;
11475 		}
11476 		break;
11477 	case IPPROTO_IPV6:
11478 		switch (name) {
11479 		case IPV6_SEC_OPT:
11480 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11481 		case IPV6_SRC_PREFERENCES: {
11482 			return (ip6_get_src_preferences(connp,
11483 			    (uint32_t *)ptr));
11484 		}
11485 		case IPV6_V6ONLY:
11486 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11487 			return (sizeof (int));
11488 		case IPV6_PATHMTU:
11489 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11490 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11491 		default:
11492 			break;
11493 		}
11494 		break;
11495 	default:
11496 		break;
11497 	}
11498 	return (-1);
11499 }
11500 
11501 /* Named Dispatch routine to get a current value out of our parameter table. */
11502 /* ARGSUSED */
11503 static int
11504 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11505 {
11506 	ipparam_t *ippa = (ipparam_t *)cp;
11507 
11508 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11509 	return (0);
11510 }
11511 
11512 /* ARGSUSED */
11513 static int
11514 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11515 {
11516 
11517 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11518 	return (0);
11519 }
11520 
11521 /*
11522  * Set ip{,6}_forwarding values.  This means walking through all of the
11523  * ill's and toggling their forwarding values.
11524  */
11525 /* ARGSUSED */
11526 static int
11527 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11528 {
11529 	long new_value;
11530 	int *forwarding_value = (int *)cp;
11531 	ill_t *ill;
11532 	boolean_t isv6;
11533 	ill_walk_context_t ctx;
11534 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11535 
11536 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11537 
11538 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11539 	    new_value < 0 || new_value > 1) {
11540 		return (EINVAL);
11541 	}
11542 
11543 	*forwarding_value = new_value;
11544 
11545 	/*
11546 	 * Regardless of the current value of ip_forwarding, set all per-ill
11547 	 * values of ip_forwarding to the value being set.
11548 	 *
11549 	 * Bring all the ill's up to date with the new global value.
11550 	 */
11551 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11552 
11553 	if (isv6)
11554 		ill = ILL_START_WALK_V6(&ctx, ipst);
11555 	else
11556 		ill = ILL_START_WALK_V4(&ctx, ipst);
11557 
11558 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11559 		(void) ill_forward_set(ill, new_value != 0);
11560 
11561 	rw_exit(&ipst->ips_ill_g_lock);
11562 	return (0);
11563 }
11564 
11565 /*
11566  * Walk through the param array specified registering each element with the
11567  * Named Dispatch handler. This is called only during init. So it is ok
11568  * not to acquire any locks
11569  */
11570 static boolean_t
11571 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11572     ipndp_t *ipnd, size_t ipnd_cnt)
11573 {
11574 	for (; ippa_cnt-- > 0; ippa++) {
11575 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11576 			if (!nd_load(ndp, ippa->ip_param_name,
11577 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11578 				nd_free(ndp);
11579 				return (B_FALSE);
11580 			}
11581 		}
11582 	}
11583 
11584 	for (; ipnd_cnt-- > 0; ipnd++) {
11585 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11586 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11587 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11588 			    ipnd->ip_ndp_data)) {
11589 				nd_free(ndp);
11590 				return (B_FALSE);
11591 			}
11592 		}
11593 	}
11594 
11595 	return (B_TRUE);
11596 }
11597 
11598 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11599 /* ARGSUSED */
11600 static int
11601 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11602 {
11603 	long		new_value;
11604 	ipparam_t	*ippa = (ipparam_t *)cp;
11605 
11606 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11607 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11608 		return (EINVAL);
11609 	}
11610 	ippa->ip_param_value = new_value;
11611 	return (0);
11612 }
11613 
11614 /*
11615  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11616  * When an ipf is passed here for the first time, if
11617  * we already have in-order fragments on the queue, we convert from the fast-
11618  * path reassembly scheme to the hard-case scheme.  From then on, additional
11619  * fragments are reassembled here.  We keep track of the start and end offsets
11620  * of each piece, and the number of holes in the chain.  When the hole count
11621  * goes to zero, we are done!
11622  *
11623  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11624  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11625  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11626  * after the call to ip_reassemble().
11627  */
11628 int
11629 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11630     size_t msg_len)
11631 {
11632 	uint_t	end;
11633 	mblk_t	*next_mp;
11634 	mblk_t	*mp1;
11635 	uint_t	offset;
11636 	boolean_t incr_dups = B_TRUE;
11637 	boolean_t offset_zero_seen = B_FALSE;
11638 	boolean_t pkt_boundary_checked = B_FALSE;
11639 
11640 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11641 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11642 
11643 	/* Add in byte count */
11644 	ipf->ipf_count += msg_len;
11645 	if (ipf->ipf_end) {
11646 		/*
11647 		 * We were part way through in-order reassembly, but now there
11648 		 * is a hole.  We walk through messages already queued, and
11649 		 * mark them for hard case reassembly.  We know that up till
11650 		 * now they were in order starting from offset zero.
11651 		 */
11652 		offset = 0;
11653 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11654 			IP_REASS_SET_START(mp1, offset);
11655 			if (offset == 0) {
11656 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11657 				offset = -ipf->ipf_nf_hdr_len;
11658 			}
11659 			offset += mp1->b_wptr - mp1->b_rptr;
11660 			IP_REASS_SET_END(mp1, offset);
11661 		}
11662 		/* One hole at the end. */
11663 		ipf->ipf_hole_cnt = 1;
11664 		/* Brand it as a hard case, forever. */
11665 		ipf->ipf_end = 0;
11666 	}
11667 	/* Walk through all the new pieces. */
11668 	do {
11669 		end = start + (mp->b_wptr - mp->b_rptr);
11670 		/*
11671 		 * If start is 0, decrease 'end' only for the first mblk of
11672 		 * the fragment. Otherwise 'end' can get wrong value in the
11673 		 * second pass of the loop if first mblk is exactly the
11674 		 * size of ipf_nf_hdr_len.
11675 		 */
11676 		if (start == 0 && !offset_zero_seen) {
11677 			/* First segment */
11678 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11679 			end -= ipf->ipf_nf_hdr_len;
11680 			offset_zero_seen = B_TRUE;
11681 		}
11682 		next_mp = mp->b_cont;
11683 		/*
11684 		 * We are checking to see if there is any interesing data
11685 		 * to process.  If there isn't and the mblk isn't the
11686 		 * one which carries the unfragmentable header then we
11687 		 * drop it.  It's possible to have just the unfragmentable
11688 		 * header come through without any data.  That needs to be
11689 		 * saved.
11690 		 *
11691 		 * If the assert at the top of this function holds then the
11692 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11693 		 * is infrequently traveled enough that the test is left in
11694 		 * to protect against future code changes which break that
11695 		 * invariant.
11696 		 */
11697 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11698 			/* Empty.  Blast it. */
11699 			IP_REASS_SET_START(mp, 0);
11700 			IP_REASS_SET_END(mp, 0);
11701 			/*
11702 			 * If the ipf points to the mblk we are about to free,
11703 			 * update ipf to point to the next mblk (or NULL
11704 			 * if none).
11705 			 */
11706 			if (ipf->ipf_mp->b_cont == mp)
11707 				ipf->ipf_mp->b_cont = next_mp;
11708 			freeb(mp);
11709 			continue;
11710 		}
11711 		mp->b_cont = NULL;
11712 		IP_REASS_SET_START(mp, start);
11713 		IP_REASS_SET_END(mp, end);
11714 		if (!ipf->ipf_tail_mp) {
11715 			ipf->ipf_tail_mp = mp;
11716 			ipf->ipf_mp->b_cont = mp;
11717 			if (start == 0 || !more) {
11718 				ipf->ipf_hole_cnt = 1;
11719 				/*
11720 				 * if the first fragment comes in more than one
11721 				 * mblk, this loop will be executed for each
11722 				 * mblk. Need to adjust hole count so exiting
11723 				 * this routine will leave hole count at 1.
11724 				 */
11725 				if (next_mp)
11726 					ipf->ipf_hole_cnt++;
11727 			} else
11728 				ipf->ipf_hole_cnt = 2;
11729 			continue;
11730 		} else if (ipf->ipf_last_frag_seen && !more &&
11731 		    !pkt_boundary_checked) {
11732 			/*
11733 			 * We check datagram boundary only if this fragment
11734 			 * claims to be the last fragment and we have seen a
11735 			 * last fragment in the past too. We do this only
11736 			 * once for a given fragment.
11737 			 *
11738 			 * start cannot be 0 here as fragments with start=0
11739 			 * and MF=0 gets handled as a complete packet. These
11740 			 * fragments should not reach here.
11741 			 */
11742 
11743 			if (start + msgdsize(mp) !=
11744 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11745 				/*
11746 				 * We have two fragments both of which claim
11747 				 * to be the last fragment but gives conflicting
11748 				 * information about the whole datagram size.
11749 				 * Something fishy is going on. Drop the
11750 				 * fragment and free up the reassembly list.
11751 				 */
11752 				return (IP_REASS_FAILED);
11753 			}
11754 
11755 			/*
11756 			 * We shouldn't come to this code block again for this
11757 			 * particular fragment.
11758 			 */
11759 			pkt_boundary_checked = B_TRUE;
11760 		}
11761 
11762 		/* New stuff at or beyond tail? */
11763 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11764 		if (start >= offset) {
11765 			if (ipf->ipf_last_frag_seen) {
11766 				/* current fragment is beyond last fragment */
11767 				return (IP_REASS_FAILED);
11768 			}
11769 			/* Link it on end. */
11770 			ipf->ipf_tail_mp->b_cont = mp;
11771 			ipf->ipf_tail_mp = mp;
11772 			if (more) {
11773 				if (start != offset)
11774 					ipf->ipf_hole_cnt++;
11775 			} else if (start == offset && next_mp == NULL)
11776 					ipf->ipf_hole_cnt--;
11777 			continue;
11778 		}
11779 		mp1 = ipf->ipf_mp->b_cont;
11780 		offset = IP_REASS_START(mp1);
11781 		/* New stuff at the front? */
11782 		if (start < offset) {
11783 			if (start == 0) {
11784 				if (end >= offset) {
11785 					/* Nailed the hole at the begining. */
11786 					ipf->ipf_hole_cnt--;
11787 				}
11788 			} else if (end < offset) {
11789 				/*
11790 				 * A hole, stuff, and a hole where there used
11791 				 * to be just a hole.
11792 				 */
11793 				ipf->ipf_hole_cnt++;
11794 			}
11795 			mp->b_cont = mp1;
11796 			/* Check for overlap. */
11797 			while (end > offset) {
11798 				if (end < IP_REASS_END(mp1)) {
11799 					mp->b_wptr -= end - offset;
11800 					IP_REASS_SET_END(mp, offset);
11801 					BUMP_MIB(ill->ill_ip_mib,
11802 					    ipIfStatsReasmPartDups);
11803 					break;
11804 				}
11805 				/* Did we cover another hole? */
11806 				if ((mp1->b_cont &&
11807 				    IP_REASS_END(mp1) !=
11808 				    IP_REASS_START(mp1->b_cont) &&
11809 				    end >= IP_REASS_START(mp1->b_cont)) ||
11810 				    (!ipf->ipf_last_frag_seen && !more)) {
11811 					ipf->ipf_hole_cnt--;
11812 				}
11813 				/* Clip out mp1. */
11814 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11815 					/*
11816 					 * After clipping out mp1, this guy
11817 					 * is now hanging off the end.
11818 					 */
11819 					ipf->ipf_tail_mp = mp;
11820 				}
11821 				IP_REASS_SET_START(mp1, 0);
11822 				IP_REASS_SET_END(mp1, 0);
11823 				/* Subtract byte count */
11824 				ipf->ipf_count -= mp1->b_datap->db_lim -
11825 				    mp1->b_datap->db_base;
11826 				freeb(mp1);
11827 				BUMP_MIB(ill->ill_ip_mib,
11828 				    ipIfStatsReasmPartDups);
11829 				mp1 = mp->b_cont;
11830 				if (!mp1)
11831 					break;
11832 				offset = IP_REASS_START(mp1);
11833 			}
11834 			ipf->ipf_mp->b_cont = mp;
11835 			continue;
11836 		}
11837 		/*
11838 		 * The new piece starts somewhere between the start of the head
11839 		 * and before the end of the tail.
11840 		 */
11841 		for (; mp1; mp1 = mp1->b_cont) {
11842 			offset = IP_REASS_END(mp1);
11843 			if (start < offset) {
11844 				if (end <= offset) {
11845 					/* Nothing new. */
11846 					IP_REASS_SET_START(mp, 0);
11847 					IP_REASS_SET_END(mp, 0);
11848 					/* Subtract byte count */
11849 					ipf->ipf_count -= mp->b_datap->db_lim -
11850 					    mp->b_datap->db_base;
11851 					if (incr_dups) {
11852 						ipf->ipf_num_dups++;
11853 						incr_dups = B_FALSE;
11854 					}
11855 					freeb(mp);
11856 					BUMP_MIB(ill->ill_ip_mib,
11857 					    ipIfStatsReasmDuplicates);
11858 					break;
11859 				}
11860 				/*
11861 				 * Trim redundant stuff off beginning of new
11862 				 * piece.
11863 				 */
11864 				IP_REASS_SET_START(mp, offset);
11865 				mp->b_rptr += offset - start;
11866 				BUMP_MIB(ill->ill_ip_mib,
11867 				    ipIfStatsReasmPartDups);
11868 				start = offset;
11869 				if (!mp1->b_cont) {
11870 					/*
11871 					 * After trimming, this guy is now
11872 					 * hanging off the end.
11873 					 */
11874 					mp1->b_cont = mp;
11875 					ipf->ipf_tail_mp = mp;
11876 					if (!more) {
11877 						ipf->ipf_hole_cnt--;
11878 					}
11879 					break;
11880 				}
11881 			}
11882 			if (start >= IP_REASS_START(mp1->b_cont))
11883 				continue;
11884 			/* Fill a hole */
11885 			if (start > offset)
11886 				ipf->ipf_hole_cnt++;
11887 			mp->b_cont = mp1->b_cont;
11888 			mp1->b_cont = mp;
11889 			mp1 = mp->b_cont;
11890 			offset = IP_REASS_START(mp1);
11891 			if (end >= offset) {
11892 				ipf->ipf_hole_cnt--;
11893 				/* Check for overlap. */
11894 				while (end > offset) {
11895 					if (end < IP_REASS_END(mp1)) {
11896 						mp->b_wptr -= end - offset;
11897 						IP_REASS_SET_END(mp, offset);
11898 						/*
11899 						 * TODO we might bump
11900 						 * this up twice if there is
11901 						 * overlap at both ends.
11902 						 */
11903 						BUMP_MIB(ill->ill_ip_mib,
11904 						    ipIfStatsReasmPartDups);
11905 						break;
11906 					}
11907 					/* Did we cover another hole? */
11908 					if ((mp1->b_cont &&
11909 					    IP_REASS_END(mp1)
11910 					    != IP_REASS_START(mp1->b_cont) &&
11911 					    end >=
11912 					    IP_REASS_START(mp1->b_cont)) ||
11913 					    (!ipf->ipf_last_frag_seen &&
11914 					    !more)) {
11915 						ipf->ipf_hole_cnt--;
11916 					}
11917 					/* Clip out mp1. */
11918 					if ((mp->b_cont = mp1->b_cont) ==
11919 					    NULL) {
11920 						/*
11921 						 * After clipping out mp1,
11922 						 * this guy is now hanging
11923 						 * off the end.
11924 						 */
11925 						ipf->ipf_tail_mp = mp;
11926 					}
11927 					IP_REASS_SET_START(mp1, 0);
11928 					IP_REASS_SET_END(mp1, 0);
11929 					/* Subtract byte count */
11930 					ipf->ipf_count -=
11931 					    mp1->b_datap->db_lim -
11932 					    mp1->b_datap->db_base;
11933 					freeb(mp1);
11934 					BUMP_MIB(ill->ill_ip_mib,
11935 					    ipIfStatsReasmPartDups);
11936 					mp1 = mp->b_cont;
11937 					if (!mp1)
11938 						break;
11939 					offset = IP_REASS_START(mp1);
11940 				}
11941 			}
11942 			break;
11943 		}
11944 	} while (start = end, mp = next_mp);
11945 
11946 	/* Fragment just processed could be the last one. Remember this fact */
11947 	if (!more)
11948 		ipf->ipf_last_frag_seen = B_TRUE;
11949 
11950 	/* Still got holes? */
11951 	if (ipf->ipf_hole_cnt)
11952 		return (IP_REASS_PARTIAL);
11953 	/* Clean up overloaded fields to avoid upstream disasters. */
11954 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11955 		IP_REASS_SET_START(mp1, 0);
11956 		IP_REASS_SET_END(mp1, 0);
11957 	}
11958 	return (IP_REASS_COMPLETE);
11959 }
11960 
11961 /*
11962  * ipsec processing for the fast path, used for input UDP Packets
11963  */
11964 static boolean_t
11965 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
11966     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present)
11967 {
11968 	uint32_t	ill_index;
11969 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
11970 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
11971 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
11972 
11973 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
11974 	/* The ill_index of the incoming ILL */
11975 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
11976 
11977 	/* pass packet up to the transport */
11978 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
11979 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
11980 		    NULL, mctl_present);
11981 		if (*first_mpp == NULL) {
11982 			return (B_FALSE);
11983 		}
11984 	}
11985 
11986 	/* Initiate IPPF processing for fastpath UDP */
11987 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
11988 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
11989 		if (*mpp == NULL) {
11990 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
11991 			    "deferred/dropped during IPPF processing\n"));
11992 			return (B_FALSE);
11993 		}
11994 	}
11995 	/*
11996 	 * We make the checks as below since we are in the fast path
11997 	 * and want to minimize the number of checks if the IP_RECVIF and/or
11998 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
11999 	 */
12000 	if (connp->conn_recvif || connp->conn_recvslla ||
12001 	    connp->conn_ip_recvpktinfo) {
12002 		if (connp->conn_recvif) {
12003 			in_flags = IPF_RECVIF;
12004 		}
12005 		/*
12006 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12007 		 * so the flag passed to ip_add_info is based on IP version
12008 		 * of connp.
12009 		 */
12010 		if (connp->conn_ip_recvpktinfo) {
12011 			if (connp->conn_af_isv6) {
12012 				/*
12013 				 * V6 only needs index
12014 				 */
12015 				in_flags |= IPF_RECVIF;
12016 			} else {
12017 				/*
12018 				 * V4 needs index + matching address.
12019 				 */
12020 				in_flags |= IPF_RECVADDR;
12021 			}
12022 		}
12023 		if (connp->conn_recvslla) {
12024 			in_flags |= IPF_RECVSLLA;
12025 		}
12026 		/*
12027 		 * since in_flags are being set ill will be
12028 		 * referenced in ip_add_info, so it better not
12029 		 * be NULL.
12030 		 */
12031 		/*
12032 		 * the actual data will be contained in b_cont
12033 		 * upon successful return of the following call.
12034 		 * If the call fails then the original mblk is
12035 		 * returned.
12036 		 */
12037 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12038 		    ipst);
12039 	}
12040 
12041 	return (B_TRUE);
12042 }
12043 
12044 /*
12045  * Fragmentation reassembly.  Each ILL has a hash table for
12046  * queuing packets undergoing reassembly for all IPIFs
12047  * associated with the ILL.  The hash is based on the packet
12048  * IP ident field.  The ILL frag hash table was allocated
12049  * as a timer block at the time the ILL was created.  Whenever
12050  * there is anything on the reassembly queue, the timer will
12051  * be running.  Returns B_TRUE if successful else B_FALSE;
12052  * frees mp on failure.
12053  */
12054 static boolean_t
12055 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12056     uint32_t *cksum_val, uint16_t *cksum_flags)
12057 {
12058 	uint32_t	frag_offset_flags;
12059 	ill_t		*ill = (ill_t *)q->q_ptr;
12060 	mblk_t		*mp = *mpp;
12061 	mblk_t		*t_mp;
12062 	ipaddr_t	dst;
12063 	uint8_t		proto = ipha->ipha_protocol;
12064 	uint32_t	sum_val;
12065 	uint16_t	sum_flags;
12066 	ipf_t		*ipf;
12067 	ipf_t		**ipfp;
12068 	ipfb_t		*ipfb;
12069 	uint16_t	ident;
12070 	uint32_t	offset;
12071 	ipaddr_t	src;
12072 	uint_t		hdr_length;
12073 	uint32_t	end;
12074 	mblk_t		*mp1;
12075 	mblk_t		*tail_mp;
12076 	size_t		count;
12077 	size_t		msg_len;
12078 	uint8_t		ecn_info = 0;
12079 	uint32_t	packet_size;
12080 	boolean_t	pruned = B_FALSE;
12081 	ip_stack_t *ipst = ill->ill_ipst;
12082 
12083 	if (cksum_val != NULL)
12084 		*cksum_val = 0;
12085 	if (cksum_flags != NULL)
12086 		*cksum_flags = 0;
12087 
12088 	/*
12089 	 * Drop the fragmented as early as possible, if
12090 	 * we don't have resource(s) to re-assemble.
12091 	 */
12092 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12093 		freemsg(mp);
12094 		return (B_FALSE);
12095 	}
12096 
12097 	/* Check for fragmentation offset; return if there's none */
12098 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12099 	    (IPH_MF | IPH_OFFSET)) == 0)
12100 		return (B_TRUE);
12101 
12102 	/*
12103 	 * We utilize hardware computed checksum info only for UDP since
12104 	 * IP fragmentation is a normal occurence for the protocol.  In
12105 	 * addition, checksum offload support for IP fragments carrying
12106 	 * UDP payload is commonly implemented across network adapters.
12107 	 */
12108 	ASSERT(ill != NULL);
12109 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12110 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12111 		mblk_t *mp1 = mp->b_cont;
12112 		int32_t len;
12113 
12114 		/* Record checksum information from the packet */
12115 		sum_val = (uint32_t)DB_CKSUM16(mp);
12116 		sum_flags = DB_CKSUMFLAGS(mp);
12117 
12118 		/* IP payload offset from beginning of mblk */
12119 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12120 
12121 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12122 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12123 		    offset >= DB_CKSUMSTART(mp) &&
12124 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12125 			uint32_t adj;
12126 			/*
12127 			 * Partial checksum has been calculated by hardware
12128 			 * and attached to the packet; in addition, any
12129 			 * prepended extraneous data is even byte aligned.
12130 			 * If any such data exists, we adjust the checksum;
12131 			 * this would also handle any postpended data.
12132 			 */
12133 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12134 			    mp, mp1, len, adj);
12135 
12136 			/* One's complement subtract extraneous checksum */
12137 			if (adj >= sum_val)
12138 				sum_val = ~(adj - sum_val) & 0xFFFF;
12139 			else
12140 				sum_val -= adj;
12141 		}
12142 	} else {
12143 		sum_val = 0;
12144 		sum_flags = 0;
12145 	}
12146 
12147 	/* Clear hardware checksumming flag */
12148 	DB_CKSUMFLAGS(mp) = 0;
12149 
12150 	ident = ipha->ipha_ident;
12151 	offset = (frag_offset_flags << 3) & 0xFFFF;
12152 	src = ipha->ipha_src;
12153 	dst = ipha->ipha_dst;
12154 	hdr_length = IPH_HDR_LENGTH(ipha);
12155 	end = ntohs(ipha->ipha_length) - hdr_length;
12156 
12157 	/* If end == 0 then we have a packet with no data, so just free it */
12158 	if (end == 0) {
12159 		freemsg(mp);
12160 		return (B_FALSE);
12161 	}
12162 
12163 	/* Record the ECN field info. */
12164 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12165 	if (offset != 0) {
12166 		/*
12167 		 * If this isn't the first piece, strip the header, and
12168 		 * add the offset to the end value.
12169 		 */
12170 		mp->b_rptr += hdr_length;
12171 		end += offset;
12172 	}
12173 
12174 	msg_len = MBLKSIZE(mp);
12175 	tail_mp = mp;
12176 	while (tail_mp->b_cont != NULL) {
12177 		tail_mp = tail_mp->b_cont;
12178 		msg_len += MBLKSIZE(tail_mp);
12179 	}
12180 
12181 	/* If the reassembly list for this ILL will get too big, prune it */
12182 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12183 	    ipst->ips_ip_reass_queue_bytes) {
12184 		ill_frag_prune(ill,
12185 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12186 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12187 		pruned = B_TRUE;
12188 	}
12189 
12190 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12191 	mutex_enter(&ipfb->ipfb_lock);
12192 
12193 	ipfp = &ipfb->ipfb_ipf;
12194 	/* Try to find an existing fragment queue for this packet. */
12195 	for (;;) {
12196 		ipf = ipfp[0];
12197 		if (ipf != NULL) {
12198 			/*
12199 			 * It has to match on ident and src/dst address.
12200 			 */
12201 			if (ipf->ipf_ident == ident &&
12202 			    ipf->ipf_src == src &&
12203 			    ipf->ipf_dst == dst &&
12204 			    ipf->ipf_protocol == proto) {
12205 				/*
12206 				 * If we have received too many
12207 				 * duplicate fragments for this packet
12208 				 * free it.
12209 				 */
12210 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12211 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12212 					freemsg(mp);
12213 					mutex_exit(&ipfb->ipfb_lock);
12214 					return (B_FALSE);
12215 				}
12216 				/* Found it. */
12217 				break;
12218 			}
12219 			ipfp = &ipf->ipf_hash_next;
12220 			continue;
12221 		}
12222 
12223 		/*
12224 		 * If we pruned the list, do we want to store this new
12225 		 * fragment?. We apply an optimization here based on the
12226 		 * fact that most fragments will be received in order.
12227 		 * So if the offset of this incoming fragment is zero,
12228 		 * it is the first fragment of a new packet. We will
12229 		 * keep it.  Otherwise drop the fragment, as we have
12230 		 * probably pruned the packet already (since the
12231 		 * packet cannot be found).
12232 		 */
12233 		if (pruned && offset != 0) {
12234 			mutex_exit(&ipfb->ipfb_lock);
12235 			freemsg(mp);
12236 			return (B_FALSE);
12237 		}
12238 
12239 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12240 			/*
12241 			 * Too many fragmented packets in this hash
12242 			 * bucket. Free the oldest.
12243 			 */
12244 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12245 		}
12246 
12247 		/* New guy.  Allocate a frag message. */
12248 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12249 		if (mp1 == NULL) {
12250 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12251 			freemsg(mp);
12252 reass_done:
12253 			mutex_exit(&ipfb->ipfb_lock);
12254 			return (B_FALSE);
12255 		}
12256 
12257 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12258 		mp1->b_cont = mp;
12259 
12260 		/* Initialize the fragment header. */
12261 		ipf = (ipf_t *)mp1->b_rptr;
12262 		ipf->ipf_mp = mp1;
12263 		ipf->ipf_ptphn = ipfp;
12264 		ipfp[0] = ipf;
12265 		ipf->ipf_hash_next = NULL;
12266 		ipf->ipf_ident = ident;
12267 		ipf->ipf_protocol = proto;
12268 		ipf->ipf_src = src;
12269 		ipf->ipf_dst = dst;
12270 		ipf->ipf_nf_hdr_len = 0;
12271 		/* Record reassembly start time. */
12272 		ipf->ipf_timestamp = gethrestime_sec();
12273 		/* Record ipf generation and account for frag header */
12274 		ipf->ipf_gen = ill->ill_ipf_gen++;
12275 		ipf->ipf_count = MBLKSIZE(mp1);
12276 		ipf->ipf_last_frag_seen = B_FALSE;
12277 		ipf->ipf_ecn = ecn_info;
12278 		ipf->ipf_num_dups = 0;
12279 		ipfb->ipfb_frag_pkts++;
12280 		ipf->ipf_checksum = 0;
12281 		ipf->ipf_checksum_flags = 0;
12282 
12283 		/* Store checksum value in fragment header */
12284 		if (sum_flags != 0) {
12285 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12286 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12287 			ipf->ipf_checksum = sum_val;
12288 			ipf->ipf_checksum_flags = sum_flags;
12289 		}
12290 
12291 		/*
12292 		 * We handle reassembly two ways.  In the easy case,
12293 		 * where all the fragments show up in order, we do
12294 		 * minimal bookkeeping, and just clip new pieces on
12295 		 * the end.  If we ever see a hole, then we go off
12296 		 * to ip_reassemble which has to mark the pieces and
12297 		 * keep track of the number of holes, etc.  Obviously,
12298 		 * the point of having both mechanisms is so we can
12299 		 * handle the easy case as efficiently as possible.
12300 		 */
12301 		if (offset == 0) {
12302 			/* Easy case, in-order reassembly so far. */
12303 			ipf->ipf_count += msg_len;
12304 			ipf->ipf_tail_mp = tail_mp;
12305 			/*
12306 			 * Keep track of next expected offset in
12307 			 * ipf_end.
12308 			 */
12309 			ipf->ipf_end = end;
12310 			ipf->ipf_nf_hdr_len = hdr_length;
12311 		} else {
12312 			/* Hard case, hole at the beginning. */
12313 			ipf->ipf_tail_mp = NULL;
12314 			/*
12315 			 * ipf_end == 0 means that we have given up
12316 			 * on easy reassembly.
12317 			 */
12318 			ipf->ipf_end = 0;
12319 
12320 			/* Forget checksum offload from now on */
12321 			ipf->ipf_checksum_flags = 0;
12322 
12323 			/*
12324 			 * ipf_hole_cnt is set by ip_reassemble.
12325 			 * ipf_count is updated by ip_reassemble.
12326 			 * No need to check for return value here
12327 			 * as we don't expect reassembly to complete
12328 			 * or fail for the first fragment itself.
12329 			 */
12330 			(void) ip_reassemble(mp, ipf,
12331 			    (frag_offset_flags & IPH_OFFSET) << 3,
12332 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12333 		}
12334 		/* Update per ipfb and ill byte counts */
12335 		ipfb->ipfb_count += ipf->ipf_count;
12336 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12337 		ill->ill_frag_count += ipf->ipf_count;
12338 		/* If the frag timer wasn't already going, start it. */
12339 		mutex_enter(&ill->ill_lock);
12340 		ill_frag_timer_start(ill);
12341 		mutex_exit(&ill->ill_lock);
12342 		goto reass_done;
12343 	}
12344 
12345 	/*
12346 	 * If the packet's flag has changed (it could be coming up
12347 	 * from an interface different than the previous, therefore
12348 	 * possibly different checksum capability), then forget about
12349 	 * any stored checksum states.  Otherwise add the value to
12350 	 * the existing one stored in the fragment header.
12351 	 */
12352 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12353 		sum_val += ipf->ipf_checksum;
12354 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12355 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12356 		ipf->ipf_checksum = sum_val;
12357 	} else if (ipf->ipf_checksum_flags != 0) {
12358 		/* Forget checksum offload from now on */
12359 		ipf->ipf_checksum_flags = 0;
12360 	}
12361 
12362 	/*
12363 	 * We have a new piece of a datagram which is already being
12364 	 * reassembled.  Update the ECN info if all IP fragments
12365 	 * are ECN capable.  If there is one which is not, clear
12366 	 * all the info.  If there is at least one which has CE
12367 	 * code point, IP needs to report that up to transport.
12368 	 */
12369 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12370 		if (ecn_info == IPH_ECN_CE)
12371 			ipf->ipf_ecn = IPH_ECN_CE;
12372 	} else {
12373 		ipf->ipf_ecn = IPH_ECN_NECT;
12374 	}
12375 	if (offset && ipf->ipf_end == offset) {
12376 		/* The new fragment fits at the end */
12377 		ipf->ipf_tail_mp->b_cont = mp;
12378 		/* Update the byte count */
12379 		ipf->ipf_count += msg_len;
12380 		/* Update per ipfb and ill byte counts */
12381 		ipfb->ipfb_count += msg_len;
12382 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12383 		ill->ill_frag_count += msg_len;
12384 		if (frag_offset_flags & IPH_MF) {
12385 			/* More to come. */
12386 			ipf->ipf_end = end;
12387 			ipf->ipf_tail_mp = tail_mp;
12388 			goto reass_done;
12389 		}
12390 	} else {
12391 		/* Go do the hard cases. */
12392 		int ret;
12393 
12394 		if (offset == 0)
12395 			ipf->ipf_nf_hdr_len = hdr_length;
12396 
12397 		/* Save current byte count */
12398 		count = ipf->ipf_count;
12399 		ret = ip_reassemble(mp, ipf,
12400 		    (frag_offset_flags & IPH_OFFSET) << 3,
12401 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12402 		/* Count of bytes added and subtracted (freeb()ed) */
12403 		count = ipf->ipf_count - count;
12404 		if (count) {
12405 			/* Update per ipfb and ill byte counts */
12406 			ipfb->ipfb_count += count;
12407 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12408 			ill->ill_frag_count += count;
12409 		}
12410 		if (ret == IP_REASS_PARTIAL) {
12411 			goto reass_done;
12412 		} else if (ret == IP_REASS_FAILED) {
12413 			/* Reassembly failed. Free up all resources */
12414 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12415 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12416 				IP_REASS_SET_START(t_mp, 0);
12417 				IP_REASS_SET_END(t_mp, 0);
12418 			}
12419 			freemsg(mp);
12420 			goto reass_done;
12421 		}
12422 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12423 	}
12424 	/*
12425 	 * We have completed reassembly.  Unhook the frag header from
12426 	 * the reassembly list.
12427 	 *
12428 	 * Before we free the frag header, record the ECN info
12429 	 * to report back to the transport.
12430 	 */
12431 	ecn_info = ipf->ipf_ecn;
12432 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12433 	ipfp = ipf->ipf_ptphn;
12434 
12435 	/* We need to supply these to caller */
12436 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12437 		sum_val = ipf->ipf_checksum;
12438 	else
12439 		sum_val = 0;
12440 
12441 	mp1 = ipf->ipf_mp;
12442 	count = ipf->ipf_count;
12443 	ipf = ipf->ipf_hash_next;
12444 	if (ipf != NULL)
12445 		ipf->ipf_ptphn = ipfp;
12446 	ipfp[0] = ipf;
12447 	ill->ill_frag_count -= count;
12448 	ASSERT(ipfb->ipfb_count >= count);
12449 	ipfb->ipfb_count -= count;
12450 	ipfb->ipfb_frag_pkts--;
12451 	mutex_exit(&ipfb->ipfb_lock);
12452 	/* Ditch the frag header. */
12453 	mp = mp1->b_cont;
12454 
12455 	freeb(mp1);
12456 
12457 	/* Restore original IP length in header. */
12458 	packet_size = (uint32_t)msgdsize(mp);
12459 	if (packet_size > IP_MAXPACKET) {
12460 		freemsg(mp);
12461 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12462 		return (B_FALSE);
12463 	}
12464 
12465 	if (DB_REF(mp) > 1) {
12466 		mblk_t *mp2 = copymsg(mp);
12467 
12468 		freemsg(mp);
12469 		if (mp2 == NULL) {
12470 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12471 			return (B_FALSE);
12472 		}
12473 		mp = mp2;
12474 	}
12475 	ipha = (ipha_t *)mp->b_rptr;
12476 
12477 	ipha->ipha_length = htons((uint16_t)packet_size);
12478 	/* We're now complete, zip the frag state */
12479 	ipha->ipha_fragment_offset_and_flags = 0;
12480 	/* Record the ECN info. */
12481 	ipha->ipha_type_of_service &= 0xFC;
12482 	ipha->ipha_type_of_service |= ecn_info;
12483 	*mpp = mp;
12484 
12485 	/* Reassembly is successful; return checksum information if needed */
12486 	if (cksum_val != NULL)
12487 		*cksum_val = sum_val;
12488 	if (cksum_flags != NULL)
12489 		*cksum_flags = sum_flags;
12490 
12491 	return (B_TRUE);
12492 }
12493 
12494 /*
12495  * Perform ip header check sum update local options.
12496  * return B_TRUE if all is well, else return B_FALSE and release
12497  * the mp. caller is responsible for decrementing ire ref cnt.
12498  */
12499 static boolean_t
12500 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12501     ip_stack_t *ipst)
12502 {
12503 	mblk_t		*first_mp;
12504 	boolean_t	mctl_present;
12505 	uint16_t	sum;
12506 
12507 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12508 	/*
12509 	 * Don't do the checksum if it has gone through AH/ESP
12510 	 * processing.
12511 	 */
12512 	if (!mctl_present) {
12513 		sum = ip_csum_hdr(ipha);
12514 		if (sum != 0) {
12515 			if (ill != NULL) {
12516 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12517 			} else {
12518 				BUMP_MIB(&ipst->ips_ip_mib,
12519 				    ipIfStatsInCksumErrs);
12520 			}
12521 			freemsg(first_mp);
12522 			return (B_FALSE);
12523 		}
12524 	}
12525 
12526 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12527 		if (mctl_present)
12528 			freeb(first_mp);
12529 		return (B_FALSE);
12530 	}
12531 
12532 	return (B_TRUE);
12533 }
12534 
12535 /*
12536  * All udp packet are delivered to the local host via this routine.
12537  */
12538 void
12539 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12540     ill_t *recv_ill)
12541 {
12542 	uint32_t	sum;
12543 	uint32_t	u1;
12544 	boolean_t	mctl_present;
12545 	conn_t		*connp;
12546 	mblk_t		*first_mp;
12547 	uint16_t	*up;
12548 	ill_t		*ill = (ill_t *)q->q_ptr;
12549 	uint16_t	reass_hck_flags = 0;
12550 	ip_stack_t	*ipst;
12551 
12552 	ASSERT(recv_ill != NULL);
12553 	ipst = recv_ill->ill_ipst;
12554 
12555 #define	rptr    ((uchar_t *)ipha)
12556 
12557 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12558 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12559 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12560 	ASSERT(ill != NULL);
12561 
12562 	/*
12563 	 * FAST PATH for udp packets
12564 	 */
12565 
12566 	/* u1 is # words of IP options */
12567 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12568 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12569 
12570 	/* IP options present */
12571 	if (u1 != 0)
12572 		goto ipoptions;
12573 
12574 	/* Check the IP header checksum.  */
12575 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12576 		/* Clear the IP header h/w cksum flag */
12577 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12578 	} else {
12579 #define	uph	((uint16_t *)ipha)
12580 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12581 		    uph[6] + uph[7] + uph[8] + uph[9];
12582 #undef	uph
12583 		/* finish doing IP checksum */
12584 		sum = (sum & 0xFFFF) + (sum >> 16);
12585 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12586 		/*
12587 		 * Don't verify header checksum if this packet is coming
12588 		 * back from AH/ESP as we already did it.
12589 		 */
12590 		if (!mctl_present && sum != 0 && sum != 0xFFFF) {
12591 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12592 			freemsg(first_mp);
12593 			return;
12594 		}
12595 	}
12596 
12597 	/*
12598 	 * Count for SNMP of inbound packets for ire.
12599 	 * if mctl is present this might be a secure packet and
12600 	 * has already been counted for in ip_proto_input().
12601 	 */
12602 	if (!mctl_present) {
12603 		UPDATE_IB_PKT_COUNT(ire);
12604 		ire->ire_last_used_time = lbolt;
12605 	}
12606 
12607 	/* packet part of fragmented IP packet? */
12608 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12609 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12610 		goto fragmented;
12611 	}
12612 
12613 	/* u1 = IP header length (20 bytes) */
12614 	u1 = IP_SIMPLE_HDR_LENGTH;
12615 
12616 	/* packet does not contain complete IP & UDP headers */
12617 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12618 		goto udppullup;
12619 
12620 	/* up points to UDP header */
12621 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12622 #define	iphs    ((uint16_t *)ipha)
12623 
12624 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12625 	if (up[3] != 0) {
12626 		mblk_t *mp1 = mp->b_cont;
12627 		boolean_t cksum_err;
12628 		uint16_t hck_flags = 0;
12629 
12630 		/* Pseudo-header checksum */
12631 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12632 		    iphs[9] + up[2];
12633 
12634 		/*
12635 		 * Revert to software checksum calculation if the interface
12636 		 * isn't capable of checksum offload or if IPsec is present.
12637 		 */
12638 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12639 			hck_flags = DB_CKSUMFLAGS(mp);
12640 
12641 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12642 			IP_STAT(ipst, ip_in_sw_cksum);
12643 
12644 		IP_CKSUM_RECV(hck_flags, u1,
12645 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12646 		    (int32_t)((uchar_t *)up - rptr),
12647 		    mp, mp1, cksum_err);
12648 
12649 		if (cksum_err) {
12650 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12651 			if (hck_flags & HCK_FULLCKSUM)
12652 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12653 			else if (hck_flags & HCK_PARTIALCKSUM)
12654 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12655 			else
12656 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12657 
12658 			freemsg(first_mp);
12659 			return;
12660 		}
12661 	}
12662 
12663 	/* Non-fragmented broadcast or multicast packet? */
12664 	if (ire->ire_type == IRE_BROADCAST)
12665 		goto udpslowpath;
12666 
12667 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12668 	    ire->ire_zoneid, ipst)) != NULL) {
12669 		ASSERT(connp->conn_upq != NULL);
12670 		IP_STAT(ipst, ip_udp_fast_path);
12671 
12672 		if (CONN_UDP_FLOWCTLD(connp)) {
12673 			freemsg(mp);
12674 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12675 		} else {
12676 			if (!mctl_present) {
12677 				BUMP_MIB(ill->ill_ip_mib,
12678 				    ipIfStatsHCInDelivers);
12679 			}
12680 			/*
12681 			 * mp and first_mp can change.
12682 			 */
12683 			if (ip_udp_check(q, connp, recv_ill,
12684 			    ipha, &mp, &first_mp, mctl_present)) {
12685 				/* Send it upstream */
12686 				CONN_UDP_RECV(connp, mp);
12687 			}
12688 		}
12689 		/*
12690 		 * freeb() cannot deal with null mblk being passed
12691 		 * in and first_mp can be set to null in the call
12692 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12693 		 */
12694 		if (mctl_present && first_mp != NULL) {
12695 			freeb(first_mp);
12696 		}
12697 		CONN_DEC_REF(connp);
12698 		return;
12699 	}
12700 
12701 	/*
12702 	 * if we got here we know the packet is not fragmented and
12703 	 * has no options. The classifier could not find a conn_t and
12704 	 * most likely its an icmp packet so send it through slow path.
12705 	 */
12706 
12707 	goto udpslowpath;
12708 
12709 ipoptions:
12710 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12711 		goto slow_done;
12712 	}
12713 
12714 	UPDATE_IB_PKT_COUNT(ire);
12715 	ire->ire_last_used_time = lbolt;
12716 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12717 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12718 fragmented:
12719 		/*
12720 		 * "sum" and "reass_hck_flags" are non-zero if the
12721 		 * reassembled packet has a valid hardware computed
12722 		 * checksum information associated with it.
12723 		 */
12724 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12725 			goto slow_done;
12726 		/*
12727 		 * Make sure that first_mp points back to mp as
12728 		 * the mp we came in with could have changed in
12729 		 * ip_rput_fragment().
12730 		 */
12731 		ASSERT(!mctl_present);
12732 		ipha = (ipha_t *)mp->b_rptr;
12733 		first_mp = mp;
12734 	}
12735 
12736 	/* Now we have a complete datagram, destined for this machine. */
12737 	u1 = IPH_HDR_LENGTH(ipha);
12738 	/* Pull up the UDP header, if necessary. */
12739 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12740 udppullup:
12741 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12742 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12743 			freemsg(first_mp);
12744 			goto slow_done;
12745 		}
12746 		ipha = (ipha_t *)mp->b_rptr;
12747 	}
12748 
12749 	/*
12750 	 * Validate the checksum for the reassembled packet; for the
12751 	 * pullup case we calculate the payload checksum in software.
12752 	 */
12753 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12754 	if (up[3] != 0) {
12755 		boolean_t cksum_err;
12756 
12757 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12758 			IP_STAT(ipst, ip_in_sw_cksum);
12759 
12760 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12761 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12762 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12763 		    iphs[9] + up[2], sum, cksum_err);
12764 
12765 		if (cksum_err) {
12766 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12767 
12768 			if (reass_hck_flags & HCK_FULLCKSUM)
12769 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12770 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12771 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12772 			else
12773 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12774 
12775 			freemsg(first_mp);
12776 			goto slow_done;
12777 		}
12778 	}
12779 udpslowpath:
12780 
12781 	/* Clear hardware checksum flag to be safe */
12782 	DB_CKSUMFLAGS(mp) = 0;
12783 
12784 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12785 	    (ire->ire_type == IRE_BROADCAST),
12786 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12787 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12788 
12789 slow_done:
12790 	IP_STAT(ipst, ip_udp_slow_path);
12791 	return;
12792 
12793 #undef  iphs
12794 #undef  rptr
12795 }
12796 
12797 /* ARGSUSED */
12798 static mblk_t *
12799 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12800     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12801     ill_rx_ring_t *ill_ring)
12802 {
12803 	conn_t		*connp;
12804 	uint32_t	sum;
12805 	uint32_t	u1;
12806 	uint16_t	*up;
12807 	int		offset;
12808 	ssize_t		len;
12809 	mblk_t		*mp1;
12810 	boolean_t	syn_present = B_FALSE;
12811 	tcph_t		*tcph;
12812 	uint_t		ip_hdr_len;
12813 	ill_t		*ill = (ill_t *)q->q_ptr;
12814 	zoneid_t	zoneid = ire->ire_zoneid;
12815 	boolean_t	cksum_err;
12816 	uint16_t	hck_flags = 0;
12817 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12818 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12819 
12820 #define	rptr	((uchar_t *)ipha)
12821 
12822 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12823 	ASSERT(ill != NULL);
12824 
12825 	/*
12826 	 * FAST PATH for tcp packets
12827 	 */
12828 
12829 	/* u1 is # words of IP options */
12830 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12831 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12832 
12833 	/* IP options present */
12834 	if (u1) {
12835 		goto ipoptions;
12836 	} else {
12837 		/* Check the IP header checksum.  */
12838 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12839 			/* Clear the IP header h/w cksum flag */
12840 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12841 		} else {
12842 #define	uph	((uint16_t *)ipha)
12843 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12844 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12845 #undef	uph
12846 			/* finish doing IP checksum */
12847 			sum = (sum & 0xFFFF) + (sum >> 16);
12848 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12849 			/*
12850 			 * Don't verify header checksum if this packet
12851 			 * is coming back from AH/ESP as we already did it.
12852 			 */
12853 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
12854 				BUMP_MIB(ill->ill_ip_mib,
12855 				    ipIfStatsInCksumErrs);
12856 				goto error;
12857 			}
12858 		}
12859 	}
12860 
12861 	if (!mctl_present) {
12862 		UPDATE_IB_PKT_COUNT(ire);
12863 		ire->ire_last_used_time = lbolt;
12864 	}
12865 
12866 	/* packet part of fragmented IP packet? */
12867 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12868 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12869 		goto fragmented;
12870 	}
12871 
12872 	/* u1 = IP header length (20 bytes) */
12873 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12874 
12875 	/* does packet contain IP+TCP headers? */
12876 	len = mp->b_wptr - rptr;
12877 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12878 		IP_STAT(ipst, ip_tcppullup);
12879 		goto tcppullup;
12880 	}
12881 
12882 	/* TCP options present? */
12883 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12884 
12885 	/*
12886 	 * If options need to be pulled up, then goto tcpoptions.
12887 	 * otherwise we are still in the fast path
12888 	 */
12889 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12890 		IP_STAT(ipst, ip_tcpoptions);
12891 		goto tcpoptions;
12892 	}
12893 
12894 	/* multiple mblks of tcp data? */
12895 	if ((mp1 = mp->b_cont) != NULL) {
12896 		/* more then two? */
12897 		if (mp1->b_cont != NULL) {
12898 			IP_STAT(ipst, ip_multipkttcp);
12899 			goto multipkttcp;
12900 		}
12901 		len += mp1->b_wptr - mp1->b_rptr;
12902 	}
12903 
12904 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
12905 
12906 	/* part of pseudo checksum */
12907 
12908 	/* TCP datagram length */
12909 	u1 = len - IP_SIMPLE_HDR_LENGTH;
12910 
12911 #define	iphs    ((uint16_t *)ipha)
12912 
12913 #ifdef	_BIG_ENDIAN
12914 	u1 += IPPROTO_TCP;
12915 #else
12916 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
12917 #endif
12918 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
12919 
12920 	/*
12921 	 * Revert to software checksum calculation if the interface
12922 	 * isn't capable of checksum offload or if IPsec is present.
12923 	 */
12924 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12925 		hck_flags = DB_CKSUMFLAGS(mp);
12926 
12927 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12928 		IP_STAT(ipst, ip_in_sw_cksum);
12929 
12930 	IP_CKSUM_RECV(hck_flags, u1,
12931 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12932 	    (int32_t)((uchar_t *)up - rptr),
12933 	    mp, mp1, cksum_err);
12934 
12935 	if (cksum_err) {
12936 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
12937 
12938 		if (hck_flags & HCK_FULLCKSUM)
12939 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
12940 		else if (hck_flags & HCK_PARTIALCKSUM)
12941 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
12942 		else
12943 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
12944 
12945 		goto error;
12946 	}
12947 
12948 try_again:
12949 
12950 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
12951 	    zoneid, ipst)) == NULL) {
12952 		/* Send the TH_RST */
12953 		goto no_conn;
12954 	}
12955 
12956 	/*
12957 	 * TCP FAST PATH for AF_INET socket.
12958 	 *
12959 	 * TCP fast path to avoid extra work. An AF_INET socket type
12960 	 * does not have facility to receive extra information via
12961 	 * ip_process or ip_add_info. Also, when the connection was
12962 	 * established, we made a check if this connection is impacted
12963 	 * by any global IPSec policy or per connection policy (a
12964 	 * policy that comes in effect later will not apply to this
12965 	 * connection). Since all this can be determined at the
12966 	 * connection establishment time, a quick check of flags
12967 	 * can avoid extra work.
12968 	 */
12969 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
12970 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12971 		ASSERT(first_mp == mp);
12972 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
12973 		SET_SQUEUE(mp, tcp_rput_data, connp);
12974 		return (mp);
12975 	}
12976 
12977 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
12978 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
12979 		if (IPCL_IS_TCP(connp)) {
12980 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
12981 			DB_CKSUMSTART(mp) =
12982 			    (intptr_t)ip_squeue_get(ill_ring);
12983 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
12984 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12985 				BUMP_MIB(ill->ill_ip_mib,
12986 				    ipIfStatsHCInDelivers);
12987 				SET_SQUEUE(mp, connp->conn_recv, connp);
12988 				return (mp);
12989 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
12990 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
12991 				BUMP_MIB(ill->ill_ip_mib,
12992 				    ipIfStatsHCInDelivers);
12993 				ip_squeue_enter_unbound++;
12994 				SET_SQUEUE(mp, tcp_conn_request_unbound,
12995 				    connp);
12996 				return (mp);
12997 			}
12998 			syn_present = B_TRUE;
12999 		}
13000 
13001 	}
13002 
13003 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13004 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13005 
13006 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13007 		/* No need to send this packet to TCP */
13008 		if ((flags & TH_RST) || (flags & TH_URG)) {
13009 			CONN_DEC_REF(connp);
13010 			freemsg(first_mp);
13011 			return (NULL);
13012 		}
13013 		if (flags & TH_ACK) {
13014 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13015 			    ipst->ips_netstack->netstack_tcp);
13016 			CONN_DEC_REF(connp);
13017 			return (NULL);
13018 		}
13019 
13020 		CONN_DEC_REF(connp);
13021 		freemsg(first_mp);
13022 		return (NULL);
13023 	}
13024 
13025 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13026 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13027 		    ipha, NULL, mctl_present);
13028 		if (first_mp == NULL) {
13029 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13030 			CONN_DEC_REF(connp);
13031 			return (NULL);
13032 		}
13033 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13034 			ASSERT(syn_present);
13035 			if (mctl_present) {
13036 				ASSERT(first_mp != mp);
13037 				first_mp->b_datap->db_struioflag |=
13038 				    STRUIO_POLICY;
13039 			} else {
13040 				ASSERT(first_mp == mp);
13041 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13042 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13043 			}
13044 		} else {
13045 			/*
13046 			 * Discard first_mp early since we're dealing with a
13047 			 * fully-connected conn_t and tcp doesn't do policy in
13048 			 * this case.
13049 			 */
13050 			if (mctl_present) {
13051 				freeb(first_mp);
13052 				mctl_present = B_FALSE;
13053 			}
13054 			first_mp = mp;
13055 		}
13056 	}
13057 
13058 	/* Initiate IPPF processing for fastpath */
13059 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13060 		uint32_t	ill_index;
13061 
13062 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13063 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13064 		if (mp == NULL) {
13065 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13066 			    "deferred/dropped during IPPF processing\n"));
13067 			CONN_DEC_REF(connp);
13068 			if (mctl_present)
13069 				freeb(first_mp);
13070 			return (NULL);
13071 		} else if (mctl_present) {
13072 			/*
13073 			 * ip_process might return a new mp.
13074 			 */
13075 			ASSERT(first_mp != mp);
13076 			first_mp->b_cont = mp;
13077 		} else {
13078 			first_mp = mp;
13079 		}
13080 
13081 	}
13082 
13083 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13084 		/*
13085 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13086 		 * make sure IPF_RECVIF is passed to ip_add_info.
13087 		 */
13088 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13089 		    IPCL_ZONEID(connp), ipst);
13090 		if (mp == NULL) {
13091 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13092 			CONN_DEC_REF(connp);
13093 			if (mctl_present)
13094 				freeb(first_mp);
13095 			return (NULL);
13096 		} else if (mctl_present) {
13097 			/*
13098 			 * ip_add_info might return a new mp.
13099 			 */
13100 			ASSERT(first_mp != mp);
13101 			first_mp->b_cont = mp;
13102 		} else {
13103 			first_mp = mp;
13104 		}
13105 	}
13106 
13107 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13108 	if (IPCL_IS_TCP(connp)) {
13109 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13110 		return (first_mp);
13111 	} else {
13112 		putnext(connp->conn_rq, first_mp);
13113 		CONN_DEC_REF(connp);
13114 		return (NULL);
13115 	}
13116 
13117 no_conn:
13118 	/* Initiate IPPf processing, if needed. */
13119 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13120 		uint32_t ill_index;
13121 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13122 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13123 		if (first_mp == NULL) {
13124 			return (NULL);
13125 		}
13126 	}
13127 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13128 
13129 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13130 	    ipst->ips_netstack->netstack_tcp);
13131 	return (NULL);
13132 ipoptions:
13133 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13134 		goto slow_done;
13135 	}
13136 
13137 	UPDATE_IB_PKT_COUNT(ire);
13138 	ire->ire_last_used_time = lbolt;
13139 
13140 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13141 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13142 fragmented:
13143 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13144 			if (mctl_present)
13145 				freeb(first_mp);
13146 			goto slow_done;
13147 		}
13148 		/*
13149 		 * Make sure that first_mp points back to mp as
13150 		 * the mp we came in with could have changed in
13151 		 * ip_rput_fragment().
13152 		 */
13153 		ASSERT(!mctl_present);
13154 		ipha = (ipha_t *)mp->b_rptr;
13155 		first_mp = mp;
13156 	}
13157 
13158 	/* Now we have a complete datagram, destined for this machine. */
13159 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13160 
13161 	len = mp->b_wptr - mp->b_rptr;
13162 	/* Pull up a minimal TCP header, if necessary. */
13163 	if (len < (u1 + 20)) {
13164 tcppullup:
13165 		if (!pullupmsg(mp, u1 + 20)) {
13166 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13167 			goto error;
13168 		}
13169 		ipha = (ipha_t *)mp->b_rptr;
13170 		len = mp->b_wptr - mp->b_rptr;
13171 	}
13172 
13173 	/*
13174 	 * Extract the offset field from the TCP header.  As usual, we
13175 	 * try to help the compiler more than the reader.
13176 	 */
13177 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13178 	if (offset != 5) {
13179 tcpoptions:
13180 		if (offset < 5) {
13181 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13182 			goto error;
13183 		}
13184 		/*
13185 		 * There must be TCP options.
13186 		 * Make sure we can grab them.
13187 		 */
13188 		offset <<= 2;
13189 		offset += u1;
13190 		if (len < offset) {
13191 			if (!pullupmsg(mp, offset)) {
13192 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13193 				goto error;
13194 			}
13195 			ipha = (ipha_t *)mp->b_rptr;
13196 			len = mp->b_wptr - rptr;
13197 		}
13198 	}
13199 
13200 	/* Get the total packet length in len, including headers. */
13201 	if (mp->b_cont) {
13202 multipkttcp:
13203 		len = msgdsize(mp);
13204 	}
13205 
13206 	/*
13207 	 * Check the TCP checksum by pulling together the pseudo-
13208 	 * header checksum, and passing it to ip_csum to be added in
13209 	 * with the TCP datagram.
13210 	 *
13211 	 * Since we are not using the hwcksum if available we must
13212 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13213 	 * If either of these fails along the way the mblk is freed.
13214 	 * If this logic ever changes and mblk is reused to say send
13215 	 * ICMP's back, then this flag may need to be cleared in
13216 	 * other places as well.
13217 	 */
13218 	DB_CKSUMFLAGS(mp) = 0;
13219 
13220 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13221 
13222 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13223 #ifdef	_BIG_ENDIAN
13224 	u1 += IPPROTO_TCP;
13225 #else
13226 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13227 #endif
13228 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13229 	/*
13230 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13231 	 */
13232 	IP_STAT(ipst, ip_in_sw_cksum);
13233 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13234 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13235 		goto error;
13236 	}
13237 
13238 	IP_STAT(ipst, ip_tcp_slow_path);
13239 	goto try_again;
13240 #undef  iphs
13241 #undef  rptr
13242 
13243 error:
13244 	freemsg(first_mp);
13245 slow_done:
13246 	return (NULL);
13247 }
13248 
13249 /* ARGSUSED */
13250 static void
13251 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13252     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13253 {
13254 	conn_t		*connp;
13255 	uint32_t	sum;
13256 	uint32_t	u1;
13257 	ssize_t		len;
13258 	sctp_hdr_t	*sctph;
13259 	zoneid_t	zoneid = ire->ire_zoneid;
13260 	uint32_t	pktsum;
13261 	uint32_t	calcsum;
13262 	uint32_t	ports;
13263 	in6_addr_t	map_src, map_dst;
13264 	ill_t		*ill = (ill_t *)q->q_ptr;
13265 	ip_stack_t	*ipst;
13266 	sctp_stack_t	*sctps;
13267 
13268 	ASSERT(recv_ill != NULL);
13269 	ipst = recv_ill->ill_ipst;
13270 	sctps = ipst->ips_netstack->netstack_sctp;
13271 
13272 #define	rptr	((uchar_t *)ipha)
13273 
13274 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13275 	ASSERT(ill != NULL);
13276 
13277 	/* u1 is # words of IP options */
13278 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13279 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13280 
13281 	/* IP options present */
13282 	if (u1 > 0) {
13283 		goto ipoptions;
13284 	} else {
13285 		/* Check the IP header checksum.  */
13286 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13287 #define	uph	((uint16_t *)ipha)
13288 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13289 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13290 #undef	uph
13291 			/* finish doing IP checksum */
13292 			sum = (sum & 0xFFFF) + (sum >> 16);
13293 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13294 			/*
13295 			 * Don't verify header checksum if this packet
13296 			 * is coming back from AH/ESP as we already did it.
13297 			 */
13298 			if (!mctl_present && (sum != 0) && sum != 0xFFFF) {
13299 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13300 				goto error;
13301 			}
13302 		}
13303 		/*
13304 		 * Since there is no SCTP h/w cksum support yet, just
13305 		 * clear the flag.
13306 		 */
13307 		DB_CKSUMFLAGS(mp) = 0;
13308 	}
13309 
13310 	/*
13311 	 * Don't verify header checksum if this packet is coming
13312 	 * back from AH/ESP as we already did it.
13313 	 */
13314 	if (!mctl_present) {
13315 		UPDATE_IB_PKT_COUNT(ire);
13316 		ire->ire_last_used_time = lbolt;
13317 	}
13318 
13319 	/* packet part of fragmented IP packet? */
13320 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13321 	if (u1 & (IPH_MF | IPH_OFFSET))
13322 		goto fragmented;
13323 
13324 	/* u1 = IP header length (20 bytes) */
13325 	u1 = IP_SIMPLE_HDR_LENGTH;
13326 
13327 find_sctp_client:
13328 	/* Pullup if we don't have the sctp common header. */
13329 	len = MBLKL(mp);
13330 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13331 		if (mp->b_cont == NULL ||
13332 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13333 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13334 			goto error;
13335 		}
13336 		ipha = (ipha_t *)mp->b_rptr;
13337 		len = MBLKL(mp);
13338 	}
13339 
13340 	sctph = (sctp_hdr_t *)(rptr + u1);
13341 #ifdef	DEBUG
13342 	if (!skip_sctp_cksum) {
13343 #endif
13344 		pktsum = sctph->sh_chksum;
13345 		sctph->sh_chksum = 0;
13346 		calcsum = sctp_cksum(mp, u1);
13347 		if (calcsum != pktsum) {
13348 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
13349 			goto error;
13350 		}
13351 		sctph->sh_chksum = pktsum;
13352 #ifdef	DEBUG	/* skip_sctp_cksum */
13353 	}
13354 #endif
13355 	/* get the ports */
13356 	ports = *(uint32_t *)&sctph->sh_sport;
13357 
13358 	IRE_REFRELE(ire);
13359 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13360 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13361 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13362 	    sctps)) == NULL) {
13363 		/* Check for raw socket or OOTB handling */
13364 		goto no_conn;
13365 	}
13366 
13367 	/* Found a client; up it goes */
13368 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13369 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13370 	return;
13371 
13372 no_conn:
13373 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13374 	    ports, mctl_present, flags, B_TRUE, zoneid);
13375 	return;
13376 
13377 ipoptions:
13378 	DB_CKSUMFLAGS(mp) = 0;
13379 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13380 		goto slow_done;
13381 
13382 	UPDATE_IB_PKT_COUNT(ire);
13383 	ire->ire_last_used_time = lbolt;
13384 
13385 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13386 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13387 fragmented:
13388 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13389 			goto slow_done;
13390 		/*
13391 		 * Make sure that first_mp points back to mp as
13392 		 * the mp we came in with could have changed in
13393 		 * ip_rput_fragment().
13394 		 */
13395 		ASSERT(!mctl_present);
13396 		ipha = (ipha_t *)mp->b_rptr;
13397 		first_mp = mp;
13398 	}
13399 
13400 	/* Now we have a complete datagram, destined for this machine. */
13401 	u1 = IPH_HDR_LENGTH(ipha);
13402 	goto find_sctp_client;
13403 #undef  iphs
13404 #undef  rptr
13405 
13406 error:
13407 	freemsg(first_mp);
13408 slow_done:
13409 	IRE_REFRELE(ire);
13410 }
13411 
13412 #define	VER_BITS	0xF0
13413 #define	VERSION_6	0x60
13414 
13415 static boolean_t
13416 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13417     ipaddr_t *dstp, ip_stack_t *ipst)
13418 {
13419 	uint_t	opt_len;
13420 	ipha_t *ipha;
13421 	ssize_t len;
13422 	uint_t	pkt_len;
13423 
13424 	ASSERT(ill != NULL);
13425 	IP_STAT(ipst, ip_ipoptions);
13426 	ipha = *iphapp;
13427 
13428 #define	rptr    ((uchar_t *)ipha)
13429 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13430 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13431 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13432 		freemsg(mp);
13433 		return (B_FALSE);
13434 	}
13435 
13436 	/* multiple mblk or too short */
13437 	pkt_len = ntohs(ipha->ipha_length);
13438 
13439 	/* Get the number of words of IP options in the IP header. */
13440 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13441 	if (opt_len) {
13442 		/* IP Options present!  Validate and process. */
13443 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13444 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13445 			goto done;
13446 		}
13447 		/*
13448 		 * Recompute complete header length and make sure we
13449 		 * have access to all of it.
13450 		 */
13451 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13452 		if (len > (mp->b_wptr - rptr)) {
13453 			if (len > pkt_len) {
13454 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13455 				goto done;
13456 			}
13457 			if (!pullupmsg(mp, len)) {
13458 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13459 				goto done;
13460 			}
13461 			ipha = (ipha_t *)mp->b_rptr;
13462 		}
13463 		/*
13464 		 * Go off to ip_rput_options which returns the next hop
13465 		 * destination address, which may have been affected
13466 		 * by source routing.
13467 		 */
13468 		IP_STAT(ipst, ip_opt);
13469 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13470 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13471 			return (B_FALSE);
13472 		}
13473 	}
13474 	*iphapp = ipha;
13475 	return (B_TRUE);
13476 done:
13477 	/* clear b_prev - used by ip_mroute_decap */
13478 	mp->b_prev = NULL;
13479 	freemsg(mp);
13480 	return (B_FALSE);
13481 #undef  rptr
13482 }
13483 
13484 /*
13485  * Deal with the fact that there is no ire for the destination.
13486  */
13487 static ire_t *
13488 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13489 {
13490 	ipha_t	*ipha;
13491 	ill_t	*ill;
13492 	ire_t	*ire;
13493 	boolean_t	check_multirt = B_FALSE;
13494 	ip_stack_t *ipst;
13495 
13496 	ipha = (ipha_t *)mp->b_rptr;
13497 	ill = (ill_t *)q->q_ptr;
13498 
13499 	ASSERT(ill != NULL);
13500 	ipst = ill->ill_ipst;
13501 
13502 	/*
13503 	 * No IRE for this destination, so it can't be for us.
13504 	 * Unless we are forwarding, drop the packet.
13505 	 * We have to let source routed packets through
13506 	 * since we don't yet know if they are 'ping -l'
13507 	 * packets i.e. if they will go out over the
13508 	 * same interface as they came in on.
13509 	 */
13510 	if (ll_multicast) {
13511 		freemsg(mp);
13512 		return (NULL);
13513 	}
13514 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13515 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13516 		freemsg(mp);
13517 		return (NULL);
13518 	}
13519 
13520 	/*
13521 	 * Mark this packet as having originated externally.
13522 	 *
13523 	 * For non-forwarding code path, ire_send later double
13524 	 * checks this interface to see if it is still exists
13525 	 * post-ARP resolution.
13526 	 *
13527 	 * Also, IPQOS uses this to differentiate between
13528 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13529 	 * QOS packet processing in ip_wput_attach_llhdr().
13530 	 * The QoS module can mark the b_band for a fastpath message
13531 	 * or the dl_priority field in a unitdata_req header for
13532 	 * CoS marking. This info can only be found in
13533 	 * ip_wput_attach_llhdr().
13534 	 */
13535 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13536 	/*
13537 	 * Clear the indication that this may have a hardware checksum
13538 	 * as we are not using it
13539 	 */
13540 	DB_CKSUMFLAGS(mp) = 0;
13541 
13542 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13543 	    MBLK_GETLABEL(mp), ipst);
13544 
13545 	if (ire == NULL && check_multirt) {
13546 		/* Let ip_newroute handle CGTP  */
13547 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13548 		return (NULL);
13549 	}
13550 
13551 	if (ire != NULL)
13552 		return (ire);
13553 
13554 	mp->b_prev = mp->b_next = 0;
13555 	/* send icmp unreachable */
13556 	q = WR(q);
13557 	/* Sent by forwarding path, and router is global zone */
13558 	if (ip_source_routed(ipha, ipst)) {
13559 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13560 		    GLOBAL_ZONEID, ipst);
13561 	} else {
13562 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13563 		    ipst);
13564 	}
13565 
13566 	return (NULL);
13567 
13568 }
13569 
13570 /*
13571  * check ip header length and align it.
13572  */
13573 static boolean_t
13574 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13575 {
13576 	ssize_t len;
13577 	ill_t *ill;
13578 	ipha_t	*ipha;
13579 
13580 	len = MBLKL(mp);
13581 
13582 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13583 		ill = (ill_t *)q->q_ptr;
13584 
13585 		if (!OK_32PTR(mp->b_rptr))
13586 			IP_STAT(ipst, ip_notaligned1);
13587 		else
13588 			IP_STAT(ipst, ip_notaligned2);
13589 		/* Guard against bogus device drivers */
13590 		if (len < 0) {
13591 			/* clear b_prev - used by ip_mroute_decap */
13592 			mp->b_prev = NULL;
13593 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13594 			freemsg(mp);
13595 			return (B_FALSE);
13596 		}
13597 
13598 		if (ip_rput_pullups++ == 0) {
13599 			ipha = (ipha_t *)mp->b_rptr;
13600 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13601 			    "ip_check_and_align_header: %s forced us to "
13602 			    " pullup pkt, hdr len %ld, hdr addr %p",
13603 			    ill->ill_name, len, ipha);
13604 		}
13605 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13606 			/* clear b_prev - used by ip_mroute_decap */
13607 			mp->b_prev = NULL;
13608 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13609 			freemsg(mp);
13610 			return (B_FALSE);
13611 		}
13612 	}
13613 	return (B_TRUE);
13614 }
13615 
13616 ire_t *
13617 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13618 {
13619 	ire_t		*new_ire;
13620 	ill_t		*ire_ill;
13621 	uint_t		ifindex;
13622 	ip_stack_t	*ipst = ill->ill_ipst;
13623 	boolean_t	strict_check = B_FALSE;
13624 
13625 	/*
13626 	 * This packet came in on an interface other than the one associated
13627 	 * with the first ire we found for the destination address. We do
13628 	 * another ire lookup here, using the ingress ill, to see if the
13629 	 * interface is in an interface group.
13630 	 * As long as the ills belong to the same group, we don't consider
13631 	 * them to be arriving on the wrong interface. Thus, if the switch
13632 	 * is doing inbound load spreading, we won't drop packets when the
13633 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13634 	 * for 'usesrc groups' where the destination address may belong to
13635 	 * another interface to allow multipathing to happen.
13636 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13637 	 * where the local address may not be unique. In this case we were
13638 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13639 	 * actually returned. The new lookup, which is more specific, should
13640 	 * only find the IRE_LOCAL associated with the ingress ill if one
13641 	 * exists.
13642 	 */
13643 
13644 	if (ire->ire_ipversion == IPV4_VERSION) {
13645 		if (ipst->ips_ip_strict_dst_multihoming)
13646 			strict_check = B_TRUE;
13647 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13648 		    ill->ill_ipif, ALL_ZONES, NULL,
13649 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13650 	} else {
13651 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13652 		if (ipst->ips_ipv6_strict_dst_multihoming)
13653 			strict_check = B_TRUE;
13654 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13655 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13656 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13657 	}
13658 	/*
13659 	 * If the same ire that was returned in ip_input() is found then this
13660 	 * is an indication that interface groups are in use. The packet
13661 	 * arrived on a different ill in the group than the one associated with
13662 	 * the destination address.  If a different ire was found then the same
13663 	 * IP address must be hosted on multiple ills. This is possible with
13664 	 * unnumbered point2point interfaces. We switch to use this new ire in
13665 	 * order to have accurate interface statistics.
13666 	 */
13667 	if (new_ire != NULL) {
13668 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13669 			ire_refrele(ire);
13670 			ire = new_ire;
13671 		} else {
13672 			ire_refrele(new_ire);
13673 		}
13674 		return (ire);
13675 	} else if ((ire->ire_rfq == NULL) &&
13676 	    (ire->ire_ipversion == IPV4_VERSION)) {
13677 		/*
13678 		 * The best match could have been the original ire which
13679 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13680 		 * the strict multihoming checks are irrelevant as we consider
13681 		 * local addresses hosted on lo0 to be interface agnostic. We
13682 		 * only expect a null ire_rfq on IREs which are associated with
13683 		 * lo0 hence we can return now.
13684 		 */
13685 		return (ire);
13686 	}
13687 
13688 	/*
13689 	 * Chase pointers once and store locally.
13690 	 */
13691 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13692 	    (ill_t *)(ire->ire_rfq->q_ptr);
13693 	ifindex = ill->ill_usesrc_ifindex;
13694 
13695 	/*
13696 	 * Check if it's a legal address on the 'usesrc' interface.
13697 	 */
13698 	if ((ifindex != 0) && (ire_ill != NULL) &&
13699 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13700 		return (ire);
13701 	}
13702 
13703 	/*
13704 	 * If the ip*_strict_dst_multihoming switch is on then we can
13705 	 * only accept this packet if the interface is marked as routing.
13706 	 */
13707 	if (!(strict_check))
13708 		return (ire);
13709 
13710 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13711 	    ILLF_ROUTER) != 0) {
13712 		return (ire);
13713 	}
13714 
13715 	ire_refrele(ire);
13716 	return (NULL);
13717 }
13718 
13719 ire_t *
13720 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13721 {
13722 	ipha_t	*ipha;
13723 	ipaddr_t ip_dst, ip_src;
13724 	ire_t	*src_ire = NULL;
13725 	ill_t	*stq_ill;
13726 	uint_t	hlen;
13727 	uint_t	pkt_len;
13728 	uint32_t sum;
13729 	queue_t	*dev_q;
13730 	boolean_t check_multirt = B_FALSE;
13731 	ip_stack_t *ipst = ill->ill_ipst;
13732 
13733 	ipha = (ipha_t *)mp->b_rptr;
13734 
13735 	/*
13736 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13737 	 * The loopback address check for both src and dst has already
13738 	 * been checked in ip_input
13739 	 */
13740 	ip_dst = ntohl(dst);
13741 	ip_src = ntohl(ipha->ipha_src);
13742 
13743 	if (ip_dst == INADDR_ANY || IN_BADCLASS(ip_dst) ||
13744 	    IN_CLASSD(ip_src)) {
13745 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13746 		goto drop;
13747 	}
13748 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13749 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13750 
13751 	if (src_ire != NULL) {
13752 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13753 		goto drop;
13754 	}
13755 
13756 
13757 	/* No ire cache of nexthop. So first create one  */
13758 	if (ire == NULL) {
13759 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13760 		/*
13761 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13762 		 * is not set. So upon return from ire_forward
13763 		 * check_multirt should remain as false.
13764 		 */
13765 		ASSERT(!check_multirt);
13766 		if (ire == NULL) {
13767 			/* An attempt was made to forward the packet */
13768 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13769 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13770 			mp->b_prev = mp->b_next = 0;
13771 			/* send icmp unreachable */
13772 			/* Sent by forwarding path, and router is global zone */
13773 			if (ip_source_routed(ipha, ipst)) {
13774 				icmp_unreachable(ill->ill_wq, mp,
13775 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13776 				    ipst);
13777 			} else {
13778 				icmp_unreachable(ill->ill_wq, mp,
13779 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13780 				    ipst);
13781 			}
13782 			return (ire);
13783 		}
13784 	}
13785 
13786 	/*
13787 	 * Forwarding fastpath exception case:
13788 	 * If either of the follwoing case is true, we take
13789 	 * the slowpath
13790 	 *	o forwarding is not enabled
13791 	 *	o incoming and outgoing interface are the same, or the same
13792 	 *	  IPMP group
13793 	 *	o corresponding ire is in incomplete state
13794 	 *	o packet needs fragmentation
13795 	 *
13796 	 * The codeflow from here on is thus:
13797 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13798 	 */
13799 	pkt_len = ntohs(ipha->ipha_length);
13800 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13801 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13802 	    !(ill->ill_flags & ILLF_ROUTER) ||
13803 	    (ill == stq_ill) ||
13804 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13805 	    (ire->ire_nce == NULL) ||
13806 	    (ire->ire_nce->nce_state != ND_REACHABLE) ||
13807 	    (pkt_len > ire->ire_max_frag) ||
13808 	    ipha->ipha_ttl <= 1) {
13809 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13810 		    ipha, ill, B_FALSE);
13811 		return (ire);
13812 	}
13813 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13814 
13815 	DTRACE_PROBE4(ip4__forwarding__start,
13816 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13817 
13818 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13819 	    ipst->ips_ipv4firewall_forwarding,
13820 	    ill, stq_ill, ipha, mp, mp, ipst);
13821 
13822 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13823 
13824 	if (mp == NULL)
13825 		goto drop;
13826 
13827 	mp->b_datap->db_struioun.cksum.flags = 0;
13828 	/* Adjust the checksum to reflect the ttl decrement. */
13829 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13830 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13831 	ipha->ipha_ttl--;
13832 
13833 	dev_q = ire->ire_stq->q_next;
13834 	if ((dev_q->q_next != NULL ||
13835 	    dev_q->q_first != NULL) && !canput(dev_q)) {
13836 		goto indiscard;
13837 	}
13838 
13839 	hlen = ire->ire_nce->nce_fp_mp != NULL ?
13840 	    MBLKL(ire->ire_nce->nce_fp_mp) : 0;
13841 
13842 	if (hlen != 0 || ire->ire_nce->nce_res_mp != NULL) {
13843 		mblk_t *mpip = mp;
13844 
13845 		mp = ip_wput_attach_llhdr(mpip, ire, 0, 0);
13846 		if (mp != NULL) {
13847 			DTRACE_PROBE4(ip4__physical__out__start,
13848 			    ill_t *, NULL, ill_t *, stq_ill,
13849 			    ipha_t *, ipha, mblk_t *, mp);
13850 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
13851 			    ipst->ips_ipv4firewall_physical_out,
13852 			    NULL, stq_ill, ipha, mp, mpip, ipst);
13853 			DTRACE_PROBE1(ip4__physical__out__end, mblk_t *,
13854 			    mp);
13855 			if (mp == NULL)
13856 				goto drop;
13857 
13858 			UPDATE_IB_PKT_COUNT(ire);
13859 			ire->ire_last_used_time = lbolt;
13860 			BUMP_MIB(stq_ill->ill_ip_mib,
13861 			    ipIfStatsHCOutForwDatagrams);
13862 			BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13863 			UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets,
13864 			    pkt_len);
13865 			putnext(ire->ire_stq, mp);
13866 			return (ire);
13867 		}
13868 	}
13869 
13870 indiscard:
13871 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13872 drop:
13873 	if (mp != NULL)
13874 		freemsg(mp);
13875 	if (src_ire != NULL)
13876 		ire_refrele(src_ire);
13877 	return (ire);
13878 
13879 }
13880 
13881 /*
13882  * This function is called in the forwarding slowpath, when
13883  * either the ire lacks the link-layer address, or the packet needs
13884  * further processing(eg. fragmentation), before transmission.
13885  */
13886 
13887 static void
13888 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
13889     ill_t *ill, boolean_t ll_multicast)
13890 {
13891 	ill_group_t	*ill_group;
13892 	ill_group_t	*ire_group;
13893 	queue_t		*dev_q;
13894 	ire_t		*src_ire;
13895 	ip_stack_t	*ipst = ill->ill_ipst;
13896 
13897 	ASSERT(ire->ire_stq != NULL);
13898 
13899 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
13900 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
13901 
13902 	if (ll_multicast != 0) {
13903 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13904 		goto drop_pkt;
13905 	}
13906 
13907 	/*
13908 	 * check if ipha_src is a broadcast address. Note that this
13909 	 * check is redundant when we get here from ip_fast_forward()
13910 	 * which has already done this check. However, since we can
13911 	 * also get here from ip_rput_process_broadcast() or, for
13912 	 * for the slow path through ip_fast_forward(), we perform
13913 	 * the check again for code-reusability
13914 	 */
13915 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13916 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13917 	if (src_ire != NULL || ntohl(ipha->ipha_dst) == INADDR_ANY ||
13918 	    IN_BADCLASS(ntohl(ipha->ipha_dst))) {
13919 		if (src_ire != NULL)
13920 			ire_refrele(src_ire);
13921 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13922 		ip2dbg(("ip_rput_process_forward: Received packet with"
13923 		    " bad src/dst address on %s\n", ill->ill_name));
13924 		goto drop_pkt;
13925 	}
13926 
13927 	ill_group = ill->ill_group;
13928 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
13929 	/*
13930 	 * Check if we want to forward this one at this time.
13931 	 * We allow source routed packets on a host provided that
13932 	 * they go out the same interface or same interface group
13933 	 * as they came in on.
13934 	 *
13935 	 * XXX To be quicker, we may wish to not chase pointers to
13936 	 * get the ILLF_ROUTER flag and instead store the
13937 	 * forwarding policy in the ire.  An unfortunate
13938 	 * side-effect of that would be requiring an ire flush
13939 	 * whenever the ILLF_ROUTER flag changes.
13940 	 */
13941 	if (((ill->ill_flags &
13942 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
13943 	    ILLF_ROUTER) == 0) &&
13944 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
13945 	    (ill_group != NULL && ill_group == ire_group)))) {
13946 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13947 		if (ip_source_routed(ipha, ipst)) {
13948 			q = WR(q);
13949 			/*
13950 			 * Clear the indication that this may have
13951 			 * hardware checksum as we are not using it.
13952 			 */
13953 			DB_CKSUMFLAGS(mp) = 0;
13954 			/* Sent by forwarding path, and router is global zone */
13955 			icmp_unreachable(q, mp,
13956 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
13957 			return;
13958 		}
13959 		goto drop_pkt;
13960 	}
13961 
13962 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13963 
13964 	/* Packet is being forwarded. Turning off hwcksum flag. */
13965 	DB_CKSUMFLAGS(mp) = 0;
13966 	if (ipst->ips_ip_g_send_redirects) {
13967 		/*
13968 		 * Check whether the incoming interface and outgoing
13969 		 * interface is part of the same group. If so,
13970 		 * send redirects.
13971 		 *
13972 		 * Check the source address to see if it originated
13973 		 * on the same logical subnet it is going back out on.
13974 		 * If so, we should be able to send it a redirect.
13975 		 * Avoid sending a redirect if the destination
13976 		 * is directly connected (i.e., ipha_dst is the same
13977 		 * as ire_gateway_addr or the ire_addr of the
13978 		 * nexthop IRE_CACHE ), or if the packet was source
13979 		 * routed out this interface.
13980 		 */
13981 		ipaddr_t src, nhop;
13982 		mblk_t	*mp1;
13983 		ire_t	*nhop_ire = NULL;
13984 
13985 		/*
13986 		 * Check whether ire_rfq and q are from the same ill
13987 		 * or if they are not same, they at least belong
13988 		 * to the same group. If so, send redirects.
13989 		 */
13990 		if ((ire->ire_rfq == q ||
13991 		    (ill_group != NULL && ill_group == ire_group)) &&
13992 		    !ip_source_routed(ipha, ipst)) {
13993 
13994 			nhop = (ire->ire_gateway_addr != 0 ?
13995 			    ire->ire_gateway_addr : ire->ire_addr);
13996 
13997 			if (ipha->ipha_dst == nhop) {
13998 				/*
13999 				 * We avoid sending a redirect if the
14000 				 * destination is directly connected
14001 				 * because it is possible that multiple
14002 				 * IP subnets may have been configured on
14003 				 * the link, and the source may not
14004 				 * be on the same subnet as ip destination,
14005 				 * even though they are on the same
14006 				 * physical link.
14007 				 */
14008 				goto sendit;
14009 			}
14010 
14011 			src = ipha->ipha_src;
14012 
14013 			/*
14014 			 * We look up the interface ire for the nexthop,
14015 			 * to see if ipha_src is in the same subnet
14016 			 * as the nexthop.
14017 			 *
14018 			 * Note that, if, in the future, IRE_CACHE entries
14019 			 * are obsoleted,  this lookup will not be needed,
14020 			 * as the ire passed to this function will be the
14021 			 * same as the nhop_ire computed below.
14022 			 */
14023 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14024 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14025 			    0, NULL, MATCH_IRE_TYPE, ipst);
14026 
14027 			if (nhop_ire != NULL) {
14028 				if ((src & nhop_ire->ire_mask) ==
14029 				    (nhop & nhop_ire->ire_mask)) {
14030 					/*
14031 					 * The source is directly connected.
14032 					 * Just copy the ip header (which is
14033 					 * in the first mblk)
14034 					 */
14035 					mp1 = copyb(mp);
14036 					if (mp1 != NULL) {
14037 						icmp_send_redirect(WR(q), mp1,
14038 						    nhop, ipst);
14039 					}
14040 				}
14041 				ire_refrele(nhop_ire);
14042 			}
14043 		}
14044 	}
14045 sendit:
14046 	dev_q = ire->ire_stq->q_next;
14047 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14048 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14049 		freemsg(mp);
14050 		return;
14051 	}
14052 
14053 	ip_rput_forward(ire, ipha, mp, ill);
14054 	return;
14055 
14056 drop_pkt:
14057 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14058 	freemsg(mp);
14059 }
14060 
14061 ire_t *
14062 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14063     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14064 {
14065 	queue_t		*q;
14066 	uint16_t	hcksumflags;
14067 	ip_stack_t	*ipst = ill->ill_ipst;
14068 
14069 	q = *qp;
14070 
14071 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14072 
14073 	/*
14074 	 * Clear the indication that this may have hardware
14075 	 * checksum as we are not using it for forwarding.
14076 	 */
14077 	hcksumflags = DB_CKSUMFLAGS(mp);
14078 	DB_CKSUMFLAGS(mp) = 0;
14079 
14080 	/*
14081 	 * Directed broadcast forwarding: if the packet came in over a
14082 	 * different interface then it is routed out over we can forward it.
14083 	 */
14084 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14085 		ire_refrele(ire);
14086 		freemsg(mp);
14087 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14088 		return (NULL);
14089 	}
14090 	/*
14091 	 * For multicast we have set dst to be INADDR_BROADCAST
14092 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14093 	 * only for broadcast packets.
14094 	 */
14095 	if (!CLASSD(ipha->ipha_dst)) {
14096 		ire_t *new_ire;
14097 		ipif_t *ipif;
14098 		/*
14099 		 * For ill groups, as the switch duplicates broadcasts
14100 		 * across all the ports, we need to filter out and
14101 		 * send up only one copy. There is one copy for every
14102 		 * broadcast address on each ill. Thus, we look for a
14103 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14104 		 * later to see whether this ill is eligible to receive
14105 		 * them or not. ill_nominate_bcast_rcv() nominates only
14106 		 * one set of IREs for receiving.
14107 		 */
14108 
14109 		ipif = ipif_get_next_ipif(NULL, ill);
14110 		if (ipif == NULL) {
14111 			ire_refrele(ire);
14112 			freemsg(mp);
14113 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14114 			return (NULL);
14115 		}
14116 		new_ire = ire_ctable_lookup(dst, 0, 0,
14117 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14118 		ipif_refrele(ipif);
14119 
14120 		if (new_ire != NULL) {
14121 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14122 				ire_refrele(ire);
14123 				ire_refrele(new_ire);
14124 				freemsg(mp);
14125 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14126 				return (NULL);
14127 			}
14128 			/*
14129 			 * In the special case of multirouted broadcast
14130 			 * packets, we unconditionally need to "gateway"
14131 			 * them to the appropriate interface here.
14132 			 * In the normal case, this cannot happen, because
14133 			 * there is no broadcast IRE tagged with the
14134 			 * RTF_MULTIRT flag.
14135 			 */
14136 			if (new_ire->ire_flags & RTF_MULTIRT) {
14137 				ire_refrele(new_ire);
14138 				if (ire->ire_rfq != NULL) {
14139 					q = ire->ire_rfq;
14140 					*qp = q;
14141 				}
14142 			} else {
14143 				ire_refrele(ire);
14144 				ire = new_ire;
14145 			}
14146 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14147 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14148 				/*
14149 				 * Free the message if
14150 				 * ip_g_forward_directed_bcast is turned
14151 				 * off for non-local broadcast.
14152 				 */
14153 				ire_refrele(ire);
14154 				freemsg(mp);
14155 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14156 				return (NULL);
14157 			}
14158 		} else {
14159 			/*
14160 			 * This CGTP packet successfully passed the
14161 			 * CGTP filter, but the related CGTP
14162 			 * broadcast IRE has not been found,
14163 			 * meaning that the redundant ipif is
14164 			 * probably down. However, if we discarded
14165 			 * this packet, its duplicate would be
14166 			 * filtered out by the CGTP filter so none
14167 			 * of them would get through. So we keep
14168 			 * going with this one.
14169 			 */
14170 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14171 			if (ire->ire_rfq != NULL) {
14172 				q = ire->ire_rfq;
14173 				*qp = q;
14174 			}
14175 		}
14176 	}
14177 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14178 		/*
14179 		 * Verify that there are not more then one
14180 		 * IRE_BROADCAST with this broadcast address which
14181 		 * has ire_stq set.
14182 		 * TODO: simplify, loop over all IRE's
14183 		 */
14184 		ire_t	*ire1;
14185 		int	num_stq = 0;
14186 		mblk_t	*mp1;
14187 
14188 		/* Find the first one with ire_stq set */
14189 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14190 		for (ire1 = ire; ire1 &&
14191 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14192 		    ire1 = ire1->ire_next)
14193 			;
14194 		if (ire1) {
14195 			ire_refrele(ire);
14196 			ire = ire1;
14197 			IRE_REFHOLD(ire);
14198 		}
14199 
14200 		/* Check if there are additional ones with stq set */
14201 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14202 			if (ire->ire_addr != ire1->ire_addr)
14203 				break;
14204 			if (ire1->ire_stq) {
14205 				num_stq++;
14206 				break;
14207 			}
14208 		}
14209 		rw_exit(&ire->ire_bucket->irb_lock);
14210 		if (num_stq == 1 && ire->ire_stq != NULL) {
14211 			ip1dbg(("ip_rput_process_broadcast: directed "
14212 			    "broadcast to 0x%x\n",
14213 			    ntohl(ire->ire_addr)));
14214 			mp1 = copymsg(mp);
14215 			if (mp1) {
14216 				switch (ipha->ipha_protocol) {
14217 				case IPPROTO_UDP:
14218 					ip_udp_input(q, mp1, ipha, ire, ill);
14219 					break;
14220 				default:
14221 					ip_proto_input(q, mp1, ipha, ire, ill);
14222 					break;
14223 				}
14224 			}
14225 			/*
14226 			 * Adjust ttl to 2 (1+1 - the forward engine
14227 			 * will decrement it by one.
14228 			 */
14229 			if (ip_csum_hdr(ipha)) {
14230 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14231 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14232 				freemsg(mp);
14233 				ire_refrele(ire);
14234 				return (NULL);
14235 			}
14236 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14237 			ipha->ipha_hdr_checksum = 0;
14238 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14239 			ip_rput_process_forward(q, mp, ire, ipha,
14240 			    ill, ll_multicast);
14241 			ire_refrele(ire);
14242 			return (NULL);
14243 		}
14244 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14245 		    ntohl(ire->ire_addr)));
14246 	}
14247 
14248 
14249 	/* Restore any hardware checksum flags */
14250 	DB_CKSUMFLAGS(mp) = hcksumflags;
14251 	return (ire);
14252 }
14253 
14254 /* ARGSUSED */
14255 static boolean_t
14256 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14257     int *ll_multicast, ipaddr_t *dstp)
14258 {
14259 	ip_stack_t	*ipst = ill->ill_ipst;
14260 
14261 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14262 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14263 	    ntohs(ipha->ipha_length));
14264 
14265 	/*
14266 	 * Forward packets only if we have joined the allmulti
14267 	 * group on this interface.
14268 	 */
14269 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14270 		int retval;
14271 
14272 		/*
14273 		 * Clear the indication that this may have hardware
14274 		 * checksum as we are not using it.
14275 		 */
14276 		DB_CKSUMFLAGS(mp) = 0;
14277 		retval = ip_mforward(ill, ipha, mp);
14278 		/* ip_mforward updates mib variables if needed */
14279 		/* clear b_prev - used by ip_mroute_decap */
14280 		mp->b_prev = NULL;
14281 
14282 		switch (retval) {
14283 		case 0:
14284 			/*
14285 			 * pkt is okay and arrived on phyint.
14286 			 *
14287 			 * If we are running as a multicast router
14288 			 * we need to see all IGMP and/or PIM packets.
14289 			 */
14290 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14291 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14292 				goto done;
14293 			}
14294 			break;
14295 		case -1:
14296 			/* pkt is mal-formed, toss it */
14297 			goto drop_pkt;
14298 		case 1:
14299 			/* pkt is okay and arrived on a tunnel */
14300 			/*
14301 			 * If we are running a multicast router
14302 			 *  we need to see all igmp packets.
14303 			 */
14304 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14305 				*dstp = INADDR_BROADCAST;
14306 				*ll_multicast = 1;
14307 				return (B_FALSE);
14308 			}
14309 
14310 			goto drop_pkt;
14311 		}
14312 	}
14313 
14314 	ILM_WALKER_HOLD(ill);
14315 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14316 		/*
14317 		 * This might just be caused by the fact that
14318 		 * multiple IP Multicast addresses map to the same
14319 		 * link layer multicast - no need to increment counter!
14320 		 */
14321 		ILM_WALKER_RELE(ill);
14322 		freemsg(mp);
14323 		return (B_TRUE);
14324 	}
14325 	ILM_WALKER_RELE(ill);
14326 done:
14327 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14328 	/*
14329 	 * This assumes the we deliver to all streams for multicast
14330 	 * and broadcast packets.
14331 	 */
14332 	*dstp = INADDR_BROADCAST;
14333 	*ll_multicast = 1;
14334 	return (B_FALSE);
14335 drop_pkt:
14336 	ip2dbg(("ip_rput: drop pkt\n"));
14337 	freemsg(mp);
14338 	return (B_TRUE);
14339 }
14340 
14341 static boolean_t
14342 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14343     int *ll_multicast, mblk_t **mpp)
14344 {
14345 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14346 	boolean_t must_copy = B_FALSE;
14347 	struct iocblk   *iocp;
14348 	ipha_t		*ipha;
14349 	ip_stack_t	*ipst = ill->ill_ipst;
14350 
14351 #define	rptr    ((uchar_t *)ipha)
14352 
14353 	first_mp = *first_mpp;
14354 	mp = *mpp;
14355 
14356 	ASSERT(first_mp == mp);
14357 
14358 	/*
14359 	 * if db_ref > 1 then copymsg and free original. Packet may be
14360 	 * changed and do not want other entity who has a reference to this
14361 	 * message to trip over the changes. This is a blind change because
14362 	 * trying to catch all places that might change packet is too
14363 	 * difficult (since it may be a module above this one)
14364 	 *
14365 	 * This corresponds to the non-fast path case. We walk down the full
14366 	 * chain in this case, and check the db_ref count of all the dblks,
14367 	 * and do a copymsg if required. It is possible that the db_ref counts
14368 	 * of the data blocks in the mblk chain can be different.
14369 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14370 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14371 	 * 'snoop' is running.
14372 	 */
14373 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14374 		if (mp1->b_datap->db_ref > 1) {
14375 			must_copy = B_TRUE;
14376 			break;
14377 		}
14378 	}
14379 
14380 	if (must_copy) {
14381 		mp1 = copymsg(mp);
14382 		if (mp1 == NULL) {
14383 			for (mp1 = mp; mp1 != NULL;
14384 			    mp1 = mp1->b_cont) {
14385 				mp1->b_next = NULL;
14386 				mp1->b_prev = NULL;
14387 			}
14388 			freemsg(mp);
14389 			if (ill != NULL) {
14390 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14391 			} else {
14392 				BUMP_MIB(&ipst->ips_ip_mib,
14393 				    ipIfStatsInDiscards);
14394 			}
14395 			return (B_TRUE);
14396 		}
14397 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14398 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14399 			/* Copy b_prev - used by ip_mroute_decap */
14400 			to_mp->b_prev = from_mp->b_prev;
14401 			from_mp->b_prev = NULL;
14402 		}
14403 		*first_mpp = first_mp = mp1;
14404 		freemsg(mp);
14405 		mp = mp1;
14406 		*mpp = mp1;
14407 	}
14408 
14409 	ipha = (ipha_t *)mp->b_rptr;
14410 
14411 	/*
14412 	 * previous code has a case for M_DATA.
14413 	 * We want to check how that happens.
14414 	 */
14415 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14416 	switch (first_mp->b_datap->db_type) {
14417 	case M_PROTO:
14418 	case M_PCPROTO:
14419 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14420 		    DL_UNITDATA_IND) {
14421 			/* Go handle anything other than data elsewhere. */
14422 			ip_rput_dlpi(q, mp);
14423 			return (B_TRUE);
14424 		}
14425 		*ll_multicast = ((dl_unitdata_ind_t *)rptr)->dl_group_address;
14426 		/* Ditch the DLPI header. */
14427 		mp1 = mp->b_cont;
14428 		ASSERT(first_mp == mp);
14429 		*first_mpp = mp1;
14430 		freeb(mp);
14431 		*mpp = mp1;
14432 		return (B_FALSE);
14433 	case M_IOCACK:
14434 		ip1dbg(("got iocack "));
14435 		iocp = (struct iocblk *)mp->b_rptr;
14436 		switch (iocp->ioc_cmd) {
14437 		case DL_IOC_HDR_INFO:
14438 			ill = (ill_t *)q->q_ptr;
14439 			ill_fastpath_ack(ill, mp);
14440 			return (B_TRUE);
14441 		case SIOCSTUNPARAM:
14442 		case OSIOCSTUNPARAM:
14443 			/* Go through qwriter_ip */
14444 			break;
14445 		case SIOCGTUNPARAM:
14446 		case OSIOCGTUNPARAM:
14447 			ip_rput_other(NULL, q, mp, NULL);
14448 			return (B_TRUE);
14449 		default:
14450 			putnext(q, mp);
14451 			return (B_TRUE);
14452 		}
14453 		/* FALLTHRU */
14454 	case M_ERROR:
14455 	case M_HANGUP:
14456 		/*
14457 		 * Since this is on the ill stream we unconditionally
14458 		 * bump up the refcount
14459 		 */
14460 		ill_refhold(ill);
14461 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14462 		return (B_TRUE);
14463 	case M_CTL:
14464 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14465 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14466 		    IPHADA_M_CTL)) {
14467 			/*
14468 			 * It's an IPsec accelerated packet.
14469 			 * Make sure that the ill from which we received the
14470 			 * packet has enabled IPsec hardware acceleration.
14471 			 */
14472 			if (!(ill->ill_capabilities &
14473 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14474 				/* IPsec kstats: bean counter */
14475 				freemsg(mp);
14476 				return (B_TRUE);
14477 			}
14478 
14479 			/*
14480 			 * Make mp point to the mblk following the M_CTL,
14481 			 * then process according to type of mp.
14482 			 * After this processing, first_mp will point to
14483 			 * the data-attributes and mp to the pkt following
14484 			 * the M_CTL.
14485 			 */
14486 			mp = first_mp->b_cont;
14487 			if (mp == NULL) {
14488 				freemsg(first_mp);
14489 				return (B_TRUE);
14490 			}
14491 			/*
14492 			 * A Hardware Accelerated packet can only be M_DATA
14493 			 * ESP or AH packet.
14494 			 */
14495 			if (mp->b_datap->db_type != M_DATA) {
14496 				/* non-M_DATA IPsec accelerated packet */
14497 				IPSECHW_DEBUG(IPSECHW_PKT,
14498 				    ("non-M_DATA IPsec accelerated pkt\n"));
14499 				freemsg(first_mp);
14500 				return (B_TRUE);
14501 			}
14502 			ipha = (ipha_t *)mp->b_rptr;
14503 			if (ipha->ipha_protocol != IPPROTO_AH &&
14504 			    ipha->ipha_protocol != IPPROTO_ESP) {
14505 				IPSECHW_DEBUG(IPSECHW_PKT,
14506 				    ("non-M_DATA IPsec accelerated pkt\n"));
14507 				freemsg(first_mp);
14508 				return (B_TRUE);
14509 			}
14510 			*mpp = mp;
14511 			return (B_FALSE);
14512 		}
14513 		putnext(q, mp);
14514 		return (B_TRUE);
14515 	case M_IOCNAK:
14516 		ip1dbg(("got iocnak "));
14517 		iocp = (struct iocblk *)mp->b_rptr;
14518 		switch (iocp->ioc_cmd) {
14519 		case SIOCSTUNPARAM:
14520 		case OSIOCSTUNPARAM:
14521 			/*
14522 			 * Since this is on the ill stream we unconditionally
14523 			 * bump up the refcount
14524 			 */
14525 			ill_refhold(ill);
14526 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14527 			return (B_TRUE);
14528 		case DL_IOC_HDR_INFO:
14529 		case SIOCGTUNPARAM:
14530 		case OSIOCGTUNPARAM:
14531 			ip_rput_other(NULL, q, mp, NULL);
14532 			return (B_TRUE);
14533 		default:
14534 			break;
14535 		}
14536 		/* FALLTHRU */
14537 	default:
14538 		putnext(q, mp);
14539 		return (B_TRUE);
14540 	}
14541 }
14542 
14543 /* Read side put procedure.  Packets coming from the wire arrive here. */
14544 void
14545 ip_rput(queue_t *q, mblk_t *mp)
14546 {
14547 	ill_t		*ill = (ill_t *)q->q_ptr;
14548 	ip_stack_t	*ipst = ill->ill_ipst;
14549 	union DL_primitives *dl;
14550 
14551 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14552 
14553 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14554 		/*
14555 		 * If things are opening or closing, only accept high-priority
14556 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14557 		 * created; on close, things hanging off the ill may have been
14558 		 * freed already.)
14559 		 */
14560 		dl = (union DL_primitives *)mp->b_rptr;
14561 		if (DB_TYPE(mp) != M_PCPROTO ||
14562 		    dl->dl_primitive == DL_UNITDATA_IND) {
14563 			/*
14564 			 * SIOC[GS]TUNPARAM ioctls can come here.
14565 			 */
14566 			inet_freemsg(mp);
14567 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14568 			    "ip_rput_end: q %p (%S)", q, "uninit");
14569 			return;
14570 		}
14571 	}
14572 
14573 	/*
14574 	 * if db_ref > 1 then copymsg and free original. Packet may be
14575 	 * changed and we do not want the other entity who has a reference to
14576 	 * this message to trip over the changes. This is a blind change because
14577 	 * trying to catch all places that might change the packet is too
14578 	 * difficult.
14579 	 *
14580 	 * This corresponds to the fast path case, where we have a chain of
14581 	 * M_DATA mblks.  We check the db_ref count of only the 1st data block
14582 	 * in the mblk chain. There doesn't seem to be a reason why a device
14583 	 * driver would send up data with varying db_ref counts in the mblk
14584 	 * chain. In any case the Fast path is a private interface, and our
14585 	 * drivers don't do such a thing. Given the above assumption, there is
14586 	 * no need to walk down the entire mblk chain (which could have a
14587 	 * potential performance problem)
14588 	 */
14589 	if (mp->b_datap->db_ref > 1) {
14590 		mblk_t  *mp1;
14591 		boolean_t adjusted = B_FALSE;
14592 		IP_STAT(ipst, ip_db_ref);
14593 
14594 		/*
14595 		 * The IP_RECVSLLA option depends on having the link layer
14596 		 * header. First check that:
14597 		 * a> the underlying device is of type ether, since this
14598 		 * option is currently supported only over ethernet.
14599 		 * b> there is enough room to copy over the link layer header.
14600 		 *
14601 		 * Once the checks are done, adjust rptr so that the link layer
14602 		 * header will be copied via copymsg. Note that, IFT_ETHER may
14603 		 * be returned by some non-ethernet drivers but in this case the
14604 		 * second check will fail.
14605 		 */
14606 		if (ill->ill_type == IFT_ETHER &&
14607 		    (mp->b_rptr - mp->b_datap->db_base) >=
14608 		    sizeof (struct ether_header)) {
14609 			mp->b_rptr -= sizeof (struct ether_header);
14610 			adjusted = B_TRUE;
14611 		}
14612 		mp1 = copymsg(mp);
14613 		if (mp1 == NULL) {
14614 			mp->b_next = NULL;
14615 			/* clear b_prev - used by ip_mroute_decap */
14616 			mp->b_prev = NULL;
14617 			freemsg(mp);
14618 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14619 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14620 			    "ip_rput_end: q %p (%S)", q, "copymsg");
14621 			return;
14622 		}
14623 		if (adjusted) {
14624 			/*
14625 			 * Copy is done. Restore the pointer in the _new_ mblk
14626 			 */
14627 			mp1->b_rptr += sizeof (struct ether_header);
14628 		}
14629 		/* Copy b_prev - used by ip_mroute_decap */
14630 		mp1->b_prev = mp->b_prev;
14631 		mp->b_prev = NULL;
14632 		freemsg(mp);
14633 		mp = mp1;
14634 	}
14635 
14636 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14637 	    "ip_rput_end: q %p (%S)", q, "end");
14638 
14639 	ip_input(ill, NULL, mp, NULL);
14640 }
14641 
14642 /*
14643  * Direct read side procedure capable of dealing with chains. GLDv3 based
14644  * drivers call this function directly with mblk chains while STREAMS
14645  * read side procedure ip_rput() calls this for single packet with ip_ring
14646  * set to NULL to process one packet at a time.
14647  *
14648  * The ill will always be valid if this function is called directly from
14649  * the driver.
14650  *
14651  * If ip_input() is called from GLDv3:
14652  *
14653  *   - This must be a non-VLAN IP stream.
14654  *   - 'mp' is either an untagged or a special priority-tagged packet.
14655  *   - Any VLAN tag that was in the MAC header has been stripped.
14656  *
14657  * If the IP header in packet is not 32-bit aligned, every message in the
14658  * chain will be aligned before further operations. This is required on SPARC
14659  * platform.
14660  */
14661 /* ARGSUSED */
14662 void
14663 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14664     struct mac_header_info_s *mhip)
14665 {
14666 	ipaddr_t		dst = NULL;
14667 	ipaddr_t		prev_dst;
14668 	ire_t			*ire = NULL;
14669 	ipha_t			*ipha;
14670 	uint_t			pkt_len;
14671 	ssize_t			len;
14672 	uint_t			opt_len;
14673 	int			ll_multicast;
14674 	int			cgtp_flt_pkt;
14675 	queue_t			*q = ill->ill_rq;
14676 	squeue_t		*curr_sqp = NULL;
14677 	mblk_t 			*head = NULL;
14678 	mblk_t			*tail = NULL;
14679 	mblk_t			*first_mp;
14680 	mblk_t 			*mp;
14681 	mblk_t			*dmp;
14682 	int			cnt = 0;
14683 	ip_stack_t		*ipst = ill->ill_ipst;
14684 
14685 	ASSERT(mp_chain != NULL);
14686 	ASSERT(ill != NULL);
14687 
14688 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14689 
14690 #define	rptr	((uchar_t *)ipha)
14691 
14692 	while (mp_chain != NULL) {
14693 		first_mp = mp = mp_chain;
14694 		mp_chain = mp_chain->b_next;
14695 		mp->b_next = NULL;
14696 		ll_multicast = 0;
14697 
14698 		/*
14699 		 * We do ire caching from one iteration to
14700 		 * another. In the event the packet chain contains
14701 		 * all packets from the same dst, this caching saves
14702 		 * an ire_cache_lookup for each of the succeeding
14703 		 * packets in a packet chain.
14704 		 */
14705 		prev_dst = dst;
14706 
14707 		/*
14708 		 * Check and align the IP header.
14709 		 */
14710 		if (DB_TYPE(mp) == M_DATA) {
14711 			dmp = mp;
14712 		} else if (DB_TYPE(mp) == M_PROTO &&
14713 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14714 			dmp = mp->b_cont;
14715 		} else {
14716 			dmp = NULL;
14717 		}
14718 		if (dmp != NULL) {
14719 			/*
14720 			 * IP header ptr not aligned?
14721 			 * OR IP header not complete in first mblk
14722 			 */
14723 			if (!OK_32PTR(dmp->b_rptr) ||
14724 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14725 				if (!ip_check_and_align_header(q, dmp, ipst))
14726 					continue;
14727 			}
14728 		}
14729 
14730 		/*
14731 		 * ip_input fast path
14732 		 */
14733 
14734 		/* mblk type is not M_DATA */
14735 		if (DB_TYPE(mp) != M_DATA) {
14736 			if (ip_rput_process_notdata(q, &first_mp, ill,
14737 			    &ll_multicast, &mp))
14738 				continue;
14739 		}
14740 
14741 		/* Make sure its an M_DATA and that its aligned */
14742 		ASSERT(DB_TYPE(mp) == M_DATA);
14743 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14744 
14745 		ipha = (ipha_t *)mp->b_rptr;
14746 		len = mp->b_wptr - rptr;
14747 		pkt_len = ntohs(ipha->ipha_length);
14748 
14749 		/*
14750 		 * We must count all incoming packets, even if they end
14751 		 * up being dropped later on.
14752 		 */
14753 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14754 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14755 
14756 		/* multiple mblk or too short */
14757 		len -= pkt_len;
14758 		if (len != 0) {
14759 			/*
14760 			 * Make sure we have data length consistent
14761 			 * with the IP header.
14762 			 */
14763 			if (mp->b_cont == NULL) {
14764 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14765 					BUMP_MIB(ill->ill_ip_mib,
14766 					    ipIfStatsInHdrErrors);
14767 					ip2dbg(("ip_input: drop pkt\n"));
14768 					freemsg(mp);
14769 					continue;
14770 				}
14771 				mp->b_wptr = rptr + pkt_len;
14772 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
14773 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
14774 					BUMP_MIB(ill->ill_ip_mib,
14775 					    ipIfStatsInHdrErrors);
14776 					ip2dbg(("ip_input: drop pkt\n"));
14777 					freemsg(mp);
14778 					continue;
14779 				}
14780 				(void) adjmsg(mp, -len);
14781 				IP_STAT(ipst, ip_multimblk3);
14782 			}
14783 		}
14784 
14785 		/* Obtain the dst of the current packet */
14786 		dst = ipha->ipha_dst;
14787 
14788 		if (IP_LOOPBACK_ADDR(dst) ||
14789 		    IP_LOOPBACK_ADDR(ipha->ipha_src)) {
14790 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
14791 			cmn_err(CE_CONT, "dst %X src %X\n",
14792 			    dst, ipha->ipha_src);
14793 			freemsg(mp);
14794 			continue;
14795 		}
14796 
14797 		/*
14798 		 * The event for packets being received from a 'physical'
14799 		 * interface is placed after validation of the source and/or
14800 		 * destination address as being local so that packets can be
14801 		 * redirected to loopback addresses using ipnat.
14802 		 */
14803 		DTRACE_PROBE4(ip4__physical__in__start,
14804 		    ill_t *, ill, ill_t *, NULL,
14805 		    ipha_t *, ipha, mblk_t *, first_mp);
14806 
14807 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
14808 		    ipst->ips_ipv4firewall_physical_in,
14809 		    ill, NULL, ipha, first_mp, mp, ipst);
14810 
14811 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
14812 
14813 		if (first_mp == NULL) {
14814 			continue;
14815 		}
14816 		dst = ipha->ipha_dst;
14817 
14818 		/*
14819 		 * Attach any necessary label information to
14820 		 * this packet
14821 		 */
14822 		if (is_system_labeled() &&
14823 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
14824 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14825 			freemsg(mp);
14826 			continue;
14827 		}
14828 
14829 		/*
14830 		 * Reuse the cached ire only if the ipha_dst of the previous
14831 		 * packet is the same as the current packet AND it is not
14832 		 * INADDR_ANY.
14833 		 */
14834 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
14835 		    (ire != NULL)) {
14836 			ire_refrele(ire);
14837 			ire = NULL;
14838 		}
14839 		opt_len = ipha->ipha_version_and_hdr_length -
14840 		    IP_SIMPLE_HDR_VERSION;
14841 
14842 		/*
14843 		 * Check to see if we can take the fastpath.
14844 		 * That is possible if the following conditions are met
14845 		 *	o Tsol disabled
14846 		 *	o CGTP disabled
14847 		 *	o ipp_action_count is 0
14848 		 *	o no options in the packet
14849 		 *	o not a RSVP packet
14850 		 * 	o not a multicast packet
14851 		 */
14852 		if (!is_system_labeled() &&
14853 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
14854 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
14855 		    !ll_multicast && !CLASSD(dst)) {
14856 			if (ire == NULL)
14857 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
14858 				    ipst);
14859 
14860 			/* incoming packet is for forwarding */
14861 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
14862 				ire = ip_fast_forward(ire, dst, ill, mp);
14863 				continue;
14864 			}
14865 			/* incoming packet is for local consumption */
14866 			if (ire->ire_type & IRE_LOCAL)
14867 				goto local;
14868 		}
14869 
14870 		/*
14871 		 * Disable ire caching for anything more complex
14872 		 * than the simple fast path case we checked for above.
14873 		 */
14874 		if (ire != NULL) {
14875 			ire_refrele(ire);
14876 			ire = NULL;
14877 		}
14878 
14879 		/* Full-blown slow path */
14880 		if (opt_len != 0) {
14881 			if (len != 0)
14882 				IP_STAT(ipst, ip_multimblk4);
14883 			else
14884 				IP_STAT(ipst, ip_ipoptions);
14885 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
14886 			    &dst, ipst))
14887 				continue;
14888 		}
14889 
14890 		/*
14891 		 * Invoke the CGTP (multirouting) filtering module to process
14892 		 * the incoming packet. Packets identified as duplicates
14893 		 * must be discarded. Filtering is active only if the
14894 		 * the ip_cgtp_filter ndd variable is non-zero.
14895 		 */
14896 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
14897 		if (ipst->ips_ip_cgtp_filter &&
14898 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
14899 			netstackid_t stackid;
14900 
14901 			stackid = ipst->ips_netstack->netstack_stackid;
14902 			cgtp_flt_pkt =
14903 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
14904 			    ill->ill_phyint->phyint_ifindex, mp);
14905 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
14906 				freemsg(first_mp);
14907 				continue;
14908 			}
14909 		}
14910 
14911 		/*
14912 		 * If rsvpd is running, let RSVP daemon handle its processing
14913 		 * and forwarding of RSVP multicast/unicast packets.
14914 		 * If rsvpd is not running but mrouted is running, RSVP
14915 		 * multicast packets are forwarded as multicast traffic
14916 		 * and RSVP unicast packets are forwarded by unicast router.
14917 		 * If neither rsvpd nor mrouted is running, RSVP multicast
14918 		 * packets are not forwarded, but the unicast packets are
14919 		 * forwarded like unicast traffic.
14920 		 */
14921 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
14922 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
14923 		    NULL) {
14924 			/* RSVP packet and rsvpd running. Treat as ours */
14925 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
14926 			/*
14927 			 * This assumes that we deliver to all streams for
14928 			 * multicast and broadcast packets.
14929 			 * We have to force ll_multicast to 1 to handle the
14930 			 * M_DATA messages passed in from ip_mroute_decap.
14931 			 */
14932 			dst = INADDR_BROADCAST;
14933 			ll_multicast = 1;
14934 		} else if (CLASSD(dst)) {
14935 			/* packet is multicast */
14936 			mp->b_next = NULL;
14937 			if (ip_rput_process_multicast(q, mp, ill, ipha,
14938 			    &ll_multicast, &dst))
14939 				continue;
14940 		}
14941 
14942 		if (ire == NULL) {
14943 			ire = ire_cache_lookup(dst, ALL_ZONES,
14944 			    MBLK_GETLABEL(mp), ipst);
14945 		}
14946 
14947 		if (ire == NULL) {
14948 			/*
14949 			 * No IRE for this destination, so it can't be for us.
14950 			 * Unless we are forwarding, drop the packet.
14951 			 * We have to let source routed packets through
14952 			 * since we don't yet know if they are 'ping -l'
14953 			 * packets i.e. if they will go out over the
14954 			 * same interface as they came in on.
14955 			 */
14956 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
14957 			if (ire == NULL)
14958 				continue;
14959 		}
14960 
14961 		/*
14962 		 * Broadcast IRE may indicate either broadcast or
14963 		 * multicast packet
14964 		 */
14965 		if (ire->ire_type == IRE_BROADCAST) {
14966 			/*
14967 			 * Skip broadcast checks if packet is UDP multicast;
14968 			 * we'd rather not enter ip_rput_process_broadcast()
14969 			 * unless the packet is broadcast for real, since
14970 			 * that routine is a no-op for multicast.
14971 			 */
14972 			if (ipha->ipha_protocol != IPPROTO_UDP ||
14973 			    !CLASSD(ipha->ipha_dst)) {
14974 				ire = ip_rput_process_broadcast(&q, mp,
14975 				    ire, ipha, ill, dst, cgtp_flt_pkt,
14976 				    ll_multicast);
14977 				if (ire == NULL)
14978 					continue;
14979 			}
14980 		} else if (ire->ire_stq != NULL) {
14981 			/* fowarding? */
14982 			ip_rput_process_forward(q, mp, ire, ipha, ill,
14983 			    ll_multicast);
14984 			/* ip_rput_process_forward consumed the packet */
14985 			continue;
14986 		}
14987 
14988 local:
14989 		/*
14990 		 * If the queue in the ire is different to the ingress queue
14991 		 * then we need to check to see if we can accept the packet.
14992 		 * Note that for multicast packets and broadcast packets sent
14993 		 * to a broadcast address which is shared between multiple
14994 		 * interfaces we should not do this since we just got a random
14995 		 * broadcast ire.
14996 		 */
14997 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
14998 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
14999 			    ill)) == NULL) {
15000 				/* Drop packet */
15001 				BUMP_MIB(ill->ill_ip_mib,
15002 				    ipIfStatsForwProhibits);
15003 				freemsg(mp);
15004 				continue;
15005 			}
15006 			if (ire->ire_rfq != NULL)
15007 				q = ire->ire_rfq;
15008 		}
15009 
15010 		switch (ipha->ipha_protocol) {
15011 		case IPPROTO_TCP:
15012 			ASSERT(first_mp == mp);
15013 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15014 			    mp, 0, q, ip_ring)) != NULL) {
15015 				if (curr_sqp == NULL) {
15016 					curr_sqp = GET_SQUEUE(mp);
15017 					ASSERT(cnt == 0);
15018 					cnt++;
15019 					head = tail = mp;
15020 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15021 					ASSERT(tail != NULL);
15022 					cnt++;
15023 					tail->b_next = mp;
15024 					tail = mp;
15025 				} else {
15026 					/*
15027 					 * A different squeue. Send the
15028 					 * chain for the previous squeue on
15029 					 * its way. This shouldn't happen
15030 					 * often unless interrupt binding
15031 					 * changes.
15032 					 */
15033 					IP_STAT(ipst, ip_input_multi_squeue);
15034 					squeue_enter_chain(curr_sqp, head,
15035 					    tail, cnt, SQTAG_IP_INPUT);
15036 					curr_sqp = GET_SQUEUE(mp);
15037 					head = mp;
15038 					tail = mp;
15039 					cnt = 1;
15040 				}
15041 			}
15042 			continue;
15043 		case IPPROTO_UDP:
15044 			ASSERT(first_mp == mp);
15045 			ip_udp_input(q, mp, ipha, ire, ill);
15046 			continue;
15047 		case IPPROTO_SCTP:
15048 			ASSERT(first_mp == mp);
15049 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15050 			    q, dst);
15051 			/* ire has been released by ip_sctp_input */
15052 			ire = NULL;
15053 			continue;
15054 		default:
15055 			ip_proto_input(q, first_mp, ipha, ire, ill);
15056 			continue;
15057 		}
15058 	}
15059 
15060 	if (ire != NULL)
15061 		ire_refrele(ire);
15062 
15063 	if (head != NULL)
15064 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15065 
15066 	/*
15067 	 * This code is there just to make netperf/ttcp look good.
15068 	 *
15069 	 * Its possible that after being in polling mode (and having cleared
15070 	 * the backlog), squeues have turned the interrupt frequency higher
15071 	 * to improve latency at the expense of more CPU utilization (less
15072 	 * packets per interrupts or more number of interrupts). Workloads
15073 	 * like ttcp/netperf do manage to tickle polling once in a while
15074 	 * but for the remaining time, stay in higher interrupt mode since
15075 	 * their packet arrival rate is pretty uniform and this shows up
15076 	 * as higher CPU utilization. Since people care about CPU utilization
15077 	 * while running netperf/ttcp, turn the interrupt frequency back to
15078 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15079 	 */
15080 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15081 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15082 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15083 			ip_ring->rr_blank(ip_ring->rr_handle,
15084 			    ip_ring->rr_normal_blank_time,
15085 			    ip_ring->rr_normal_pkt_cnt);
15086 		}
15087 		}
15088 
15089 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15090 	    "ip_input_end: q %p (%S)", q, "end");
15091 #undef  rptr
15092 }
15093 
15094 static void
15095 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15096     t_uscalar_t err)
15097 {
15098 	if (dl_err == DL_SYSERR) {
15099 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15100 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15101 		    ill->ill_name, dlpi_prim_str(prim), err);
15102 		return;
15103 	}
15104 
15105 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15106 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15107 	    dlpi_err_str(dl_err));
15108 }
15109 
15110 /*
15111  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15112  * than DL_UNITDATA_IND messages. If we need to process this message
15113  * exclusively, we call qwriter_ip, in which case we also need to call
15114  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15115  */
15116 void
15117 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15118 {
15119 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15120 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15121 	ill_t		*ill = (ill_t *)q->q_ptr;
15122 	boolean_t	pending;
15123 
15124 	ip1dbg(("ip_rput_dlpi"));
15125 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15126 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15127 		    "%s (0x%x), unix %u\n", ill->ill_name,
15128 		    dlpi_prim_str(dlea->dl_error_primitive),
15129 		    dlea->dl_error_primitive,
15130 		    dlpi_err_str(dlea->dl_errno),
15131 		    dlea->dl_errno,
15132 		    dlea->dl_unix_errno));
15133 	}
15134 
15135 	/*
15136 	 * If we received an ACK but didn't send a request for it, then it
15137 	 * can't be part of any pending operation; discard up-front.
15138 	 */
15139 	switch (dloa->dl_primitive) {
15140 	case DL_NOTIFY_IND:
15141 		pending = B_TRUE;
15142 		break;
15143 	case DL_ERROR_ACK:
15144 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15145 		break;
15146 	case DL_OK_ACK:
15147 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15148 		break;
15149 	case DL_INFO_ACK:
15150 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15151 		break;
15152 	case DL_BIND_ACK:
15153 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15154 		break;
15155 	case DL_PHYS_ADDR_ACK:
15156 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15157 		break;
15158 	case DL_NOTIFY_ACK:
15159 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15160 		break;
15161 	case DL_CONTROL_ACK:
15162 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15163 		break;
15164 	case DL_CAPABILITY_ACK:
15165 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15166 		break;
15167 	default:
15168 		/* Not a DLPI message we support or were expecting */
15169 		freemsg(mp);
15170 		return;
15171 	}
15172 
15173 	if (!pending) {
15174 		freemsg(mp);
15175 		return;
15176 	}
15177 
15178 	switch (dloa->dl_primitive) {
15179 	case DL_ERROR_ACK:
15180 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15181 			mutex_enter(&ill->ill_lock);
15182 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15183 			cv_signal(&ill->ill_cv);
15184 			mutex_exit(&ill->ill_lock);
15185 		}
15186 		break;
15187 
15188 	case DL_OK_ACK:
15189 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15190 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15191 		switch (dloa->dl_correct_primitive) {
15192 		case DL_UNBIND_REQ:
15193 			mutex_enter(&ill->ill_lock);
15194 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15195 			cv_signal(&ill->ill_cv);
15196 			mutex_exit(&ill->ill_lock);
15197 			break;
15198 
15199 		case DL_ENABMULTI_REQ:
15200 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15201 				ill->ill_dlpi_multicast_state = IDS_OK;
15202 			break;
15203 		}
15204 		break;
15205 	default:
15206 		break;
15207 	}
15208 
15209 	/*
15210 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15211 	 * and we need to become writer to continue to process it. If it's not
15212 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15213 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15214 	 * some work as part of the current exclusive operation that actually
15215 	 * is not part of it -- which is wrong, but better than the
15216 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15217 	 * should track which DLPI requests have ACKs that we wait on
15218 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15219 	 *
15220 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15221 	 * Since this is on the ill stream we unconditionally bump up the
15222 	 * refcount without doing ILL_CAN_LOOKUP().
15223 	 */
15224 	ill_refhold(ill);
15225 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15226 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15227 	else
15228 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15229 }
15230 
15231 /*
15232  * Handling of DLPI messages that require exclusive access to the ipsq.
15233  *
15234  * Need to do ill_pending_mp_release on ioctl completion, which could
15235  * happen here. (along with mi_copy_done)
15236  */
15237 /* ARGSUSED */
15238 static void
15239 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15240 {
15241 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15242 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15243 	int		err = 0;
15244 	ill_t		*ill;
15245 	ipif_t		*ipif = NULL;
15246 	mblk_t		*mp1 = NULL;
15247 	conn_t		*connp = NULL;
15248 	t_uscalar_t	paddrreq;
15249 	mblk_t		*mp_hw;
15250 	boolean_t	success;
15251 	boolean_t	ioctl_aborted = B_FALSE;
15252 	boolean_t	log = B_TRUE;
15253 	hook_nic_event_t	*info;
15254 	ip_stack_t		*ipst;
15255 
15256 	ip1dbg(("ip_rput_dlpi_writer .."));
15257 	ill = (ill_t *)q->q_ptr;
15258 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15259 
15260 	ASSERT(IAM_WRITER_ILL(ill));
15261 
15262 	ipst = ill->ill_ipst;
15263 
15264 	/*
15265 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15266 	 * both are null or non-null. However we can assert that only
15267 	 * after grabbing the ipsq_lock. So we don't make any assertion
15268 	 * here and in other places in the code.
15269 	 */
15270 	ipif = ipsq->ipsq_pending_ipif;
15271 	/*
15272 	 * The current ioctl could have been aborted by the user and a new
15273 	 * ioctl to bring up another ill could have started. We could still
15274 	 * get a response from the driver later.
15275 	 */
15276 	if (ipif != NULL && ipif->ipif_ill != ill)
15277 		ioctl_aborted = B_TRUE;
15278 
15279 	switch (dloa->dl_primitive) {
15280 	case DL_ERROR_ACK:
15281 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15282 		    dlpi_prim_str(dlea->dl_error_primitive)));
15283 
15284 		switch (dlea->dl_error_primitive) {
15285 		case DL_PROMISCON_REQ:
15286 		case DL_PROMISCOFF_REQ:
15287 		case DL_DISABMULTI_REQ:
15288 		case DL_UNBIND_REQ:
15289 		case DL_ATTACH_REQ:
15290 		case DL_INFO_REQ:
15291 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15292 			break;
15293 		case DL_NOTIFY_REQ:
15294 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15295 			log = B_FALSE;
15296 			break;
15297 		case DL_PHYS_ADDR_REQ:
15298 			/*
15299 			 * For IPv6 only, there are two additional
15300 			 * phys_addr_req's sent to the driver to get the
15301 			 * IPv6 token and lla. This allows IP to acquire
15302 			 * the hardware address format for a given interface
15303 			 * without having built in knowledge of the hardware
15304 			 * address. ill_phys_addr_pend keeps track of the last
15305 			 * DL_PAR sent so we know which response we are
15306 			 * dealing with. ill_dlpi_done will update
15307 			 * ill_phys_addr_pend when it sends the next req.
15308 			 * We don't complete the IOCTL until all three DL_PARs
15309 			 * have been attempted, so set *_len to 0 and break.
15310 			 */
15311 			paddrreq = ill->ill_phys_addr_pend;
15312 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15313 			if (paddrreq == DL_IPV6_TOKEN) {
15314 				ill->ill_token_length = 0;
15315 				log = B_FALSE;
15316 				break;
15317 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15318 				ill->ill_nd_lla_len = 0;
15319 				log = B_FALSE;
15320 				break;
15321 			}
15322 			/*
15323 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15324 			 * We presumably have an IOCTL hanging out waiting
15325 			 * for completion. Find it and complete the IOCTL
15326 			 * with the error noted.
15327 			 * However, ill_dl_phys was called on an ill queue
15328 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15329 			 * set. But the ioctl is known to be pending on ill_wq.
15330 			 */
15331 			if (!ill->ill_ifname_pending)
15332 				break;
15333 			ill->ill_ifname_pending = 0;
15334 			if (!ioctl_aborted)
15335 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15336 			if (mp1 != NULL) {
15337 				/*
15338 				 * This operation (SIOCSLIFNAME) must have
15339 				 * happened on the ill. Assert there is no conn
15340 				 */
15341 				ASSERT(connp == NULL);
15342 				q = ill->ill_wq;
15343 			}
15344 			break;
15345 		case DL_BIND_REQ:
15346 			ill_dlpi_done(ill, DL_BIND_REQ);
15347 			if (ill->ill_ifname_pending)
15348 				break;
15349 			/*
15350 			 * Something went wrong with the bind.  We presumably
15351 			 * have an IOCTL hanging out waiting for completion.
15352 			 * Find it, take down the interface that was coming
15353 			 * up, and complete the IOCTL with the error noted.
15354 			 */
15355 			if (!ioctl_aborted)
15356 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15357 			if (mp1 != NULL) {
15358 				/*
15359 				 * This operation (SIOCSLIFFLAGS) must have
15360 				 * happened from a conn.
15361 				 */
15362 				ASSERT(connp != NULL);
15363 				q = CONNP_TO_WQ(connp);
15364 				if (ill->ill_move_in_progress) {
15365 					ILL_CLEAR_MOVE(ill);
15366 				}
15367 				(void) ipif_down(ipif, NULL, NULL);
15368 				/* error is set below the switch */
15369 			}
15370 			break;
15371 		case DL_ENABMULTI_REQ:
15372 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15373 
15374 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15375 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15376 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15377 				ipif_t *ipif;
15378 
15379 				printf("ip: joining multicasts failed (%d)"
15380 				    " on %s - will use link layer "
15381 				    "broadcasts for multicast\n",
15382 				    dlea->dl_errno, ill->ill_name);
15383 
15384 				/*
15385 				 * Set up the multicast mapping alone.
15386 				 * writer, so ok to access ill->ill_ipif
15387 				 * without any lock.
15388 				 */
15389 				ipif = ill->ill_ipif;
15390 				mutex_enter(&ill->ill_phyint->phyint_lock);
15391 				ill->ill_phyint->phyint_flags |=
15392 				    PHYI_MULTI_BCAST;
15393 				mutex_exit(&ill->ill_phyint->phyint_lock);
15394 
15395 				if (!ill->ill_isv6) {
15396 					(void) ipif_arp_setup_multicast(ipif,
15397 					    NULL);
15398 				} else {
15399 					(void) ipif_ndp_setup_multicast(ipif,
15400 					    NULL);
15401 				}
15402 			}
15403 			freemsg(mp);	/* Don't want to pass this up */
15404 			return;
15405 
15406 		case DL_CAPABILITY_REQ:
15407 		case DL_CONTROL_REQ:
15408 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15409 			ill->ill_dlpi_capab_state = IDS_FAILED;
15410 			freemsg(mp);
15411 			return;
15412 		}
15413 		/*
15414 		 * Note the error for IOCTL completion (mp1 is set when
15415 		 * ready to complete ioctl). If ill_ifname_pending_err is
15416 		 * set, an error occured during plumbing (ill_ifname_pending),
15417 		 * so we want to report that error.
15418 		 *
15419 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15420 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15421 		 * expected to get errack'd if the driver doesn't support
15422 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15423 		 * if these error conditions are encountered.
15424 		 */
15425 		if (mp1 != NULL) {
15426 			if (ill->ill_ifname_pending_err != 0)  {
15427 				err = ill->ill_ifname_pending_err;
15428 				ill->ill_ifname_pending_err = 0;
15429 			} else {
15430 				err = dlea->dl_unix_errno ?
15431 				    dlea->dl_unix_errno : ENXIO;
15432 			}
15433 		/*
15434 		 * If we're plumbing an interface and an error hasn't already
15435 		 * been saved, set ill_ifname_pending_err to the error passed
15436 		 * up. Ignore the error if log is B_FALSE (see comment above).
15437 		 */
15438 		} else if (log && ill->ill_ifname_pending &&
15439 		    ill->ill_ifname_pending_err == 0) {
15440 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15441 			    dlea->dl_unix_errno : ENXIO;
15442 		}
15443 
15444 		if (log)
15445 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15446 			    dlea->dl_errno, dlea->dl_unix_errno);
15447 		break;
15448 	case DL_CAPABILITY_ACK: {
15449 		boolean_t reneg_flag = B_FALSE;
15450 		/* Call a routine to handle this one. */
15451 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15452 		/*
15453 		 * Check if the ACK is due to renegotiation case since we
15454 		 * will need to send a new CAPABILITY_REQ later.
15455 		 */
15456 		if (ill->ill_dlpi_capab_state == IDS_RENEG) {
15457 			/* This is the ack for a renogiation case */
15458 			reneg_flag = B_TRUE;
15459 			ill->ill_dlpi_capab_state = IDS_UNKNOWN;
15460 		}
15461 		ill_capability_ack(ill, mp);
15462 		if (reneg_flag)
15463 			ill_capability_probe(ill);
15464 		break;
15465 	}
15466 	case DL_CONTROL_ACK:
15467 		/* We treat all of these as "fire and forget" */
15468 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15469 		break;
15470 	case DL_INFO_ACK:
15471 		/* Call a routine to handle this one. */
15472 		ill_dlpi_done(ill, DL_INFO_REQ);
15473 		ip_ll_subnet_defaults(ill, mp);
15474 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15475 		return;
15476 	case DL_BIND_ACK:
15477 		/*
15478 		 * We should have an IOCTL waiting on this unless
15479 		 * sent by ill_dl_phys, in which case just return
15480 		 */
15481 		ill_dlpi_done(ill, DL_BIND_REQ);
15482 		if (ill->ill_ifname_pending)
15483 			break;
15484 
15485 		if (!ioctl_aborted)
15486 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15487 		if (mp1 == NULL)
15488 			break;
15489 		/*
15490 		 * Because mp1 was added by ill_dl_up(), and it always
15491 		 * passes a valid connp, connp must be valid here.
15492 		 */
15493 		ASSERT(connp != NULL);
15494 		q = CONNP_TO_WQ(connp);
15495 
15496 		/*
15497 		 * We are exclusive. So nothing can change even after
15498 		 * we get the pending mp. If need be we can put it back
15499 		 * and restart, as in calling ipif_arp_up()  below.
15500 		 */
15501 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15502 
15503 		mutex_enter(&ill->ill_lock);
15504 
15505 		ill->ill_dl_up = 1;
15506 
15507 		if ((info = ill->ill_nic_event_info) != NULL) {
15508 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15509 			    "attached for %s\n", info->hne_event,
15510 			    ill->ill_name));
15511 			if (info->hne_data != NULL)
15512 				kmem_free(info->hne_data, info->hne_datalen);
15513 			kmem_free(info, sizeof (hook_nic_event_t));
15514 		}
15515 
15516 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15517 		if (info != NULL) {
15518 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15519 			info->hne_lif = 0;
15520 			info->hne_event = NE_UP;
15521 			info->hne_data = NULL;
15522 			info->hne_datalen = 0;
15523 			info->hne_family = ill->ill_isv6 ?
15524 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15525 		} else
15526 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15527 			    "event information for %s (ENOMEM)\n",
15528 			    ill->ill_name));
15529 
15530 		ill->ill_nic_event_info = info;
15531 
15532 		mutex_exit(&ill->ill_lock);
15533 
15534 		/*
15535 		 * Now bring up the resolver; when that is complete, we'll
15536 		 * create IREs.  Note that we intentionally mirror what
15537 		 * ipif_up() would have done, because we got here by way of
15538 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15539 		 */
15540 		if (ill->ill_isv6) {
15541 			/*
15542 			 * v6 interfaces.
15543 			 * Unlike ARP which has to do another bind
15544 			 * and attach, once we get here we are
15545 			 * done with NDP. Except in the case of
15546 			 * ILLF_XRESOLV, in which case we send an
15547 			 * AR_INTERFACE_UP to the external resolver.
15548 			 * If all goes well, the ioctl will complete
15549 			 * in ip_rput(). If there's an error, we
15550 			 * complete it here.
15551 			 */
15552 			if ((err = ipif_ndp_up(ipif)) == 0) {
15553 				if (ill->ill_flags & ILLF_XRESOLV) {
15554 					mutex_enter(&connp->conn_lock);
15555 					mutex_enter(&ill->ill_lock);
15556 					success = ipsq_pending_mp_add(
15557 					    connp, ipif, q, mp1, 0);
15558 					mutex_exit(&ill->ill_lock);
15559 					mutex_exit(&connp->conn_lock);
15560 					if (success) {
15561 						err = ipif_resolver_up(ipif,
15562 						    Res_act_initial);
15563 						if (err == EINPROGRESS) {
15564 							freemsg(mp);
15565 							return;
15566 						}
15567 						ASSERT(err != 0);
15568 						mp1 = ipsq_pending_mp_get(ipsq,
15569 						    &connp);
15570 						ASSERT(mp1 != NULL);
15571 					} else {
15572 						/* conn has started closing */
15573 						err = EINTR;
15574 					}
15575 				} else { /* Non XRESOLV interface */
15576 					(void) ipif_resolver_up(ipif,
15577 					    Res_act_initial);
15578 					err = ipif_up_done_v6(ipif);
15579 				}
15580 			}
15581 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15582 			/*
15583 			 * ARP and other v4 external resolvers.
15584 			 * Leave the pending mblk intact so that
15585 			 * the ioctl completes in ip_rput().
15586 			 */
15587 			mutex_enter(&connp->conn_lock);
15588 			mutex_enter(&ill->ill_lock);
15589 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15590 			mutex_exit(&ill->ill_lock);
15591 			mutex_exit(&connp->conn_lock);
15592 			if (success) {
15593 				err = ipif_resolver_up(ipif, Res_act_initial);
15594 				if (err == EINPROGRESS) {
15595 					freemsg(mp);
15596 					return;
15597 				}
15598 				ASSERT(err != 0);
15599 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15600 			} else {
15601 				/* The conn has started closing */
15602 				err = EINTR;
15603 			}
15604 		} else {
15605 			/*
15606 			 * This one is complete. Reply to pending ioctl.
15607 			 */
15608 			(void) ipif_resolver_up(ipif, Res_act_initial);
15609 			err = ipif_up_done(ipif);
15610 		}
15611 
15612 		if ((err == 0) && (ill->ill_up_ipifs)) {
15613 			err = ill_up_ipifs(ill, q, mp1);
15614 			if (err == EINPROGRESS) {
15615 				freemsg(mp);
15616 				return;
15617 			}
15618 		}
15619 
15620 		if (ill->ill_up_ipifs) {
15621 			ill_group_cleanup(ill);
15622 		}
15623 
15624 		break;
15625 	case DL_NOTIFY_IND: {
15626 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15627 		ire_t *ire;
15628 		boolean_t need_ire_walk_v4 = B_FALSE;
15629 		boolean_t need_ire_walk_v6 = B_FALSE;
15630 
15631 		switch (notify->dl_notification) {
15632 		case DL_NOTE_PHYS_ADDR:
15633 			err = ill_set_phys_addr(ill, mp);
15634 			break;
15635 
15636 		case DL_NOTE_FASTPATH_FLUSH:
15637 			ill_fastpath_flush(ill);
15638 			break;
15639 
15640 		case DL_NOTE_SDU_SIZE:
15641 			/*
15642 			 * Change the MTU size of the interface, of all
15643 			 * attached ipif's, and of all relevant ire's.  The
15644 			 * new value's a uint32_t at notify->dl_data.
15645 			 * Mtu change Vs. new ire creation - protocol below.
15646 			 *
15647 			 * a Mark the ipif as IPIF_CHANGING.
15648 			 * b Set the new mtu in the ipif.
15649 			 * c Change the ire_max_frag on all affected ires
15650 			 * d Unmark the IPIF_CHANGING
15651 			 *
15652 			 * To see how the protocol works, assume an interface
15653 			 * route is also being added simultaneously by
15654 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15655 			 * the ire. If the ire is created before step a,
15656 			 * it will be cleaned up by step c. If the ire is
15657 			 * created after step d, it will see the new value of
15658 			 * ipif_mtu. Any attempt to create the ire between
15659 			 * steps a to d will fail because of the IPIF_CHANGING
15660 			 * flag. Note that ire_create() is passed a pointer to
15661 			 * the ipif_mtu, and not the value. During ire_add
15662 			 * under the bucket lock, the ire_max_frag of the
15663 			 * new ire being created is set from the ipif/ire from
15664 			 * which it is being derived.
15665 			 */
15666 			mutex_enter(&ill->ill_lock);
15667 			ill->ill_max_frag = (uint_t)notify->dl_data;
15668 
15669 			/*
15670 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15671 			 * leave it alone
15672 			 */
15673 			if (ill->ill_mtu_userspecified) {
15674 				mutex_exit(&ill->ill_lock);
15675 				break;
15676 			}
15677 			ill->ill_max_mtu = ill->ill_max_frag;
15678 			if (ill->ill_isv6) {
15679 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15680 					ill->ill_max_mtu = IPV6_MIN_MTU;
15681 			} else {
15682 				if (ill->ill_max_mtu < IP_MIN_MTU)
15683 					ill->ill_max_mtu = IP_MIN_MTU;
15684 			}
15685 			for (ipif = ill->ill_ipif; ipif != NULL;
15686 			    ipif = ipif->ipif_next) {
15687 				/*
15688 				 * Don't override the mtu if the user
15689 				 * has explicitly set it.
15690 				 */
15691 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15692 					continue;
15693 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15694 				if (ipif->ipif_isv6)
15695 					ire = ipif_to_ire_v6(ipif);
15696 				else
15697 					ire = ipif_to_ire(ipif);
15698 				if (ire != NULL) {
15699 					ire->ire_max_frag = ipif->ipif_mtu;
15700 					ire_refrele(ire);
15701 				}
15702 				if (ipif->ipif_flags & IPIF_UP) {
15703 					if (ill->ill_isv6)
15704 						need_ire_walk_v6 = B_TRUE;
15705 					else
15706 						need_ire_walk_v4 = B_TRUE;
15707 				}
15708 			}
15709 			mutex_exit(&ill->ill_lock);
15710 			if (need_ire_walk_v4)
15711 				ire_walk_v4(ill_mtu_change, (char *)ill,
15712 				    ALL_ZONES, ipst);
15713 			if (need_ire_walk_v6)
15714 				ire_walk_v6(ill_mtu_change, (char *)ill,
15715 				    ALL_ZONES, ipst);
15716 			break;
15717 		case DL_NOTE_LINK_UP:
15718 		case DL_NOTE_LINK_DOWN: {
15719 			/*
15720 			 * We are writer. ill / phyint / ipsq assocs stable.
15721 			 * The RUNNING flag reflects the state of the link.
15722 			 */
15723 			phyint_t *phyint = ill->ill_phyint;
15724 			uint64_t new_phyint_flags;
15725 			boolean_t changed = B_FALSE;
15726 			boolean_t went_up;
15727 
15728 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15729 			mutex_enter(&phyint->phyint_lock);
15730 			new_phyint_flags = went_up ?
15731 			    phyint->phyint_flags | PHYI_RUNNING :
15732 			    phyint->phyint_flags & ~PHYI_RUNNING;
15733 			if (new_phyint_flags != phyint->phyint_flags) {
15734 				phyint->phyint_flags = new_phyint_flags;
15735 				changed = B_TRUE;
15736 			}
15737 			mutex_exit(&phyint->phyint_lock);
15738 			/*
15739 			 * ill_restart_dad handles the DAD restart and routing
15740 			 * socket notification logic.
15741 			 */
15742 			if (changed) {
15743 				ill_restart_dad(phyint->phyint_illv4, went_up);
15744 				ill_restart_dad(phyint->phyint_illv6, went_up);
15745 			}
15746 			break;
15747 		}
15748 		case DL_NOTE_PROMISC_ON_PHYS:
15749 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15750 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15751 			mutex_enter(&ill->ill_lock);
15752 			ill->ill_promisc_on_phys = B_TRUE;
15753 			mutex_exit(&ill->ill_lock);
15754 			break;
15755 		case DL_NOTE_PROMISC_OFF_PHYS:
15756 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15757 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
15758 			mutex_enter(&ill->ill_lock);
15759 			ill->ill_promisc_on_phys = B_FALSE;
15760 			mutex_exit(&ill->ill_lock);
15761 			break;
15762 		case DL_NOTE_CAPAB_RENEG:
15763 			/*
15764 			 * Something changed on the driver side.
15765 			 * It wants us to renegotiate the capabilities
15766 			 * on this ill. The most likely cause is the
15767 			 * aggregation interface under us where a
15768 			 * port got added or went away.
15769 			 *
15770 			 * We reset the capabilities and set the
15771 			 * state to IDS_RENG so that when the ack
15772 			 * comes back, we can start the
15773 			 * renegotiation process.
15774 			 */
15775 			ill_capability_reset(ill);
15776 			ill->ill_dlpi_capab_state = IDS_RENEG;
15777 			break;
15778 		default:
15779 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
15780 			    "type 0x%x for DL_NOTIFY_IND\n",
15781 			    notify->dl_notification));
15782 			break;
15783 		}
15784 
15785 		/*
15786 		 * As this is an asynchronous operation, we
15787 		 * should not call ill_dlpi_done
15788 		 */
15789 		break;
15790 	}
15791 	case DL_NOTIFY_ACK: {
15792 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
15793 
15794 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
15795 			ill->ill_note_link = 1;
15796 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
15797 		break;
15798 	}
15799 	case DL_PHYS_ADDR_ACK: {
15800 		/*
15801 		 * As part of plumbing the interface via SIOCSLIFNAME,
15802 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
15803 		 * whose answers we receive here.  As each answer is received,
15804 		 * we call ill_dlpi_done() to dispatch the next request as
15805 		 * we're processing the current one.  Once all answers have
15806 		 * been received, we use ipsq_pending_mp_get() to dequeue the
15807 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
15808 		 * is invoked from an ill queue, conn_oper_pending_ill is not
15809 		 * available, but we know the ioctl is pending on ill_wq.)
15810 		 */
15811 		uint_t paddrlen, paddroff;
15812 
15813 		paddrreq = ill->ill_phys_addr_pend;
15814 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
15815 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
15816 
15817 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15818 		if (paddrreq == DL_IPV6_TOKEN) {
15819 			/*
15820 			 * bcopy to low-order bits of ill_token
15821 			 *
15822 			 * XXX Temporary hack - currently, all known tokens
15823 			 * are 64 bits, so I'll cheat for the moment.
15824 			 */
15825 			bcopy(mp->b_rptr + paddroff,
15826 			    &ill->ill_token.s6_addr32[2], paddrlen);
15827 			ill->ill_token_length = paddrlen;
15828 			break;
15829 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15830 			ASSERT(ill->ill_nd_lla_mp == NULL);
15831 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
15832 			mp = NULL;
15833 			break;
15834 		}
15835 
15836 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
15837 		ASSERT(ill->ill_phys_addr_mp == NULL);
15838 		if (!ill->ill_ifname_pending)
15839 			break;
15840 		ill->ill_ifname_pending = 0;
15841 		if (!ioctl_aborted)
15842 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15843 		if (mp1 != NULL) {
15844 			ASSERT(connp == NULL);
15845 			q = ill->ill_wq;
15846 		}
15847 		/*
15848 		 * If any error acks received during the plumbing sequence,
15849 		 * ill_ifname_pending_err will be set. Break out and send up
15850 		 * the error to the pending ioctl.
15851 		 */
15852 		if (ill->ill_ifname_pending_err != 0) {
15853 			err = ill->ill_ifname_pending_err;
15854 			ill->ill_ifname_pending_err = 0;
15855 			break;
15856 		}
15857 
15858 		ill->ill_phys_addr_mp = mp;
15859 		ill->ill_phys_addr = mp->b_rptr + paddroff;
15860 		mp = NULL;
15861 
15862 		/*
15863 		 * If paddrlen is zero, the DLPI provider doesn't support
15864 		 * physical addresses.  The other two tests were historical
15865 		 * workarounds for bugs in our former PPP implementation, but
15866 		 * now other things have grown dependencies on them -- e.g.,
15867 		 * the tun module specifies a dl_addr_length of zero in its
15868 		 * DL_BIND_ACK, but then specifies an incorrect value in its
15869 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
15870 		 * but only after careful testing ensures that all dependent
15871 		 * broken DLPI providers have been fixed.
15872 		 */
15873 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
15874 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
15875 			ill->ill_phys_addr = NULL;
15876 		} else if (paddrlen != ill->ill_phys_addr_length) {
15877 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
15878 			    paddrlen, ill->ill_phys_addr_length));
15879 			err = EINVAL;
15880 			break;
15881 		}
15882 
15883 		if (ill->ill_nd_lla_mp == NULL) {
15884 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
15885 				err = ENOMEM;
15886 				break;
15887 			}
15888 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
15889 		}
15890 
15891 		/*
15892 		 * Set the interface token.  If the zeroth interface address
15893 		 * is unspecified, then set it to the link local address.
15894 		 */
15895 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
15896 			(void) ill_setdefaulttoken(ill);
15897 
15898 		ASSERT(ill->ill_ipif->ipif_id == 0);
15899 		if (ipif != NULL &&
15900 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
15901 			(void) ipif_setlinklocal(ipif);
15902 		}
15903 		break;
15904 	}
15905 	case DL_OK_ACK:
15906 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
15907 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
15908 		    dloa->dl_correct_primitive));
15909 		switch (dloa->dl_correct_primitive) {
15910 		case DL_PROMISCON_REQ:
15911 		case DL_PROMISCOFF_REQ:
15912 		case DL_ENABMULTI_REQ:
15913 		case DL_DISABMULTI_REQ:
15914 		case DL_UNBIND_REQ:
15915 		case DL_ATTACH_REQ:
15916 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
15917 			break;
15918 		}
15919 		break;
15920 	default:
15921 		break;
15922 	}
15923 
15924 	freemsg(mp);
15925 	if (mp1 != NULL) {
15926 		/*
15927 		 * The operation must complete without EINPROGRESS
15928 		 * since ipsq_pending_mp_get() has removed the mblk
15929 		 * from ipsq_pending_mp.  Otherwise, the operation
15930 		 * will be stuck forever in the ipsq.
15931 		 */
15932 		ASSERT(err != EINPROGRESS);
15933 
15934 		switch (ipsq->ipsq_current_ioctl) {
15935 		case 0:
15936 			ipsq_current_finish(ipsq);
15937 			break;
15938 
15939 		case SIOCLIFADDIF:
15940 		case SIOCSLIFNAME:
15941 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
15942 			break;
15943 
15944 		default:
15945 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
15946 			break;
15947 		}
15948 	}
15949 }
15950 
15951 /*
15952  * ip_rput_other is called by ip_rput to handle messages modifying the global
15953  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
15954  */
15955 /* ARGSUSED */
15956 void
15957 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15958 {
15959 	ill_t		*ill;
15960 	struct iocblk	*iocp;
15961 	mblk_t		*mp1;
15962 	conn_t		*connp = NULL;
15963 
15964 	ip1dbg(("ip_rput_other "));
15965 	ill = (ill_t *)q->q_ptr;
15966 	/*
15967 	 * This routine is not a writer in the case of SIOCGTUNPARAM
15968 	 * in which case ipsq is NULL.
15969 	 */
15970 	if (ipsq != NULL) {
15971 		ASSERT(IAM_WRITER_IPSQ(ipsq));
15972 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15973 	}
15974 
15975 	switch (mp->b_datap->db_type) {
15976 	case M_ERROR:
15977 	case M_HANGUP:
15978 		/*
15979 		 * The device has a problem.  We force the ILL down.  It can
15980 		 * be brought up again manually using SIOCSIFFLAGS (via
15981 		 * ifconfig or equivalent).
15982 		 */
15983 		ASSERT(ipsq != NULL);
15984 		if (mp->b_rptr < mp->b_wptr)
15985 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
15986 		if (ill->ill_error == 0)
15987 			ill->ill_error = ENXIO;
15988 		if (!ill_down_start(q, mp))
15989 			return;
15990 		ipif_all_down_tail(ipsq, q, mp, NULL);
15991 		break;
15992 	case M_IOCACK:
15993 		iocp = (struct iocblk *)mp->b_rptr;
15994 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
15995 		switch (iocp->ioc_cmd) {
15996 		case SIOCSTUNPARAM:
15997 		case OSIOCSTUNPARAM:
15998 			ASSERT(ipsq != NULL);
15999 			/*
16000 			 * Finish socket ioctl passed through to tun.
16001 			 * We should have an IOCTL waiting on this.
16002 			 */
16003 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16004 			if (ill->ill_isv6) {
16005 				struct iftun_req *ta;
16006 
16007 				/*
16008 				 * if a source or destination is
16009 				 * being set, try and set the link
16010 				 * local address for the tunnel
16011 				 */
16012 				ta = (struct iftun_req *)mp->b_cont->
16013 				    b_cont->b_rptr;
16014 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16015 					ipif_set_tun_llink(ill, ta);
16016 				}
16017 
16018 			}
16019 			if (mp1 != NULL) {
16020 				/*
16021 				 * Now copy back the b_next/b_prev used by
16022 				 * mi code for the mi_copy* functions.
16023 				 * See ip_sioctl_tunparam() for the reason.
16024 				 * Also protect against missing b_cont.
16025 				 */
16026 				if (mp->b_cont != NULL) {
16027 					mp->b_cont->b_next =
16028 					    mp1->b_cont->b_next;
16029 					mp->b_cont->b_prev =
16030 					    mp1->b_cont->b_prev;
16031 				}
16032 				inet_freemsg(mp1);
16033 				ASSERT(connp != NULL);
16034 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16035 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16036 			} else {
16037 				ASSERT(connp == NULL);
16038 				putnext(q, mp);
16039 			}
16040 			break;
16041 		case SIOCGTUNPARAM:
16042 		case OSIOCGTUNPARAM:
16043 			/*
16044 			 * This is really M_IOCDATA from the tunnel driver.
16045 			 * convert back and complete the ioctl.
16046 			 * We should have an IOCTL waiting on this.
16047 			 */
16048 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16049 			if (mp1) {
16050 				/*
16051 				 * Now copy back the b_next/b_prev used by
16052 				 * mi code for the mi_copy* functions.
16053 				 * See ip_sioctl_tunparam() for the reason.
16054 				 * Also protect against missing b_cont.
16055 				 */
16056 				if (mp->b_cont != NULL) {
16057 					mp->b_cont->b_next =
16058 					    mp1->b_cont->b_next;
16059 					mp->b_cont->b_prev =
16060 					    mp1->b_cont->b_prev;
16061 				}
16062 				inet_freemsg(mp1);
16063 				if (iocp->ioc_error == 0)
16064 					mp->b_datap->db_type = M_IOCDATA;
16065 				ASSERT(connp != NULL);
16066 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16067 				    iocp->ioc_error, COPYOUT, NULL);
16068 			} else {
16069 				ASSERT(connp == NULL);
16070 				putnext(q, mp);
16071 			}
16072 			break;
16073 		default:
16074 			break;
16075 		}
16076 		break;
16077 	case M_IOCNAK:
16078 		iocp = (struct iocblk *)mp->b_rptr;
16079 
16080 		switch (iocp->ioc_cmd) {
16081 		int mode;
16082 
16083 		case DL_IOC_HDR_INFO:
16084 			/*
16085 			 * If this was the first attempt turn of the
16086 			 * fastpath probing.
16087 			 */
16088 			mutex_enter(&ill->ill_lock);
16089 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16090 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16091 				mutex_exit(&ill->ill_lock);
16092 				ill_fastpath_nack(ill);
16093 				ip1dbg(("ip_rput: DLPI fastpath off on "
16094 				    "interface %s\n",
16095 				    ill->ill_name));
16096 			} else {
16097 				mutex_exit(&ill->ill_lock);
16098 			}
16099 			freemsg(mp);
16100 			break;
16101 		case SIOCSTUNPARAM:
16102 		case OSIOCSTUNPARAM:
16103 			ASSERT(ipsq != NULL);
16104 			/*
16105 			 * Finish socket ioctl passed through to tun
16106 			 * We should have an IOCTL waiting on this.
16107 			 */
16108 			/* FALLTHRU */
16109 		case SIOCGTUNPARAM:
16110 		case OSIOCGTUNPARAM:
16111 			/*
16112 			 * This is really M_IOCDATA from the tunnel driver.
16113 			 * convert back and complete the ioctl.
16114 			 * We should have an IOCTL waiting on this.
16115 			 */
16116 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16117 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16118 				mp1 = ill_pending_mp_get(ill, &connp,
16119 				    iocp->ioc_id);
16120 				mode = COPYOUT;
16121 				ipsq = NULL;
16122 			} else {
16123 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16124 				mode = NO_COPYOUT;
16125 			}
16126 			if (mp1 != NULL) {
16127 				/*
16128 				 * Now copy back the b_next/b_prev used by
16129 				 * mi code for the mi_copy* functions.
16130 				 * See ip_sioctl_tunparam() for the reason.
16131 				 * Also protect against missing b_cont.
16132 				 */
16133 				if (mp->b_cont != NULL) {
16134 					mp->b_cont->b_next =
16135 					    mp1->b_cont->b_next;
16136 					mp->b_cont->b_prev =
16137 					    mp1->b_cont->b_prev;
16138 				}
16139 				inet_freemsg(mp1);
16140 				if (iocp->ioc_error == 0)
16141 					iocp->ioc_error = EINVAL;
16142 				ASSERT(connp != NULL);
16143 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16144 				    iocp->ioc_error, mode, ipsq);
16145 			} else {
16146 				ASSERT(connp == NULL);
16147 				putnext(q, mp);
16148 			}
16149 			break;
16150 		default:
16151 			break;
16152 		}
16153 	default:
16154 		break;
16155 	}
16156 }
16157 
16158 /*
16159  * NOTE : This function does not ire_refrele the ire argument passed in.
16160  *
16161  * IPQoS notes
16162  * IP policy is invoked twice for a forwarded packet, once on the read side
16163  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16164  * enabled. An additional parameter, in_ill, has been added for this purpose.
16165  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16166  * because ip_mroute drops this information.
16167  *
16168  */
16169 void
16170 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16171 {
16172 	uint32_t	old_pkt_len;
16173 	uint32_t	pkt_len;
16174 	queue_t	*q;
16175 	uint32_t	sum;
16176 #define	rptr	((uchar_t *)ipha)
16177 	uint32_t	max_frag;
16178 	uint32_t	ill_index;
16179 	ill_t		*out_ill;
16180 	mib2_ipIfStatsEntry_t *mibptr;
16181 	ip_stack_t	*ipst = in_ill->ill_ipst;
16182 
16183 	/* Get the ill_index of the incoming ILL */
16184 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16185 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16186 
16187 	/* Initiate Read side IPPF processing */
16188 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16189 		ip_process(IPP_FWD_IN, &mp, ill_index);
16190 		if (mp == NULL) {
16191 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16192 			    "during IPPF processing\n"));
16193 			return;
16194 		}
16195 	}
16196 
16197 	/* Adjust the checksum to reflect the ttl decrement. */
16198 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16199 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16200 
16201 	if (ipha->ipha_ttl-- <= 1) {
16202 		if (ip_csum_hdr(ipha)) {
16203 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16204 			goto drop_pkt;
16205 		}
16206 		/*
16207 		 * Note: ire_stq this will be NULL for multicast
16208 		 * datagrams using the long path through arp (the IRE
16209 		 * is not an IRE_CACHE). This should not cause
16210 		 * problems since we don't generate ICMP errors for
16211 		 * multicast packets.
16212 		 */
16213 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16214 		q = ire->ire_stq;
16215 		if (q != NULL) {
16216 			/* Sent by forwarding path, and router is global zone */
16217 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16218 			    GLOBAL_ZONEID, ipst);
16219 		} else
16220 			freemsg(mp);
16221 		return;
16222 	}
16223 
16224 	/*
16225 	 * Don't forward if the interface is down
16226 	 */
16227 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16228 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16229 		ip2dbg(("ip_rput_forward:interface is down\n"));
16230 		goto drop_pkt;
16231 	}
16232 
16233 	/* Get the ill_index of the outgoing ILL */
16234 	ill_index = ire->ire_ipif->ipif_ill->ill_phyint->phyint_ifindex;
16235 
16236 	out_ill = ire->ire_ipif->ipif_ill;
16237 
16238 	DTRACE_PROBE4(ip4__forwarding__start,
16239 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16240 
16241 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16242 	    ipst->ips_ipv4firewall_forwarding,
16243 	    in_ill, out_ill, ipha, mp, mp, ipst);
16244 
16245 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16246 
16247 	if (mp == NULL)
16248 		return;
16249 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16250 
16251 	if (is_system_labeled()) {
16252 		mblk_t *mp1;
16253 
16254 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16255 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16256 			goto drop_pkt;
16257 		}
16258 		/* Size may have changed */
16259 		mp = mp1;
16260 		ipha = (ipha_t *)mp->b_rptr;
16261 		pkt_len = ntohs(ipha->ipha_length);
16262 	}
16263 
16264 	/* Check if there are options to update */
16265 	if (!IS_SIMPLE_IPH(ipha)) {
16266 		if (ip_csum_hdr(ipha)) {
16267 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16268 			goto drop_pkt;
16269 		}
16270 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16271 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16272 			return;
16273 		}
16274 
16275 		ipha->ipha_hdr_checksum = 0;
16276 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16277 	}
16278 	max_frag = ire->ire_max_frag;
16279 	if (pkt_len > max_frag) {
16280 		/*
16281 		 * It needs fragging on its way out.  We haven't
16282 		 * verified the header checksum yet.  Since we
16283 		 * are going to put a surely good checksum in the
16284 		 * outgoing header, we have to make sure that it
16285 		 * was good coming in.
16286 		 */
16287 		if (ip_csum_hdr(ipha)) {
16288 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16289 			goto drop_pkt;
16290 		}
16291 		/* Initiate Write side IPPF processing */
16292 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16293 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16294 			if (mp == NULL) {
16295 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16296 				    " during IPPF processing\n"));
16297 				return;
16298 			}
16299 		}
16300 		/*
16301 		 * Handle labeled packet resizing.
16302 		 *
16303 		 * If we have added a label, inform ip_wput_frag() of its
16304 		 * effect on the MTU for ICMP messages.
16305 		 */
16306 		if (pkt_len > old_pkt_len) {
16307 			uint32_t secopt_size;
16308 
16309 			secopt_size = pkt_len - old_pkt_len;
16310 			if (secopt_size < max_frag)
16311 				max_frag -= secopt_size;
16312 		}
16313 
16314 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16315 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16316 		return;
16317 	}
16318 
16319 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16320 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16321 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16322 	    ipst->ips_ipv4firewall_physical_out,
16323 	    NULL, out_ill, ipha, mp, mp, ipst);
16324 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16325 	if (mp == NULL)
16326 		return;
16327 
16328 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16329 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16330 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16331 	/* ip_xmit_v4 always consumes the packet */
16332 	return;
16333 
16334 drop_pkt:;
16335 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16336 	freemsg(mp);
16337 #undef	rptr
16338 }
16339 
16340 void
16341 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16342 {
16343 	ire_t	*ire;
16344 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16345 
16346 	ASSERT(!ipif->ipif_isv6);
16347 	/*
16348 	 * Find an IRE which matches the destination and the outgoing
16349 	 * queue in the cache table. All we need is an IRE_CACHE which
16350 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16351 	 * then it is enough to have some IRE_CACHE in the group.
16352 	 */
16353 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16354 		dst = ipif->ipif_pp_dst_addr;
16355 
16356 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16357 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16358 	if (ire == NULL) {
16359 		/*
16360 		 * Mark this packet to make it be delivered to
16361 		 * ip_rput_forward after the new ire has been
16362 		 * created.
16363 		 */
16364 		mp->b_prev = NULL;
16365 		mp->b_next = mp;
16366 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16367 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16368 	} else {
16369 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16370 		IRE_REFRELE(ire);
16371 	}
16372 }
16373 
16374 /* Update any source route, record route or timestamp options */
16375 static int
16376 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16377 {
16378 	ipoptp_t	opts;
16379 	uchar_t		*opt;
16380 	uint8_t		optval;
16381 	uint8_t		optlen;
16382 	ipaddr_t	dst;
16383 	uint32_t	ts;
16384 	ire_t		*dst_ire = NULL;
16385 	ire_t		*tmp_ire = NULL;
16386 	timestruc_t	now;
16387 
16388 	ip2dbg(("ip_rput_forward_options\n"));
16389 	dst = ipha->ipha_dst;
16390 	for (optval = ipoptp_first(&opts, ipha);
16391 	    optval != IPOPT_EOL;
16392 	    optval = ipoptp_next(&opts)) {
16393 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16394 		opt = opts.ipoptp_cur;
16395 		optlen = opts.ipoptp_len;
16396 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16397 		    optval, opts.ipoptp_len));
16398 		switch (optval) {
16399 			uint32_t off;
16400 		case IPOPT_SSRR:
16401 		case IPOPT_LSRR:
16402 			/* Check if adminstratively disabled */
16403 			if (!ipst->ips_ip_forward_src_routed) {
16404 				if (ire->ire_stq != NULL) {
16405 					/*
16406 					 * Sent by forwarding path, and router
16407 					 * is global zone
16408 					 */
16409 					icmp_unreachable(ire->ire_stq, mp,
16410 					    ICMP_SOURCE_ROUTE_FAILED,
16411 					    GLOBAL_ZONEID, ipst);
16412 				} else {
16413 					ip0dbg(("ip_rput_forward_options: "
16414 					    "unable to send unreach\n"));
16415 					freemsg(mp);
16416 				}
16417 				return (-1);
16418 			}
16419 
16420 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16421 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16422 			if (dst_ire == NULL) {
16423 				/*
16424 				 * Must be partial since ip_rput_options
16425 				 * checked for strict.
16426 				 */
16427 				break;
16428 			}
16429 			off = opt[IPOPT_OFFSET];
16430 			off--;
16431 		redo_srr:
16432 			if (optlen < IP_ADDR_LEN ||
16433 			    off > optlen - IP_ADDR_LEN) {
16434 				/* End of source route */
16435 				ip1dbg((
16436 				    "ip_rput_forward_options: end of SR\n"));
16437 				ire_refrele(dst_ire);
16438 				break;
16439 			}
16440 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16441 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16442 			    IP_ADDR_LEN);
16443 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16444 			    ntohl(dst)));
16445 
16446 			/*
16447 			 * Check if our address is present more than
16448 			 * once as consecutive hops in source route.
16449 			 */
16450 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16451 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16452 			if (tmp_ire != NULL) {
16453 				ire_refrele(tmp_ire);
16454 				off += IP_ADDR_LEN;
16455 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16456 				goto redo_srr;
16457 			}
16458 			ipha->ipha_dst = dst;
16459 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16460 			ire_refrele(dst_ire);
16461 			break;
16462 		case IPOPT_RR:
16463 			off = opt[IPOPT_OFFSET];
16464 			off--;
16465 			if (optlen < IP_ADDR_LEN ||
16466 			    off > optlen - IP_ADDR_LEN) {
16467 				/* No more room - ignore */
16468 				ip1dbg((
16469 				    "ip_rput_forward_options: end of RR\n"));
16470 				break;
16471 			}
16472 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16473 			    IP_ADDR_LEN);
16474 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16475 			break;
16476 		case IPOPT_TS:
16477 			/* Insert timestamp if there is room */
16478 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16479 			case IPOPT_TS_TSONLY:
16480 				off = IPOPT_TS_TIMELEN;
16481 				break;
16482 			case IPOPT_TS_PRESPEC:
16483 			case IPOPT_TS_PRESPEC_RFC791:
16484 				/* Verify that the address matched */
16485 				off = opt[IPOPT_OFFSET] - 1;
16486 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16487 				dst_ire = ire_ctable_lookup(dst, 0,
16488 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16489 				    MATCH_IRE_TYPE, ipst);
16490 				if (dst_ire == NULL) {
16491 					/* Not for us */
16492 					break;
16493 				}
16494 				ire_refrele(dst_ire);
16495 				/* FALLTHRU */
16496 			case IPOPT_TS_TSANDADDR:
16497 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16498 				break;
16499 			default:
16500 				/*
16501 				 * ip_*put_options should have already
16502 				 * dropped this packet.
16503 				 */
16504 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16505 				    "unknown IT - bug in ip_rput_options?\n");
16506 				return (0);	/* Keep "lint" happy */
16507 			}
16508 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16509 				/* Increase overflow counter */
16510 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16511 				opt[IPOPT_POS_OV_FLG] =
16512 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16513 				    (off << 4));
16514 				break;
16515 			}
16516 			off = opt[IPOPT_OFFSET] - 1;
16517 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16518 			case IPOPT_TS_PRESPEC:
16519 			case IPOPT_TS_PRESPEC_RFC791:
16520 			case IPOPT_TS_TSANDADDR:
16521 				bcopy(&ire->ire_src_addr,
16522 				    (char *)opt + off, IP_ADDR_LEN);
16523 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16524 				/* FALLTHRU */
16525 			case IPOPT_TS_TSONLY:
16526 				off = opt[IPOPT_OFFSET] - 1;
16527 				/* Compute # of milliseconds since midnight */
16528 				gethrestime(&now);
16529 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16530 				    now.tv_nsec / (NANOSEC / MILLISEC);
16531 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16532 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16533 				break;
16534 			}
16535 			break;
16536 		}
16537 	}
16538 	return (0);
16539 }
16540 
16541 /*
16542  * This is called after processing at least one of AH/ESP headers.
16543  *
16544  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16545  * the actual, physical interface on which the packet was received,
16546  * but, when ip_strict_dst_multihoming is set to 1, could be the
16547  * interface which had the ipha_dst configured when the packet went
16548  * through ip_rput. The ill_index corresponding to the recv_ill
16549  * is saved in ipsec_in_rill_index
16550  *
16551  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16552  * cannot assume "ire" points to valid data for any IPv6 cases.
16553  */
16554 void
16555 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16556 {
16557 	mblk_t *mp;
16558 	ipaddr_t dst;
16559 	in6_addr_t *v6dstp;
16560 	ipha_t *ipha;
16561 	ip6_t *ip6h;
16562 	ipsec_in_t *ii;
16563 	boolean_t ill_need_rele = B_FALSE;
16564 	boolean_t rill_need_rele = B_FALSE;
16565 	boolean_t ire_need_rele = B_FALSE;
16566 	netstack_t	*ns;
16567 	ip_stack_t	*ipst;
16568 
16569 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16570 	ASSERT(ii->ipsec_in_ill_index != 0);
16571 	ns = ii->ipsec_in_ns;
16572 	ASSERT(ii->ipsec_in_ns != NULL);
16573 	ipst = ns->netstack_ip;
16574 
16575 	mp = ipsec_mp->b_cont;
16576 	ASSERT(mp != NULL);
16577 
16578 
16579 	if (ill == NULL) {
16580 		ASSERT(recv_ill == NULL);
16581 		/*
16582 		 * We need to get the original queue on which ip_rput_local
16583 		 * or ip_rput_data_v6 was called.
16584 		 */
16585 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16586 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16587 		ill_need_rele = B_TRUE;
16588 
16589 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16590 			recv_ill = ill_lookup_on_ifindex(
16591 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16592 			    NULL, NULL, NULL, NULL, ipst);
16593 			rill_need_rele = B_TRUE;
16594 		} else {
16595 			recv_ill = ill;
16596 		}
16597 
16598 		if ((ill == NULL) || (recv_ill == NULL)) {
16599 			ip0dbg(("ip_fanout_proto_again: interface "
16600 			    "disappeared\n"));
16601 			if (ill != NULL)
16602 				ill_refrele(ill);
16603 			if (recv_ill != NULL)
16604 				ill_refrele(recv_ill);
16605 			freemsg(ipsec_mp);
16606 			return;
16607 		}
16608 	}
16609 
16610 	ASSERT(ill != NULL && recv_ill != NULL);
16611 
16612 	if (mp->b_datap->db_type == M_CTL) {
16613 		/*
16614 		 * AH/ESP is returning the ICMP message after
16615 		 * removing their headers. Fanout again till
16616 		 * it gets to the right protocol.
16617 		 */
16618 		if (ii->ipsec_in_v4) {
16619 			icmph_t *icmph;
16620 			int iph_hdr_length;
16621 			int hdr_length;
16622 
16623 			ipha = (ipha_t *)mp->b_rptr;
16624 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16625 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16626 			ipha = (ipha_t *)&icmph[1];
16627 			hdr_length = IPH_HDR_LENGTH(ipha);
16628 			/*
16629 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16630 			 * Reset the type to M_DATA.
16631 			 */
16632 			mp->b_datap->db_type = M_DATA;
16633 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16634 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16635 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16636 		} else {
16637 			icmp6_t *icmp6;
16638 			int hdr_length;
16639 
16640 			ip6h = (ip6_t *)mp->b_rptr;
16641 			/* Don't call hdr_length_v6() unless you have to. */
16642 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16643 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16644 			else
16645 				hdr_length = IPV6_HDR_LEN;
16646 
16647 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16648 			/*
16649 			 * icmp_inbound_error_fanout_v6 may need to do
16650 			 * pullupmsg.  Reset the type to M_DATA.
16651 			 */
16652 			mp->b_datap->db_type = M_DATA;
16653 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16654 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16655 		}
16656 		if (ill_need_rele)
16657 			ill_refrele(ill);
16658 		if (rill_need_rele)
16659 			ill_refrele(recv_ill);
16660 		return;
16661 	}
16662 
16663 	if (ii->ipsec_in_v4) {
16664 		ipha = (ipha_t *)mp->b_rptr;
16665 		dst = ipha->ipha_dst;
16666 		if (CLASSD(dst)) {
16667 			/*
16668 			 * Multicast has to be delivered to all streams.
16669 			 */
16670 			dst = INADDR_BROADCAST;
16671 		}
16672 
16673 		if (ire == NULL) {
16674 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16675 			    MBLK_GETLABEL(mp), ipst);
16676 			if (ire == NULL) {
16677 				if (ill_need_rele)
16678 					ill_refrele(ill);
16679 				if (rill_need_rele)
16680 					ill_refrele(recv_ill);
16681 				ip1dbg(("ip_fanout_proto_again: "
16682 				    "IRE not found"));
16683 				freemsg(ipsec_mp);
16684 				return;
16685 			}
16686 			ire_need_rele = B_TRUE;
16687 		}
16688 
16689 		switch (ipha->ipha_protocol) {
16690 			case IPPROTO_UDP:
16691 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16692 				    recv_ill);
16693 				if (ire_need_rele)
16694 					ire_refrele(ire);
16695 				break;
16696 			case IPPROTO_TCP:
16697 				if (!ire_need_rele)
16698 					IRE_REFHOLD(ire);
16699 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16700 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16701 				IRE_REFRELE(ire);
16702 				if (mp != NULL)
16703 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16704 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16705 				break;
16706 			case IPPROTO_SCTP:
16707 				if (!ire_need_rele)
16708 					IRE_REFHOLD(ire);
16709 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16710 				    ipsec_mp, 0, ill->ill_rq, dst);
16711 				break;
16712 			default:
16713 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16714 				    recv_ill);
16715 				if (ire_need_rele)
16716 					ire_refrele(ire);
16717 				break;
16718 		}
16719 	} else {
16720 		uint32_t rput_flags = 0;
16721 
16722 		ip6h = (ip6_t *)mp->b_rptr;
16723 		v6dstp = &ip6h->ip6_dst;
16724 		/*
16725 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16726 		 * address.
16727 		 *
16728 		 * Currently, we don't store that state in the IPSEC_IN
16729 		 * message, and we may need to.
16730 		 */
16731 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16732 		    IP6_IN_LLMCAST : 0);
16733 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16734 		    NULL, NULL);
16735 	}
16736 	if (ill_need_rele)
16737 		ill_refrele(ill);
16738 	if (rill_need_rele)
16739 		ill_refrele(recv_ill);
16740 }
16741 
16742 /*
16743  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16744  * returns 'true' if there are still fragments left on the queue, in
16745  * which case we restart the timer.
16746  */
16747 void
16748 ill_frag_timer(void *arg)
16749 {
16750 	ill_t	*ill = (ill_t *)arg;
16751 	boolean_t frag_pending;
16752 	ip_stack_t	*ipst = ill->ill_ipst;
16753 
16754 	mutex_enter(&ill->ill_lock);
16755 	ASSERT(!ill->ill_fragtimer_executing);
16756 	if (ill->ill_state_flags & ILL_CONDEMNED) {
16757 		ill->ill_frag_timer_id = 0;
16758 		mutex_exit(&ill->ill_lock);
16759 		return;
16760 	}
16761 	ill->ill_fragtimer_executing = 1;
16762 	mutex_exit(&ill->ill_lock);
16763 
16764 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
16765 
16766 	/*
16767 	 * Restart the timer, if we have fragments pending or if someone
16768 	 * wanted us to be scheduled again.
16769 	 */
16770 	mutex_enter(&ill->ill_lock);
16771 	ill->ill_fragtimer_executing = 0;
16772 	ill->ill_frag_timer_id = 0;
16773 	if (frag_pending || ill->ill_fragtimer_needrestart)
16774 		ill_frag_timer_start(ill);
16775 	mutex_exit(&ill->ill_lock);
16776 }
16777 
16778 void
16779 ill_frag_timer_start(ill_t *ill)
16780 {
16781 	ip_stack_t	*ipst = ill->ill_ipst;
16782 
16783 	ASSERT(MUTEX_HELD(&ill->ill_lock));
16784 
16785 	/* If the ill is closing or opening don't proceed */
16786 	if (ill->ill_state_flags & ILL_CONDEMNED)
16787 		return;
16788 
16789 	if (ill->ill_fragtimer_executing) {
16790 		/*
16791 		 * ill_frag_timer is currently executing. Just record the
16792 		 * the fact that we want the timer to be restarted.
16793 		 * ill_frag_timer will post a timeout before it returns,
16794 		 * ensuring it will be called again.
16795 		 */
16796 		ill->ill_fragtimer_needrestart = 1;
16797 		return;
16798 	}
16799 
16800 	if (ill->ill_frag_timer_id == 0) {
16801 		/*
16802 		 * The timer is neither running nor is the timeout handler
16803 		 * executing. Post a timeout so that ill_frag_timer will be
16804 		 * called
16805 		 */
16806 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
16807 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
16808 		ill->ill_fragtimer_needrestart = 0;
16809 	}
16810 }
16811 
16812 /*
16813  * This routine is needed for loopback when forwarding multicasts.
16814  *
16815  * IPQoS Notes:
16816  * IPPF processing is done in fanout routines.
16817  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
16818  * processing for IPSec packets is done when it comes back in clear.
16819  * NOTE : The callers of this function need to do the ire_refrele for the
16820  *	  ire that is being passed in.
16821  */
16822 void
16823 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
16824     ill_t *recv_ill)
16825 {
16826 	ill_t	*ill = (ill_t *)q->q_ptr;
16827 	uint32_t	sum;
16828 	uint32_t	u1;
16829 	uint32_t	u2;
16830 	int		hdr_length;
16831 	boolean_t	mctl_present;
16832 	mblk_t		*first_mp = mp;
16833 	mblk_t		*hada_mp = NULL;
16834 	ipha_t		*inner_ipha;
16835 	ip_stack_t	*ipst;
16836 
16837 	ASSERT(recv_ill != NULL);
16838 	ipst = recv_ill->ill_ipst;
16839 
16840 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
16841 	    "ip_rput_locl_start: q %p", q);
16842 
16843 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
16844 	ASSERT(ill != NULL);
16845 
16846 
16847 #define	rptr	((uchar_t *)ipha)
16848 #define	iphs	((uint16_t *)ipha)
16849 
16850 	/*
16851 	 * no UDP or TCP packet should come here anymore.
16852 	 */
16853 	ASSERT((ipha->ipha_protocol != IPPROTO_TCP) &&
16854 	    (ipha->ipha_protocol != IPPROTO_UDP));
16855 
16856 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
16857 	if (mctl_present &&
16858 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
16859 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
16860 
16861 		/*
16862 		 * It's an IPsec accelerated packet.
16863 		 * Keep a pointer to the data attributes around until
16864 		 * we allocate the ipsec_info_t.
16865 		 */
16866 		IPSECHW_DEBUG(IPSECHW_PKT,
16867 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
16868 		hada_mp = first_mp;
16869 		hada_mp->b_cont = NULL;
16870 		/*
16871 		 * Since it is accelerated, it comes directly from
16872 		 * the ill and the data attributes is followed by
16873 		 * the packet data.
16874 		 */
16875 		ASSERT(mp->b_datap->db_type != M_CTL);
16876 		first_mp = mp;
16877 		mctl_present = B_FALSE;
16878 	}
16879 
16880 	/*
16881 	 * IF M_CTL is not present, then ipsec_in_is_secure
16882 	 * should return B_TRUE. There is a case where loopback
16883 	 * packets has an M_CTL in the front with all the
16884 	 * IPSEC options set to IPSEC_PREF_NEVER - which means
16885 	 * ipsec_in_is_secure will return B_FALSE. As loopback
16886 	 * packets never comes here, it is safe to ASSERT the
16887 	 * following.
16888 	 */
16889 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
16890 
16891 
16892 	/* u1 is # words of IP options */
16893 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
16894 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
16895 
16896 	if (u1) {
16897 		if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
16898 			if (hada_mp != NULL)
16899 				freemsg(hada_mp);
16900 			return;
16901 		}
16902 	} else {
16903 		/* Check the IP header checksum.  */
16904 #define	uph	((uint16_t *)ipha)
16905 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
16906 		    uph[6] + uph[7] + uph[8] + uph[9];
16907 #undef  uph
16908 		/* finish doing IP checksum */
16909 		sum = (sum & 0xFFFF) + (sum >> 16);
16910 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
16911 		/*
16912 		 * Don't verify header checksum if this packet is coming
16913 		 * back from AH/ESP as we already did it.
16914 		 */
16915 		if (!mctl_present && (sum && sum != 0xFFFF)) {
16916 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
16917 			goto drop_pkt;
16918 		}
16919 	}
16920 
16921 	/*
16922 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
16923 	 * might be called more than once for secure packets, count only
16924 	 * the first time.
16925 	 */
16926 	if (!mctl_present) {
16927 		UPDATE_IB_PKT_COUNT(ire);
16928 		ire->ire_last_used_time = lbolt;
16929 	}
16930 
16931 	/* Check for fragmentation offset. */
16932 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
16933 	u1 = u2 & (IPH_MF | IPH_OFFSET);
16934 	if (u1) {
16935 		/*
16936 		 * We re-assemble fragments before we do the AH/ESP
16937 		 * processing. Thus, M_CTL should not be present
16938 		 * while we are re-assembling.
16939 		 */
16940 		ASSERT(!mctl_present);
16941 		ASSERT(first_mp == mp);
16942 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
16943 			return;
16944 		}
16945 		/*
16946 		 * Make sure that first_mp points back to mp as
16947 		 * the mp we came in with could have changed in
16948 		 * ip_rput_fragment().
16949 		 */
16950 		ipha = (ipha_t *)mp->b_rptr;
16951 		first_mp = mp;
16952 	}
16953 
16954 	/*
16955 	 * Clear hardware checksumming flag as it is currently only
16956 	 * used by TCP and UDP.
16957 	 */
16958 	DB_CKSUMFLAGS(mp) = 0;
16959 
16960 	/* Now we have a complete datagram, destined for this machine. */
16961 	u1 = IPH_HDR_LENGTH(ipha);
16962 	switch (ipha->ipha_protocol) {
16963 	case IPPROTO_ICMP: {
16964 		ire_t		*ire_zone;
16965 		ilm_t		*ilm;
16966 		mblk_t		*mp1;
16967 		zoneid_t	last_zoneid;
16968 
16969 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
16970 			ASSERT(ire->ire_type == IRE_BROADCAST);
16971 			/*
16972 			 * In the multicast case, applications may have joined
16973 			 * the group from different zones, so we need to deliver
16974 			 * the packet to each of them. Loop through the
16975 			 * multicast memberships structures (ilm) on the receive
16976 			 * ill and send a copy of the packet up each matching
16977 			 * one. However, we don't do this for multicasts sent on
16978 			 * the loopback interface (PHYI_LOOPBACK flag set) as
16979 			 * they must stay in the sender's zone.
16980 			 *
16981 			 * ilm_add_v6() ensures that ilms in the same zone are
16982 			 * contiguous in the ill_ilm list. We use this property
16983 			 * to avoid sending duplicates needed when two
16984 			 * applications in the same zone join the same group on
16985 			 * different logical interfaces: we ignore the ilm if
16986 			 * its zoneid is the same as the last matching one.
16987 			 * In addition, the sending of the packet for
16988 			 * ire_zoneid is delayed until all of the other ilms
16989 			 * have been exhausted.
16990 			 */
16991 			last_zoneid = -1;
16992 			ILM_WALKER_HOLD(recv_ill);
16993 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
16994 			    ilm = ilm->ilm_next) {
16995 				if ((ilm->ilm_flags & ILM_DELETED) ||
16996 				    ipha->ipha_dst != ilm->ilm_addr ||
16997 				    ilm->ilm_zoneid == last_zoneid ||
16998 				    ilm->ilm_zoneid == ire->ire_zoneid ||
16999 				    ilm->ilm_zoneid == ALL_ZONES ||
17000 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17001 					continue;
17002 				mp1 = ip_copymsg(first_mp);
17003 				if (mp1 == NULL)
17004 					continue;
17005 				icmp_inbound(q, mp1, B_TRUE, ill,
17006 				    0, sum, mctl_present, B_TRUE,
17007 				    recv_ill, ilm->ilm_zoneid);
17008 				last_zoneid = ilm->ilm_zoneid;
17009 			}
17010 			ILM_WALKER_RELE(recv_ill);
17011 		} else if (ire->ire_type == IRE_BROADCAST) {
17012 			/*
17013 			 * In the broadcast case, there may be many zones
17014 			 * which need a copy of the packet delivered to them.
17015 			 * There is one IRE_BROADCAST per broadcast address
17016 			 * and per zone; we walk those using a helper function.
17017 			 * In addition, the sending of the packet for ire is
17018 			 * delayed until all of the other ires have been
17019 			 * processed.
17020 			 */
17021 			IRB_REFHOLD(ire->ire_bucket);
17022 			ire_zone = NULL;
17023 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17024 			    ire)) != NULL) {
17025 				mp1 = ip_copymsg(first_mp);
17026 				if (mp1 == NULL)
17027 					continue;
17028 
17029 				UPDATE_IB_PKT_COUNT(ire_zone);
17030 				ire_zone->ire_last_used_time = lbolt;
17031 				icmp_inbound(q, mp1, B_TRUE, ill,
17032 				    0, sum, mctl_present, B_TRUE,
17033 				    recv_ill, ire_zone->ire_zoneid);
17034 			}
17035 			IRB_REFRELE(ire->ire_bucket);
17036 		}
17037 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17038 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17039 		    ire->ire_zoneid);
17040 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17041 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17042 		return;
17043 	}
17044 	case IPPROTO_IGMP:
17045 		/*
17046 		 * If we are not willing to accept IGMP packets in clear,
17047 		 * then check with global policy.
17048 		 */
17049 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17050 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17051 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17052 			if (first_mp == NULL)
17053 				return;
17054 		}
17055 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17056 			freemsg(first_mp);
17057 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17058 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17059 			return;
17060 		}
17061 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17062 			/* Bad packet - discarded by igmp_input */
17063 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17064 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17065 			if (mctl_present)
17066 				freeb(first_mp);
17067 			return;
17068 		}
17069 		/*
17070 		 * igmp_input() may have returned the pulled up message.
17071 		 * So first_mp and ipha need to be reinitialized.
17072 		 */
17073 		ipha = (ipha_t *)mp->b_rptr;
17074 		if (mctl_present)
17075 			first_mp->b_cont = mp;
17076 		else
17077 			first_mp = mp;
17078 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17079 		    connf_head != NULL) {
17080 			/* No user-level listener for IGMP packets */
17081 			goto drop_pkt;
17082 		}
17083 		/* deliver to local raw users */
17084 		break;
17085 	case IPPROTO_PIM:
17086 		/*
17087 		 * If we are not willing to accept PIM packets in clear,
17088 		 * then check with global policy.
17089 		 */
17090 		if (ipst->ips_pim_accept_clear_messages == 0) {
17091 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17092 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17093 			if (first_mp == NULL)
17094 				return;
17095 		}
17096 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17097 			freemsg(first_mp);
17098 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17099 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17100 			return;
17101 		}
17102 		if (pim_input(q, mp, ill) != 0) {
17103 			/* Bad packet - discarded by pim_input */
17104 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17105 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17106 			if (mctl_present)
17107 				freeb(first_mp);
17108 			return;
17109 		}
17110 
17111 		/*
17112 		 * pim_input() may have pulled up the message so ipha needs to
17113 		 * be reinitialized.
17114 		 */
17115 		ipha = (ipha_t *)mp->b_rptr;
17116 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17117 		    connf_head != NULL) {
17118 			/* No user-level listener for PIM packets */
17119 			goto drop_pkt;
17120 		}
17121 		/* deliver to local raw users */
17122 		break;
17123 	case IPPROTO_ENCAP:
17124 		/*
17125 		 * Handle self-encapsulated packets (IP-in-IP where
17126 		 * the inner addresses == the outer addresses).
17127 		 */
17128 		hdr_length = IPH_HDR_LENGTH(ipha);
17129 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17130 		    mp->b_wptr) {
17131 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17132 			    sizeof (ipha_t) - mp->b_rptr)) {
17133 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17134 				freemsg(first_mp);
17135 				return;
17136 			}
17137 			ipha = (ipha_t *)mp->b_rptr;
17138 		}
17139 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17140 		/*
17141 		 * Check the sanity of the inner IP header.
17142 		 */
17143 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17145 			freemsg(first_mp);
17146 			return;
17147 		}
17148 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17149 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17150 			freemsg(first_mp);
17151 			return;
17152 		}
17153 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17154 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17155 			ipsec_in_t *ii;
17156 
17157 			/*
17158 			 * Self-encapsulated tunnel packet. Remove
17159 			 * the outer IP header and fanout again.
17160 			 * We also need to make sure that the inner
17161 			 * header is pulled up until options.
17162 			 */
17163 			mp->b_rptr = (uchar_t *)inner_ipha;
17164 			ipha = inner_ipha;
17165 			hdr_length = IPH_HDR_LENGTH(ipha);
17166 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17167 				if (!pullupmsg(mp, (uchar_t *)ipha +
17168 				    + hdr_length - mp->b_rptr)) {
17169 					freemsg(first_mp);
17170 					return;
17171 				}
17172 				ipha = (ipha_t *)mp->b_rptr;
17173 			}
17174 			if (!mctl_present) {
17175 				ASSERT(first_mp == mp);
17176 				/*
17177 				 * This means that somebody is sending
17178 				 * Self-encapsualted packets without AH/ESP.
17179 				 * If AH/ESP was present, we would have already
17180 				 * allocated the first_mp.
17181 				 */
17182 				first_mp = ipsec_in_alloc(B_TRUE,
17183 				    ipst->ips_netstack);
17184 				if (first_mp == NULL) {
17185 					ip1dbg(("ip_proto_input: IPSEC_IN "
17186 					    "allocation failure.\n"));
17187 					BUMP_MIB(ill->ill_ip_mib,
17188 					    ipIfStatsInDiscards);
17189 					freemsg(mp);
17190 					return;
17191 				}
17192 				first_mp->b_cont = mp;
17193 			}
17194 			/*
17195 			 * We generally store the ill_index if we need to
17196 			 * do IPSEC processing as we lose the ill queue when
17197 			 * we come back. But in this case, we never should
17198 			 * have to store the ill_index here as it should have
17199 			 * been stored previously when we processed the
17200 			 * AH/ESP header in this routine or for non-ipsec
17201 			 * cases, we still have the queue. But for some bad
17202 			 * packets from the wire, we can get to IPSEC after
17203 			 * this and we better store the index for that case.
17204 			 */
17205 			ill = (ill_t *)q->q_ptr;
17206 			ii = (ipsec_in_t *)first_mp->b_rptr;
17207 			ii->ipsec_in_ill_index =
17208 			    ill->ill_phyint->phyint_ifindex;
17209 			ii->ipsec_in_rill_index =
17210 			    recv_ill->ill_phyint->phyint_ifindex;
17211 			if (ii->ipsec_in_decaps) {
17212 				/*
17213 				 * This packet is self-encapsulated multiple
17214 				 * times. We don't want to recurse infinitely.
17215 				 * To keep it simple, drop the packet.
17216 				 */
17217 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17218 				freemsg(first_mp);
17219 				return;
17220 			}
17221 			ii->ipsec_in_decaps = B_TRUE;
17222 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17223 			    ire);
17224 			return;
17225 		}
17226 		break;
17227 	case IPPROTO_AH:
17228 	case IPPROTO_ESP: {
17229 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17230 
17231 		/*
17232 		 * Fast path for AH/ESP. If this is the first time
17233 		 * we are sending a datagram to AH/ESP, allocate
17234 		 * a IPSEC_IN message and prepend it. Otherwise,
17235 		 * just fanout.
17236 		 */
17237 
17238 		int ipsec_rc;
17239 		ipsec_in_t *ii;
17240 		netstack_t *ns = ipst->ips_netstack;
17241 
17242 		IP_STAT(ipst, ipsec_proto_ahesp);
17243 		if (!mctl_present) {
17244 			ASSERT(first_mp == mp);
17245 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17246 			if (first_mp == NULL) {
17247 				ip1dbg(("ip_proto_input: IPSEC_IN "
17248 				    "allocation failure.\n"));
17249 				freemsg(hada_mp); /* okay ifnull */
17250 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17251 				freemsg(mp);
17252 				return;
17253 			}
17254 			/*
17255 			 * Store the ill_index so that when we come back
17256 			 * from IPSEC we ride on the same queue.
17257 			 */
17258 			ill = (ill_t *)q->q_ptr;
17259 			ii = (ipsec_in_t *)first_mp->b_rptr;
17260 			ii->ipsec_in_ill_index =
17261 			    ill->ill_phyint->phyint_ifindex;
17262 			ii->ipsec_in_rill_index =
17263 			    recv_ill->ill_phyint->phyint_ifindex;
17264 			first_mp->b_cont = mp;
17265 			/*
17266 			 * Cache hardware acceleration info.
17267 			 */
17268 			if (hada_mp != NULL) {
17269 				IPSECHW_DEBUG(IPSECHW_PKT,
17270 				    ("ip_rput_local: caching data attr.\n"));
17271 				ii->ipsec_in_accelerated = B_TRUE;
17272 				ii->ipsec_in_da = hada_mp;
17273 				hada_mp = NULL;
17274 			}
17275 		} else {
17276 			ii = (ipsec_in_t *)first_mp->b_rptr;
17277 		}
17278 
17279 		if (!ipsec_loaded(ipss)) {
17280 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17281 			    ire->ire_zoneid, ipst);
17282 			return;
17283 		}
17284 
17285 		ns = ipst->ips_netstack;
17286 		/* select inbound SA and have IPsec process the pkt */
17287 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17288 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17289 			if (esph == NULL)
17290 				return;
17291 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17292 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17293 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17294 			    first_mp, esph);
17295 		} else {
17296 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17297 			if (ah == NULL)
17298 				return;
17299 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17300 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17301 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17302 			    first_mp, ah);
17303 		}
17304 
17305 		switch (ipsec_rc) {
17306 		case IPSEC_STATUS_SUCCESS:
17307 			break;
17308 		case IPSEC_STATUS_FAILED:
17309 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17310 			/* FALLTHRU */
17311 		case IPSEC_STATUS_PENDING:
17312 			return;
17313 		}
17314 		/* we're done with IPsec processing, send it up */
17315 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17316 		return;
17317 	}
17318 	default:
17319 		break;
17320 	}
17321 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17322 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17323 		    ire->ire_zoneid));
17324 		goto drop_pkt;
17325 	}
17326 	/*
17327 	 * Handle protocols with which IP is less intimate.  There
17328 	 * can be more than one stream bound to a particular
17329 	 * protocol.  When this is the case, each one gets a copy
17330 	 * of any incoming packets.
17331 	 */
17332 	ip_fanout_proto(q, first_mp, ill, ipha,
17333 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17334 	    B_TRUE, recv_ill, ire->ire_zoneid);
17335 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17336 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17337 	return;
17338 
17339 drop_pkt:
17340 	freemsg(first_mp);
17341 	if (hada_mp != NULL)
17342 		freeb(hada_mp);
17343 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17344 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17345 #undef	rptr
17346 #undef  iphs
17347 
17348 }
17349 
17350 /*
17351  * Update any source route, record route or timestamp options.
17352  * Check that we are at end of strict source route.
17353  * The options have already been checked for sanity in ip_rput_options().
17354  */
17355 static boolean_t
17356 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17357     ip_stack_t *ipst)
17358 {
17359 	ipoptp_t	opts;
17360 	uchar_t		*opt;
17361 	uint8_t		optval;
17362 	uint8_t		optlen;
17363 	ipaddr_t	dst;
17364 	uint32_t	ts;
17365 	ire_t		*dst_ire;
17366 	timestruc_t	now;
17367 	zoneid_t	zoneid;
17368 	ill_t		*ill;
17369 
17370 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17371 
17372 	ip2dbg(("ip_rput_local_options\n"));
17373 
17374 	for (optval = ipoptp_first(&opts, ipha);
17375 	    optval != IPOPT_EOL;
17376 	    optval = ipoptp_next(&opts)) {
17377 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17378 		opt = opts.ipoptp_cur;
17379 		optlen = opts.ipoptp_len;
17380 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17381 		    optval, optlen));
17382 		switch (optval) {
17383 			uint32_t off;
17384 		case IPOPT_SSRR:
17385 		case IPOPT_LSRR:
17386 			off = opt[IPOPT_OFFSET];
17387 			off--;
17388 			if (optlen < IP_ADDR_LEN ||
17389 			    off > optlen - IP_ADDR_LEN) {
17390 				/* End of source route */
17391 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17392 				break;
17393 			}
17394 			/*
17395 			 * This will only happen if two consecutive entries
17396 			 * in the source route contains our address or if
17397 			 * it is a packet with a loose source route which
17398 			 * reaches us before consuming the whole source route
17399 			 */
17400 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17401 			if (optval == IPOPT_SSRR) {
17402 				goto bad_src_route;
17403 			}
17404 			/*
17405 			 * Hack: instead of dropping the packet truncate the
17406 			 * source route to what has been used by filling the
17407 			 * rest with IPOPT_NOP.
17408 			 */
17409 			opt[IPOPT_OLEN] = (uint8_t)off;
17410 			while (off < optlen) {
17411 				opt[off++] = IPOPT_NOP;
17412 			}
17413 			break;
17414 		case IPOPT_RR:
17415 			off = opt[IPOPT_OFFSET];
17416 			off--;
17417 			if (optlen < IP_ADDR_LEN ||
17418 			    off > optlen - IP_ADDR_LEN) {
17419 				/* No more room - ignore */
17420 				ip1dbg((
17421 				    "ip_rput_local_options: end of RR\n"));
17422 				break;
17423 			}
17424 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17425 			    IP_ADDR_LEN);
17426 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17427 			break;
17428 		case IPOPT_TS:
17429 			/* Insert timestamp if there is romm */
17430 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17431 			case IPOPT_TS_TSONLY:
17432 				off = IPOPT_TS_TIMELEN;
17433 				break;
17434 			case IPOPT_TS_PRESPEC:
17435 			case IPOPT_TS_PRESPEC_RFC791:
17436 				/* Verify that the address matched */
17437 				off = opt[IPOPT_OFFSET] - 1;
17438 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17439 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17440 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17441 				    ipst);
17442 				if (dst_ire == NULL) {
17443 					/* Not for us */
17444 					break;
17445 				}
17446 				ire_refrele(dst_ire);
17447 				/* FALLTHRU */
17448 			case IPOPT_TS_TSANDADDR:
17449 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17450 				break;
17451 			default:
17452 				/*
17453 				 * ip_*put_options should have already
17454 				 * dropped this packet.
17455 				 */
17456 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17457 				    "unknown IT - bug in ip_rput_options?\n");
17458 				return (B_TRUE);	/* Keep "lint" happy */
17459 			}
17460 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17461 				/* Increase overflow counter */
17462 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17463 				opt[IPOPT_POS_OV_FLG] =
17464 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17465 				    (off << 4));
17466 				break;
17467 			}
17468 			off = opt[IPOPT_OFFSET] - 1;
17469 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17470 			case IPOPT_TS_PRESPEC:
17471 			case IPOPT_TS_PRESPEC_RFC791:
17472 			case IPOPT_TS_TSANDADDR:
17473 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17474 				    IP_ADDR_LEN);
17475 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17476 				/* FALLTHRU */
17477 			case IPOPT_TS_TSONLY:
17478 				off = opt[IPOPT_OFFSET] - 1;
17479 				/* Compute # of milliseconds since midnight */
17480 				gethrestime(&now);
17481 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17482 				    now.tv_nsec / (NANOSEC / MILLISEC);
17483 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17484 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17485 				break;
17486 			}
17487 			break;
17488 		}
17489 	}
17490 	return (B_TRUE);
17491 
17492 bad_src_route:
17493 	q = WR(q);
17494 	if (q->q_next != NULL)
17495 		ill = q->q_ptr;
17496 	else
17497 		ill = NULL;
17498 
17499 	/* make sure we clear any indication of a hardware checksum */
17500 	DB_CKSUMFLAGS(mp) = 0;
17501 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17502 	if (zoneid == ALL_ZONES)
17503 		freemsg(mp);
17504 	else
17505 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17506 	return (B_FALSE);
17507 
17508 }
17509 
17510 /*
17511  * Process IP options in an inbound packet.  If an option affects the
17512  * effective destination address, return the next hop address via dstp.
17513  * Returns -1 if something fails in which case an ICMP error has been sent
17514  * and mp freed.
17515  */
17516 static int
17517 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17518     ip_stack_t *ipst)
17519 {
17520 	ipoptp_t	opts;
17521 	uchar_t		*opt;
17522 	uint8_t		optval;
17523 	uint8_t		optlen;
17524 	ipaddr_t	dst;
17525 	intptr_t	code = 0;
17526 	ire_t		*ire = NULL;
17527 	zoneid_t	zoneid;
17528 	ill_t		*ill;
17529 
17530 	ip2dbg(("ip_rput_options\n"));
17531 	dst = ipha->ipha_dst;
17532 	for (optval = ipoptp_first(&opts, ipha);
17533 	    optval != IPOPT_EOL;
17534 	    optval = ipoptp_next(&opts)) {
17535 		opt = opts.ipoptp_cur;
17536 		optlen = opts.ipoptp_len;
17537 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17538 		    optval, optlen));
17539 		/*
17540 		 * Note: we need to verify the checksum before we
17541 		 * modify anything thus this routine only extracts the next
17542 		 * hop dst from any source route.
17543 		 */
17544 		switch (optval) {
17545 			uint32_t off;
17546 		case IPOPT_SSRR:
17547 		case IPOPT_LSRR:
17548 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17549 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17550 			if (ire == NULL) {
17551 				if (optval == IPOPT_SSRR) {
17552 					ip1dbg(("ip_rput_options: not next"
17553 					    " strict source route 0x%x\n",
17554 					    ntohl(dst)));
17555 					code = (char *)&ipha->ipha_dst -
17556 					    (char *)ipha;
17557 					goto param_prob; /* RouterReq's */
17558 				}
17559 				ip2dbg(("ip_rput_options: "
17560 				    "not next source route 0x%x\n",
17561 				    ntohl(dst)));
17562 				break;
17563 			}
17564 			ire_refrele(ire);
17565 
17566 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17567 				ip1dbg((
17568 				    "ip_rput_options: bad option offset\n"));
17569 				code = (char *)&opt[IPOPT_OLEN] -
17570 				    (char *)ipha;
17571 				goto param_prob;
17572 			}
17573 			off = opt[IPOPT_OFFSET];
17574 			off--;
17575 		redo_srr:
17576 			if (optlen < IP_ADDR_LEN ||
17577 			    off > optlen - IP_ADDR_LEN) {
17578 				/* End of source route */
17579 				ip1dbg(("ip_rput_options: end of SR\n"));
17580 				break;
17581 			}
17582 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17583 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17584 			    ntohl(dst)));
17585 
17586 			/*
17587 			 * Check if our address is present more than
17588 			 * once as consecutive hops in source route.
17589 			 * XXX verify per-interface ip_forwarding
17590 			 * for source route?
17591 			 */
17592 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17593 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17594 
17595 			if (ire != NULL) {
17596 				ire_refrele(ire);
17597 				off += IP_ADDR_LEN;
17598 				goto redo_srr;
17599 			}
17600 
17601 			if (dst == htonl(INADDR_LOOPBACK)) {
17602 				ip1dbg(("ip_rput_options: loopback addr in "
17603 				    "source route!\n"));
17604 				goto bad_src_route;
17605 			}
17606 			/*
17607 			 * For strict: verify that dst is directly
17608 			 * reachable.
17609 			 */
17610 			if (optval == IPOPT_SSRR) {
17611 				ire = ire_ftable_lookup(dst, 0, 0,
17612 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17613 				    MBLK_GETLABEL(mp),
17614 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17615 				if (ire == NULL) {
17616 					ip1dbg(("ip_rput_options: SSRR not "
17617 					    "directly reachable: 0x%x\n",
17618 					    ntohl(dst)));
17619 					goto bad_src_route;
17620 				}
17621 				ire_refrele(ire);
17622 			}
17623 			/*
17624 			 * Defer update of the offset and the record route
17625 			 * until the packet is forwarded.
17626 			 */
17627 			break;
17628 		case IPOPT_RR:
17629 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17630 				ip1dbg((
17631 				    "ip_rput_options: bad option offset\n"));
17632 				code = (char *)&opt[IPOPT_OLEN] -
17633 				    (char *)ipha;
17634 				goto param_prob;
17635 			}
17636 			break;
17637 		case IPOPT_TS:
17638 			/*
17639 			 * Verify that length >= 5 and that there is either
17640 			 * room for another timestamp or that the overflow
17641 			 * counter is not maxed out.
17642 			 */
17643 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17644 			if (optlen < IPOPT_MINLEN_IT) {
17645 				goto param_prob;
17646 			}
17647 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17648 				ip1dbg((
17649 				    "ip_rput_options: bad option offset\n"));
17650 				code = (char *)&opt[IPOPT_OFFSET] -
17651 				    (char *)ipha;
17652 				goto param_prob;
17653 			}
17654 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17655 			case IPOPT_TS_TSONLY:
17656 				off = IPOPT_TS_TIMELEN;
17657 				break;
17658 			case IPOPT_TS_TSANDADDR:
17659 			case IPOPT_TS_PRESPEC:
17660 			case IPOPT_TS_PRESPEC_RFC791:
17661 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17662 				break;
17663 			default:
17664 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17665 				    (char *)ipha;
17666 				goto param_prob;
17667 			}
17668 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17669 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17670 				/*
17671 				 * No room and the overflow counter is 15
17672 				 * already.
17673 				 */
17674 				goto param_prob;
17675 			}
17676 			break;
17677 		}
17678 	}
17679 
17680 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17681 		*dstp = dst;
17682 		return (0);
17683 	}
17684 
17685 	ip1dbg(("ip_rput_options: error processing IP options."));
17686 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17687 
17688 param_prob:
17689 	q = WR(q);
17690 	if (q->q_next != NULL)
17691 		ill = q->q_ptr;
17692 	else
17693 		ill = NULL;
17694 
17695 	/* make sure we clear any indication of a hardware checksum */
17696 	DB_CKSUMFLAGS(mp) = 0;
17697 	/* Don't know whether this is for non-global or global/forwarding */
17698 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17699 	if (zoneid == ALL_ZONES)
17700 		freemsg(mp);
17701 	else
17702 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17703 	return (-1);
17704 
17705 bad_src_route:
17706 	q = WR(q);
17707 	if (q->q_next != NULL)
17708 		ill = q->q_ptr;
17709 	else
17710 		ill = NULL;
17711 
17712 	/* make sure we clear any indication of a hardware checksum */
17713 	DB_CKSUMFLAGS(mp) = 0;
17714 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17715 	if (zoneid == ALL_ZONES)
17716 		freemsg(mp);
17717 	else
17718 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17719 	return (-1);
17720 }
17721 
17722 /*
17723  * IP & ICMP info in >=14 msg's ...
17724  *  - ip fixed part (mib2_ip_t)
17725  *  - icmp fixed part (mib2_icmp_t)
17726  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
17727  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
17728  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
17729  *  - ipRouteAttributeTable (ip 102)	labeled routes
17730  *  - ip multicast membership (ip_member_t)
17731  *  - ip multicast source filtering (ip_grpsrc_t)
17732  *  - igmp fixed part (struct igmpstat)
17733  *  - multicast routing stats (struct mrtstat)
17734  *  - multicast routing vifs (array of struct vifctl)
17735  *  - multicast routing routes (array of struct mfcctl)
17736  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
17737  *					One per ill plus one generic
17738  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
17739  *					One per ill plus one generic
17740  *  - ipv6RouteEntry			all IPv6 IREs
17741  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
17742  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
17743  *  - ipv6AddrEntry			all IPv6 ipifs
17744  *  - ipv6 multicast membership (ipv6_member_t)
17745  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
17746  *
17747  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
17748  *
17749  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
17750  * already filled in by the caller.
17751  * Return value of 0 indicates that no messages were sent and caller
17752  * should free mpctl.
17753  */
17754 int
17755 ip_snmp_get(queue_t *q, mblk_t *mpctl)
17756 {
17757 	ip_stack_t *ipst;
17758 	sctp_stack_t *sctps;
17759 
17760 
17761 	if (q->q_next != NULL) {
17762 		ipst = ILLQ_TO_IPST(q);
17763 	} else {
17764 		ipst = CONNQ_TO_IPST(q);
17765 	}
17766 	ASSERT(ipst != NULL);
17767 	sctps = ipst->ips_netstack->netstack_sctp;
17768 
17769 	if (mpctl == NULL || mpctl->b_cont == NULL) {
17770 		return (0);
17771 	}
17772 
17773 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
17774 	    ipst)) == NULL) {
17775 		return (1);
17776 	}
17777 
17778 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
17779 		return (1);
17780 	}
17781 
17782 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
17783 		return (1);
17784 	}
17785 
17786 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
17787 		return (1);
17788 	}
17789 
17790 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
17791 		return (1);
17792 	}
17793 
17794 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
17795 		return (1);
17796 	}
17797 
17798 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
17799 		return (1);
17800 	}
17801 
17802 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
17803 		return (1);
17804 	}
17805 
17806 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
17807 		return (1);
17808 	}
17809 
17810 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
17811 		return (1);
17812 	}
17813 
17814 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
17815 		return (1);
17816 	}
17817 
17818 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
17819 		return (1);
17820 	}
17821 
17822 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
17823 		return (1);
17824 	}
17825 
17826 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
17827 		return (1);
17828 	}
17829 
17830 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
17831 		return (1);
17832 	}
17833 
17834 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
17835 	if (mpctl == NULL) {
17836 		return (1);
17837 	}
17838 
17839 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
17840 		return (1);
17841 	}
17842 	freemsg(mpctl);
17843 	return (1);
17844 }
17845 
17846 
17847 /* Get global (legacy) IPv4 statistics */
17848 static mblk_t *
17849 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
17850     ip_stack_t *ipst)
17851 {
17852 	mib2_ip_t		old_ip_mib;
17853 	struct opthdr		*optp;
17854 	mblk_t			*mp2ctl;
17855 
17856 	/*
17857 	 * make a copy of the original message
17858 	 */
17859 	mp2ctl = copymsg(mpctl);
17860 
17861 	/* fixed length IP structure... */
17862 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17863 	optp->level = MIB2_IP;
17864 	optp->name = 0;
17865 	SET_MIB(old_ip_mib.ipForwarding,
17866 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
17867 	SET_MIB(old_ip_mib.ipDefaultTTL,
17868 	    (uint32_t)ipst->ips_ip_def_ttl);
17869 	SET_MIB(old_ip_mib.ipReasmTimeout,
17870 	    ipst->ips_ip_g_frag_timeout);
17871 	SET_MIB(old_ip_mib.ipAddrEntrySize,
17872 	    sizeof (mib2_ipAddrEntry_t));
17873 	SET_MIB(old_ip_mib.ipRouteEntrySize,
17874 	    sizeof (mib2_ipRouteEntry_t));
17875 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
17876 	    sizeof (mib2_ipNetToMediaEntry_t));
17877 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
17878 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
17879 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
17880 	    sizeof (mib2_ipAttributeEntry_t));
17881 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
17882 
17883 	/*
17884 	 * Grab the statistics from the new IP MIB
17885 	 */
17886 	SET_MIB(old_ip_mib.ipInReceives,
17887 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
17888 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
17889 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
17890 	SET_MIB(old_ip_mib.ipForwDatagrams,
17891 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
17892 	SET_MIB(old_ip_mib.ipInUnknownProtos,
17893 	    ipmib->ipIfStatsInUnknownProtos);
17894 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
17895 	SET_MIB(old_ip_mib.ipInDelivers,
17896 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
17897 	SET_MIB(old_ip_mib.ipOutRequests,
17898 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
17899 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
17900 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
17901 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
17902 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
17903 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
17904 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
17905 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
17906 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
17907 
17908 	/* ipRoutingDiscards is not being used */
17909 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
17910 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
17911 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
17912 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
17913 	SET_MIB(old_ip_mib.ipReasmDuplicates,
17914 	    ipmib->ipIfStatsReasmDuplicates);
17915 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
17916 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
17917 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
17918 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
17919 	SET_MIB(old_ip_mib.rawipInOverflows,
17920 	    ipmib->rawipIfStatsInOverflows);
17921 
17922 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
17923 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
17924 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
17925 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
17926 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
17927 	    ipmib->ipIfStatsOutSwitchIPVersion);
17928 
17929 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
17930 	    (int)sizeof (old_ip_mib))) {
17931 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
17932 		    (uint_t)sizeof (old_ip_mib)));
17933 	}
17934 
17935 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
17936 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
17937 	    (int)optp->level, (int)optp->name, (int)optp->len));
17938 	qreply(q, mpctl);
17939 	return (mp2ctl);
17940 }
17941 
17942 /* Per interface IPv4 statistics */
17943 static mblk_t *
17944 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
17945 {
17946 	struct opthdr		*optp;
17947 	mblk_t			*mp2ctl;
17948 	ill_t			*ill;
17949 	ill_walk_context_t	ctx;
17950 	mblk_t			*mp_tail = NULL;
17951 	mib2_ipIfStatsEntry_t	global_ip_mib;
17952 
17953 	/*
17954 	 * Make a copy of the original message
17955 	 */
17956 	mp2ctl = copymsg(mpctl);
17957 
17958 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
17959 	optp->level = MIB2_IP;
17960 	optp->name = MIB2_IP_TRAFFIC_STATS;
17961 	/* Include "unknown interface" ip_mib */
17962 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
17963 	ipst->ips_ip_mib.ipIfStatsIfIndex =
17964 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
17965 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
17966 	    (ipst->ips_ip_g_forward ? 1 : 2));
17967 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
17968 	    (uint32_t)ipst->ips_ip_def_ttl);
17969 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
17970 	    sizeof (mib2_ipIfStatsEntry_t));
17971 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
17972 	    sizeof (mib2_ipAddrEntry_t));
17973 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
17974 	    sizeof (mib2_ipRouteEntry_t));
17975 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
17976 	    sizeof (mib2_ipNetToMediaEntry_t));
17977 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
17978 	    sizeof (ip_member_t));
17979 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
17980 	    sizeof (ip_grpsrc_t));
17981 
17982 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
17983 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
17984 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
17985 		    "failed to allocate %u bytes\n",
17986 		    (uint_t)sizeof (ipst->ips_ip_mib)));
17987 	}
17988 
17989 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
17990 
17991 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
17992 	ill = ILL_START_WALK_V4(&ctx, ipst);
17993 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
17994 		ill->ill_ip_mib->ipIfStatsIfIndex =
17995 		    ill->ill_phyint->phyint_ifindex;
17996 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
17997 		    (ipst->ips_ip_g_forward ? 1 : 2));
17998 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
17999 		    (uint32_t)ipst->ips_ip_def_ttl);
18000 
18001 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18002 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18003 		    (char *)ill->ill_ip_mib,
18004 		    (int)sizeof (*ill->ill_ip_mib))) {
18005 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18006 			    "failed to allocate %u bytes\n",
18007 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18008 		}
18009 	}
18010 	rw_exit(&ipst->ips_ill_g_lock);
18011 
18012 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18013 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18014 	    "level %d, name %d, len %d\n",
18015 	    (int)optp->level, (int)optp->name, (int)optp->len));
18016 	qreply(q, mpctl);
18017 
18018 	if (mp2ctl == NULL)
18019 		return (NULL);
18020 
18021 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18022 }
18023 
18024 /* Global IPv4 ICMP statistics */
18025 static mblk_t *
18026 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18027 {
18028 	struct opthdr		*optp;
18029 	mblk_t			*mp2ctl;
18030 
18031 	/*
18032 	 * Make a copy of the original message
18033 	 */
18034 	mp2ctl = copymsg(mpctl);
18035 
18036 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18037 	optp->level = MIB2_ICMP;
18038 	optp->name = 0;
18039 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18040 	    (int)sizeof (ipst->ips_icmp_mib))) {
18041 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18042 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18043 	}
18044 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18045 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18046 	    (int)optp->level, (int)optp->name, (int)optp->len));
18047 	qreply(q, mpctl);
18048 	return (mp2ctl);
18049 }
18050 
18051 /* Global IPv4 IGMP statistics */
18052 static mblk_t *
18053 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18054 {
18055 	struct opthdr		*optp;
18056 	mblk_t			*mp2ctl;
18057 
18058 	/*
18059 	 * make a copy of the original message
18060 	 */
18061 	mp2ctl = copymsg(mpctl);
18062 
18063 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18064 	optp->level = EXPER_IGMP;
18065 	optp->name = 0;
18066 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18067 	    (int)sizeof (ipst->ips_igmpstat))) {
18068 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18069 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18070 	}
18071 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18072 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18073 	    (int)optp->level, (int)optp->name, (int)optp->len));
18074 	qreply(q, mpctl);
18075 	return (mp2ctl);
18076 }
18077 
18078 /* Global IPv4 Multicast Routing statistics */
18079 static mblk_t *
18080 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18081 {
18082 	struct opthdr		*optp;
18083 	mblk_t			*mp2ctl;
18084 
18085 	/*
18086 	 * make a copy of the original message
18087 	 */
18088 	mp2ctl = copymsg(mpctl);
18089 
18090 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18091 	optp->level = EXPER_DVMRP;
18092 	optp->name = 0;
18093 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18094 		ip0dbg(("ip_mroute_stats: failed\n"));
18095 	}
18096 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18097 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18098 	    (int)optp->level, (int)optp->name, (int)optp->len));
18099 	qreply(q, mpctl);
18100 	return (mp2ctl);
18101 }
18102 
18103 /* IPv4 address information */
18104 static mblk_t *
18105 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18106 {
18107 	struct opthdr		*optp;
18108 	mblk_t			*mp2ctl;
18109 	mblk_t			*mp_tail = NULL;
18110 	ill_t			*ill;
18111 	ipif_t			*ipif;
18112 	uint_t			bitval;
18113 	mib2_ipAddrEntry_t	mae;
18114 	zoneid_t		zoneid;
18115 	ill_walk_context_t ctx;
18116 
18117 	/*
18118 	 * make a copy of the original message
18119 	 */
18120 	mp2ctl = copymsg(mpctl);
18121 
18122 	/* ipAddrEntryTable */
18123 
18124 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18125 	optp->level = MIB2_IP;
18126 	optp->name = MIB2_IP_ADDR;
18127 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18128 
18129 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18130 	ill = ILL_START_WALK_V4(&ctx, ipst);
18131 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18132 		for (ipif = ill->ill_ipif; ipif != NULL;
18133 		    ipif = ipif->ipif_next) {
18134 			if (ipif->ipif_zoneid != zoneid &&
18135 			    ipif->ipif_zoneid != ALL_ZONES)
18136 				continue;
18137 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18138 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18139 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18140 
18141 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18142 			    OCTET_LENGTH);
18143 			mae.ipAdEntIfIndex.o_length =
18144 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18145 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18146 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18147 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18148 			mae.ipAdEntInfo.ae_subnet_len =
18149 			    ip_mask_to_plen(ipif->ipif_net_mask);
18150 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18151 			for (bitval = 1;
18152 			    bitval &&
18153 			    !(bitval & ipif->ipif_brd_addr);
18154 			    bitval <<= 1)
18155 				noop;
18156 			mae.ipAdEntBcastAddr = bitval;
18157 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18158 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18159 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18160 			mae.ipAdEntInfo.ae_broadcast_addr =
18161 			    ipif->ipif_brd_addr;
18162 			mae.ipAdEntInfo.ae_pp_dst_addr =
18163 			    ipif->ipif_pp_dst_addr;
18164 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18165 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18166 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18167 
18168 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18169 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18170 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18171 				    "allocate %u bytes\n",
18172 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18173 			}
18174 		}
18175 	}
18176 	rw_exit(&ipst->ips_ill_g_lock);
18177 
18178 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18179 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18180 	    (int)optp->level, (int)optp->name, (int)optp->len));
18181 	qreply(q, mpctl);
18182 	return (mp2ctl);
18183 }
18184 
18185 /* IPv6 address information */
18186 static mblk_t *
18187 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18188 {
18189 	struct opthdr		*optp;
18190 	mblk_t			*mp2ctl;
18191 	mblk_t			*mp_tail = NULL;
18192 	ill_t			*ill;
18193 	ipif_t			*ipif;
18194 	mib2_ipv6AddrEntry_t	mae6;
18195 	zoneid_t		zoneid;
18196 	ill_walk_context_t	ctx;
18197 
18198 	/*
18199 	 * make a copy of the original message
18200 	 */
18201 	mp2ctl = copymsg(mpctl);
18202 
18203 	/* ipv6AddrEntryTable */
18204 
18205 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18206 	optp->level = MIB2_IP6;
18207 	optp->name = MIB2_IP6_ADDR;
18208 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18209 
18210 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18211 	ill = ILL_START_WALK_V6(&ctx, ipst);
18212 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18213 		for (ipif = ill->ill_ipif; ipif != NULL;
18214 		    ipif = ipif->ipif_next) {
18215 			if (ipif->ipif_zoneid != zoneid &&
18216 			    ipif->ipif_zoneid != ALL_ZONES)
18217 				continue;
18218 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18219 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18220 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18221 
18222 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18223 			    OCTET_LENGTH);
18224 			mae6.ipv6AddrIfIndex.o_length =
18225 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18226 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18227 			mae6.ipv6AddrPfxLength =
18228 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18229 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18230 			mae6.ipv6AddrInfo.ae_subnet_len =
18231 			    mae6.ipv6AddrPfxLength;
18232 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18233 
18234 			/* Type: stateless(1), stateful(2), unknown(3) */
18235 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18236 				mae6.ipv6AddrType = 1;
18237 			else
18238 				mae6.ipv6AddrType = 2;
18239 			/* Anycast: true(1), false(2) */
18240 			if (ipif->ipif_flags & IPIF_ANYCAST)
18241 				mae6.ipv6AddrAnycastFlag = 1;
18242 			else
18243 				mae6.ipv6AddrAnycastFlag = 2;
18244 
18245 			/*
18246 			 * Address status: preferred(1), deprecated(2),
18247 			 * invalid(3), inaccessible(4), unknown(5)
18248 			 */
18249 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18250 				mae6.ipv6AddrStatus = 3;
18251 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18252 				mae6.ipv6AddrStatus = 2;
18253 			else
18254 				mae6.ipv6AddrStatus = 1;
18255 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18256 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18257 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18258 			    ipif->ipif_v6pp_dst_addr;
18259 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18260 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18261 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18262 			mae6.ipv6AddrIdentifier = ill->ill_token;
18263 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18264 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18265 			mae6.ipv6AddrRetransmitTime =
18266 			    ill->ill_reachable_retrans_time;
18267 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18268 			    (char *)&mae6,
18269 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18270 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18271 				    "allocate %u bytes\n",
18272 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18273 			}
18274 		}
18275 	}
18276 	rw_exit(&ipst->ips_ill_g_lock);
18277 
18278 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18279 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18280 	    (int)optp->level, (int)optp->name, (int)optp->len));
18281 	qreply(q, mpctl);
18282 	return (mp2ctl);
18283 }
18284 
18285 /* IPv4 multicast group membership. */
18286 static mblk_t *
18287 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18288 {
18289 	struct opthdr		*optp;
18290 	mblk_t			*mp2ctl;
18291 	ill_t			*ill;
18292 	ipif_t			*ipif;
18293 	ilm_t			*ilm;
18294 	ip_member_t		ipm;
18295 	mblk_t			*mp_tail = NULL;
18296 	ill_walk_context_t	ctx;
18297 	zoneid_t		zoneid;
18298 
18299 	/*
18300 	 * make a copy of the original message
18301 	 */
18302 	mp2ctl = copymsg(mpctl);
18303 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18304 
18305 	/* ipGroupMember table */
18306 	optp = (struct opthdr *)&mpctl->b_rptr[
18307 	    sizeof (struct T_optmgmt_ack)];
18308 	optp->level = MIB2_IP;
18309 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18310 
18311 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18312 	ill = ILL_START_WALK_V4(&ctx, ipst);
18313 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18314 		ILM_WALKER_HOLD(ill);
18315 		for (ipif = ill->ill_ipif; ipif != NULL;
18316 		    ipif = ipif->ipif_next) {
18317 			if (ipif->ipif_zoneid != zoneid &&
18318 			    ipif->ipif_zoneid != ALL_ZONES)
18319 				continue;	/* not this zone */
18320 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18321 			    OCTET_LENGTH);
18322 			ipm.ipGroupMemberIfIndex.o_length =
18323 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18324 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18325 				ASSERT(ilm->ilm_ipif != NULL);
18326 				ASSERT(ilm->ilm_ill == NULL);
18327 				if (ilm->ilm_ipif != ipif)
18328 					continue;
18329 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18330 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18331 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18332 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18333 				    (char *)&ipm, (int)sizeof (ipm))) {
18334 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18335 					    "failed to allocate %u bytes\n",
18336 					    (uint_t)sizeof (ipm)));
18337 				}
18338 			}
18339 		}
18340 		ILM_WALKER_RELE(ill);
18341 	}
18342 	rw_exit(&ipst->ips_ill_g_lock);
18343 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18344 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18345 	    (int)optp->level, (int)optp->name, (int)optp->len));
18346 	qreply(q, mpctl);
18347 	return (mp2ctl);
18348 }
18349 
18350 /* IPv6 multicast group membership. */
18351 static mblk_t *
18352 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18353 {
18354 	struct opthdr		*optp;
18355 	mblk_t			*mp2ctl;
18356 	ill_t			*ill;
18357 	ilm_t			*ilm;
18358 	ipv6_member_t		ipm6;
18359 	mblk_t			*mp_tail = NULL;
18360 	ill_walk_context_t	ctx;
18361 	zoneid_t		zoneid;
18362 
18363 	/*
18364 	 * make a copy of the original message
18365 	 */
18366 	mp2ctl = copymsg(mpctl);
18367 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18368 
18369 	/* ip6GroupMember table */
18370 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18371 	optp->level = MIB2_IP6;
18372 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18373 
18374 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18375 	ill = ILL_START_WALK_V6(&ctx, ipst);
18376 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18377 		ILM_WALKER_HOLD(ill);
18378 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18379 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18380 			ASSERT(ilm->ilm_ipif == NULL);
18381 			ASSERT(ilm->ilm_ill != NULL);
18382 			if (ilm->ilm_zoneid != zoneid)
18383 				continue;	/* not this zone */
18384 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18385 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18386 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18387 			if (!snmp_append_data2(mpctl->b_cont,
18388 			    &mp_tail,
18389 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18390 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18391 				    "failed to allocate %u bytes\n",
18392 				    (uint_t)sizeof (ipm6)));
18393 			}
18394 		}
18395 		ILM_WALKER_RELE(ill);
18396 	}
18397 	rw_exit(&ipst->ips_ill_g_lock);
18398 
18399 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18400 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18401 	    (int)optp->level, (int)optp->name, (int)optp->len));
18402 	qreply(q, mpctl);
18403 	return (mp2ctl);
18404 }
18405 
18406 /* IP multicast filtered sources */
18407 static mblk_t *
18408 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18409 {
18410 	struct opthdr		*optp;
18411 	mblk_t			*mp2ctl;
18412 	ill_t			*ill;
18413 	ipif_t			*ipif;
18414 	ilm_t			*ilm;
18415 	ip_grpsrc_t		ips;
18416 	mblk_t			*mp_tail = NULL;
18417 	ill_walk_context_t	ctx;
18418 	zoneid_t		zoneid;
18419 	int			i;
18420 	slist_t			*sl;
18421 
18422 	/*
18423 	 * make a copy of the original message
18424 	 */
18425 	mp2ctl = copymsg(mpctl);
18426 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18427 
18428 	/* ipGroupSource table */
18429 	optp = (struct opthdr *)&mpctl->b_rptr[
18430 	    sizeof (struct T_optmgmt_ack)];
18431 	optp->level = MIB2_IP;
18432 	optp->name = EXPER_IP_GROUP_SOURCES;
18433 
18434 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18435 	ill = ILL_START_WALK_V4(&ctx, ipst);
18436 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18437 		ILM_WALKER_HOLD(ill);
18438 		for (ipif = ill->ill_ipif; ipif != NULL;
18439 		    ipif = ipif->ipif_next) {
18440 			if (ipif->ipif_zoneid != zoneid)
18441 				continue;	/* not this zone */
18442 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18443 			    OCTET_LENGTH);
18444 			ips.ipGroupSourceIfIndex.o_length =
18445 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18446 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18447 				ASSERT(ilm->ilm_ipif != NULL);
18448 				ASSERT(ilm->ilm_ill == NULL);
18449 				sl = ilm->ilm_filter;
18450 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18451 					continue;
18452 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18453 				for (i = 0; i < sl->sl_numsrc; i++) {
18454 					if (!IN6_IS_ADDR_V4MAPPED(
18455 					    &sl->sl_addr[i]))
18456 						continue;
18457 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18458 					    ips.ipGroupSourceAddress);
18459 					if (snmp_append_data2(mpctl->b_cont,
18460 					    &mp_tail, (char *)&ips,
18461 					    (int)sizeof (ips)) == 0) {
18462 						ip1dbg(("ip_snmp_get_mib2_"
18463 						    "ip_group_src: failed to "
18464 						    "allocate %u bytes\n",
18465 						    (uint_t)sizeof (ips)));
18466 					}
18467 				}
18468 			}
18469 		}
18470 		ILM_WALKER_RELE(ill);
18471 	}
18472 	rw_exit(&ipst->ips_ill_g_lock);
18473 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18474 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18475 	    (int)optp->level, (int)optp->name, (int)optp->len));
18476 	qreply(q, mpctl);
18477 	return (mp2ctl);
18478 }
18479 
18480 /* IPv6 multicast filtered sources. */
18481 static mblk_t *
18482 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18483 {
18484 	struct opthdr		*optp;
18485 	mblk_t			*mp2ctl;
18486 	ill_t			*ill;
18487 	ilm_t			*ilm;
18488 	ipv6_grpsrc_t		ips6;
18489 	mblk_t			*mp_tail = NULL;
18490 	ill_walk_context_t	ctx;
18491 	zoneid_t		zoneid;
18492 	int			i;
18493 	slist_t			*sl;
18494 
18495 	/*
18496 	 * make a copy of the original message
18497 	 */
18498 	mp2ctl = copymsg(mpctl);
18499 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18500 
18501 	/* ip6GroupMember table */
18502 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18503 	optp->level = MIB2_IP6;
18504 	optp->name = EXPER_IP6_GROUP_SOURCES;
18505 
18506 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18507 	ill = ILL_START_WALK_V6(&ctx, ipst);
18508 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18509 		ILM_WALKER_HOLD(ill);
18510 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18511 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18512 			ASSERT(ilm->ilm_ipif == NULL);
18513 			ASSERT(ilm->ilm_ill != NULL);
18514 			sl = ilm->ilm_filter;
18515 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18516 				continue;
18517 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18518 			for (i = 0; i < sl->sl_numsrc; i++) {
18519 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18520 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18521 				    (char *)&ips6, (int)sizeof (ips6))) {
18522 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18523 					    "group_src: failed to allocate "
18524 					    "%u bytes\n",
18525 					    (uint_t)sizeof (ips6)));
18526 				}
18527 			}
18528 		}
18529 		ILM_WALKER_RELE(ill);
18530 	}
18531 	rw_exit(&ipst->ips_ill_g_lock);
18532 
18533 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18534 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18535 	    (int)optp->level, (int)optp->name, (int)optp->len));
18536 	qreply(q, mpctl);
18537 	return (mp2ctl);
18538 }
18539 
18540 /* Multicast routing virtual interface table. */
18541 static mblk_t *
18542 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18543 {
18544 	struct opthdr		*optp;
18545 	mblk_t			*mp2ctl;
18546 
18547 	/*
18548 	 * make a copy of the original message
18549 	 */
18550 	mp2ctl = copymsg(mpctl);
18551 
18552 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18553 	optp->level = EXPER_DVMRP;
18554 	optp->name = EXPER_DVMRP_VIF;
18555 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18556 		ip0dbg(("ip_mroute_vif: failed\n"));
18557 	}
18558 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18559 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18560 	    (int)optp->level, (int)optp->name, (int)optp->len));
18561 	qreply(q, mpctl);
18562 	return (mp2ctl);
18563 }
18564 
18565 /* Multicast routing table. */
18566 static mblk_t *
18567 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18568 {
18569 	struct opthdr		*optp;
18570 	mblk_t			*mp2ctl;
18571 
18572 	/*
18573 	 * make a copy of the original message
18574 	 */
18575 	mp2ctl = copymsg(mpctl);
18576 
18577 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18578 	optp->level = EXPER_DVMRP;
18579 	optp->name = EXPER_DVMRP_MRT;
18580 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18581 		ip0dbg(("ip_mroute_mrt: failed\n"));
18582 	}
18583 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18584 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18585 	    (int)optp->level, (int)optp->name, (int)optp->len));
18586 	qreply(q, mpctl);
18587 	return (mp2ctl);
18588 }
18589 
18590 /*
18591  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18592  * in one IRE walk.
18593  */
18594 static mblk_t *
18595 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18596 {
18597 	struct opthdr	*optp;
18598 	mblk_t		*mp2ctl;	/* Returned */
18599 	mblk_t		*mp3ctl;	/* nettomedia */
18600 	mblk_t		*mp4ctl;	/* routeattrs */
18601 	iproutedata_t	ird;
18602 	zoneid_t	zoneid;
18603 
18604 	/*
18605 	 * make copies of the original message
18606 	 *	- mp2ctl is returned unchanged to the caller for his use
18607 	 *	- mpctl is sent upstream as ipRouteEntryTable
18608 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18609 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18610 	 */
18611 	mp2ctl = copymsg(mpctl);
18612 	mp3ctl = copymsg(mpctl);
18613 	mp4ctl = copymsg(mpctl);
18614 	if (mp3ctl == NULL || mp4ctl == NULL) {
18615 		freemsg(mp4ctl);
18616 		freemsg(mp3ctl);
18617 		freemsg(mp2ctl);
18618 		freemsg(mpctl);
18619 		return (NULL);
18620 	}
18621 
18622 	bzero(&ird, sizeof (ird));
18623 
18624 	ird.ird_route.lp_head = mpctl->b_cont;
18625 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18626 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18627 
18628 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18629 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18630 
18631 	/* ipRouteEntryTable in mpctl */
18632 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18633 	optp->level = MIB2_IP;
18634 	optp->name = MIB2_IP_ROUTE;
18635 	optp->len = msgdsize(ird.ird_route.lp_head);
18636 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18637 	    (int)optp->level, (int)optp->name, (int)optp->len));
18638 	qreply(q, mpctl);
18639 
18640 	/* ipNetToMediaEntryTable in mp3ctl */
18641 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18642 	optp->level = MIB2_IP;
18643 	optp->name = MIB2_IP_MEDIA;
18644 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18645 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18646 	    (int)optp->level, (int)optp->name, (int)optp->len));
18647 	qreply(q, mp3ctl);
18648 
18649 	/* ipRouteAttributeTable in mp4ctl */
18650 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18651 	optp->level = MIB2_IP;
18652 	optp->name = EXPER_IP_RTATTR;
18653 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18654 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18655 	    (int)optp->level, (int)optp->name, (int)optp->len));
18656 	if (optp->len == 0)
18657 		freemsg(mp4ctl);
18658 	else
18659 		qreply(q, mp4ctl);
18660 
18661 	return (mp2ctl);
18662 }
18663 
18664 /*
18665  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18666  * ipv6NetToMediaEntryTable in an NDP walk.
18667  */
18668 static mblk_t *
18669 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18670 {
18671 	struct opthdr	*optp;
18672 	mblk_t		*mp2ctl;	/* Returned */
18673 	mblk_t		*mp3ctl;	/* nettomedia */
18674 	mblk_t		*mp4ctl;	/* routeattrs */
18675 	iproutedata_t	ird;
18676 	zoneid_t	zoneid;
18677 
18678 	/*
18679 	 * make copies of the original message
18680 	 *	- mp2ctl is returned unchanged to the caller for his use
18681 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18682 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18683 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18684 	 */
18685 	mp2ctl = copymsg(mpctl);
18686 	mp3ctl = copymsg(mpctl);
18687 	mp4ctl = copymsg(mpctl);
18688 	if (mp3ctl == NULL || mp4ctl == NULL) {
18689 		freemsg(mp4ctl);
18690 		freemsg(mp3ctl);
18691 		freemsg(mp2ctl);
18692 		freemsg(mpctl);
18693 		return (NULL);
18694 	}
18695 
18696 	bzero(&ird, sizeof (ird));
18697 
18698 	ird.ird_route.lp_head = mpctl->b_cont;
18699 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18700 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18701 
18702 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18703 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
18704 
18705 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18706 	optp->level = MIB2_IP6;
18707 	optp->name = MIB2_IP6_ROUTE;
18708 	optp->len = msgdsize(ird.ird_route.lp_head);
18709 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18710 	    (int)optp->level, (int)optp->name, (int)optp->len));
18711 	qreply(q, mpctl);
18712 
18713 	/* ipv6NetToMediaEntryTable in mp3ctl */
18714 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
18715 
18716 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18717 	optp->level = MIB2_IP6;
18718 	optp->name = MIB2_IP6_MEDIA;
18719 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18720 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18721 	    (int)optp->level, (int)optp->name, (int)optp->len));
18722 	qreply(q, mp3ctl);
18723 
18724 	/* ipv6RouteAttributeTable in mp4ctl */
18725 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18726 	optp->level = MIB2_IP6;
18727 	optp->name = EXPER_IP_RTATTR;
18728 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18729 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
18730 	    (int)optp->level, (int)optp->name, (int)optp->len));
18731 	if (optp->len == 0)
18732 		freemsg(mp4ctl);
18733 	else
18734 		qreply(q, mp4ctl);
18735 
18736 	return (mp2ctl);
18737 }
18738 
18739 /*
18740  * IPv6 mib: One per ill
18741  */
18742 static mblk_t *
18743 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18744 {
18745 	struct opthdr		*optp;
18746 	mblk_t			*mp2ctl;
18747 	ill_t			*ill;
18748 	ill_walk_context_t	ctx;
18749 	mblk_t			*mp_tail = NULL;
18750 
18751 	/*
18752 	 * Make a copy of the original message
18753 	 */
18754 	mp2ctl = copymsg(mpctl);
18755 
18756 	/* fixed length IPv6 structure ... */
18757 
18758 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18759 	optp->level = MIB2_IP6;
18760 	optp->name = 0;
18761 	/* Include "unknown interface" ip6_mib */
18762 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
18763 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
18764 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18765 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
18766 	    ipst->ips_ipv6_forward ? 1 : 2);
18767 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
18768 	    ipst->ips_ipv6_def_hops);
18769 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
18770 	    sizeof (mib2_ipIfStatsEntry_t));
18771 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
18772 	    sizeof (mib2_ipv6AddrEntry_t));
18773 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
18774 	    sizeof (mib2_ipv6RouteEntry_t));
18775 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
18776 	    sizeof (mib2_ipv6NetToMediaEntry_t));
18777 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
18778 	    sizeof (ipv6_member_t));
18779 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
18780 	    sizeof (ipv6_grpsrc_t));
18781 
18782 	/*
18783 	 * Synchronize 64- and 32-bit counters
18784 	 */
18785 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
18786 	    ipIfStatsHCInReceives);
18787 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
18788 	    ipIfStatsHCInDelivers);
18789 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
18790 	    ipIfStatsHCOutRequests);
18791 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
18792 	    ipIfStatsHCOutForwDatagrams);
18793 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
18794 	    ipIfStatsHCOutMcastPkts);
18795 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
18796 	    ipIfStatsHCInMcastPkts);
18797 
18798 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18799 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
18800 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
18801 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
18802 	}
18803 
18804 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18805 	ill = ILL_START_WALK_V6(&ctx, ipst);
18806 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18807 		ill->ill_ip_mib->ipIfStatsIfIndex =
18808 		    ill->ill_phyint->phyint_ifindex;
18809 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18810 		    ipst->ips_ipv6_forward ? 1 : 2);
18811 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
18812 		    ill->ill_max_hops);
18813 
18814 		/*
18815 		 * Synchronize 64- and 32-bit counters
18816 		 */
18817 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
18818 		    ipIfStatsHCInReceives);
18819 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
18820 		    ipIfStatsHCInDelivers);
18821 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
18822 		    ipIfStatsHCOutRequests);
18823 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
18824 		    ipIfStatsHCOutForwDatagrams);
18825 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
18826 		    ipIfStatsHCOutMcastPkts);
18827 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
18828 		    ipIfStatsHCInMcastPkts);
18829 
18830 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18831 		    (char *)ill->ill_ip_mib,
18832 		    (int)sizeof (*ill->ill_ip_mib))) {
18833 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
18834 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
18835 		}
18836 	}
18837 	rw_exit(&ipst->ips_ill_g_lock);
18838 
18839 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18840 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
18841 	    (int)optp->level, (int)optp->name, (int)optp->len));
18842 	qreply(q, mpctl);
18843 	return (mp2ctl);
18844 }
18845 
18846 /*
18847  * ICMPv6 mib: One per ill
18848  */
18849 static mblk_t *
18850 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18851 {
18852 	struct opthdr		*optp;
18853 	mblk_t			*mp2ctl;
18854 	ill_t			*ill;
18855 	ill_walk_context_t	ctx;
18856 	mblk_t			*mp_tail = NULL;
18857 	/*
18858 	 * Make a copy of the original message
18859 	 */
18860 	mp2ctl = copymsg(mpctl);
18861 
18862 	/* fixed length ICMPv6 structure ... */
18863 
18864 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18865 	optp->level = MIB2_ICMP6;
18866 	optp->name = 0;
18867 	/* Include "unknown interface" icmp6_mib */
18868 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
18869 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
18870 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
18871 	    sizeof (mib2_ipv6IfIcmpEntry_t);
18872 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18873 	    (char *)&ipst->ips_icmp6_mib,
18874 	    (int)sizeof (ipst->ips_icmp6_mib))) {
18875 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
18876 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
18877 	}
18878 
18879 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18880 	ill = ILL_START_WALK_V6(&ctx, ipst);
18881 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18882 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
18883 		    ill->ill_phyint->phyint_ifindex;
18884 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18885 		    (char *)ill->ill_icmp6_mib,
18886 		    (int)sizeof (*ill->ill_icmp6_mib))) {
18887 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
18888 			    "%u bytes\n",
18889 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
18890 		}
18891 	}
18892 	rw_exit(&ipst->ips_ill_g_lock);
18893 
18894 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18895 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
18896 	    (int)optp->level, (int)optp->name, (int)optp->len));
18897 	qreply(q, mpctl);
18898 	return (mp2ctl);
18899 }
18900 
18901 /*
18902  * ire_walk routine to create both ipRouteEntryTable and
18903  * ipRouteAttributeTable in one IRE walk
18904  */
18905 static void
18906 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
18907 {
18908 	ill_t				*ill;
18909 	ipif_t				*ipif;
18910 	mib2_ipRouteEntry_t		*re;
18911 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
18912 	ipaddr_t			gw_addr;
18913 	tsol_ire_gw_secattr_t		*attrp;
18914 	tsol_gc_t			*gc = NULL;
18915 	tsol_gcgrp_t			*gcgrp = NULL;
18916 	uint_t				sacnt = 0;
18917 	int				i;
18918 
18919 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
18920 
18921 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
18922 		return;
18923 
18924 	if ((attrp = ire->ire_gw_secattr) != NULL) {
18925 		mutex_enter(&attrp->igsa_lock);
18926 		if ((gc = attrp->igsa_gc) != NULL) {
18927 			gcgrp = gc->gc_grp;
18928 			ASSERT(gcgrp != NULL);
18929 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18930 			sacnt = 1;
18931 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
18932 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
18933 			gc = gcgrp->gcgrp_head;
18934 			sacnt = gcgrp->gcgrp_count;
18935 		}
18936 		mutex_exit(&attrp->igsa_lock);
18937 
18938 		/* do nothing if there's no gc to report */
18939 		if (gc == NULL) {
18940 			ASSERT(sacnt == 0);
18941 			if (gcgrp != NULL) {
18942 				/* we might as well drop the lock now */
18943 				rw_exit(&gcgrp->gcgrp_rwlock);
18944 				gcgrp = NULL;
18945 			}
18946 			attrp = NULL;
18947 		}
18948 
18949 		ASSERT(gc == NULL || (gcgrp != NULL &&
18950 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
18951 	}
18952 	ASSERT(sacnt == 0 || gc != NULL);
18953 
18954 	if (sacnt != 0 &&
18955 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
18956 		kmem_free(re, sizeof (*re));
18957 		rw_exit(&gcgrp->gcgrp_rwlock);
18958 		return;
18959 	}
18960 
18961 	/*
18962 	 * Return all IRE types for route table... let caller pick and choose
18963 	 */
18964 	re->ipRouteDest = ire->ire_addr;
18965 	ipif = ire->ire_ipif;
18966 	re->ipRouteIfIndex.o_length = 0;
18967 	if (ire->ire_type == IRE_CACHE) {
18968 		ill = (ill_t *)ire->ire_stq->q_ptr;
18969 		re->ipRouteIfIndex.o_length =
18970 		    ill->ill_name_length == 0 ? 0 :
18971 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
18972 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
18973 		    re->ipRouteIfIndex.o_length);
18974 	} else if (ipif != NULL) {
18975 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
18976 		re->ipRouteIfIndex.o_length =
18977 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
18978 	}
18979 	re->ipRouteMetric1 = -1;
18980 	re->ipRouteMetric2 = -1;
18981 	re->ipRouteMetric3 = -1;
18982 	re->ipRouteMetric4 = -1;
18983 
18984 	gw_addr = ire->ire_gateway_addr;
18985 
18986 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
18987 		re->ipRouteNextHop = ire->ire_src_addr;
18988 	else
18989 		re->ipRouteNextHop = gw_addr;
18990 	/* indirect(4), direct(3), or invalid(2) */
18991 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
18992 		re->ipRouteType = 2;
18993 	else
18994 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
18995 	re->ipRouteProto = -1;
18996 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
18997 	re->ipRouteMask = ire->ire_mask;
18998 	re->ipRouteMetric5 = -1;
18999 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19000 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19001 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19002 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19003 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19004 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19005 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19006 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19007 
19008 	if (ire->ire_flags & RTF_DYNAMIC) {
19009 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19010 	} else {
19011 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19012 	}
19013 
19014 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19015 	    (char *)re, (int)sizeof (*re))) {
19016 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19017 		    (uint_t)sizeof (*re)));
19018 	}
19019 
19020 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19021 		iaeptr->iae_routeidx = ird->ird_idx;
19022 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19023 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19024 	}
19025 
19026 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19027 	    (char *)iae, sacnt * sizeof (*iae))) {
19028 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19029 		    (unsigned)(sacnt * sizeof (*iae))));
19030 	}
19031 
19032 	/* bump route index for next pass */
19033 	ird->ird_idx++;
19034 
19035 	kmem_free(re, sizeof (*re));
19036 	if (sacnt != 0)
19037 		kmem_free(iae, sacnt * sizeof (*iae));
19038 
19039 	if (gcgrp != NULL)
19040 		rw_exit(&gcgrp->gcgrp_rwlock);
19041 }
19042 
19043 /*
19044  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19045  */
19046 static void
19047 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19048 {
19049 	ill_t				*ill;
19050 	ipif_t				*ipif;
19051 	mib2_ipv6RouteEntry_t		*re;
19052 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19053 	in6_addr_t			gw_addr_v6;
19054 	tsol_ire_gw_secattr_t		*attrp;
19055 	tsol_gc_t			*gc = NULL;
19056 	tsol_gcgrp_t			*gcgrp = NULL;
19057 	uint_t				sacnt = 0;
19058 	int				i;
19059 
19060 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19061 
19062 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19063 		return;
19064 
19065 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19066 		mutex_enter(&attrp->igsa_lock);
19067 		if ((gc = attrp->igsa_gc) != NULL) {
19068 			gcgrp = gc->gc_grp;
19069 			ASSERT(gcgrp != NULL);
19070 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19071 			sacnt = 1;
19072 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19073 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19074 			gc = gcgrp->gcgrp_head;
19075 			sacnt = gcgrp->gcgrp_count;
19076 		}
19077 		mutex_exit(&attrp->igsa_lock);
19078 
19079 		/* do nothing if there's no gc to report */
19080 		if (gc == NULL) {
19081 			ASSERT(sacnt == 0);
19082 			if (gcgrp != NULL) {
19083 				/* we might as well drop the lock now */
19084 				rw_exit(&gcgrp->gcgrp_rwlock);
19085 				gcgrp = NULL;
19086 			}
19087 			attrp = NULL;
19088 		}
19089 
19090 		ASSERT(gc == NULL || (gcgrp != NULL &&
19091 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19092 	}
19093 	ASSERT(sacnt == 0 || gc != NULL);
19094 
19095 	if (sacnt != 0 &&
19096 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19097 		kmem_free(re, sizeof (*re));
19098 		rw_exit(&gcgrp->gcgrp_rwlock);
19099 		return;
19100 	}
19101 
19102 	/*
19103 	 * Return all IRE types for route table... let caller pick and choose
19104 	 */
19105 	re->ipv6RouteDest = ire->ire_addr_v6;
19106 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19107 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19108 	re->ipv6RouteIfIndex.o_length = 0;
19109 	ipif = ire->ire_ipif;
19110 	if (ire->ire_type == IRE_CACHE) {
19111 		ill = (ill_t *)ire->ire_stq->q_ptr;
19112 		re->ipv6RouteIfIndex.o_length =
19113 		    ill->ill_name_length == 0 ? 0 :
19114 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19115 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19116 		    re->ipv6RouteIfIndex.o_length);
19117 	} else if (ipif != NULL) {
19118 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19119 		re->ipv6RouteIfIndex.o_length =
19120 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19121 	}
19122 
19123 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19124 
19125 	mutex_enter(&ire->ire_lock);
19126 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19127 	mutex_exit(&ire->ire_lock);
19128 
19129 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19130 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19131 	else
19132 		re->ipv6RouteNextHop = gw_addr_v6;
19133 
19134 	/* remote(4), local(3), or discard(2) */
19135 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19136 		re->ipv6RouteType = 2;
19137 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19138 		re->ipv6RouteType = 3;
19139 	else
19140 		re->ipv6RouteType = 4;
19141 
19142 	re->ipv6RouteProtocol	= -1;
19143 	re->ipv6RoutePolicy	= 0;
19144 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19145 	re->ipv6RouteNextHopRDI	= 0;
19146 	re->ipv6RouteWeight	= 0;
19147 	re->ipv6RouteMetric	= 0;
19148 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19149 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19150 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19151 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19152 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19153 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19154 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19155 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19156 
19157 	if (ire->ire_flags & RTF_DYNAMIC) {
19158 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19159 	} else {
19160 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19161 	}
19162 
19163 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19164 	    (char *)re, (int)sizeof (*re))) {
19165 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19166 		    (uint_t)sizeof (*re)));
19167 	}
19168 
19169 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19170 		iaeptr->iae_routeidx = ird->ird_idx;
19171 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19172 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19173 	}
19174 
19175 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19176 	    (char *)iae, sacnt * sizeof (*iae))) {
19177 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19178 		    (unsigned)(sacnt * sizeof (*iae))));
19179 	}
19180 
19181 	/* bump route index for next pass */
19182 	ird->ird_idx++;
19183 
19184 	kmem_free(re, sizeof (*re));
19185 	if (sacnt != 0)
19186 		kmem_free(iae, sacnt * sizeof (*iae));
19187 
19188 	if (gcgrp != NULL)
19189 		rw_exit(&gcgrp->gcgrp_rwlock);
19190 }
19191 
19192 /*
19193  * ndp_walk routine to create ipv6NetToMediaEntryTable
19194  */
19195 static int
19196 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19197 {
19198 	ill_t				*ill;
19199 	mib2_ipv6NetToMediaEntry_t	ntme;
19200 	dl_unitdata_req_t		*dl;
19201 
19202 	ill = nce->nce_ill;
19203 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19204 		return (0);
19205 
19206 	/*
19207 	 * Neighbor cache entry attached to IRE with on-link
19208 	 * destination.
19209 	 */
19210 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19211 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19212 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19213 	    (nce->nce_res_mp != NULL)) {
19214 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19215 		ntme.ipv6NetToMediaPhysAddress.o_length =
19216 		    dl->dl_dest_addr_length;
19217 	} else {
19218 		ntme.ipv6NetToMediaPhysAddress.o_length =
19219 		    ill->ill_phys_addr_length;
19220 	}
19221 	if (nce->nce_res_mp != NULL) {
19222 		bcopy((char *)nce->nce_res_mp->b_rptr +
19223 		    NCE_LL_ADDR_OFFSET(ill),
19224 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19225 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19226 	} else {
19227 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19228 		    ill->ill_phys_addr_length);
19229 	}
19230 	/*
19231 	 * Note: Returns ND_* states. Should be:
19232 	 * reachable(1), stale(2), delay(3), probe(4),
19233 	 * invalid(5), unknown(6)
19234 	 */
19235 	ntme.ipv6NetToMediaState = nce->nce_state;
19236 	ntme.ipv6NetToMediaLastUpdated = 0;
19237 
19238 	/* other(1), dynamic(2), static(3), local(4) */
19239 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19240 		ntme.ipv6NetToMediaType = 4;
19241 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19242 		ntme.ipv6NetToMediaType = 1;
19243 	} else {
19244 		ntme.ipv6NetToMediaType = 2;
19245 	}
19246 
19247 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19248 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19249 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19250 		    (uint_t)sizeof (ntme)));
19251 	}
19252 	return (0);
19253 }
19254 
19255 /*
19256  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19257  */
19258 /* ARGSUSED */
19259 int
19260 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19261 {
19262 	switch (level) {
19263 	case MIB2_IP:
19264 	case MIB2_ICMP:
19265 		switch (name) {
19266 		default:
19267 			break;
19268 		}
19269 		return (1);
19270 	default:
19271 		return (1);
19272 	}
19273 }
19274 
19275 /*
19276  * When there exists both a 64- and 32-bit counter of a particular type
19277  * (i.e., InReceives), only the 64-bit counters are added.
19278  */
19279 void
19280 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19281 {
19282 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19283 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19284 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19285 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19286 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19287 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19288 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19289 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19290 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19291 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19292 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19293 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19294 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19295 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19296 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19297 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19298 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19299 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19300 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19301 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19302 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19303 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19304 	    o2->ipIfStatsInWrongIPVersion);
19305 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19306 	    o2->ipIfStatsInWrongIPVersion);
19307 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19308 	    o2->ipIfStatsOutSwitchIPVersion);
19309 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19310 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19311 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19312 	    o2->ipIfStatsHCInForwDatagrams);
19313 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19314 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19315 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19316 	    o2->ipIfStatsHCOutForwDatagrams);
19317 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19318 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19319 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19320 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19321 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19322 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19323 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19324 	    o2->ipIfStatsHCOutMcastOctets);
19325 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19326 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19327 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19328 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19329 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19330 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19331 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19332 }
19333 
19334 void
19335 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19336 {
19337 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19338 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19339 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19340 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19341 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19342 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19343 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19344 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19345 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19346 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19347 	    o2->ipv6IfIcmpInRouterSolicits);
19348 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19349 	    o2->ipv6IfIcmpInRouterAdvertisements);
19350 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19351 	    o2->ipv6IfIcmpInNeighborSolicits);
19352 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19353 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19354 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19355 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19356 	    o2->ipv6IfIcmpInGroupMembQueries);
19357 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19358 	    o2->ipv6IfIcmpInGroupMembResponses);
19359 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19360 	    o2->ipv6IfIcmpInGroupMembReductions);
19361 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19362 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19363 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19364 	    o2->ipv6IfIcmpOutDestUnreachs);
19365 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19366 	    o2->ipv6IfIcmpOutAdminProhibs);
19367 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19368 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19369 	    o2->ipv6IfIcmpOutParmProblems);
19370 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19371 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19372 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19373 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19374 	    o2->ipv6IfIcmpOutRouterSolicits);
19375 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19376 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19377 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19378 	    o2->ipv6IfIcmpOutNeighborSolicits);
19379 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19380 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19381 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19382 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19383 	    o2->ipv6IfIcmpOutGroupMembQueries);
19384 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19385 	    o2->ipv6IfIcmpOutGroupMembResponses);
19386 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19387 	    o2->ipv6IfIcmpOutGroupMembReductions);
19388 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19389 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19390 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19391 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19392 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19393 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19394 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19395 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19396 	    o2->ipv6IfIcmpInGroupMembTotal);
19397 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19398 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19399 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19400 	    o2->ipv6IfIcmpInGroupMembBadReports);
19401 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19402 	    o2->ipv6IfIcmpInGroupMembOurReports);
19403 }
19404 
19405 /*
19406  * Called before the options are updated to check if this packet will
19407  * be source routed from here.
19408  * This routine assumes that the options are well formed i.e. that they
19409  * have already been checked.
19410  */
19411 static boolean_t
19412 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19413 {
19414 	ipoptp_t	opts;
19415 	uchar_t		*opt;
19416 	uint8_t		optval;
19417 	uint8_t		optlen;
19418 	ipaddr_t	dst;
19419 	ire_t		*ire;
19420 
19421 	if (IS_SIMPLE_IPH(ipha)) {
19422 		ip2dbg(("not source routed\n"));
19423 		return (B_FALSE);
19424 	}
19425 	dst = ipha->ipha_dst;
19426 	for (optval = ipoptp_first(&opts, ipha);
19427 	    optval != IPOPT_EOL;
19428 	    optval = ipoptp_next(&opts)) {
19429 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19430 		opt = opts.ipoptp_cur;
19431 		optlen = opts.ipoptp_len;
19432 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19433 		    optval, optlen));
19434 		switch (optval) {
19435 			uint32_t off;
19436 		case IPOPT_SSRR:
19437 		case IPOPT_LSRR:
19438 			/*
19439 			 * If dst is one of our addresses and there are some
19440 			 * entries left in the source route return (true).
19441 			 */
19442 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19443 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19444 			if (ire == NULL) {
19445 				ip2dbg(("ip_source_routed: not next"
19446 				    " source route 0x%x\n",
19447 				    ntohl(dst)));
19448 				return (B_FALSE);
19449 			}
19450 			ire_refrele(ire);
19451 			off = opt[IPOPT_OFFSET];
19452 			off--;
19453 			if (optlen < IP_ADDR_LEN ||
19454 			    off > optlen - IP_ADDR_LEN) {
19455 				/* End of source route */
19456 				ip1dbg(("ip_source_routed: end of SR\n"));
19457 				return (B_FALSE);
19458 			}
19459 			return (B_TRUE);
19460 		}
19461 	}
19462 	ip2dbg(("not source routed\n"));
19463 	return (B_FALSE);
19464 }
19465 
19466 /*
19467  * Check if the packet contains any source route.
19468  */
19469 static boolean_t
19470 ip_source_route_included(ipha_t *ipha)
19471 {
19472 	ipoptp_t	opts;
19473 	uint8_t		optval;
19474 
19475 	if (IS_SIMPLE_IPH(ipha))
19476 		return (B_FALSE);
19477 	for (optval = ipoptp_first(&opts, ipha);
19478 	    optval != IPOPT_EOL;
19479 	    optval = ipoptp_next(&opts)) {
19480 		switch (optval) {
19481 		case IPOPT_SSRR:
19482 		case IPOPT_LSRR:
19483 			return (B_TRUE);
19484 		}
19485 	}
19486 	return (B_FALSE);
19487 }
19488 
19489 /*
19490  * Called when the IRE expiration timer fires.
19491  */
19492 void
19493 ip_trash_timer_expire(void *args)
19494 {
19495 	int			flush_flag = 0;
19496 	ire_expire_arg_t	iea;
19497 	ip_stack_t		*ipst = (ip_stack_t *)args;
19498 
19499 	iea.iea_ipst = ipst;	/* No netstack_hold */
19500 
19501 	/*
19502 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19503 	 * This lock makes sure that a new invocation of this function
19504 	 * that occurs due to an almost immediate timer firing will not
19505 	 * progress beyond this point until the current invocation is done
19506 	 */
19507 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19508 	ipst->ips_ip_ire_expire_id = 0;
19509 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19510 
19511 	/* Periodic timer */
19512 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19513 	    ipst->ips_ip_ire_arp_interval) {
19514 		/*
19515 		 * Remove all IRE_CACHE entries since they might
19516 		 * contain arp information.
19517 		 */
19518 		flush_flag |= FLUSH_ARP_TIME;
19519 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19520 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19521 	}
19522 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19523 	    ipst->ips_ip_ire_redir_interval) {
19524 		/* Remove all redirects */
19525 		flush_flag |= FLUSH_REDIRECT_TIME;
19526 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19527 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19528 	}
19529 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19530 	    ipst->ips_ip_ire_pathmtu_interval) {
19531 		/* Increase path mtu */
19532 		flush_flag |= FLUSH_MTU_TIME;
19533 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19534 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19535 	}
19536 
19537 	/*
19538 	 * Optimize for the case when there are no redirects in the
19539 	 * ftable, that is, no need to walk the ftable in that case.
19540 	 */
19541 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19542 		iea.iea_flush_flag = flush_flag;
19543 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19544 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19545 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19546 		    NULL, ALL_ZONES, ipst);
19547 	}
19548 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19549 	    ipst->ips_ip_redirect_cnt > 0) {
19550 		iea.iea_flush_flag = flush_flag;
19551 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19552 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19553 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19554 	}
19555 	if (flush_flag & FLUSH_MTU_TIME) {
19556 		/*
19557 		 * Walk all IPv6 IRE's and update them
19558 		 * Note that ARP and redirect timers are not
19559 		 * needed since NUD handles stale entries.
19560 		 */
19561 		flush_flag = FLUSH_MTU_TIME;
19562 		iea.iea_flush_flag = flush_flag;
19563 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19564 		    ALL_ZONES, ipst);
19565 	}
19566 
19567 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19568 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19569 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19570 
19571 	/*
19572 	 * Hold the lock to serialize timeout calls and prevent
19573 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19574 	 * for the timer to fire and a new invocation of this function
19575 	 * to start before the return value of timeout has been stored
19576 	 * in ip_ire_expire_id by the current invocation.
19577 	 */
19578 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19579 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19580 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19581 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19582 }
19583 
19584 /*
19585  * Called by the memory allocator subsystem directly, when the system
19586  * is running low on memory.
19587  */
19588 /* ARGSUSED */
19589 void
19590 ip_trash_ire_reclaim(void *args)
19591 {
19592 	netstack_handle_t nh;
19593 	netstack_t *ns;
19594 
19595 	netstack_next_init(&nh);
19596 	while ((ns = netstack_next(&nh)) != NULL) {
19597 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19598 		netstack_rele(ns);
19599 	}
19600 	netstack_next_fini(&nh);
19601 }
19602 
19603 static void
19604 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19605 {
19606 	ire_cache_count_t icc;
19607 	ire_cache_reclaim_t icr;
19608 	ncc_cache_count_t ncc;
19609 	nce_cache_reclaim_t ncr;
19610 	uint_t delete_cnt;
19611 	/*
19612 	 * Memory reclaim call back.
19613 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19614 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19615 	 * entries, determine what fraction to free for
19616 	 * each category of IRE_CACHE entries giving absolute priority
19617 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19618 	 * entry will be freed unless all offlink entries are freed).
19619 	 */
19620 	icc.icc_total = 0;
19621 	icc.icc_unused = 0;
19622 	icc.icc_offlink = 0;
19623 	icc.icc_pmtu = 0;
19624 	icc.icc_onlink = 0;
19625 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19626 
19627 	/*
19628 	 * Free NCEs for IPv6 like the onlink ires.
19629 	 */
19630 	ncc.ncc_total = 0;
19631 	ncc.ncc_host = 0;
19632 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19633 
19634 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19635 	    icc.icc_pmtu + icc.icc_onlink);
19636 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19637 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19638 	if (delete_cnt == 0)
19639 		return;
19640 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19641 	/* Always delete all unused offlink entries */
19642 	icr.icr_ipst = ipst;
19643 	icr.icr_unused = 1;
19644 	if (delete_cnt <= icc.icc_unused) {
19645 		/*
19646 		 * Only need to free unused entries.  In other words,
19647 		 * there are enough unused entries to free to meet our
19648 		 * target number of freed ire cache entries.
19649 		 */
19650 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19651 		ncr.ncr_host = 0;
19652 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19653 		/*
19654 		 * Only need to free unused entries, plus a fraction of offlink
19655 		 * entries.  It follows from the first if statement that
19656 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19657 		 */
19658 		delete_cnt -= icc.icc_unused;
19659 		/* Round up # deleted by truncating fraction */
19660 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19661 		icr.icr_pmtu = icr.icr_onlink = 0;
19662 		ncr.ncr_host = 0;
19663 	} else if (delete_cnt <=
19664 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19665 		/*
19666 		 * Free all unused and offlink entries, plus a fraction of
19667 		 * pmtu entries.  It follows from the previous if statement
19668 		 * that icc_pmtu is non-zero, and that
19669 		 * delete_cnt != icc_unused + icc_offlink.
19670 		 */
19671 		icr.icr_offlink = 1;
19672 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19673 		/* Round up # deleted by truncating fraction */
19674 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19675 		icr.icr_onlink = 0;
19676 		ncr.ncr_host = 0;
19677 	} else {
19678 		/*
19679 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19680 		 * of onlink entries.  If we're here, then we know that
19681 		 * icc_onlink is non-zero, and that
19682 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19683 		 */
19684 		icr.icr_offlink = icr.icr_pmtu = 1;
19685 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19686 		    icc.icc_pmtu;
19687 		/* Round up # deleted by truncating fraction */
19688 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19689 		/* Using the same delete fraction as for onlink IREs */
19690 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19691 	}
19692 #ifdef DEBUG
19693 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19694 	    "fractions %d/%d/%d/%d\n",
19695 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19696 	    icc.icc_unused, icc.icc_offlink,
19697 	    icc.icc_pmtu, icc.icc_onlink,
19698 	    icr.icr_unused, icr.icr_offlink,
19699 	    icr.icr_pmtu, icr.icr_onlink));
19700 #endif
19701 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
19702 	if (ncr.ncr_host != 0)
19703 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
19704 		    (uchar_t *)&ncr, ipst);
19705 #ifdef DEBUG
19706 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
19707 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
19708 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19709 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
19710 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
19711 	    icc.icc_pmtu, icc.icc_onlink));
19712 #endif
19713 }
19714 
19715 /*
19716  * ip_unbind is called when a copy of an unbind request is received from the
19717  * upper level protocol.  We remove this conn from any fanout hash list it is
19718  * on, and zero out the bind information.  No reply is expected up above.
19719  */
19720 mblk_t *
19721 ip_unbind(queue_t *q, mblk_t *mp)
19722 {
19723 	conn_t	*connp = Q_TO_CONN(q);
19724 
19725 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
19726 
19727 	if (is_system_labeled() && connp->conn_anon_port) {
19728 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
19729 		    connp->conn_mlp_type, connp->conn_ulp,
19730 		    ntohs(connp->conn_lport), B_FALSE);
19731 		connp->conn_anon_port = 0;
19732 	}
19733 	connp->conn_mlp_type = mlptSingle;
19734 
19735 	ipcl_hash_remove(connp);
19736 
19737 	ASSERT(mp->b_cont == NULL);
19738 	/*
19739 	 * Convert mp into a T_OK_ACK
19740 	 */
19741 	mp = mi_tpi_ok_ack_alloc(mp);
19742 
19743 	/*
19744 	 * should not happen in practice... T_OK_ACK is smaller than the
19745 	 * original message.
19746 	 */
19747 	if (mp == NULL)
19748 		return (NULL);
19749 
19750 	/*
19751 	 * Don't bzero the ports if its TCP since TCP still needs the
19752 	 * lport to remove it from its own bind hash. TCP will do the
19753 	 * cleanup.
19754 	 */
19755 	if (!IPCL_IS_TCP(connp))
19756 		bzero(&connp->u_port, sizeof (connp->u_port));
19757 
19758 	return (mp);
19759 }
19760 
19761 /*
19762  * Write side put procedure.  Outbound data, IOCTLs, responses from
19763  * resolvers, etc, come down through here.
19764  *
19765  * arg2 is always a queue_t *.
19766  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
19767  * the zoneid.
19768  * When that queue is not an ill_t, then arg must be a conn_t pointer.
19769  */
19770 void
19771 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
19772 {
19773 	ip_output_options(arg, mp, arg2, caller, &zero_info);
19774 }
19775 
19776 void
19777 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
19778     ip_opt_info_t *infop)
19779 {
19780 	conn_t		*connp = NULL;
19781 	queue_t		*q = (queue_t *)arg2;
19782 	ipha_t		*ipha;
19783 #define	rptr	((uchar_t *)ipha)
19784 	ire_t		*ire = NULL;
19785 	ire_t		*sctp_ire = NULL;
19786 	uint32_t	v_hlen_tos_len;
19787 	ipaddr_t	dst;
19788 	mblk_t		*first_mp = NULL;
19789 	boolean_t	mctl_present;
19790 	ipsec_out_t	*io;
19791 	int		match_flags;
19792 	ill_t		*attach_ill = NULL;
19793 					/* Bind to IPIF_NOFAILOVER ill etc. */
19794 	ill_t		*xmit_ill = NULL;	/* IP_XMIT_IF etc. */
19795 	ipif_t		*dst_ipif;
19796 	boolean_t	multirt_need_resolve = B_FALSE;
19797 	mblk_t		*copy_mp = NULL;
19798 	int		err;
19799 	zoneid_t	zoneid;
19800 	int	adjust;
19801 	uint16_t iplen;
19802 	boolean_t	need_decref = B_FALSE;
19803 	boolean_t	ignore_dontroute = B_FALSE;
19804 	boolean_t	ignore_nexthop = B_FALSE;
19805 	boolean_t	ip_nexthop = B_FALSE;
19806 	ipaddr_t	nexthop_addr;
19807 	ip_stack_t	*ipst;
19808 
19809 #ifdef	_BIG_ENDIAN
19810 #define	V_HLEN	(v_hlen_tos_len >> 24)
19811 #else
19812 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
19813 #endif
19814 
19815 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
19816 	    "ip_wput_start: q %p", q);
19817 
19818 	/*
19819 	 * ip_wput fast path
19820 	 */
19821 
19822 	/* is packet from ARP ? */
19823 	if (q->q_next != NULL) {
19824 		zoneid = (zoneid_t)(uintptr_t)arg;
19825 		goto qnext;
19826 	}
19827 
19828 	connp = (conn_t *)arg;
19829 	ASSERT(connp != NULL);
19830 	zoneid = connp->conn_zoneid;
19831 	ipst = connp->conn_netstack->netstack_ip;
19832 
19833 	/* is queue flow controlled? */
19834 	if ((q->q_first != NULL || connp->conn_draining) &&
19835 	    (caller == IP_WPUT)) {
19836 		ASSERT(!need_decref);
19837 		(void) putq(q, mp);
19838 		return;
19839 	}
19840 
19841 	/* Multidata transmit? */
19842 	if (DB_TYPE(mp) == M_MULTIDATA) {
19843 		/*
19844 		 * We should never get here, since all Multidata messages
19845 		 * originating from tcp should have been directed over to
19846 		 * tcp_multisend() in the first place.
19847 		 */
19848 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
19849 		freemsg(mp);
19850 		return;
19851 	} else if (DB_TYPE(mp) != M_DATA)
19852 		goto notdata;
19853 
19854 	if (mp->b_flag & MSGHASREF) {
19855 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
19856 		mp->b_flag &= ~MSGHASREF;
19857 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
19858 		need_decref = B_TRUE;
19859 	}
19860 	ipha = (ipha_t *)mp->b_rptr;
19861 
19862 	/* is IP header non-aligned or mblk smaller than basic IP header */
19863 #ifndef SAFETY_BEFORE_SPEED
19864 	if (!OK_32PTR(rptr) ||
19865 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
19866 		goto hdrtoosmall;
19867 #endif
19868 
19869 	ASSERT(OK_32PTR(ipha));
19870 
19871 	/*
19872 	 * This function assumes that mp points to an IPv4 packet.  If it's the
19873 	 * wrong version, we'll catch it again in ip_output_v6.
19874 	 *
19875 	 * Note that this is *only* locally-generated output here, and never
19876 	 * forwarded data, and that we need to deal only with transports that
19877 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
19878 	 * label.)
19879 	 */
19880 	if (is_system_labeled() &&
19881 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
19882 	    !connp->conn_ulp_labeled) {
19883 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
19884 		    connp->conn_mac_exempt, ipst);
19885 		ipha = (ipha_t *)mp->b_rptr;
19886 		if (err != 0) {
19887 			first_mp = mp;
19888 			if (err == EINVAL)
19889 				goto icmp_parameter_problem;
19890 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
19891 			goto discard_pkt;
19892 		}
19893 		iplen = ntohs(ipha->ipha_length) + adjust;
19894 		ipha->ipha_length = htons(iplen);
19895 	}
19896 
19897 	ASSERT(infop != NULL);
19898 
19899 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
19900 		/*
19901 		 * IP_PKTINFO ancillary option is present.
19902 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
19903 		 * allows using address of any zone as the source address.
19904 		 */
19905 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
19906 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
19907 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
19908 		if (ire == NULL)
19909 			goto drop_pkt;
19910 		ire_refrele(ire);
19911 		ire = NULL;
19912 	}
19913 
19914 	/*
19915 	 * IP_DONTFAILOVER_IF and IP_XMIT_IF have precedence over
19916 	 * ill index passed in IP_PKTINFO.
19917 	 */
19918 	if (infop->ip_opt_ill_index != 0 &&
19919 	    connp->conn_xmit_if_ill == NULL &&
19920 	    connp->conn_nofailover_ill == NULL) {
19921 
19922 		xmit_ill = ill_lookup_on_ifindex(
19923 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
19924 		    ipst);
19925 
19926 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
19927 			goto drop_pkt;
19928 		/*
19929 		 * check that there is an ipif belonging
19930 		 * to our zone. IPCL_ZONEID is not used because
19931 		 * IP_ALLZONES option is valid only when the ill is
19932 		 * accessible from all zones i.e has a valid ipif in
19933 		 * all zones.
19934 		 */
19935 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
19936 			goto drop_pkt;
19937 		}
19938 	}
19939 
19940 	/*
19941 	 * If there is a policy, try to attach an ipsec_out in
19942 	 * the front. At the end, first_mp either points to a
19943 	 * M_DATA message or IPSEC_OUT message linked to a
19944 	 * M_DATA message. We have to do it now as we might
19945 	 * lose the "conn" if we go through ip_newroute.
19946 	 */
19947 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
19948 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
19949 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
19950 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
19951 			if (need_decref)
19952 				CONN_DEC_REF(connp);
19953 			return;
19954 		} else {
19955 			ASSERT(mp->b_datap->db_type == M_CTL);
19956 			first_mp = mp;
19957 			mp = mp->b_cont;
19958 			mctl_present = B_TRUE;
19959 		}
19960 	} else {
19961 		first_mp = mp;
19962 		mctl_present = B_FALSE;
19963 	}
19964 
19965 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
19966 
19967 	/* is wrong version or IP options present */
19968 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
19969 		goto version_hdrlen_check;
19970 	dst = ipha->ipha_dst;
19971 
19972 	if (connp->conn_nofailover_ill != NULL) {
19973 		attach_ill = conn_get_held_ill(connp,
19974 		    &connp->conn_nofailover_ill, &err);
19975 		if (err == ILL_LOOKUP_FAILED) {
19976 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
19977 			if (need_decref)
19978 				CONN_DEC_REF(connp);
19979 			freemsg(first_mp);
19980 			return;
19981 		}
19982 	}
19983 
19984 
19985 	/* is packet multicast? */
19986 	if (CLASSD(dst))
19987 		goto multicast;
19988 
19989 	/*
19990 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
19991 	 * takes precedence over conn_dontroute and conn_nexthop_set
19992 	 */
19993 	if (xmit_ill != NULL) {
19994 		goto send_from_ill;
19995 	}
19996 
19997 	if ((connp->conn_dontroute) || (connp->conn_xmit_if_ill != NULL) ||
19998 	    (connp->conn_nexthop_set)) {
19999 		/*
20000 		 * If the destination is a broadcast or a loopback
20001 		 * address, SO_DONTROUTE, IP_XMIT_IF and IP_NEXTHOP go
20002 		 * through the standard path. But in the case of local
20003 		 * destination only SO_DONTROUTE and IP_NEXTHOP go through
20004 		 * the standard path not IP_XMIT_IF.
20005 		 */
20006 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20007 		if ((ire == NULL) || ((ire->ire_type != IRE_BROADCAST) &&
20008 		    (ire->ire_type != IRE_LOOPBACK))) {
20009 			if ((connp->conn_dontroute ||
20010 			    connp->conn_nexthop_set) && (ire != NULL) &&
20011 			    (ire->ire_type == IRE_LOCAL))
20012 				goto standard_path;
20013 
20014 			if (ire != NULL) {
20015 				ire_refrele(ire);
20016 				/* No more access to ire */
20017 				ire = NULL;
20018 			}
20019 			/*
20020 			 * bypass routing checks and go directly to
20021 			 * interface.
20022 			 */
20023 			if (connp->conn_dontroute) {
20024 				goto dontroute;
20025 			} else if (connp->conn_nexthop_set) {
20026 				ip_nexthop = B_TRUE;
20027 				nexthop_addr = connp->conn_nexthop_v4;
20028 				goto send_from_ill;
20029 			}
20030 
20031 			/*
20032 			 * If IP_XMIT_IF socket option is set,
20033 			 * then we allow unicast and multicast
20034 			 * packets to go through the ill. It is
20035 			 * quite possible that the destination
20036 			 * is not in the ire cache table and we
20037 			 * do not want to go to ip_newroute()
20038 			 * instead we call ip_newroute_ipif.
20039 			 */
20040 			xmit_ill = conn_get_held_ill(connp,
20041 			    &connp->conn_xmit_if_ill, &err);
20042 			if (err == ILL_LOOKUP_FAILED) {
20043 				BUMP_MIB(&ipst->ips_ip_mib,
20044 				    ipIfStatsOutDiscards);
20045 				if (attach_ill != NULL)
20046 					ill_refrele(attach_ill);
20047 				if (need_decref)
20048 					CONN_DEC_REF(connp);
20049 				freemsg(first_mp);
20050 				return;
20051 			}
20052 			goto send_from_ill;
20053 		}
20054 standard_path:
20055 		/* Must be a broadcast, a loopback or a local ire */
20056 		if (ire != NULL) {
20057 			ire_refrele(ire);
20058 			/* No more access to ire */
20059 			ire = NULL;
20060 		}
20061 	}
20062 
20063 	if (attach_ill != NULL)
20064 		goto send_from_ill;
20065 
20066 	/*
20067 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20068 	 * this for the tcp global queue and listen end point
20069 	 * as it does not really have a real destination to
20070 	 * talk to.  This is also true for SCTP.
20071 	 */
20072 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20073 	    !connp->conn_fully_bound) {
20074 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20075 		if (ire == NULL)
20076 			goto noirefound;
20077 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20078 		    "ip_wput_end: q %p (%S)", q, "end");
20079 
20080 		/*
20081 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20082 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20083 		 */
20084 		if (ire->ire_flags & RTF_MULTIRT) {
20085 
20086 			/*
20087 			 * Force the TTL of multirouted packets if required.
20088 			 * The TTL of such packets is bounded by the
20089 			 * ip_multirt_ttl ndd variable.
20090 			 */
20091 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20092 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20093 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20094 				    "(was %d), dst 0x%08x\n",
20095 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20096 				    ntohl(ire->ire_addr)));
20097 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20098 			}
20099 			/*
20100 			 * We look at this point if there are pending
20101 			 * unresolved routes. ire_multirt_resolvable()
20102 			 * checks in O(n) that all IRE_OFFSUBNET ire
20103 			 * entries for the packet's destination and
20104 			 * flagged RTF_MULTIRT are currently resolved.
20105 			 * If some remain unresolved, we make a copy
20106 			 * of the current message. It will be used
20107 			 * to initiate additional route resolutions.
20108 			 */
20109 			multirt_need_resolve =
20110 			    ire_multirt_need_resolve(ire->ire_addr,
20111 			    MBLK_GETLABEL(first_mp), ipst);
20112 			ip2dbg(("ip_wput[TCP]: ire %p, "
20113 			    "multirt_need_resolve %d, first_mp %p\n",
20114 			    (void *)ire, multirt_need_resolve,
20115 			    (void *)first_mp));
20116 			if (multirt_need_resolve) {
20117 				copy_mp = copymsg(first_mp);
20118 				if (copy_mp != NULL) {
20119 					MULTIRT_DEBUG_TAG(copy_mp);
20120 				}
20121 			}
20122 		}
20123 
20124 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20125 
20126 		/*
20127 		 * Try to resolve another multiroute if
20128 		 * ire_multirt_need_resolve() deemed it necessary.
20129 		 */
20130 		if (copy_mp != NULL)
20131 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20132 		if (need_decref)
20133 			CONN_DEC_REF(connp);
20134 		return;
20135 	}
20136 
20137 	/*
20138 	 * Access to conn_ire_cache. (protected by conn_lock)
20139 	 *
20140 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20141 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20142 	 * send a packet or two with the IRE_CACHE that is going away.
20143 	 * Access to the ire requires an ire refhold on the ire prior to
20144 	 * its use since an interface unplumb thread may delete the cached
20145 	 * ire and release the refhold at any time.
20146 	 *
20147 	 * Caching an ire in the conn_ire_cache
20148 	 *
20149 	 * o Caching an ire pointer in the conn requires a strict check for
20150 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20151 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20152 	 * in the conn is done after making sure under the bucket lock that the
20153 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20154 	 * caching an ire after the unplumb thread has cleaned up the conn.
20155 	 * If the conn does not send a packet subsequently the unplumb thread
20156 	 * will be hanging waiting for the ire count to drop to zero.
20157 	 *
20158 	 * o We also need to atomically test for a null conn_ire_cache and
20159 	 * set the conn_ire_cache under the the protection of the conn_lock
20160 	 * to avoid races among concurrent threads trying to simultaneously
20161 	 * cache an ire in the conn_ire_cache.
20162 	 */
20163 	mutex_enter(&connp->conn_lock);
20164 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20165 
20166 	if (ire != NULL && ire->ire_addr == dst &&
20167 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20168 
20169 		IRE_REFHOLD(ire);
20170 		mutex_exit(&connp->conn_lock);
20171 
20172 	} else {
20173 		boolean_t cached = B_FALSE;
20174 		connp->conn_ire_cache = NULL;
20175 		mutex_exit(&connp->conn_lock);
20176 		/* Release the old ire */
20177 		if (ire != NULL && sctp_ire == NULL)
20178 			IRE_REFRELE_NOTR(ire);
20179 
20180 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20181 		if (ire == NULL)
20182 			goto noirefound;
20183 		IRE_REFHOLD_NOTR(ire);
20184 
20185 		mutex_enter(&connp->conn_lock);
20186 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20187 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20188 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20189 				if (connp->conn_ulp == IPPROTO_TCP)
20190 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20191 				connp->conn_ire_cache = ire;
20192 				cached = B_TRUE;
20193 			}
20194 			rw_exit(&ire->ire_bucket->irb_lock);
20195 		}
20196 		mutex_exit(&connp->conn_lock);
20197 
20198 		/*
20199 		 * We can continue to use the ire but since it was
20200 		 * not cached, we should drop the extra reference.
20201 		 */
20202 		if (!cached)
20203 			IRE_REFRELE_NOTR(ire);
20204 	}
20205 
20206 
20207 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20208 	    "ip_wput_end: q %p (%S)", q, "end");
20209 
20210 	/*
20211 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20212 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20213 	 */
20214 	if (ire->ire_flags & RTF_MULTIRT) {
20215 
20216 		/*
20217 		 * Force the TTL of multirouted packets if required.
20218 		 * The TTL of such packets is bounded by the
20219 		 * ip_multirt_ttl ndd variable.
20220 		 */
20221 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20222 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20223 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20224 			    "(was %d), dst 0x%08x\n",
20225 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20226 			    ntohl(ire->ire_addr)));
20227 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20228 		}
20229 
20230 		/*
20231 		 * At this point, we check to see if there are any pending
20232 		 * unresolved routes. ire_multirt_resolvable()
20233 		 * checks in O(n) that all IRE_OFFSUBNET ire
20234 		 * entries for the packet's destination and
20235 		 * flagged RTF_MULTIRT are currently resolved.
20236 		 * If some remain unresolved, we make a copy
20237 		 * of the current message. It will be used
20238 		 * to initiate additional route resolutions.
20239 		 */
20240 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20241 		    MBLK_GETLABEL(first_mp), ipst);
20242 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20243 		    "multirt_need_resolve %d, first_mp %p\n",
20244 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20245 		if (multirt_need_resolve) {
20246 			copy_mp = copymsg(first_mp);
20247 			if (copy_mp != NULL) {
20248 				MULTIRT_DEBUG_TAG(copy_mp);
20249 			}
20250 		}
20251 	}
20252 
20253 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20254 
20255 	/*
20256 	 * Try to resolve another multiroute if
20257 	 * ire_multirt_resolvable() deemed it necessary
20258 	 */
20259 	if (copy_mp != NULL)
20260 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20261 	if (need_decref)
20262 		CONN_DEC_REF(connp);
20263 	return;
20264 
20265 qnext:
20266 	/*
20267 	 * Upper Level Protocols pass down complete IP datagrams
20268 	 * as M_DATA messages.	Everything else is a sideshow.
20269 	 *
20270 	 * 1) We could be re-entering ip_wput because of ip_neworute
20271 	 *    in which case we could have a IPSEC_OUT message. We
20272 	 *    need to pass through ip_wput like other datagrams and
20273 	 *    hence cannot branch to ip_wput_nondata.
20274 	 *
20275 	 * 2) ARP, AH, ESP, and other clients who are on the module
20276 	 *    instance of IP stream, give us something to deal with.
20277 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20278 	 *
20279 	 * 3) ICMP replies also could come here.
20280 	 */
20281 	ipst = ILLQ_TO_IPST(q);
20282 
20283 	if (DB_TYPE(mp) != M_DATA) {
20284 notdata:
20285 		if (DB_TYPE(mp) == M_CTL) {
20286 			/*
20287 			 * M_CTL messages are used by ARP, AH and ESP to
20288 			 * communicate with IP. We deal with IPSEC_IN and
20289 			 * IPSEC_OUT here. ip_wput_nondata handles other
20290 			 * cases.
20291 			 */
20292 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20293 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20294 				first_mp = mp->b_cont;
20295 				first_mp->b_flag &= ~MSGHASREF;
20296 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20297 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20298 				CONN_DEC_REF(connp);
20299 				connp = NULL;
20300 			}
20301 			if (ii->ipsec_info_type == IPSEC_IN) {
20302 				/*
20303 				 * Either this message goes back to
20304 				 * IPSEC for further processing or to
20305 				 * ULP after policy checks.
20306 				 */
20307 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20308 				return;
20309 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20310 				io = (ipsec_out_t *)ii;
20311 				if (io->ipsec_out_proc_begin) {
20312 					/*
20313 					 * IPSEC processing has already started.
20314 					 * Complete it.
20315 					 * IPQoS notes: We don't care what is
20316 					 * in ipsec_out_ill_index since this
20317 					 * won't be processed for IPQoS policies
20318 					 * in ipsec_out_process.
20319 					 */
20320 					ipsec_out_process(q, mp, NULL,
20321 					    io->ipsec_out_ill_index);
20322 					return;
20323 				} else {
20324 					connp = (q->q_next != NULL) ?
20325 					    NULL : Q_TO_CONN(q);
20326 					first_mp = mp;
20327 					mp = mp->b_cont;
20328 					mctl_present = B_TRUE;
20329 				}
20330 				zoneid = io->ipsec_out_zoneid;
20331 				ASSERT(zoneid != ALL_ZONES);
20332 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20333 				/*
20334 				 * It's an IPsec control message requesting
20335 				 * an SADB update to be sent to the IPsec
20336 				 * hardware acceleration capable ills.
20337 				 */
20338 				ipsec_ctl_t *ipsec_ctl =
20339 				    (ipsec_ctl_t *)mp->b_rptr;
20340 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20341 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20342 				mblk_t *cmp = mp->b_cont;
20343 
20344 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20345 				ASSERT(cmp != NULL);
20346 
20347 				freeb(mp);
20348 				ill_ipsec_capab_send_all(satype, cmp, sa,
20349 				    ipst->ips_netstack);
20350 				return;
20351 			} else {
20352 				/*
20353 				 * This must be ARP or special TSOL signaling.
20354 				 */
20355 				ip_wput_nondata(NULL, q, mp, NULL);
20356 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20357 				    "ip_wput_end: q %p (%S)", q, "nondata");
20358 				return;
20359 			}
20360 		} else {
20361 			/*
20362 			 * This must be non-(ARP/AH/ESP) messages.
20363 			 */
20364 			ASSERT(!need_decref);
20365 			ip_wput_nondata(NULL, q, mp, NULL);
20366 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20367 			    "ip_wput_end: q %p (%S)", q, "nondata");
20368 			return;
20369 		}
20370 	} else {
20371 		first_mp = mp;
20372 		mctl_present = B_FALSE;
20373 	}
20374 
20375 	ASSERT(first_mp != NULL);
20376 	/*
20377 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20378 	 * to make sure that this packet goes out on the same interface it
20379 	 * came in. We handle that here.
20380 	 */
20381 	if (mctl_present) {
20382 		uint_t ifindex;
20383 
20384 		io = (ipsec_out_t *)first_mp->b_rptr;
20385 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20386 			/*
20387 			 * We may have lost the conn context if we are
20388 			 * coming here from ip_newroute(). Copy the
20389 			 * nexthop information.
20390 			 */
20391 			if (io->ipsec_out_ip_nexthop) {
20392 				ip_nexthop = B_TRUE;
20393 				nexthop_addr = io->ipsec_out_nexthop_addr;
20394 
20395 				ipha = (ipha_t *)mp->b_rptr;
20396 				dst = ipha->ipha_dst;
20397 				goto send_from_ill;
20398 			} else {
20399 				ASSERT(io->ipsec_out_ill_index != 0);
20400 				ifindex = io->ipsec_out_ill_index;
20401 				attach_ill = ill_lookup_on_ifindex(ifindex,
20402 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20403 				if (attach_ill == NULL) {
20404 					ASSERT(xmit_ill == NULL);
20405 					ip1dbg(("ip_output: bad ifindex for "
20406 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20407 					    ifindex));
20408 					freemsg(first_mp);
20409 					BUMP_MIB(&ipst->ips_ip_mib,
20410 					    ipIfStatsOutDiscards);
20411 					ASSERT(!need_decref);
20412 					return;
20413 				}
20414 			}
20415 		}
20416 	}
20417 
20418 	ASSERT(xmit_ill == NULL);
20419 
20420 	/* We have a complete IP datagram heading outbound. */
20421 	ipha = (ipha_t *)mp->b_rptr;
20422 
20423 #ifndef SPEED_BEFORE_SAFETY
20424 	/*
20425 	 * Make sure we have a full-word aligned message and that at least
20426 	 * a simple IP header is accessible in the first message.  If not,
20427 	 * try a pullup.
20428 	 */
20429 	if (!OK_32PTR(rptr) ||
20430 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20431 hdrtoosmall:
20432 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20433 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20434 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20435 			if (first_mp == NULL)
20436 				first_mp = mp;
20437 			goto discard_pkt;
20438 		}
20439 
20440 		/* This function assumes that mp points to an IPv4 packet. */
20441 		if (is_system_labeled() && q->q_next == NULL &&
20442 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20443 		    !connp->conn_ulp_labeled) {
20444 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20445 			    &adjust, connp->conn_mac_exempt, ipst);
20446 			ipha = (ipha_t *)mp->b_rptr;
20447 			if (first_mp != NULL)
20448 				first_mp->b_cont = mp;
20449 			if (err != 0) {
20450 				if (first_mp == NULL)
20451 					first_mp = mp;
20452 				if (err == EINVAL)
20453 					goto icmp_parameter_problem;
20454 				ip2dbg(("ip_wput: label check failed (%d)\n",
20455 				    err));
20456 				goto discard_pkt;
20457 			}
20458 			iplen = ntohs(ipha->ipha_length) + adjust;
20459 			ipha->ipha_length = htons(iplen);
20460 		}
20461 
20462 		ipha = (ipha_t *)mp->b_rptr;
20463 		if (first_mp == NULL) {
20464 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20465 			/*
20466 			 * If we got here because of "goto hdrtoosmall"
20467 			 * We need to attach a IPSEC_OUT.
20468 			 */
20469 			if (connp->conn_out_enforce_policy) {
20470 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20471 				    NULL, ipha->ipha_protocol,
20472 				    ipst->ips_netstack)) == NULL)) {
20473 					BUMP_MIB(&ipst->ips_ip_mib,
20474 					    ipIfStatsOutDiscards);
20475 					if (need_decref)
20476 						CONN_DEC_REF(connp);
20477 					return;
20478 				} else {
20479 					ASSERT(mp->b_datap->db_type == M_CTL);
20480 					first_mp = mp;
20481 					mp = mp->b_cont;
20482 					mctl_present = B_TRUE;
20483 				}
20484 			} else {
20485 				first_mp = mp;
20486 				mctl_present = B_FALSE;
20487 			}
20488 		}
20489 	}
20490 #endif
20491 
20492 	/* Most of the code below is written for speed, not readability */
20493 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20494 
20495 	/*
20496 	 * If ip_newroute() fails, we're going to need a full
20497 	 * header for the icmp wraparound.
20498 	 */
20499 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20500 		uint_t	v_hlen;
20501 version_hdrlen_check:
20502 		ASSERT(first_mp != NULL);
20503 		v_hlen = V_HLEN;
20504 		/*
20505 		 * siphon off IPv6 packets coming down from transport
20506 		 * layer modules here.
20507 		 * Note: high-order bit carries NUD reachability confirmation
20508 		 */
20509 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20510 			/*
20511 			 * XXX implement a IPv4 and IPv6 packet counter per
20512 			 * conn and switch when ratio exceeds e.g. 10:1
20513 			 */
20514 #ifdef notyet
20515 			if (q->q_next == NULL) /* Avoid ill queue */
20516 				ip_setqinfo(RD(q), B_TRUE, B_TRUE, ipst);
20517 #endif
20518 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20519 			ASSERT(xmit_ill == NULL);
20520 			if (attach_ill != NULL)
20521 				ill_refrele(attach_ill);
20522 			if (need_decref)
20523 				mp->b_flag |= MSGHASREF;
20524 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20525 			return;
20526 		}
20527 
20528 		if ((v_hlen >> 4) != IP_VERSION) {
20529 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20530 			    "ip_wput_end: q %p (%S)", q, "badvers");
20531 			goto discard_pkt;
20532 		}
20533 		/*
20534 		 * Is the header length at least 20 bytes?
20535 		 *
20536 		 * Are there enough bytes accessible in the header?  If
20537 		 * not, try a pullup.
20538 		 */
20539 		v_hlen &= 0xF;
20540 		v_hlen <<= 2;
20541 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20542 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20543 			    "ip_wput_end: q %p (%S)", q, "badlen");
20544 			goto discard_pkt;
20545 		}
20546 		if (v_hlen > (mp->b_wptr - rptr)) {
20547 			if (!pullupmsg(mp, v_hlen)) {
20548 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20549 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20550 				goto discard_pkt;
20551 			}
20552 			ipha = (ipha_t *)mp->b_rptr;
20553 		}
20554 		/*
20555 		 * Move first entry from any source route into ipha_dst and
20556 		 * verify the options
20557 		 */
20558 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20559 		    zoneid, ipst)) {
20560 			ASSERT(xmit_ill == NULL);
20561 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20562 			if (attach_ill != NULL)
20563 				ill_refrele(attach_ill);
20564 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20565 			    "ip_wput_end: q %p (%S)", q, "badopts");
20566 			if (need_decref)
20567 				CONN_DEC_REF(connp);
20568 			return;
20569 		}
20570 	}
20571 	dst = ipha->ipha_dst;
20572 
20573 	/*
20574 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20575 	 * we have to run the packet through ip_newroute which will take
20576 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20577 	 * a resolver, or assigning a default gateway, etc.
20578 	 */
20579 	if (CLASSD(dst)) {
20580 		ipif_t	*ipif;
20581 		uint32_t setsrc = 0;
20582 
20583 multicast:
20584 		ASSERT(first_mp != NULL);
20585 		ip2dbg(("ip_wput: CLASSD\n"));
20586 		if (connp == NULL) {
20587 			/*
20588 			 * Use the first good ipif on the ill.
20589 			 * XXX Should this ever happen? (Appears
20590 			 * to show up with just ppp and no ethernet due
20591 			 * to in.rdisc.)
20592 			 * However, ire_send should be able to
20593 			 * call ip_wput_ire directly.
20594 			 *
20595 			 * XXX Also, this can happen for ICMP and other packets
20596 			 * with multicast source addresses.  Perhaps we should
20597 			 * fix things so that we drop the packet in question,
20598 			 * but for now, just run with it.
20599 			 */
20600 			ill_t *ill = (ill_t *)q->q_ptr;
20601 
20602 			/*
20603 			 * Don't honor attach_if for this case. If ill
20604 			 * is part of the group, ipif could belong to
20605 			 * any ill and we cannot maintain attach_ill
20606 			 * and ipif_ill same anymore and the assert
20607 			 * below would fail.
20608 			 */
20609 			if (mctl_present && io->ipsec_out_attach_if) {
20610 				io->ipsec_out_ill_index = 0;
20611 				io->ipsec_out_attach_if = B_FALSE;
20612 				ASSERT(attach_ill != NULL);
20613 				ill_refrele(attach_ill);
20614 				attach_ill = NULL;
20615 			}
20616 
20617 			ASSERT(attach_ill == NULL);
20618 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20619 			if (ipif == NULL) {
20620 				if (need_decref)
20621 					CONN_DEC_REF(connp);
20622 				freemsg(first_mp);
20623 				return;
20624 			}
20625 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20626 			    ntohl(dst), ill->ill_name));
20627 		} else {
20628 			/*
20629 			 * The order of precedence is IP_XMIT_IF, IP_PKTINFO
20630 			 * and IP_MULTICAST_IF.
20631 			 * Block comment above this function explains the
20632 			 * locking mechanism used here
20633 			 */
20634 			if (xmit_ill == NULL) {
20635 				xmit_ill = conn_get_held_ill(connp,
20636 				    &connp->conn_xmit_if_ill, &err);
20637 				if (err == ILL_LOOKUP_FAILED) {
20638 					ip1dbg(("ip_wput: No ill for "
20639 					    "IP_XMIT_IF\n"));
20640 					BUMP_MIB(&ipst->ips_ip_mib,
20641 					    ipIfStatsOutNoRoutes);
20642 					goto drop_pkt;
20643 				}
20644 			}
20645 
20646 			if (xmit_ill == NULL) {
20647 				ipif = conn_get_held_ipif(connp,
20648 				    &connp->conn_multicast_ipif, &err);
20649 				if (err == IPIF_LOOKUP_FAILED) {
20650 					ip1dbg(("ip_wput: No ipif for "
20651 					    "multicast\n"));
20652 					BUMP_MIB(&ipst->ips_ip_mib,
20653 					    ipIfStatsOutNoRoutes);
20654 					goto drop_pkt;
20655 				}
20656 			}
20657 			if (xmit_ill != NULL) {
20658 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20659 				if (ipif == NULL) {
20660 					ip1dbg(("ip_wput: No ipif for "
20661 					    "IP_XMIT_IF\n"));
20662 					BUMP_MIB(&ipst->ips_ip_mib,
20663 					    ipIfStatsOutNoRoutes);
20664 					goto drop_pkt;
20665 				}
20666 			} else if (ipif == NULL || ipif->ipif_isv6) {
20667 				/*
20668 				 * We must do this ipif determination here
20669 				 * else we could pass through ip_newroute
20670 				 * and come back here without the conn context.
20671 				 *
20672 				 * Note: we do late binding i.e. we bind to
20673 				 * the interface when the first packet is sent.
20674 				 * For performance reasons we do not rebind on
20675 				 * each packet but keep the binding until the
20676 				 * next IP_MULTICAST_IF option.
20677 				 *
20678 				 * conn_multicast_{ipif,ill} are shared between
20679 				 * IPv4 and IPv6 and AF_INET6 sockets can
20680 				 * send both IPv4 and IPv6 packets. Hence
20681 				 * we have to check that "isv6" matches above.
20682 				 */
20683 				if (ipif != NULL)
20684 					ipif_refrele(ipif);
20685 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20686 				if (ipif == NULL) {
20687 					ip1dbg(("ip_wput: No ipif for "
20688 					    "multicast\n"));
20689 					BUMP_MIB(&ipst->ips_ip_mib,
20690 					    ipIfStatsOutNoRoutes);
20691 					goto drop_pkt;
20692 				}
20693 				err = conn_set_held_ipif(connp,
20694 				    &connp->conn_multicast_ipif, ipif);
20695 				if (err == IPIF_LOOKUP_FAILED) {
20696 					ipif_refrele(ipif);
20697 					ip1dbg(("ip_wput: No ipif for "
20698 					    "multicast\n"));
20699 					BUMP_MIB(&ipst->ips_ip_mib,
20700 					    ipIfStatsOutNoRoutes);
20701 					goto drop_pkt;
20702 				}
20703 			}
20704 		}
20705 		ASSERT(!ipif->ipif_isv6);
20706 		/*
20707 		 * As we may lose the conn by the time we reach ip_wput_ire,
20708 		 * we copy conn_multicast_loop and conn_dontroute on to an
20709 		 * ipsec_out. In case if this datagram goes out secure,
20710 		 * we need the ill_index also. Copy that also into the
20711 		 * ipsec_out.
20712 		 */
20713 		if (mctl_present) {
20714 			io = (ipsec_out_t *)first_mp->b_rptr;
20715 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20716 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20717 		} else {
20718 			ASSERT(mp == first_mp);
20719 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20720 			    BPRI_HI)) == NULL) {
20721 				ipif_refrele(ipif);
20722 				first_mp = mp;
20723 				goto discard_pkt;
20724 			}
20725 			first_mp->b_datap->db_type = M_CTL;
20726 			first_mp->b_wptr += sizeof (ipsec_info_t);
20727 			/* ipsec_out_secure is B_FALSE now */
20728 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20729 			io = (ipsec_out_t *)first_mp->b_rptr;
20730 			io->ipsec_out_type = IPSEC_OUT;
20731 			io->ipsec_out_len = sizeof (ipsec_out_t);
20732 			io->ipsec_out_use_global_policy = B_TRUE;
20733 			io->ipsec_out_ns = ipst->ips_netstack;
20734 			first_mp->b_cont = mp;
20735 			mctl_present = B_TRUE;
20736 		}
20737 		if (attach_ill != NULL) {
20738 			ASSERT(attach_ill == ipif->ipif_ill);
20739 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20740 
20741 			/*
20742 			 * Check if we need an ire that will not be
20743 			 * looked up by anybody else i.e. HIDDEN.
20744 			 */
20745 			if (ill_is_probeonly(attach_ill)) {
20746 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20747 			}
20748 			io->ipsec_out_ill_index =
20749 			    attach_ill->ill_phyint->phyint_ifindex;
20750 			io->ipsec_out_attach_if = B_TRUE;
20751 		} else {
20752 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
20753 			io->ipsec_out_ill_index =
20754 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
20755 		}
20756 		if (connp != NULL) {
20757 			io->ipsec_out_multicast_loop =
20758 			    connp->conn_multicast_loop;
20759 			io->ipsec_out_dontroute = connp->conn_dontroute;
20760 			io->ipsec_out_zoneid = connp->conn_zoneid;
20761 		}
20762 		/*
20763 		 * If the application uses IP_MULTICAST_IF with
20764 		 * different logical addresses of the same ILL, we
20765 		 * need to make sure that the soruce address of
20766 		 * the packet matches the logical IP address used
20767 		 * in the option. We do it by initializing ipha_src
20768 		 * here. This should keep IPSEC also happy as
20769 		 * when we return from IPSEC processing, we don't
20770 		 * have to worry about getting the right address on
20771 		 * the packet. Thus it is sufficient to look for
20772 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
20773 		 * MATCH_IRE_IPIF.
20774 		 *
20775 		 * NOTE : We need to do it for non-secure case also as
20776 		 * this might go out secure if there is a global policy
20777 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
20778 		 * address, the source should be initialized already and
20779 		 * hence we won't be initializing here.
20780 		 *
20781 		 * As we do not have the ire yet, it is possible that
20782 		 * we set the source address here and then later discover
20783 		 * that the ire implies the source address to be assigned
20784 		 * through the RTF_SETSRC flag.
20785 		 * In that case, the setsrc variable will remind us
20786 		 * that overwritting the source address by the one
20787 		 * of the RTF_SETSRC-flagged ire is allowed.
20788 		 */
20789 		if (ipha->ipha_src == INADDR_ANY &&
20790 		    (connp == NULL || !connp->conn_unspec_src)) {
20791 			ipha->ipha_src = ipif->ipif_src_addr;
20792 			setsrc = RTF_SETSRC;
20793 		}
20794 		/*
20795 		 * Find an IRE which matches the destination and the outgoing
20796 		 * queue (i.e. the outgoing interface.)
20797 		 * For loopback use a unicast IP address for
20798 		 * the ire lookup.
20799 		 */
20800 		if (IS_LOOPBACK(ipif->ipif_ill))
20801 			dst = ipif->ipif_lcl_addr;
20802 
20803 		/*
20804 		 * If IP_XMIT_IF is set, we branch out to ip_newroute_ipif.
20805 		 * We don't need to lookup ire in ctable as the packet
20806 		 * needs to be sent to the destination through the specified
20807 		 * ill irrespective of ires in the cache table.
20808 		 */
20809 		ire = NULL;
20810 		if (xmit_ill == NULL) {
20811 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
20812 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
20813 		}
20814 
20815 		/*
20816 		 * refrele attach_ill as its not needed anymore.
20817 		 */
20818 		if (attach_ill != NULL) {
20819 			ill_refrele(attach_ill);
20820 			attach_ill = NULL;
20821 		}
20822 
20823 		if (ire == NULL) {
20824 			/*
20825 			 * Multicast loopback and multicast forwarding is
20826 			 * done in ip_wput_ire.
20827 			 *
20828 			 * Mark this packet to make it be delivered to
20829 			 * ip_wput_ire after the new ire has been
20830 			 * created.
20831 			 *
20832 			 * The call to ip_newroute_ipif takes into account
20833 			 * the setsrc reminder. In any case, we take care
20834 			 * of the RTF_MULTIRT flag.
20835 			 */
20836 			mp->b_prev = mp->b_next = NULL;
20837 			if (xmit_ill == NULL ||
20838 			    xmit_ill->ill_ipif_up_count > 0) {
20839 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
20840 				    setsrc | RTF_MULTIRT, zoneid, infop);
20841 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20842 				    "ip_wput_end: q %p (%S)", q, "noire");
20843 			} else {
20844 				freemsg(first_mp);
20845 			}
20846 			ipif_refrele(ipif);
20847 			if (xmit_ill != NULL)
20848 				ill_refrele(xmit_ill);
20849 			if (need_decref)
20850 				CONN_DEC_REF(connp);
20851 			return;
20852 		}
20853 
20854 		ipif_refrele(ipif);
20855 		ipif = NULL;
20856 		ASSERT(xmit_ill == NULL);
20857 
20858 		/*
20859 		 * Honor the RTF_SETSRC flag for multicast packets,
20860 		 * if allowed by the setsrc reminder.
20861 		 */
20862 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
20863 			ipha->ipha_src = ire->ire_src_addr;
20864 		}
20865 
20866 		/*
20867 		 * Unconditionally force the TTL to 1 for
20868 		 * multirouted multicast packets:
20869 		 * multirouted multicast should not cross
20870 		 * multicast routers.
20871 		 */
20872 		if (ire->ire_flags & RTF_MULTIRT) {
20873 			if (ipha->ipha_ttl > 1) {
20874 				ip2dbg(("ip_wput: forcing multicast "
20875 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
20876 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
20877 				ipha->ipha_ttl = 1;
20878 			}
20879 		}
20880 	} else {
20881 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20882 		if ((ire != NULL) && (ire->ire_type &
20883 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
20884 			ignore_dontroute = B_TRUE;
20885 			ignore_nexthop = B_TRUE;
20886 		}
20887 		if (ire != NULL) {
20888 			ire_refrele(ire);
20889 			ire = NULL;
20890 		}
20891 		/*
20892 		 * Guard against coming in from arp in which case conn is NULL.
20893 		 * Also guard against non M_DATA with dontroute set but
20894 		 * destined to local, loopback or broadcast addresses.
20895 		 */
20896 		if (connp != NULL && connp->conn_dontroute &&
20897 		    !ignore_dontroute) {
20898 dontroute:
20899 			/*
20900 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
20901 			 * routing protocols from seeing false direct
20902 			 * connectivity.
20903 			 */
20904 			ipha->ipha_ttl = 1;
20905 			/*
20906 			 * If IP_XMIT_IF is also set (conn_xmit_if_ill != NULL)
20907 			 * along with SO_DONTROUTE, higher precedence is
20908 			 * given to IP_XMIT_IF and the IP_XMIT_IF ipif is used.
20909 			 */
20910 			if (connp->conn_xmit_if_ill == NULL) {
20911 				/* If suitable ipif not found, drop packet */
20912 				dst_ipif = ipif_lookup_onlink_addr(dst, zoneid,
20913 				    ipst);
20914 				if (dst_ipif == NULL) {
20915 					ip1dbg(("ip_wput: no route for "
20916 					    "dst using SO_DONTROUTE\n"));
20917 					BUMP_MIB(&ipst->ips_ip_mib,
20918 					    ipIfStatsOutNoRoutes);
20919 					mp->b_prev = mp->b_next = NULL;
20920 					if (first_mp == NULL)
20921 						first_mp = mp;
20922 					goto drop_pkt;
20923 				} else {
20924 					/*
20925 					 * If suitable ipif has been found, set
20926 					 * xmit_ill to the corresponding
20927 					 * ipif_ill because we'll be following
20928 					 * the IP_XMIT_IF logic.
20929 					 */
20930 					ASSERT(xmit_ill == NULL);
20931 					xmit_ill = dst_ipif->ipif_ill;
20932 					mutex_enter(&xmit_ill->ill_lock);
20933 					if (!ILL_CAN_LOOKUP(xmit_ill)) {
20934 						mutex_exit(&xmit_ill->ill_lock);
20935 						xmit_ill = NULL;
20936 						ipif_refrele(dst_ipif);
20937 						ip1dbg(("ip_wput: no route for"
20938 						    " dst using"
20939 						    " SO_DONTROUTE\n"));
20940 						BUMP_MIB(&ipst->ips_ip_mib,
20941 						    ipIfStatsOutNoRoutes);
20942 						mp->b_prev = mp->b_next = NULL;
20943 						if (first_mp == NULL)
20944 							first_mp = mp;
20945 						goto drop_pkt;
20946 					}
20947 					ill_refhold_locked(xmit_ill);
20948 					mutex_exit(&xmit_ill->ill_lock);
20949 					ipif_refrele(dst_ipif);
20950 				}
20951 			}
20952 
20953 		}
20954 		/*
20955 		 * If we are bound to IPIF_NOFAILOVER address, look for
20956 		 * an IRE_CACHE matching the ill.
20957 		 */
20958 send_from_ill:
20959 		if (attach_ill != NULL) {
20960 			ipif_t	*attach_ipif;
20961 
20962 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
20963 
20964 			/*
20965 			 * Check if we need an ire that will not be
20966 			 * looked up by anybody else i.e. HIDDEN.
20967 			 */
20968 			if (ill_is_probeonly(attach_ill)) {
20969 				match_flags |= MATCH_IRE_MARK_HIDDEN;
20970 			}
20971 
20972 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
20973 			if (attach_ipif == NULL) {
20974 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
20975 				goto discard_pkt;
20976 			}
20977 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
20978 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
20979 			ipif_refrele(attach_ipif);
20980 		} else if (xmit_ill != NULL || (connp != NULL &&
20981 		    connp->conn_xmit_if_ill != NULL)) {
20982 			/*
20983 			 * Mark this packet as originated locally
20984 			 */
20985 			mp->b_prev = mp->b_next = NULL;
20986 			/*
20987 			 * xmit_ill could be NULL if SO_DONTROUTE
20988 			 * is also set.
20989 			 */
20990 			if (xmit_ill == NULL) {
20991 				xmit_ill = conn_get_held_ill(connp,
20992 				    &connp->conn_xmit_if_ill, &err);
20993 				if (err == ILL_LOOKUP_FAILED) {
20994 					BUMP_MIB(&ipst->ips_ip_mib,
20995 					    ipIfStatsOutDiscards);
20996 					if (need_decref)
20997 						CONN_DEC_REF(connp);
20998 					freemsg(first_mp);
20999 					return;
21000 				}
21001 				if (xmit_ill == NULL) {
21002 					if (connp->conn_dontroute)
21003 						goto dontroute;
21004 					goto send_from_ill;
21005 				}
21006 			}
21007 			/*
21008 			 * Could be SO_DONTROUTE case also.
21009 			 * check at least one interface is UP as
21010 			 * specified by this ILL
21011 			 */
21012 			if (xmit_ill->ill_ipif_up_count > 0) {
21013 				ipif_t *ipif;
21014 
21015 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21016 				if (ipif == NULL) {
21017 					ip1dbg(("ip_output: "
21018 					    "xmit_ill NULL ipif\n"));
21019 					goto drop_pkt;
21020 				}
21021 				/*
21022 				 * Look for a ire that is part of the group,
21023 				 * if found use it else call ip_newroute_ipif.
21024 				 * IPCL_ZONEID is not used for matching because
21025 				 * IP_ALLZONES option is valid only when the
21026 				 * ill is accessible from all zones i.e has a
21027 				 * valid ipif in all zones.
21028 				 */
21029 				match_flags = MATCH_IRE_ILL_GROUP |
21030 				    MATCH_IRE_SECATTR;
21031 				ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21032 				    MBLK_GETLABEL(mp), match_flags, ipst);
21033 				/*
21034 				 * If an ire exists use it or else create
21035 				 * an ire but don't add it to the cache.
21036 				 * Adding an ire may cause issues with
21037 				 * asymmetric routing.
21038 				 * In case of multiroute always act as if
21039 				 * ire does not exist.
21040 				 */
21041 				if (ire == NULL ||
21042 				    ire->ire_flags & RTF_MULTIRT) {
21043 					if (ire != NULL)
21044 						ire_refrele(ire);
21045 					ip_newroute_ipif(q, first_mp, ipif,
21046 					    dst, connp, 0, zoneid, infop);
21047 					ipif_refrele(ipif);
21048 					ip1dbg(("ip_wput: ip_unicast_if\n"));
21049 					ill_refrele(xmit_ill);
21050 					if (need_decref)
21051 						CONN_DEC_REF(connp);
21052 					return;
21053 				}
21054 				ipif_refrele(ipif);
21055 			} else {
21056 				goto drop_pkt;
21057 			}
21058 		} else if (ip_nexthop || (connp != NULL &&
21059 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21060 			if (!ip_nexthop) {
21061 				ip_nexthop = B_TRUE;
21062 				nexthop_addr = connp->conn_nexthop_v4;
21063 			}
21064 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21065 			    MATCH_IRE_GW;
21066 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21067 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21068 		} else {
21069 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21070 			    ipst);
21071 		}
21072 		if (!ire) {
21073 			/*
21074 			 * Make sure we don't load spread if this
21075 			 * is IPIF_NOFAILOVER case.
21076 			 */
21077 			if ((attach_ill != NULL) ||
21078 			    (ip_nexthop && !ignore_nexthop)) {
21079 				if (mctl_present) {
21080 					io = (ipsec_out_t *)first_mp->b_rptr;
21081 					ASSERT(first_mp->b_datap->db_type ==
21082 					    M_CTL);
21083 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21084 				} else {
21085 					ASSERT(mp == first_mp);
21086 					first_mp = allocb(
21087 					    sizeof (ipsec_info_t), BPRI_HI);
21088 					if (first_mp == NULL) {
21089 						first_mp = mp;
21090 						goto discard_pkt;
21091 					}
21092 					first_mp->b_datap->db_type = M_CTL;
21093 					first_mp->b_wptr +=
21094 					    sizeof (ipsec_info_t);
21095 					/* ipsec_out_secure is B_FALSE now */
21096 					bzero(first_mp->b_rptr,
21097 					    sizeof (ipsec_info_t));
21098 					io = (ipsec_out_t *)first_mp->b_rptr;
21099 					io->ipsec_out_type = IPSEC_OUT;
21100 					io->ipsec_out_len =
21101 					    sizeof (ipsec_out_t);
21102 					io->ipsec_out_use_global_policy =
21103 					    B_TRUE;
21104 					io->ipsec_out_ns = ipst->ips_netstack;
21105 					first_mp->b_cont = mp;
21106 					mctl_present = B_TRUE;
21107 				}
21108 				if (attach_ill != NULL) {
21109 					io->ipsec_out_ill_index = attach_ill->
21110 					    ill_phyint->phyint_ifindex;
21111 					io->ipsec_out_attach_if = B_TRUE;
21112 				} else {
21113 					io->ipsec_out_ip_nexthop = ip_nexthop;
21114 					io->ipsec_out_nexthop_addr =
21115 					    nexthop_addr;
21116 				}
21117 			}
21118 noirefound:
21119 			/*
21120 			 * Mark this packet as having originated on
21121 			 * this machine.  This will be noted in
21122 			 * ire_add_then_send, which needs to know
21123 			 * whether to run it back through ip_wput or
21124 			 * ip_rput following successful resolution.
21125 			 */
21126 			mp->b_prev = NULL;
21127 			mp->b_next = NULL;
21128 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21129 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21130 			    "ip_wput_end: q %p (%S)", q, "newroute");
21131 			if (attach_ill != NULL)
21132 				ill_refrele(attach_ill);
21133 			if (xmit_ill != NULL)
21134 				ill_refrele(xmit_ill);
21135 			if (need_decref)
21136 				CONN_DEC_REF(connp);
21137 			return;
21138 		}
21139 	}
21140 
21141 	/* We now know where we are going with it. */
21142 
21143 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21144 	    "ip_wput_end: q %p (%S)", q, "end");
21145 
21146 	/*
21147 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21148 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21149 	 */
21150 	if (ire->ire_flags & RTF_MULTIRT) {
21151 		/*
21152 		 * Force the TTL of multirouted packets if required.
21153 		 * The TTL of such packets is bounded by the
21154 		 * ip_multirt_ttl ndd variable.
21155 		 */
21156 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21157 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21158 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21159 			    "(was %d), dst 0x%08x\n",
21160 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21161 			    ntohl(ire->ire_addr)));
21162 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21163 		}
21164 		/*
21165 		 * At this point, we check to see if there are any pending
21166 		 * unresolved routes. ire_multirt_resolvable()
21167 		 * checks in O(n) that all IRE_OFFSUBNET ire
21168 		 * entries for the packet's destination and
21169 		 * flagged RTF_MULTIRT are currently resolved.
21170 		 * If some remain unresolved, we make a copy
21171 		 * of the current message. It will be used
21172 		 * to initiate additional route resolutions.
21173 		 */
21174 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21175 		    MBLK_GETLABEL(first_mp), ipst);
21176 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21177 		    "multirt_need_resolve %d, first_mp %p\n",
21178 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21179 		if (multirt_need_resolve) {
21180 			copy_mp = copymsg(first_mp);
21181 			if (copy_mp != NULL) {
21182 				MULTIRT_DEBUG_TAG(copy_mp);
21183 			}
21184 		}
21185 	}
21186 
21187 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21188 	/*
21189 	 * Try to resolve another multiroute if
21190 	 * ire_multirt_resolvable() deemed it necessary.
21191 	 * At this point, we need to distinguish
21192 	 * multicasts from other packets. For multicasts,
21193 	 * we call ip_newroute_ipif() and request that both
21194 	 * multirouting and setsrc flags are checked.
21195 	 */
21196 	if (copy_mp != NULL) {
21197 		if (CLASSD(dst)) {
21198 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21199 			if (ipif) {
21200 				ASSERT(infop->ip_opt_ill_index == 0);
21201 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21202 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21203 				ipif_refrele(ipif);
21204 			} else {
21205 				MULTIRT_DEBUG_UNTAG(copy_mp);
21206 				freemsg(copy_mp);
21207 				copy_mp = NULL;
21208 			}
21209 		} else {
21210 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21211 		}
21212 	}
21213 	if (attach_ill != NULL)
21214 		ill_refrele(attach_ill);
21215 	if (xmit_ill != NULL)
21216 		ill_refrele(xmit_ill);
21217 	if (need_decref)
21218 		CONN_DEC_REF(connp);
21219 	return;
21220 
21221 icmp_parameter_problem:
21222 	/* could not have originated externally */
21223 	ASSERT(mp->b_prev == NULL);
21224 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21225 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21226 		/* it's the IP header length that's in trouble */
21227 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21228 		first_mp = NULL;
21229 	}
21230 
21231 discard_pkt:
21232 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21233 drop_pkt:
21234 	ip1dbg(("ip_wput: dropped packet\n"));
21235 	if (ire != NULL)
21236 		ire_refrele(ire);
21237 	if (need_decref)
21238 		CONN_DEC_REF(connp);
21239 	freemsg(first_mp);
21240 	if (attach_ill != NULL)
21241 		ill_refrele(attach_ill);
21242 	if (xmit_ill != NULL)
21243 		ill_refrele(xmit_ill);
21244 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21245 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21246 }
21247 
21248 /*
21249  * If this is a conn_t queue, then we pass in the conn. This includes the
21250  * zoneid.
21251  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21252  * in which case we use the global zoneid since those are all part of
21253  * the global zone.
21254  */
21255 void
21256 ip_wput(queue_t *q, mblk_t *mp)
21257 {
21258 	if (CONN_Q(q))
21259 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21260 	else
21261 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21262 }
21263 
21264 /*
21265  *
21266  * The following rules must be observed when accessing any ipif or ill
21267  * that has been cached in the conn. Typically conn_nofailover_ill,
21268  * conn_xmit_if_ill, conn_multicast_ipif and conn_multicast_ill.
21269  *
21270  * Access: The ipif or ill pointed to from the conn can be accessed under
21271  * the protection of the conn_lock or after it has been refheld under the
21272  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21273  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21274  * The reason for this is that a concurrent unplumb could actually be
21275  * cleaning up these cached pointers by walking the conns and might have
21276  * finished cleaning up the conn in question. The macros check that an
21277  * unplumb has not yet started on the ipif or ill.
21278  *
21279  * Caching: An ipif or ill pointer may be cached in the conn only after
21280  * making sure that an unplumb has not started. So the caching is done
21281  * while holding both the conn_lock and the ill_lock and after using the
21282  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21283  * flag before starting the cleanup of conns.
21284  *
21285  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21286  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21287  * or a reference to the ipif or a reference to an ire that references the
21288  * ipif. An ipif does not change its ill except for failover/failback. Since
21289  * failover/failback happens only after bringing down the ipif and making sure
21290  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21291  * the above holds.
21292  */
21293 ipif_t *
21294 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21295 {
21296 	ipif_t	*ipif;
21297 	ill_t	*ill;
21298 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21299 
21300 	*err = 0;
21301 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21302 	mutex_enter(&connp->conn_lock);
21303 	ipif = *ipifp;
21304 	if (ipif != NULL) {
21305 		ill = ipif->ipif_ill;
21306 		mutex_enter(&ill->ill_lock);
21307 		if (IPIF_CAN_LOOKUP(ipif)) {
21308 			ipif_refhold_locked(ipif);
21309 			mutex_exit(&ill->ill_lock);
21310 			mutex_exit(&connp->conn_lock);
21311 			rw_exit(&ipst->ips_ill_g_lock);
21312 			return (ipif);
21313 		} else {
21314 			*err = IPIF_LOOKUP_FAILED;
21315 		}
21316 		mutex_exit(&ill->ill_lock);
21317 	}
21318 	mutex_exit(&connp->conn_lock);
21319 	rw_exit(&ipst->ips_ill_g_lock);
21320 	return (NULL);
21321 }
21322 
21323 ill_t *
21324 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21325 {
21326 	ill_t	*ill;
21327 
21328 	*err = 0;
21329 	mutex_enter(&connp->conn_lock);
21330 	ill = *illp;
21331 	if (ill != NULL) {
21332 		mutex_enter(&ill->ill_lock);
21333 		if (ILL_CAN_LOOKUP(ill)) {
21334 			ill_refhold_locked(ill);
21335 			mutex_exit(&ill->ill_lock);
21336 			mutex_exit(&connp->conn_lock);
21337 			return (ill);
21338 		} else {
21339 			*err = ILL_LOOKUP_FAILED;
21340 		}
21341 		mutex_exit(&ill->ill_lock);
21342 	}
21343 	mutex_exit(&connp->conn_lock);
21344 	return (NULL);
21345 }
21346 
21347 static int
21348 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21349 {
21350 	ill_t	*ill;
21351 
21352 	ill = ipif->ipif_ill;
21353 	mutex_enter(&connp->conn_lock);
21354 	mutex_enter(&ill->ill_lock);
21355 	if (IPIF_CAN_LOOKUP(ipif)) {
21356 		*ipifp = ipif;
21357 		mutex_exit(&ill->ill_lock);
21358 		mutex_exit(&connp->conn_lock);
21359 		return (0);
21360 	}
21361 	mutex_exit(&ill->ill_lock);
21362 	mutex_exit(&connp->conn_lock);
21363 	return (IPIF_LOOKUP_FAILED);
21364 }
21365 
21366 /*
21367  * This is called if the outbound datagram needs fragmentation.
21368  *
21369  * NOTE : This function does not ire_refrele the ire argument passed in.
21370  */
21371 static void
21372 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21373     ip_stack_t *ipst)
21374 {
21375 	ipha_t		*ipha;
21376 	mblk_t		*mp;
21377 	uint32_t	v_hlen_tos_len;
21378 	uint32_t	max_frag;
21379 	uint32_t	frag_flag;
21380 	boolean_t	dont_use;
21381 
21382 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21383 		mp = ipsec_mp->b_cont;
21384 	} else {
21385 		mp = ipsec_mp;
21386 	}
21387 
21388 	ipha = (ipha_t *)mp->b_rptr;
21389 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21390 
21391 #ifdef	_BIG_ENDIAN
21392 #define	V_HLEN	(v_hlen_tos_len >> 24)
21393 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21394 #else
21395 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21396 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21397 #endif
21398 
21399 #ifndef SPEED_BEFORE_SAFETY
21400 	/*
21401 	 * Check that ipha_length is consistent with
21402 	 * the mblk length
21403 	 */
21404 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21405 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21406 		    LENGTH, msgdsize(mp)));
21407 		freemsg(ipsec_mp);
21408 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21409 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21410 		    "packet length mismatch");
21411 		return;
21412 	}
21413 #endif
21414 	/*
21415 	 * Don't use frag_flag if pre-built packet or source
21416 	 * routed or if multicast (since multicast packets do not solicit
21417 	 * ICMP "packet too big" messages). Get the values of
21418 	 * max_frag and frag_flag atomically by acquiring the
21419 	 * ire_lock.
21420 	 */
21421 	mutex_enter(&ire->ire_lock);
21422 	max_frag = ire->ire_max_frag;
21423 	frag_flag = ire->ire_frag_flag;
21424 	mutex_exit(&ire->ire_lock);
21425 
21426 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21427 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21428 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21429 
21430 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21431 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21432 }
21433 
21434 /*
21435  * Used for deciding the MSS size for the upper layer. Thus
21436  * we need to check the outbound policy values in the conn.
21437  */
21438 int
21439 conn_ipsec_length(conn_t *connp)
21440 {
21441 	ipsec_latch_t *ipl;
21442 
21443 	ipl = connp->conn_latch;
21444 	if (ipl == NULL)
21445 		return (0);
21446 
21447 	if (ipl->ipl_out_policy == NULL)
21448 		return (0);
21449 
21450 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21451 }
21452 
21453 /*
21454  * Returns an estimate of the IPSEC headers size. This is used if
21455  * we don't want to call into IPSEC to get the exact size.
21456  */
21457 int
21458 ipsec_out_extra_length(mblk_t *ipsec_mp)
21459 {
21460 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21461 	ipsec_action_t *a;
21462 
21463 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21464 	if (!io->ipsec_out_secure)
21465 		return (0);
21466 
21467 	a = io->ipsec_out_act;
21468 
21469 	if (a == NULL) {
21470 		ASSERT(io->ipsec_out_policy != NULL);
21471 		a = io->ipsec_out_policy->ipsp_act;
21472 	}
21473 	ASSERT(a != NULL);
21474 
21475 	return (a->ipa_ovhd);
21476 }
21477 
21478 /*
21479  * Returns an estimate of the IPSEC headers size. This is used if
21480  * we don't want to call into IPSEC to get the exact size.
21481  */
21482 int
21483 ipsec_in_extra_length(mblk_t *ipsec_mp)
21484 {
21485 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21486 	ipsec_action_t *a;
21487 
21488 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21489 
21490 	a = ii->ipsec_in_action;
21491 	return (a == NULL ? 0 : a->ipa_ovhd);
21492 }
21493 
21494 /*
21495  * If there are any source route options, return the true final
21496  * destination. Otherwise, return the destination.
21497  */
21498 ipaddr_t
21499 ip_get_dst(ipha_t *ipha)
21500 {
21501 	ipoptp_t	opts;
21502 	uchar_t		*opt;
21503 	uint8_t		optval;
21504 	uint8_t		optlen;
21505 	ipaddr_t	dst;
21506 	uint32_t off;
21507 
21508 	dst = ipha->ipha_dst;
21509 
21510 	if (IS_SIMPLE_IPH(ipha))
21511 		return (dst);
21512 
21513 	for (optval = ipoptp_first(&opts, ipha);
21514 	    optval != IPOPT_EOL;
21515 	    optval = ipoptp_next(&opts)) {
21516 		opt = opts.ipoptp_cur;
21517 		optlen = opts.ipoptp_len;
21518 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21519 		switch (optval) {
21520 		case IPOPT_SSRR:
21521 		case IPOPT_LSRR:
21522 			off = opt[IPOPT_OFFSET];
21523 			/*
21524 			 * If one of the conditions is true, it means
21525 			 * end of options and dst already has the right
21526 			 * value.
21527 			 */
21528 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21529 				off = optlen - IP_ADDR_LEN;
21530 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21531 			}
21532 			return (dst);
21533 		default:
21534 			break;
21535 		}
21536 	}
21537 
21538 	return (dst);
21539 }
21540 
21541 mblk_t *
21542 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21543     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21544 {
21545 	ipsec_out_t	*io;
21546 	mblk_t		*first_mp;
21547 	boolean_t policy_present;
21548 	ip_stack_t	*ipst;
21549 	ipsec_stack_t	*ipss;
21550 
21551 	ASSERT(ire != NULL);
21552 	ipst = ire->ire_ipst;
21553 	ipss = ipst->ips_netstack->netstack_ipsec;
21554 
21555 	first_mp = mp;
21556 	if (mp->b_datap->db_type == M_CTL) {
21557 		io = (ipsec_out_t *)first_mp->b_rptr;
21558 		/*
21559 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21560 		 *
21561 		 * 1) There is per-socket policy (including cached global
21562 		 *    policy) or a policy on the IP-in-IP tunnel.
21563 		 * 2) There is no per-socket policy, but it is
21564 		 *    a multicast packet that needs to go out
21565 		 *    on a specific interface. This is the case
21566 		 *    where (ip_wput and ip_wput_multicast) attaches
21567 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21568 		 *
21569 		 * In case (2) we check with global policy to
21570 		 * see if there is a match and set the ill_index
21571 		 * appropriately so that we can lookup the ire
21572 		 * properly in ip_wput_ipsec_out.
21573 		 */
21574 
21575 		/*
21576 		 * ipsec_out_use_global_policy is set to B_FALSE
21577 		 * in ipsec_in_to_out(). Refer to that function for
21578 		 * details.
21579 		 */
21580 		if ((io->ipsec_out_latch == NULL) &&
21581 		    (io->ipsec_out_use_global_policy)) {
21582 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21583 			    ire, connp, unspec_src, zoneid));
21584 		}
21585 		if (!io->ipsec_out_secure) {
21586 			/*
21587 			 * If this is not a secure packet, drop
21588 			 * the IPSEC_OUT mp and treat it as a clear
21589 			 * packet. This happens when we are sending
21590 			 * a ICMP reply back to a clear packet. See
21591 			 * ipsec_in_to_out() for details.
21592 			 */
21593 			mp = first_mp->b_cont;
21594 			freeb(first_mp);
21595 		}
21596 		return (mp);
21597 	}
21598 	/*
21599 	 * See whether we need to attach a global policy here. We
21600 	 * don't depend on the conn (as it could be null) for deciding
21601 	 * what policy this datagram should go through because it
21602 	 * should have happened in ip_wput if there was some
21603 	 * policy. This normally happens for connections which are not
21604 	 * fully bound preventing us from caching policies in
21605 	 * ip_bind. Packets coming from the TCP listener/global queue
21606 	 * - which are non-hard_bound - could also be affected by
21607 	 * applying policy here.
21608 	 *
21609 	 * If this packet is coming from tcp global queue or listener,
21610 	 * we will be applying policy here.  This may not be *right*
21611 	 * if these packets are coming from the detached connection as
21612 	 * it could have gone in clear before. This happens only if a
21613 	 * TCP connection started when there is no policy and somebody
21614 	 * added policy before it became detached. Thus packets of the
21615 	 * detached connection could go out secure and the other end
21616 	 * would drop it because it will be expecting in clear. The
21617 	 * converse is not true i.e if somebody starts a TCP
21618 	 * connection and deletes the policy, all the packets will
21619 	 * still go out with the policy that existed before deleting
21620 	 * because ip_unbind sends up policy information which is used
21621 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21622 	 * TCP to attach a dummy IPSEC_OUT and set
21623 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21624 	 * affect performance for normal cases, we are not doing it.
21625 	 * Thus, set policy before starting any TCP connections.
21626 	 *
21627 	 * NOTE - We might apply policy even for a hard bound connection
21628 	 * - for which we cached policy in ip_bind - if somebody added
21629 	 * global policy after we inherited the policy in ip_bind.
21630 	 * This means that the packets that were going out in clear
21631 	 * previously would start going secure and hence get dropped
21632 	 * on the other side. To fix this, TCP attaches a dummy
21633 	 * ipsec_out and make sure that we don't apply global policy.
21634 	 */
21635 	if (ipha != NULL)
21636 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21637 	else
21638 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21639 	if (!policy_present)
21640 		return (mp);
21641 
21642 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21643 	    zoneid));
21644 }
21645 
21646 ire_t *
21647 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21648 {
21649 	ipaddr_t addr;
21650 	ire_t *save_ire;
21651 	irb_t *irb;
21652 	ill_group_t *illgrp;
21653 	int	err;
21654 
21655 	save_ire = ire;
21656 	addr = ire->ire_addr;
21657 
21658 	ASSERT(ire->ire_type == IRE_BROADCAST);
21659 
21660 	illgrp = connp->conn_outgoing_ill->ill_group;
21661 	if (illgrp == NULL) {
21662 		*conn_outgoing_ill = conn_get_held_ill(connp,
21663 		    &connp->conn_outgoing_ill, &err);
21664 		if (err == ILL_LOOKUP_FAILED) {
21665 			ire_refrele(save_ire);
21666 			return (NULL);
21667 		}
21668 		return (save_ire);
21669 	}
21670 	/*
21671 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21672 	 * If it is part of the group, we need to send on the ire
21673 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21674 	 * to this group. This is okay as IP_BOUND_IF really means
21675 	 * any ill in the group. We depend on the fact that the
21676 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21677 	 * if such an ire exists. This is possible only if you have
21678 	 * at least one ill in the group that has not failed.
21679 	 *
21680 	 * First get to the ire that matches the address and group.
21681 	 *
21682 	 * We don't look for an ire with a matching zoneid because a given zone
21683 	 * won't always have broadcast ires on all ills in the group.
21684 	 */
21685 	irb = ire->ire_bucket;
21686 	rw_enter(&irb->irb_lock, RW_READER);
21687 	if (ire->ire_marks & IRE_MARK_NORECV) {
21688 		/*
21689 		 * If the current zone only has an ire broadcast for this
21690 		 * address marked NORECV, the ire we want is ahead in the
21691 		 * bucket, so we look it up deliberately ignoring the zoneid.
21692 		 */
21693 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21694 			if (ire->ire_addr != addr)
21695 				continue;
21696 			/* skip over deleted ires */
21697 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21698 				continue;
21699 		}
21700 	}
21701 	while (ire != NULL) {
21702 		/*
21703 		 * If a new interface is coming up, we could end up
21704 		 * seeing the loopback ire and the non-loopback ire
21705 		 * may not have been added yet. So check for ire_stq
21706 		 */
21707 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21708 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21709 			break;
21710 		}
21711 		ire = ire->ire_next;
21712 	}
21713 	if (ire != NULL && ire->ire_addr == addr &&
21714 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21715 		IRE_REFHOLD(ire);
21716 		rw_exit(&irb->irb_lock);
21717 		ire_refrele(save_ire);
21718 		*conn_outgoing_ill = ire_to_ill(ire);
21719 		/*
21720 		 * Refhold the ill to make the conn_outgoing_ill
21721 		 * independent of the ire. ip_wput_ire goes in a loop
21722 		 * and may refrele the ire. Since we have an ire at this
21723 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21724 		 */
21725 		ill_refhold(*conn_outgoing_ill);
21726 		return (ire);
21727 	}
21728 	rw_exit(&irb->irb_lock);
21729 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21730 	/*
21731 	 * If we can't find a suitable ire, return the original ire.
21732 	 */
21733 	return (save_ire);
21734 }
21735 
21736 /*
21737  * This function does the ire_refrele of the ire passed in as the
21738  * argument. As this function looks up more ires i.e broadcast ires,
21739  * it needs to REFRELE them. Currently, for simplicity we don't
21740  * differentiate the one passed in and looked up here. We always
21741  * REFRELE.
21742  * IPQoS Notes:
21743  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21744  * IPSec packets are done in ipsec_out_process.
21745  *
21746  */
21747 void
21748 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21749     zoneid_t zoneid)
21750 {
21751 	ipha_t		*ipha;
21752 #define	rptr	((uchar_t *)ipha)
21753 	queue_t		*stq;
21754 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21755 	uint32_t	v_hlen_tos_len;
21756 	uint32_t	ttl_protocol;
21757 	ipaddr_t	src;
21758 	ipaddr_t	dst;
21759 	uint32_t	cksum;
21760 	ipaddr_t	orig_src;
21761 	ire_t		*ire1;
21762 	mblk_t		*next_mp;
21763 	uint_t		hlen;
21764 	uint16_t	*up;
21765 	uint32_t	max_frag = ire->ire_max_frag;
21766 	ill_t		*ill = ire_to_ill(ire);
21767 	int		clusterwide;
21768 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21769 	int		ipsec_len;
21770 	mblk_t		*first_mp;
21771 	ipsec_out_t	*io;
21772 	boolean_t	conn_dontroute;		/* conn value for multicast */
21773 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
21774 	boolean_t	multicast_forward;	/* Should we forward ? */
21775 	boolean_t	unspec_src;
21776 	ill_t		*conn_outgoing_ill = NULL;
21777 	ill_t		*ire_ill;
21778 	ill_t		*ire1_ill;
21779 	ill_t		*out_ill;
21780 	uint32_t 	ill_index = 0;
21781 	boolean_t	multirt_send = B_FALSE;
21782 	int		err;
21783 	ipxmit_state_t	pktxmit_state;
21784 	ip_stack_t	*ipst = ire->ire_ipst;
21785 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
21786 
21787 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
21788 	    "ip_wput_ire_start: q %p", q);
21789 
21790 	multicast_forward = B_FALSE;
21791 	unspec_src = (connp != NULL && connp->conn_unspec_src);
21792 
21793 	if (ire->ire_flags & RTF_MULTIRT) {
21794 		/*
21795 		 * Multirouting case. The bucket where ire is stored
21796 		 * probably holds other RTF_MULTIRT flagged ire
21797 		 * to the destination. In this call to ip_wput_ire,
21798 		 * we attempt to send the packet through all
21799 		 * those ires. Thus, we first ensure that ire is the
21800 		 * first RTF_MULTIRT ire in the bucket,
21801 		 * before walking the ire list.
21802 		 */
21803 		ire_t *first_ire;
21804 		irb_t *irb = ire->ire_bucket;
21805 		ASSERT(irb != NULL);
21806 
21807 		/* Make sure we do not omit any multiroute ire. */
21808 		IRB_REFHOLD(irb);
21809 		for (first_ire = irb->irb_ire;
21810 		    first_ire != NULL;
21811 		    first_ire = first_ire->ire_next) {
21812 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
21813 			    (first_ire->ire_addr == ire->ire_addr) &&
21814 			    !(first_ire->ire_marks &
21815 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
21816 				break;
21817 			}
21818 		}
21819 
21820 		if ((first_ire != NULL) && (first_ire != ire)) {
21821 			IRE_REFHOLD(first_ire);
21822 			ire_refrele(ire);
21823 			ire = first_ire;
21824 			ill = ire_to_ill(ire);
21825 		}
21826 		IRB_REFRELE(irb);
21827 	}
21828 
21829 	/*
21830 	 * conn_outgoing_ill is used only in the broadcast loop.
21831 	 * for performance we don't grab the mutexs in the fastpath
21832 	 */
21833 	if ((connp != NULL) &&
21834 	    (connp->conn_xmit_if_ill == NULL) &&
21835 	    (ire->ire_type == IRE_BROADCAST) &&
21836 	    ((connp->conn_nofailover_ill != NULL) ||
21837 	    (connp->conn_outgoing_ill != NULL))) {
21838 		/*
21839 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
21840 		 * option. So, see if this endpoint is bound to a
21841 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
21842 		 * that if the interface is failed, we will still send
21843 		 * the packet on the same ill which is what we want.
21844 		 */
21845 		conn_outgoing_ill = conn_get_held_ill(connp,
21846 		    &connp->conn_nofailover_ill, &err);
21847 		if (err == ILL_LOOKUP_FAILED) {
21848 			ire_refrele(ire);
21849 			freemsg(mp);
21850 			return;
21851 		}
21852 		if (conn_outgoing_ill == NULL) {
21853 			/*
21854 			 * Choose a good ill in the group to send the
21855 			 * packets on.
21856 			 */
21857 			ire = conn_set_outgoing_ill(connp, ire,
21858 			    &conn_outgoing_ill);
21859 			if (ire == NULL) {
21860 				freemsg(mp);
21861 				return;
21862 			}
21863 		}
21864 	}
21865 
21866 	if (mp->b_datap->db_type != M_CTL) {
21867 		ipha = (ipha_t *)mp->b_rptr;
21868 	} else {
21869 		io = (ipsec_out_t *)mp->b_rptr;
21870 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21871 		ASSERT(zoneid == io->ipsec_out_zoneid);
21872 		ASSERT(zoneid != ALL_ZONES);
21873 		ipha = (ipha_t *)mp->b_cont->b_rptr;
21874 		dst = ipha->ipha_dst;
21875 		/*
21876 		 * For the multicast case, ipsec_out carries conn_dontroute and
21877 		 * conn_multicast_loop as conn may not be available here. We
21878 		 * need this for multicast loopback and forwarding which is done
21879 		 * later in the code.
21880 		 */
21881 		if (CLASSD(dst)) {
21882 			conn_dontroute = io->ipsec_out_dontroute;
21883 			conn_multicast_loop = io->ipsec_out_multicast_loop;
21884 			/*
21885 			 * If conn_dontroute is not set or conn_multicast_loop
21886 			 * is set, we need to do forwarding/loopback. For
21887 			 * datagrams from ip_wput_multicast, conn_dontroute is
21888 			 * set to B_TRUE and conn_multicast_loop is set to
21889 			 * B_FALSE so that we neither do forwarding nor
21890 			 * loopback.
21891 			 */
21892 			if (!conn_dontroute || conn_multicast_loop)
21893 				multicast_forward = B_TRUE;
21894 		}
21895 	}
21896 
21897 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
21898 	    ire->ire_zoneid != ALL_ZONES) {
21899 		/*
21900 		 * When a zone sends a packet to another zone, we try to deliver
21901 		 * the packet under the same conditions as if the destination
21902 		 * was a real node on the network. To do so, we look for a
21903 		 * matching route in the forwarding table.
21904 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
21905 		 * ip_newroute() does.
21906 		 * Note that IRE_LOCAL are special, since they are used
21907 		 * when the zoneid doesn't match in some cases. This means that
21908 		 * we need to handle ipha_src differently since ire_src_addr
21909 		 * belongs to the receiving zone instead of the sending zone.
21910 		 * When ip_restrict_interzone_loopback is set, then
21911 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
21912 		 * for loopback between zones when the logical "Ethernet" would
21913 		 * have looped them back.
21914 		 */
21915 		ire_t *src_ire;
21916 
21917 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
21918 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
21919 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
21920 		if (src_ire != NULL &&
21921 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
21922 		    (!ipst->ips_ip_restrict_interzone_loopback ||
21923 		    ire_local_same_ill_group(ire, src_ire))) {
21924 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
21925 				ipha->ipha_src = src_ire->ire_src_addr;
21926 			ire_refrele(src_ire);
21927 		} else {
21928 			ire_refrele(ire);
21929 			if (conn_outgoing_ill != NULL)
21930 				ill_refrele(conn_outgoing_ill);
21931 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21932 			if (src_ire != NULL) {
21933 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
21934 					ire_refrele(src_ire);
21935 					freemsg(mp);
21936 					return;
21937 				}
21938 				ire_refrele(src_ire);
21939 			}
21940 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
21941 				/* Failed */
21942 				freemsg(mp);
21943 				return;
21944 			}
21945 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
21946 			    ipst);
21947 			return;
21948 		}
21949 	}
21950 
21951 	if (mp->b_datap->db_type == M_CTL ||
21952 	    ipss->ipsec_outbound_v4_policy_present) {
21953 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
21954 		    unspec_src, zoneid);
21955 		if (mp == NULL) {
21956 			ire_refrele(ire);
21957 			if (conn_outgoing_ill != NULL)
21958 				ill_refrele(conn_outgoing_ill);
21959 			return;
21960 		}
21961 	}
21962 
21963 	first_mp = mp;
21964 	ipsec_len = 0;
21965 
21966 	if (first_mp->b_datap->db_type == M_CTL) {
21967 		io = (ipsec_out_t *)first_mp->b_rptr;
21968 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
21969 		mp = first_mp->b_cont;
21970 		ipsec_len = ipsec_out_extra_length(first_mp);
21971 		ASSERT(ipsec_len >= 0);
21972 		/* We already picked up the zoneid from the M_CTL above */
21973 		ASSERT(zoneid == io->ipsec_out_zoneid);
21974 		ASSERT(zoneid != ALL_ZONES);
21975 
21976 		/*
21977 		 * Drop M_CTL here if IPsec processing is not needed.
21978 		 * (Non-IPsec use of M_CTL extracted any information it
21979 		 * needed above).
21980 		 */
21981 		if (ipsec_len == 0) {
21982 			freeb(first_mp);
21983 			first_mp = mp;
21984 		}
21985 	}
21986 
21987 	/*
21988 	 * Fast path for ip_wput_ire
21989 	 */
21990 
21991 	ipha = (ipha_t *)mp->b_rptr;
21992 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21993 	dst = ipha->ipha_dst;
21994 
21995 	/*
21996 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
21997 	 * if the socket is a SOCK_RAW type. The transport checksum should
21998 	 * be provided in the pre-built packet, so we don't need to compute it.
21999 	 * Also, other application set flags, like DF, should not be altered.
22000 	 * Other transport MUST pass down zero.
22001 	 */
22002 	ip_hdr_included = ipha->ipha_ident;
22003 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22004 
22005 	if (CLASSD(dst)) {
22006 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22007 		    ntohl(dst),
22008 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22009 		    ntohl(ire->ire_addr)));
22010 	}
22011 
22012 /* Macros to extract header fields from data already in registers */
22013 #ifdef	_BIG_ENDIAN
22014 #define	V_HLEN	(v_hlen_tos_len >> 24)
22015 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22016 #define	PROTO	(ttl_protocol & 0xFF)
22017 #else
22018 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22019 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22020 #define	PROTO	(ttl_protocol >> 8)
22021 #endif
22022 
22023 
22024 	orig_src = src = ipha->ipha_src;
22025 	/* (The loop back to "another" is explained down below.) */
22026 another:;
22027 	/*
22028 	 * Assign an ident value for this packet.  We assign idents on
22029 	 * a per destination basis out of the IRE.  There could be
22030 	 * other threads targeting the same destination, so we have to
22031 	 * arrange for a atomic increment.  Note that we use a 32-bit
22032 	 * atomic add because it has better performance than its
22033 	 * 16-bit sibling.
22034 	 *
22035 	 * If running in cluster mode and if the source address
22036 	 * belongs to a replicated service then vector through
22037 	 * cl_inet_ipident vector to allocate ip identifier
22038 	 * NOTE: This is a contract private interface with the
22039 	 * clustering group.
22040 	 */
22041 	clusterwide = 0;
22042 	if (cl_inet_ipident) {
22043 		ASSERT(cl_inet_isclusterwide);
22044 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22045 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22046 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22047 			    AF_INET, (uint8_t *)(uintptr_t)src,
22048 			    (uint8_t *)(uintptr_t)dst);
22049 			clusterwide = 1;
22050 		}
22051 	}
22052 	if (!clusterwide) {
22053 		ipha->ipha_ident =
22054 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22055 	}
22056 
22057 #ifndef _BIG_ENDIAN
22058 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22059 #endif
22060 
22061 	/*
22062 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22063 	 * This is needed to obey conn_unspec_src when packets go through
22064 	 * ip_newroute + arp.
22065 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22066 	 */
22067 	if (src == INADDR_ANY && !unspec_src) {
22068 		/*
22069 		 * Assign the appropriate source address from the IRE if none
22070 		 * was specified.
22071 		 */
22072 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22073 
22074 		/*
22075 		 * With IP multipathing, broadcast packets are sent on the ire
22076 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22077 		 * the group. However, this ire might not be in the same zone so
22078 		 * we can't always use its source address. We look for a
22079 		 * broadcast ire in the same group and in the right zone.
22080 		 */
22081 		if (ire->ire_type == IRE_BROADCAST &&
22082 		    ire->ire_zoneid != zoneid) {
22083 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22084 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22085 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22086 			if (src_ire != NULL) {
22087 				src = src_ire->ire_src_addr;
22088 				ire_refrele(src_ire);
22089 			} else {
22090 				ire_refrele(ire);
22091 				if (conn_outgoing_ill != NULL)
22092 					ill_refrele(conn_outgoing_ill);
22093 				freemsg(first_mp);
22094 				if (ill != NULL) {
22095 					BUMP_MIB(ill->ill_ip_mib,
22096 					    ipIfStatsOutDiscards);
22097 				} else {
22098 					BUMP_MIB(&ipst->ips_ip_mib,
22099 					    ipIfStatsOutDiscards);
22100 				}
22101 				return;
22102 			}
22103 		} else {
22104 			src = ire->ire_src_addr;
22105 		}
22106 
22107 		if (connp == NULL) {
22108 			ip1dbg(("ip_wput_ire: no connp and no src "
22109 			    "address for dst 0x%x, using src 0x%x\n",
22110 			    ntohl(dst),
22111 			    ntohl(src)));
22112 		}
22113 		ipha->ipha_src = src;
22114 	}
22115 	stq = ire->ire_stq;
22116 
22117 	/*
22118 	 * We only allow ire chains for broadcasts since there will
22119 	 * be multiple IRE_CACHE entries for the same multicast
22120 	 * address (one per ipif).
22121 	 */
22122 	next_mp = NULL;
22123 
22124 	/* broadcast packet */
22125 	if (ire->ire_type == IRE_BROADCAST)
22126 		goto broadcast;
22127 
22128 	/* loopback ? */
22129 	if (stq == NULL)
22130 		goto nullstq;
22131 
22132 	/* The ill_index for outbound ILL */
22133 	ill_index = Q_TO_INDEX(stq);
22134 
22135 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22136 	ttl_protocol = ((uint16_t *)ipha)[4];
22137 
22138 	/* pseudo checksum (do it in parts for IP header checksum) */
22139 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22140 
22141 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22142 		queue_t *dev_q = stq->q_next;
22143 
22144 		/* flow controlled */
22145 		if ((dev_q->q_next || dev_q->q_first) &&
22146 		    !canput(dev_q))
22147 			goto blocked;
22148 		if ((PROTO == IPPROTO_UDP) &&
22149 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22150 			hlen = (V_HLEN & 0xF) << 2;
22151 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22152 			if (*up != 0) {
22153 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22154 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22155 				/* Software checksum? */
22156 				if (DB_CKSUMFLAGS(mp) == 0) {
22157 					IP_STAT(ipst, ip_out_sw_cksum);
22158 					IP_STAT_UPDATE(ipst,
22159 					    ip_udp_out_sw_cksum_bytes,
22160 					    LENGTH - hlen);
22161 				}
22162 			}
22163 		}
22164 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22165 		hlen = (V_HLEN & 0xF) << 2;
22166 		if (PROTO == IPPROTO_TCP) {
22167 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22168 			/*
22169 			 * The packet header is processed once and for all, even
22170 			 * in the multirouting case. We disable hardware
22171 			 * checksum if the packet is multirouted, as it will be
22172 			 * replicated via several interfaces, and not all of
22173 			 * them may have this capability.
22174 			 */
22175 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22176 			    LENGTH, max_frag, ipsec_len, cksum);
22177 			/* Software checksum? */
22178 			if (DB_CKSUMFLAGS(mp) == 0) {
22179 				IP_STAT(ipst, ip_out_sw_cksum);
22180 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22181 				    LENGTH - hlen);
22182 			}
22183 		} else {
22184 			sctp_hdr_t	*sctph;
22185 
22186 			ASSERT(PROTO == IPPROTO_SCTP);
22187 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22188 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22189 			/*
22190 			 * Zero out the checksum field to ensure proper
22191 			 * checksum calculation.
22192 			 */
22193 			sctph->sh_chksum = 0;
22194 #ifdef	DEBUG
22195 			if (!skip_sctp_cksum)
22196 #endif
22197 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22198 		}
22199 	}
22200 
22201 	/*
22202 	 * If this is a multicast packet and originated from ip_wput
22203 	 * we need to do loopback and forwarding checks. If it comes
22204 	 * from ip_wput_multicast, we SHOULD not do this.
22205 	 */
22206 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22207 
22208 	/* checksum */
22209 	cksum += ttl_protocol;
22210 
22211 	/* fragment the packet */
22212 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22213 		goto fragmentit;
22214 	/*
22215 	 * Don't use frag_flag if packet is pre-built or source
22216 	 * routed or if multicast (since multicast packets do
22217 	 * not solicit ICMP "packet too big" messages).
22218 	 */
22219 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22220 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22221 	    !ip_source_route_included(ipha)) &&
22222 	    !CLASSD(ipha->ipha_dst))
22223 		ipha->ipha_fragment_offset_and_flags |=
22224 		    htons(ire->ire_frag_flag);
22225 
22226 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22227 		/* calculate IP header checksum */
22228 		cksum += ipha->ipha_ident;
22229 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22230 		cksum += ipha->ipha_fragment_offset_and_flags;
22231 
22232 		/* IP options present */
22233 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22234 		if (hlen)
22235 			goto checksumoptions;
22236 
22237 		/* calculate hdr checksum */
22238 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22239 		cksum = ~(cksum + (cksum >> 16));
22240 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22241 	}
22242 	if (ipsec_len != 0) {
22243 		/*
22244 		 * We will do the rest of the processing after
22245 		 * we come back from IPSEC in ip_wput_ipsec_out().
22246 		 */
22247 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22248 
22249 		io = (ipsec_out_t *)first_mp->b_rptr;
22250 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22251 		    ill_phyint->phyint_ifindex;
22252 
22253 		ipsec_out_process(q, first_mp, ire, ill_index);
22254 		ire_refrele(ire);
22255 		if (conn_outgoing_ill != NULL)
22256 			ill_refrele(conn_outgoing_ill);
22257 		return;
22258 	}
22259 
22260 	/*
22261 	 * In most cases, the emission loop below is entered only
22262 	 * once. Only in the case where the ire holds the
22263 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22264 	 * flagged ires in the bucket, and send the packet
22265 	 * through all crossed RTF_MULTIRT routes.
22266 	 */
22267 	if (ire->ire_flags & RTF_MULTIRT) {
22268 		multirt_send = B_TRUE;
22269 	}
22270 	do {
22271 		if (multirt_send) {
22272 			irb_t *irb;
22273 			/*
22274 			 * We are in a multiple send case, need to get
22275 			 * the next ire and make a duplicate of the packet.
22276 			 * ire1 holds here the next ire to process in the
22277 			 * bucket. If multirouting is expected,
22278 			 * any non-RTF_MULTIRT ire that has the
22279 			 * right destination address is ignored.
22280 			 */
22281 			irb = ire->ire_bucket;
22282 			ASSERT(irb != NULL);
22283 
22284 			IRB_REFHOLD(irb);
22285 			for (ire1 = ire->ire_next;
22286 			    ire1 != NULL;
22287 			    ire1 = ire1->ire_next) {
22288 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22289 					continue;
22290 				if (ire1->ire_addr != ire->ire_addr)
22291 					continue;
22292 				if (ire1->ire_marks &
22293 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22294 					continue;
22295 
22296 				/* Got one */
22297 				IRE_REFHOLD(ire1);
22298 				break;
22299 			}
22300 			IRB_REFRELE(irb);
22301 
22302 			if (ire1 != NULL) {
22303 				next_mp = copyb(mp);
22304 				if ((next_mp == NULL) ||
22305 				    ((mp->b_cont != NULL) &&
22306 				    ((next_mp->b_cont =
22307 				    dupmsg(mp->b_cont)) == NULL))) {
22308 					freemsg(next_mp);
22309 					next_mp = NULL;
22310 					ire_refrele(ire1);
22311 					ire1 = NULL;
22312 				}
22313 			}
22314 
22315 			/* Last multiroute ire; don't loop anymore. */
22316 			if (ire1 == NULL) {
22317 				multirt_send = B_FALSE;
22318 			}
22319 		}
22320 
22321 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22322 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22323 		    mblk_t *, mp);
22324 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22325 		    ipst->ips_ipv4firewall_physical_out,
22326 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, ipst);
22327 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22328 		if (mp == NULL)
22329 			goto release_ire_and_ill;
22330 
22331 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22332 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22333 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22334 		if ((pktxmit_state == SEND_FAILED) ||
22335 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22336 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22337 			    "- packet dropped\n"));
22338 release_ire_and_ill:
22339 			ire_refrele(ire);
22340 			if (next_mp != NULL) {
22341 				freemsg(next_mp);
22342 				ire_refrele(ire1);
22343 			}
22344 			if (conn_outgoing_ill != NULL)
22345 				ill_refrele(conn_outgoing_ill);
22346 			return;
22347 		}
22348 
22349 		if (CLASSD(dst)) {
22350 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22351 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22352 			    LENGTH);
22353 		}
22354 
22355 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22356 		    "ip_wput_ire_end: q %p (%S)",
22357 		    q, "last copy out");
22358 		IRE_REFRELE(ire);
22359 
22360 		if (multirt_send) {
22361 			ASSERT(ire1);
22362 			/*
22363 			 * Proceed with the next RTF_MULTIRT ire,
22364 			 * Also set up the send-to queue accordingly.
22365 			 */
22366 			ire = ire1;
22367 			ire1 = NULL;
22368 			stq = ire->ire_stq;
22369 			mp = next_mp;
22370 			next_mp = NULL;
22371 			ipha = (ipha_t *)mp->b_rptr;
22372 			ill_index = Q_TO_INDEX(stq);
22373 			ill = (ill_t *)stq->q_ptr;
22374 		}
22375 	} while (multirt_send);
22376 	if (conn_outgoing_ill != NULL)
22377 		ill_refrele(conn_outgoing_ill);
22378 	return;
22379 
22380 	/*
22381 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22382 	 */
22383 broadcast:
22384 	{
22385 		/*
22386 		 * Avoid broadcast storms by setting the ttl to 1
22387 		 * for broadcasts. This parameter can be set
22388 		 * via ndd, so make sure that for the SO_DONTROUTE
22389 		 * case that ipha_ttl is always set to 1.
22390 		 * In the event that we are replying to incoming
22391 		 * ICMP packets, conn could be NULL.
22392 		 */
22393 		if ((connp != NULL) && connp->conn_dontroute)
22394 			ipha->ipha_ttl = 1;
22395 		else
22396 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22397 
22398 		/*
22399 		 * Note that we are not doing a IRB_REFHOLD here.
22400 		 * Actually we don't care if the list changes i.e
22401 		 * if somebody deletes an IRE from the list while
22402 		 * we drop the lock, the next time we come around
22403 		 * ire_next will be NULL and hence we won't send
22404 		 * out multiple copies which is fine.
22405 		 */
22406 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22407 		ire1 = ire->ire_next;
22408 		if (conn_outgoing_ill != NULL) {
22409 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22410 				ASSERT(ire1 == ire->ire_next);
22411 				if (ire1 != NULL && ire1->ire_addr == dst) {
22412 					ire_refrele(ire);
22413 					ire = ire1;
22414 					IRE_REFHOLD(ire);
22415 					ire1 = ire->ire_next;
22416 					continue;
22417 				}
22418 				rw_exit(&ire->ire_bucket->irb_lock);
22419 				/* Did not find a matching ill */
22420 				ip1dbg(("ip_wput_ire: broadcast with no "
22421 				    "matching IP_BOUND_IF ill %s\n",
22422 				    conn_outgoing_ill->ill_name));
22423 				freemsg(first_mp);
22424 				if (ire != NULL)
22425 					ire_refrele(ire);
22426 				ill_refrele(conn_outgoing_ill);
22427 				return;
22428 			}
22429 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22430 			/*
22431 			 * If the next IRE has the same address and is not one
22432 			 * of the two copies that we need to send, try to see
22433 			 * whether this copy should be sent at all. This
22434 			 * assumes that we insert loopbacks first and then
22435 			 * non-loopbacks. This is acheived by inserting the
22436 			 * loopback always before non-loopback.
22437 			 * This is used to send a single copy of a broadcast
22438 			 * packet out all physical interfaces that have an
22439 			 * matching IRE_BROADCAST while also looping
22440 			 * back one copy (to ip_wput_local) for each
22441 			 * matching physical interface. However, we avoid
22442 			 * sending packets out different logical that match by
22443 			 * having ipif_up/ipif_down supress duplicate
22444 			 * IRE_BROADCASTS.
22445 			 *
22446 			 * This feature is currently used to get broadcasts
22447 			 * sent to multiple interfaces, when the broadcast
22448 			 * address being used applies to multiple interfaces.
22449 			 * For example, a whole net broadcast will be
22450 			 * replicated on every connected subnet of
22451 			 * the target net.
22452 			 *
22453 			 * Each zone has its own set of IRE_BROADCASTs, so that
22454 			 * we're able to distribute inbound packets to multiple
22455 			 * zones who share a broadcast address. We avoid looping
22456 			 * back outbound packets in different zones but on the
22457 			 * same ill, as the application would see duplicates.
22458 			 *
22459 			 * If the interfaces are part of the same group,
22460 			 * we would want to send only one copy out for
22461 			 * whole group.
22462 			 *
22463 			 * This logic assumes that ire_add_v4() groups the
22464 			 * IRE_BROADCAST entries so that those with the same
22465 			 * ire_addr and ill_group are kept together.
22466 			 */
22467 			ire_ill = ire->ire_ipif->ipif_ill;
22468 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22469 				if (ire_ill->ill_group != NULL &&
22470 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22471 					/*
22472 					 * If the current zone only has an ire
22473 					 * broadcast for this address marked
22474 					 * NORECV, the ire we want is ahead in
22475 					 * the bucket, so we look it up
22476 					 * deliberately ignoring the zoneid.
22477 					 */
22478 					for (ire1 = ire->ire_bucket->irb_ire;
22479 					    ire1 != NULL;
22480 					    ire1 = ire1->ire_next) {
22481 						ire1_ill =
22482 						    ire1->ire_ipif->ipif_ill;
22483 						if (ire1->ire_addr != dst)
22484 							continue;
22485 						/* skip over the current ire */
22486 						if (ire1 == ire)
22487 							continue;
22488 						/* skip over deleted ires */
22489 						if (ire1->ire_marks &
22490 						    IRE_MARK_CONDEMNED)
22491 							continue;
22492 						/*
22493 						 * non-loopback ire in our
22494 						 * group: use it for the next
22495 						 * pass in the loop
22496 						 */
22497 						if (ire1->ire_stq != NULL &&
22498 						    ire1_ill->ill_group ==
22499 						    ire_ill->ill_group)
22500 							break;
22501 					}
22502 				}
22503 			} else {
22504 				while (ire1 != NULL && ire1->ire_addr == dst) {
22505 					ire1_ill = ire1->ire_ipif->ipif_ill;
22506 					/*
22507 					 * We can have two broadcast ires on the
22508 					 * same ill in different zones; here
22509 					 * we'll send a copy of the packet on
22510 					 * each ill and the fanout code will
22511 					 * call conn_wantpacket() to check that
22512 					 * the zone has the broadcast address
22513 					 * configured on the ill. If the two
22514 					 * ires are in the same group we only
22515 					 * send one copy up.
22516 					 */
22517 					if (ire1_ill != ire_ill &&
22518 					    (ire1_ill->ill_group == NULL ||
22519 					    ire_ill->ill_group == NULL ||
22520 					    ire1_ill->ill_group !=
22521 					    ire_ill->ill_group)) {
22522 						break;
22523 					}
22524 					ire1 = ire1->ire_next;
22525 				}
22526 			}
22527 		}
22528 		ASSERT(multirt_send == B_FALSE);
22529 		if (ire1 != NULL && ire1->ire_addr == dst) {
22530 			if ((ire->ire_flags & RTF_MULTIRT) &&
22531 			    (ire1->ire_flags & RTF_MULTIRT)) {
22532 				/*
22533 				 * We are in the multirouting case.
22534 				 * The message must be sent at least
22535 				 * on both ires. These ires have been
22536 				 * inserted AFTER the standard ones
22537 				 * in ip_rt_add(). There are thus no
22538 				 * other ire entries for the destination
22539 				 * address in the rest of the bucket
22540 				 * that do not have the RTF_MULTIRT
22541 				 * flag. We don't process a copy
22542 				 * of the message here. This will be
22543 				 * done in the final sending loop.
22544 				 */
22545 				multirt_send = B_TRUE;
22546 			} else {
22547 				next_mp = ip_copymsg(first_mp);
22548 				if (next_mp != NULL)
22549 					IRE_REFHOLD(ire1);
22550 			}
22551 		}
22552 		rw_exit(&ire->ire_bucket->irb_lock);
22553 	}
22554 
22555 	if (stq) {
22556 		/*
22557 		 * A non-NULL send-to queue means this packet is going
22558 		 * out of this machine.
22559 		 */
22560 		out_ill = (ill_t *)stq->q_ptr;
22561 
22562 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22563 		ttl_protocol = ((uint16_t *)ipha)[4];
22564 		/*
22565 		 * We accumulate the pseudo header checksum in cksum.
22566 		 * This is pretty hairy code, so watch close.  One
22567 		 * thing to keep in mind is that UDP and TCP have
22568 		 * stored their respective datagram lengths in their
22569 		 * checksum fields.  This lines things up real nice.
22570 		 */
22571 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22572 		    (src >> 16) + (src & 0xFFFF);
22573 		/*
22574 		 * We assume the udp checksum field contains the
22575 		 * length, so to compute the pseudo header checksum,
22576 		 * all we need is the protocol number and src/dst.
22577 		 */
22578 		/* Provide the checksums for UDP and TCP. */
22579 		if ((PROTO == IPPROTO_TCP) &&
22580 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22581 			/* hlen gets the number of uchar_ts in the IP header */
22582 			hlen = (V_HLEN & 0xF) << 2;
22583 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22584 			IP_STAT(ipst, ip_out_sw_cksum);
22585 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22586 			    LENGTH - hlen);
22587 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22588 		} else if (PROTO == IPPROTO_SCTP &&
22589 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22590 			sctp_hdr_t	*sctph;
22591 
22592 			hlen = (V_HLEN & 0xF) << 2;
22593 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22594 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22595 			sctph->sh_chksum = 0;
22596 #ifdef	DEBUG
22597 			if (!skip_sctp_cksum)
22598 #endif
22599 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22600 		} else {
22601 			queue_t *dev_q = stq->q_next;
22602 
22603 			if ((dev_q->q_next || dev_q->q_first) &&
22604 			    !canput(dev_q)) {
22605 blocked:
22606 				ipha->ipha_ident = ip_hdr_included;
22607 				/*
22608 				 * If we don't have a conn to apply
22609 				 * backpressure, free the message.
22610 				 * In the ire_send path, we don't know
22611 				 * the position to requeue the packet. Rather
22612 				 * than reorder packets, we just drop this
22613 				 * packet.
22614 				 */
22615 				if (ipst->ips_ip_output_queue &&
22616 				    connp != NULL &&
22617 				    caller != IRE_SEND) {
22618 					if (caller == IP_WSRV) {
22619 						connp->conn_did_putbq = 1;
22620 						(void) putbq(connp->conn_wq,
22621 						    first_mp);
22622 						conn_drain_insert(connp);
22623 						/*
22624 						 * This is the service thread,
22625 						 * and the queue is already
22626 						 * noenabled. The check for
22627 						 * canput and the putbq is not
22628 						 * atomic. So we need to check
22629 						 * again.
22630 						 */
22631 						if (canput(stq->q_next))
22632 							connp->conn_did_putbq
22633 							    = 0;
22634 						IP_STAT(ipst, ip_conn_flputbq);
22635 					} else {
22636 						/*
22637 						 * We are not the service proc.
22638 						 * ip_wsrv will be scheduled or
22639 						 * is already running.
22640 						 */
22641 						(void) putq(connp->conn_wq,
22642 						    first_mp);
22643 					}
22644 				} else {
22645 					out_ill = (ill_t *)stq->q_ptr;
22646 					BUMP_MIB(out_ill->ill_ip_mib,
22647 					    ipIfStatsOutDiscards);
22648 					freemsg(first_mp);
22649 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22650 					    "ip_wput_ire_end: q %p (%S)",
22651 					    q, "discard");
22652 				}
22653 				ire_refrele(ire);
22654 				if (next_mp) {
22655 					ire_refrele(ire1);
22656 					freemsg(next_mp);
22657 				}
22658 				if (conn_outgoing_ill != NULL)
22659 					ill_refrele(conn_outgoing_ill);
22660 				return;
22661 			}
22662 			if ((PROTO == IPPROTO_UDP) &&
22663 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22664 				/*
22665 				 * hlen gets the number of uchar_ts in the
22666 				 * IP header
22667 				 */
22668 				hlen = (V_HLEN & 0xF) << 2;
22669 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22670 				max_frag = ire->ire_max_frag;
22671 				if (*up != 0) {
22672 					IP_CKSUM_XMIT(ire_ill, ire, mp, ipha,
22673 					    up, PROTO, hlen, LENGTH, max_frag,
22674 					    ipsec_len, cksum);
22675 					/* Software checksum? */
22676 					if (DB_CKSUMFLAGS(mp) == 0) {
22677 						IP_STAT(ipst, ip_out_sw_cksum);
22678 						IP_STAT_UPDATE(ipst,
22679 						    ip_udp_out_sw_cksum_bytes,
22680 						    LENGTH - hlen);
22681 					}
22682 				}
22683 			}
22684 		}
22685 		/*
22686 		 * Need to do this even when fragmenting. The local
22687 		 * loopback can be done without computing checksums
22688 		 * but forwarding out other interface must be done
22689 		 * after the IP checksum (and ULP checksums) have been
22690 		 * computed.
22691 		 *
22692 		 * NOTE : multicast_forward is set only if this packet
22693 		 * originated from ip_wput. For packets originating from
22694 		 * ip_wput_multicast, it is not set.
22695 		 */
22696 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22697 multi_loopback:
22698 			ip2dbg(("ip_wput: multicast, loop %d\n",
22699 			    conn_multicast_loop));
22700 
22701 			/*  Forget header checksum offload */
22702 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22703 
22704 			/*
22705 			 * Local loopback of multicasts?  Check the
22706 			 * ill.
22707 			 *
22708 			 * Note that the loopback function will not come
22709 			 * in through ip_rput - it will only do the
22710 			 * client fanout thus we need to do an mforward
22711 			 * as well.  The is different from the BSD
22712 			 * logic.
22713 			 */
22714 			if (ill != NULL) {
22715 				ilm_t	*ilm;
22716 
22717 				ILM_WALKER_HOLD(ill);
22718 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22719 				    ALL_ZONES);
22720 				ILM_WALKER_RELE(ill);
22721 				if (ilm != NULL) {
22722 					/*
22723 					 * Pass along the virtual output q.
22724 					 * ip_wput_local() will distribute the
22725 					 * packet to all the matching zones,
22726 					 * except the sending zone when
22727 					 * IP_MULTICAST_LOOP is false.
22728 					 */
22729 					ip_multicast_loopback(q, ill, first_mp,
22730 					    conn_multicast_loop ? 0 :
22731 					    IP_FF_NO_MCAST_LOOP, zoneid);
22732 				}
22733 			}
22734 			if (ipha->ipha_ttl == 0) {
22735 				/*
22736 				 * 0 => only to this host i.e. we are
22737 				 * done. We are also done if this was the
22738 				 * loopback interface since it is sufficient
22739 				 * to loopback one copy of a multicast packet.
22740 				 */
22741 				freemsg(first_mp);
22742 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22743 				    "ip_wput_ire_end: q %p (%S)",
22744 				    q, "loopback");
22745 				ire_refrele(ire);
22746 				if (conn_outgoing_ill != NULL)
22747 					ill_refrele(conn_outgoing_ill);
22748 				return;
22749 			}
22750 			/*
22751 			 * ILLF_MULTICAST is checked in ip_newroute
22752 			 * i.e. we don't need to check it here since
22753 			 * all IRE_CACHEs come from ip_newroute.
22754 			 * For multicast traffic, SO_DONTROUTE is interpreted
22755 			 * to mean only send the packet out the interface
22756 			 * (optionally specified with IP_MULTICAST_IF)
22757 			 * and do not forward it out additional interfaces.
22758 			 * RSVP and the rsvp daemon is an example of a
22759 			 * protocol and user level process that
22760 			 * handles it's own routing. Hence, it uses the
22761 			 * SO_DONTROUTE option to accomplish this.
22762 			 */
22763 
22764 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22765 			    ill != NULL) {
22766 				/* Unconditionally redo the checksum */
22767 				ipha->ipha_hdr_checksum = 0;
22768 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22769 
22770 				/*
22771 				 * If this needs to go out secure, we need
22772 				 * to wait till we finish the IPSEC
22773 				 * processing.
22774 				 */
22775 				if (ipsec_len == 0 &&
22776 				    ip_mforward(ill, ipha, mp)) {
22777 					freemsg(first_mp);
22778 					ip1dbg(("ip_wput: mforward failed\n"));
22779 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22780 					    "ip_wput_ire_end: q %p (%S)",
22781 					    q, "mforward failed");
22782 					ire_refrele(ire);
22783 					if (conn_outgoing_ill != NULL)
22784 						ill_refrele(conn_outgoing_ill);
22785 					return;
22786 				}
22787 			}
22788 		}
22789 		max_frag = ire->ire_max_frag;
22790 		cksum += ttl_protocol;
22791 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
22792 			/* No fragmentation required for this one. */
22793 			/*
22794 			 * Don't use frag_flag if packet is pre-built or source
22795 			 * routed or if multicast (since multicast packets do
22796 			 * not solicit ICMP "packet too big" messages).
22797 			 */
22798 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22799 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22800 			    !ip_source_route_included(ipha)) &&
22801 			    !CLASSD(ipha->ipha_dst))
22802 				ipha->ipha_fragment_offset_and_flags |=
22803 				    htons(ire->ire_frag_flag);
22804 
22805 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22806 				/* Complete the IP header checksum. */
22807 				cksum += ipha->ipha_ident;
22808 				cksum += (v_hlen_tos_len >> 16)+
22809 				    (v_hlen_tos_len & 0xFFFF);
22810 				cksum += ipha->ipha_fragment_offset_and_flags;
22811 				hlen = (V_HLEN & 0xF) -
22812 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22813 				if (hlen) {
22814 checksumoptions:
22815 					/*
22816 					 * Account for the IP Options in the IP
22817 					 * header checksum.
22818 					 */
22819 					up = (uint16_t *)(rptr+
22820 					    IP_SIMPLE_HDR_LENGTH);
22821 					do {
22822 						cksum += up[0];
22823 						cksum += up[1];
22824 						up += 2;
22825 					} while (--hlen);
22826 				}
22827 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22828 				cksum = ~(cksum + (cksum >> 16));
22829 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
22830 			}
22831 			if (ipsec_len != 0) {
22832 				ipsec_out_process(q, first_mp, ire, ill_index);
22833 				if (!next_mp) {
22834 					ire_refrele(ire);
22835 					if (conn_outgoing_ill != NULL)
22836 						ill_refrele(conn_outgoing_ill);
22837 					return;
22838 				}
22839 				goto next;
22840 			}
22841 
22842 			/*
22843 			 * multirt_send has already been handled
22844 			 * for broadcast, but not yet for multicast
22845 			 * or IP options.
22846 			 */
22847 			if (next_mp == NULL) {
22848 				if (ire->ire_flags & RTF_MULTIRT) {
22849 					multirt_send = B_TRUE;
22850 				}
22851 			}
22852 
22853 			/*
22854 			 * In most cases, the emission loop below is
22855 			 * entered only once. Only in the case where
22856 			 * the ire holds the RTF_MULTIRT flag, do we loop
22857 			 * to process all RTF_MULTIRT ires in the bucket,
22858 			 * and send the packet through all crossed
22859 			 * RTF_MULTIRT routes.
22860 			 */
22861 			do {
22862 				if (multirt_send) {
22863 					irb_t *irb;
22864 
22865 					irb = ire->ire_bucket;
22866 					ASSERT(irb != NULL);
22867 					/*
22868 					 * We are in a multiple send case,
22869 					 * need to get the next IRE and make
22870 					 * a duplicate of the packet.
22871 					 */
22872 					IRB_REFHOLD(irb);
22873 					for (ire1 = ire->ire_next;
22874 					    ire1 != NULL;
22875 					    ire1 = ire1->ire_next) {
22876 						if (!(ire1->ire_flags &
22877 						    RTF_MULTIRT)) {
22878 							continue;
22879 						}
22880 						if (ire1->ire_addr !=
22881 						    ire->ire_addr) {
22882 							continue;
22883 						}
22884 						if (ire1->ire_marks &
22885 						    (IRE_MARK_CONDEMNED|
22886 						    IRE_MARK_HIDDEN)) {
22887 							continue;
22888 						}
22889 
22890 						/* Got one */
22891 						IRE_REFHOLD(ire1);
22892 						break;
22893 					}
22894 					IRB_REFRELE(irb);
22895 
22896 					if (ire1 != NULL) {
22897 						next_mp = copyb(mp);
22898 						if ((next_mp == NULL) ||
22899 						    ((mp->b_cont != NULL) &&
22900 						    ((next_mp->b_cont =
22901 						    dupmsg(mp->b_cont))
22902 						    == NULL))) {
22903 							freemsg(next_mp);
22904 							next_mp = NULL;
22905 							ire_refrele(ire1);
22906 							ire1 = NULL;
22907 						}
22908 					}
22909 
22910 					/*
22911 					 * Last multiroute ire; don't loop
22912 					 * anymore. The emission is over
22913 					 * and next_mp is NULL.
22914 					 */
22915 					if (ire1 == NULL) {
22916 						multirt_send = B_FALSE;
22917 					}
22918 				}
22919 
22920 				out_ill = ire->ire_ipif->ipif_ill;
22921 				DTRACE_PROBE4(ip4__physical__out__start,
22922 				    ill_t *, NULL,
22923 				    ill_t *, out_ill,
22924 				    ipha_t *, ipha, mblk_t *, mp);
22925 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
22926 				    ipst->ips_ipv4firewall_physical_out,
22927 				    NULL, out_ill, ipha, mp, mp, ipst);
22928 				DTRACE_PROBE1(ip4__physical__out__end,
22929 				    mblk_t *, mp);
22930 				if (mp == NULL)
22931 					goto release_ire_and_ill_2;
22932 
22933 				ASSERT(ipsec_len == 0);
22934 				mp->b_prev =
22935 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
22936 				DTRACE_PROBE2(ip__xmit__2,
22937 				    mblk_t *, mp, ire_t *, ire);
22938 				pktxmit_state = ip_xmit_v4(mp, ire,
22939 				    NULL, B_TRUE);
22940 				if ((pktxmit_state == SEND_FAILED) ||
22941 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22942 release_ire_and_ill_2:
22943 					if (next_mp) {
22944 						freemsg(next_mp);
22945 						ire_refrele(ire1);
22946 					}
22947 					ire_refrele(ire);
22948 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22949 					    "ip_wput_ire_end: q %p (%S)",
22950 					    q, "discard MDATA");
22951 					if (conn_outgoing_ill != NULL)
22952 						ill_refrele(conn_outgoing_ill);
22953 					return;
22954 				}
22955 
22956 				if (CLASSD(dst)) {
22957 					BUMP_MIB(out_ill->ill_ip_mib,
22958 					    ipIfStatsHCOutMcastPkts);
22959 					UPDATE_MIB(out_ill->ill_ip_mib,
22960 					    ipIfStatsHCOutMcastOctets,
22961 					    LENGTH);
22962 				} else if (ire->ire_type == IRE_BROADCAST) {
22963 					BUMP_MIB(out_ill->ill_ip_mib,
22964 					    ipIfStatsHCOutBcastPkts);
22965 				}
22966 
22967 				if (multirt_send) {
22968 					/*
22969 					 * We are in a multiple send case,
22970 					 * need to re-enter the sending loop
22971 					 * using the next ire.
22972 					 */
22973 					ire_refrele(ire);
22974 					ire = ire1;
22975 					stq = ire->ire_stq;
22976 					mp = next_mp;
22977 					next_mp = NULL;
22978 					ipha = (ipha_t *)mp->b_rptr;
22979 					ill_index = Q_TO_INDEX(stq);
22980 				}
22981 			} while (multirt_send);
22982 
22983 			if (!next_mp) {
22984 				/*
22985 				 * Last copy going out (the ultra-common
22986 				 * case).  Note that we intentionally replicate
22987 				 * the putnext rather than calling it before
22988 				 * the next_mp check in hopes of a little
22989 				 * tail-call action out of the compiler.
22990 				 */
22991 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22992 				    "ip_wput_ire_end: q %p (%S)",
22993 				    q, "last copy out(1)");
22994 				ire_refrele(ire);
22995 				if (conn_outgoing_ill != NULL)
22996 					ill_refrele(conn_outgoing_ill);
22997 				return;
22998 			}
22999 			/* More copies going out below. */
23000 		} else {
23001 			int offset;
23002 fragmentit:
23003 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23004 			/*
23005 			 * If this would generate a icmp_frag_needed message,
23006 			 * we need to handle it before we do the IPSEC
23007 			 * processing. Otherwise, we need to strip the IPSEC
23008 			 * headers before we send up the message to the ULPs
23009 			 * which becomes messy and difficult.
23010 			 */
23011 			if (ipsec_len != 0) {
23012 				if ((max_frag < (unsigned int)(LENGTH +
23013 				    ipsec_len)) && (offset & IPH_DF)) {
23014 					out_ill = (ill_t *)stq->q_ptr;
23015 					BUMP_MIB(out_ill->ill_ip_mib,
23016 					    ipIfStatsOutFragFails);
23017 					BUMP_MIB(out_ill->ill_ip_mib,
23018 					    ipIfStatsOutFragReqds);
23019 					ipha->ipha_hdr_checksum = 0;
23020 					ipha->ipha_hdr_checksum =
23021 					    (uint16_t)ip_csum_hdr(ipha);
23022 					icmp_frag_needed(ire->ire_stq, first_mp,
23023 					    max_frag, zoneid, ipst);
23024 					if (!next_mp) {
23025 						ire_refrele(ire);
23026 						if (conn_outgoing_ill != NULL) {
23027 							ill_refrele(
23028 							    conn_outgoing_ill);
23029 						}
23030 						return;
23031 					}
23032 				} else {
23033 					/*
23034 					 * This won't cause a icmp_frag_needed
23035 					 * message. to be generated. Send it on
23036 					 * the wire. Note that this could still
23037 					 * cause fragmentation and all we
23038 					 * do is the generation of the message
23039 					 * to the ULP if needed before IPSEC.
23040 					 */
23041 					if (!next_mp) {
23042 						ipsec_out_process(q, first_mp,
23043 						    ire, ill_index);
23044 						TRACE_2(TR_FAC_IP,
23045 						    TR_IP_WPUT_IRE_END,
23046 						    "ip_wput_ire_end: q %p "
23047 						    "(%S)", q,
23048 						    "last ipsec_out_process");
23049 						ire_refrele(ire);
23050 						if (conn_outgoing_ill != NULL) {
23051 							ill_refrele(
23052 							    conn_outgoing_ill);
23053 						}
23054 						return;
23055 					}
23056 					ipsec_out_process(q, first_mp,
23057 					    ire, ill_index);
23058 				}
23059 			} else {
23060 				/*
23061 				 * Initiate IPPF processing. For
23062 				 * fragmentable packets we finish
23063 				 * all QOS packet processing before
23064 				 * calling:
23065 				 * ip_wput_ire_fragmentit->ip_wput_frag
23066 				 */
23067 
23068 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23069 					ip_process(IPP_LOCAL_OUT, &mp,
23070 					    ill_index);
23071 					if (mp == NULL) {
23072 						out_ill = (ill_t *)stq->q_ptr;
23073 						BUMP_MIB(out_ill->ill_ip_mib,
23074 						    ipIfStatsOutDiscards);
23075 						if (next_mp != NULL) {
23076 							freemsg(next_mp);
23077 							ire_refrele(ire1);
23078 						}
23079 						ire_refrele(ire);
23080 						TRACE_2(TR_FAC_IP,
23081 						    TR_IP_WPUT_IRE_END,
23082 						    "ip_wput_ire: q %p (%S)",
23083 						    q, "discard MDATA");
23084 						if (conn_outgoing_ill != NULL) {
23085 							ill_refrele(
23086 							    conn_outgoing_ill);
23087 						}
23088 						return;
23089 					}
23090 				}
23091 				if (!next_mp) {
23092 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23093 					    "ip_wput_ire_end: q %p (%S)",
23094 					    q, "last fragmentation");
23095 					ip_wput_ire_fragmentit(mp, ire,
23096 					    zoneid, ipst);
23097 					ire_refrele(ire);
23098 					if (conn_outgoing_ill != NULL)
23099 						ill_refrele(conn_outgoing_ill);
23100 					return;
23101 				}
23102 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23103 			}
23104 		}
23105 	} else {
23106 nullstq:
23107 		/* A NULL stq means the destination address is local. */
23108 		UPDATE_OB_PKT_COUNT(ire);
23109 		ire->ire_last_used_time = lbolt;
23110 		ASSERT(ire->ire_ipif != NULL);
23111 		if (!next_mp) {
23112 			/*
23113 			 * Is there an "in" and "out" for traffic local
23114 			 * to a host (loopback)?  The code in Solaris doesn't
23115 			 * explicitly draw a line in its code for in vs out,
23116 			 * so we've had to draw a line in the sand: ip_wput_ire
23117 			 * is considered to be the "output" side and
23118 			 * ip_wput_local to be the "input" side.
23119 			 */
23120 			out_ill = ire->ire_ipif->ipif_ill;
23121 
23122 			DTRACE_PROBE4(ip4__loopback__out__start,
23123 			    ill_t *, NULL, ill_t *, out_ill,
23124 			    ipha_t *, ipha, mblk_t *, first_mp);
23125 
23126 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23127 			    ipst->ips_ipv4firewall_loopback_out,
23128 			    NULL, out_ill, ipha, first_mp, mp, ipst);
23129 
23130 			DTRACE_PROBE1(ip4__loopback__out_end,
23131 			    mblk_t *, first_mp);
23132 
23133 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23134 			    "ip_wput_ire_end: q %p (%S)",
23135 			    q, "local address");
23136 
23137 			if (first_mp != NULL)
23138 				ip_wput_local(q, out_ill, ipha,
23139 				    first_mp, ire, 0, ire->ire_zoneid);
23140 			ire_refrele(ire);
23141 			if (conn_outgoing_ill != NULL)
23142 				ill_refrele(conn_outgoing_ill);
23143 			return;
23144 		}
23145 
23146 		out_ill = ire->ire_ipif->ipif_ill;
23147 
23148 		DTRACE_PROBE4(ip4__loopback__out__start,
23149 		    ill_t *, NULL, ill_t *, out_ill,
23150 		    ipha_t *, ipha, mblk_t *, first_mp);
23151 
23152 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23153 		    ipst->ips_ipv4firewall_loopback_out,
23154 		    NULL, out_ill, ipha, first_mp, mp, ipst);
23155 
23156 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23157 
23158 		if (first_mp != NULL)
23159 			ip_wput_local(q, out_ill, ipha,
23160 			    first_mp, ire, 0, ire->ire_zoneid);
23161 	}
23162 next:
23163 	/*
23164 	 * More copies going out to additional interfaces.
23165 	 * ire1 has already been held. We don't need the
23166 	 * "ire" anymore.
23167 	 */
23168 	ire_refrele(ire);
23169 	ire = ire1;
23170 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23171 	mp = next_mp;
23172 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23173 	ill = ire_to_ill(ire);
23174 	first_mp = mp;
23175 	if (ipsec_len != 0) {
23176 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23177 		mp = mp->b_cont;
23178 	}
23179 	dst = ire->ire_addr;
23180 	ipha = (ipha_t *)mp->b_rptr;
23181 	/*
23182 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23183 	 * Restore ipha_ident "no checksum" flag.
23184 	 */
23185 	src = orig_src;
23186 	ipha->ipha_ident = ip_hdr_included;
23187 	goto another;
23188 
23189 #undef	rptr
23190 #undef	Q_TO_INDEX
23191 }
23192 
23193 /*
23194  * Routine to allocate a message that is used to notify the ULP about MDT.
23195  * The caller may provide a pointer to the link-layer MDT capabilities,
23196  * or NULL if MDT is to be disabled on the stream.
23197  */
23198 mblk_t *
23199 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23200 {
23201 	mblk_t *mp;
23202 	ip_mdt_info_t *mdti;
23203 	ill_mdt_capab_t *idst;
23204 
23205 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23206 		DB_TYPE(mp) = M_CTL;
23207 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23208 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23209 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23210 		idst = &(mdti->mdt_capab);
23211 
23212 		/*
23213 		 * If the caller provides us with the capability, copy
23214 		 * it over into our notification message; otherwise
23215 		 * we zero out the capability portion.
23216 		 */
23217 		if (isrc != NULL)
23218 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23219 		else
23220 			bzero((caddr_t)idst, sizeof (*idst));
23221 	}
23222 	return (mp);
23223 }
23224 
23225 /*
23226  * Routine which determines whether MDT can be enabled on the destination
23227  * IRE and IPC combination, and if so, allocates and returns the MDT
23228  * notification mblk that may be used by ULP.  We also check if we need to
23229  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23230  * MDT usage in the past have been lifted.  This gets called during IP
23231  * and ULP binding.
23232  */
23233 mblk_t *
23234 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23235     ill_mdt_capab_t *mdt_cap)
23236 {
23237 	mblk_t *mp;
23238 	boolean_t rc = B_FALSE;
23239 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23240 
23241 	ASSERT(dst_ire != NULL);
23242 	ASSERT(connp != NULL);
23243 	ASSERT(mdt_cap != NULL);
23244 
23245 	/*
23246 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23247 	 * Multidata, which is handled in tcp_multisend().  This
23248 	 * is the reason why we do all these checks here, to ensure
23249 	 * that we don't enable Multidata for the cases which we
23250 	 * can't handle at the moment.
23251 	 */
23252 	do {
23253 		/* Only do TCP at the moment */
23254 		if (connp->conn_ulp != IPPROTO_TCP)
23255 			break;
23256 
23257 		/*
23258 		 * IPSEC outbound policy present?  Note that we get here
23259 		 * after calling ipsec_conn_cache_policy() where the global
23260 		 * policy checking is performed.  conn_latch will be
23261 		 * non-NULL as long as there's a policy defined,
23262 		 * i.e. conn_out_enforce_policy may be NULL in such case
23263 		 * when the connection is non-secure, and hence we check
23264 		 * further if the latch refers to an outbound policy.
23265 		 */
23266 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23267 			break;
23268 
23269 		/* CGTP (multiroute) is enabled? */
23270 		if (dst_ire->ire_flags & RTF_MULTIRT)
23271 			break;
23272 
23273 		/* Outbound IPQoS enabled? */
23274 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23275 			/*
23276 			 * In this case, we disable MDT for this and all
23277 			 * future connections going over the interface.
23278 			 */
23279 			mdt_cap->ill_mdt_on = 0;
23280 			break;
23281 		}
23282 
23283 		/* socket option(s) present? */
23284 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23285 			break;
23286 
23287 		rc = B_TRUE;
23288 	/* CONSTCOND */
23289 	} while (0);
23290 
23291 	/* Remember the result */
23292 	connp->conn_mdt_ok = rc;
23293 
23294 	if (!rc)
23295 		return (NULL);
23296 	else if (!mdt_cap->ill_mdt_on) {
23297 		/*
23298 		 * If MDT has been previously turned off in the past, and we
23299 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23300 		 * then enable it for this interface.
23301 		 */
23302 		mdt_cap->ill_mdt_on = 1;
23303 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23304 		    "interface %s\n", ill_name));
23305 	}
23306 
23307 	/* Allocate the MDT info mblk */
23308 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23309 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23310 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23311 		return (NULL);
23312 	}
23313 	return (mp);
23314 }
23315 
23316 /*
23317  * Routine to allocate a message that is used to notify the ULP about LSO.
23318  * The caller may provide a pointer to the link-layer LSO capabilities,
23319  * or NULL if LSO is to be disabled on the stream.
23320  */
23321 mblk_t *
23322 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23323 {
23324 	mblk_t *mp;
23325 	ip_lso_info_t *lsoi;
23326 	ill_lso_capab_t *idst;
23327 
23328 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23329 		DB_TYPE(mp) = M_CTL;
23330 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23331 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23332 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23333 		idst = &(lsoi->lso_capab);
23334 
23335 		/*
23336 		 * If the caller provides us with the capability, copy
23337 		 * it over into our notification message; otherwise
23338 		 * we zero out the capability portion.
23339 		 */
23340 		if (isrc != NULL)
23341 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23342 		else
23343 			bzero((caddr_t)idst, sizeof (*idst));
23344 	}
23345 	return (mp);
23346 }
23347 
23348 /*
23349  * Routine which determines whether LSO can be enabled on the destination
23350  * IRE and IPC combination, and if so, allocates and returns the LSO
23351  * notification mblk that may be used by ULP.  We also check if we need to
23352  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23353  * LSO usage in the past have been lifted.  This gets called during IP
23354  * and ULP binding.
23355  */
23356 mblk_t *
23357 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23358     ill_lso_capab_t *lso_cap)
23359 {
23360 	mblk_t *mp;
23361 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23362 
23363 	ASSERT(dst_ire != NULL);
23364 	ASSERT(connp != NULL);
23365 	ASSERT(lso_cap != NULL);
23366 
23367 	connp->conn_lso_ok = B_TRUE;
23368 
23369 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23370 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23371 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23372 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23373 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23374 		connp->conn_lso_ok = B_FALSE;
23375 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23376 			/*
23377 			 * Disable LSO for this and all future connections going
23378 			 * over the interface.
23379 			 */
23380 			lso_cap->ill_lso_on = 0;
23381 		}
23382 	}
23383 
23384 	if (!connp->conn_lso_ok)
23385 		return (NULL);
23386 	else if (!lso_cap->ill_lso_on) {
23387 		/*
23388 		 * If LSO has been previously turned off in the past, and we
23389 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23390 		 * then enable it for this interface.
23391 		 */
23392 		lso_cap->ill_lso_on = 1;
23393 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23394 		    ill_name));
23395 	}
23396 
23397 	/* Allocate the LSO info mblk */
23398 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23399 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23400 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23401 
23402 	return (mp);
23403 }
23404 
23405 /*
23406  * Create destination address attribute, and fill it with the physical
23407  * destination address and SAP taken from the template DL_UNITDATA_REQ
23408  * message block.
23409  */
23410 boolean_t
23411 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23412 {
23413 	dl_unitdata_req_t *dlurp;
23414 	pattr_t *pa;
23415 	pattrinfo_t pa_info;
23416 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23417 	uint_t das_len, das_off;
23418 
23419 	ASSERT(dlmp != NULL);
23420 
23421 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23422 	das_len = dlurp->dl_dest_addr_length;
23423 	das_off = dlurp->dl_dest_addr_offset;
23424 
23425 	pa_info.type = PATTR_DSTADDRSAP;
23426 	pa_info.len = sizeof (**das) + das_len - 1;
23427 
23428 	/* create and associate the attribute */
23429 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23430 	if (pa != NULL) {
23431 		ASSERT(*das != NULL);
23432 		(*das)->addr_is_group = 0;
23433 		(*das)->addr_len = (uint8_t)das_len;
23434 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23435 	}
23436 
23437 	return (pa != NULL);
23438 }
23439 
23440 /*
23441  * Create hardware checksum attribute and fill it with the values passed.
23442  */
23443 boolean_t
23444 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23445     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23446 {
23447 	pattr_t *pa;
23448 	pattrinfo_t pa_info;
23449 
23450 	ASSERT(mmd != NULL);
23451 
23452 	pa_info.type = PATTR_HCKSUM;
23453 	pa_info.len = sizeof (pattr_hcksum_t);
23454 
23455 	/* create and associate the attribute */
23456 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23457 	if (pa != NULL) {
23458 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23459 
23460 		hck->hcksum_start_offset = start_offset;
23461 		hck->hcksum_stuff_offset = stuff_offset;
23462 		hck->hcksum_end_offset = end_offset;
23463 		hck->hcksum_flags = flags;
23464 	}
23465 	return (pa != NULL);
23466 }
23467 
23468 /*
23469  * Create zerocopy attribute and fill it with the specified flags
23470  */
23471 boolean_t
23472 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23473 {
23474 	pattr_t *pa;
23475 	pattrinfo_t pa_info;
23476 
23477 	ASSERT(mmd != NULL);
23478 	pa_info.type = PATTR_ZCOPY;
23479 	pa_info.len = sizeof (pattr_zcopy_t);
23480 
23481 	/* create and associate the attribute */
23482 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23483 	if (pa != NULL) {
23484 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23485 
23486 		zcopy->zcopy_flags = flags;
23487 	}
23488 	return (pa != NULL);
23489 }
23490 
23491 /*
23492  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23493  * block chain. We could rewrite to handle arbitrary message block chains but
23494  * that would make the code complicated and slow. Right now there three
23495  * restrictions:
23496  *
23497  *   1. The first message block must contain the complete IP header and
23498  *	at least 1 byte of payload data.
23499  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23500  *	so that we can use a single Multidata message.
23501  *   3. No frag must be distributed over two or more message blocks so
23502  *	that we don't need more than two packet descriptors per frag.
23503  *
23504  * The above restrictions allow us to support userland applications (which
23505  * will send down a single message block) and NFS over UDP (which will
23506  * send down a chain of at most three message blocks).
23507  *
23508  * We also don't use MDT for payloads with less than or equal to
23509  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23510  */
23511 boolean_t
23512 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23513 {
23514 	int	blocks;
23515 	ssize_t	total, missing, size;
23516 
23517 	ASSERT(mp != NULL);
23518 	ASSERT(hdr_len > 0);
23519 
23520 	size = MBLKL(mp) - hdr_len;
23521 	if (size <= 0)
23522 		return (B_FALSE);
23523 
23524 	/* The first mblk contains the header and some payload. */
23525 	blocks = 1;
23526 	total = size;
23527 	size %= len;
23528 	missing = (size == 0) ? 0 : (len - size);
23529 	mp = mp->b_cont;
23530 
23531 	while (mp != NULL) {
23532 		/*
23533 		 * Give up if we encounter a zero length message block.
23534 		 * In practice, this should rarely happen and therefore
23535 		 * not worth the trouble of freeing and re-linking the
23536 		 * mblk from the chain to handle such case.
23537 		 */
23538 		if ((size = MBLKL(mp)) == 0)
23539 			return (B_FALSE);
23540 
23541 		/* Too many payload buffers for a single Multidata message? */
23542 		if (++blocks > MULTIDATA_MAX_PBUFS)
23543 			return (B_FALSE);
23544 
23545 		total += size;
23546 		/* Is a frag distributed over two or more message blocks? */
23547 		if (missing > size)
23548 			return (B_FALSE);
23549 		size -= missing;
23550 
23551 		size %= len;
23552 		missing = (size == 0) ? 0 : (len - size);
23553 
23554 		mp = mp->b_cont;
23555 	}
23556 
23557 	return (total > ip_wput_frag_mdt_min);
23558 }
23559 
23560 /*
23561  * Outbound IPv4 fragmentation routine using MDT.
23562  */
23563 static void
23564 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23565     uint32_t frag_flag, int offset)
23566 {
23567 	ipha_t		*ipha_orig;
23568 	int		i1, ip_data_end;
23569 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23570 	mblk_t		*hdr_mp, *md_mp = NULL;
23571 	unsigned char	*hdr_ptr, *pld_ptr;
23572 	multidata_t	*mmd;
23573 	ip_pdescinfo_t	pdi;
23574 	ill_t		*ill;
23575 	ip_stack_t	*ipst = ire->ire_ipst;
23576 
23577 	ASSERT(DB_TYPE(mp) == M_DATA);
23578 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23579 
23580 	ill = ire_to_ill(ire);
23581 	ASSERT(ill != NULL);
23582 
23583 	ipha_orig = (ipha_t *)mp->b_rptr;
23584 	mp->b_rptr += sizeof (ipha_t);
23585 
23586 	/* Calculate how many packets we will send out */
23587 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23588 	pkts = (i1 + len - 1) / len;
23589 	ASSERT(pkts > 1);
23590 
23591 	/* Allocate a message block which will hold all the IP Headers. */
23592 	wroff = ipst->ips_ip_wroff_extra;
23593 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23594 
23595 	i1 = pkts * hdr_chunk_len;
23596 	/*
23597 	 * Create the header buffer, Multidata and destination address
23598 	 * and SAP attribute that should be associated with it.
23599 	 */
23600 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23601 	    ((hdr_mp->b_wptr += i1),
23602 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23603 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23604 		freemsg(mp);
23605 		if (md_mp == NULL) {
23606 			freemsg(hdr_mp);
23607 		} else {
23608 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23609 			freemsg(md_mp);
23610 		}
23611 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23612 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23613 		return;
23614 	}
23615 	IP_STAT(ipst, ip_frag_mdt_allocd);
23616 
23617 	/*
23618 	 * Add a payload buffer to the Multidata; this operation must not
23619 	 * fail, or otherwise our logic in this routine is broken.  There
23620 	 * is no memory allocation done by the routine, so any returned
23621 	 * failure simply tells us that we've done something wrong.
23622 	 *
23623 	 * A failure tells us that either we're adding the same payload
23624 	 * buffer more than once, or we're trying to add more buffers than
23625 	 * allowed.  None of the above cases should happen, and we panic
23626 	 * because either there's horrible heap corruption, and/or
23627 	 * programming mistake.
23628 	 */
23629 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23630 		goto pbuf_panic;
23631 
23632 	hdr_ptr = hdr_mp->b_rptr;
23633 	pld_ptr = mp->b_rptr;
23634 
23635 	/* Establish the ending byte offset, based on the starting offset. */
23636 	offset <<= 3;
23637 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23638 	    IP_SIMPLE_HDR_LENGTH;
23639 
23640 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23641 
23642 	while (pld_ptr < mp->b_wptr) {
23643 		ipha_t		*ipha;
23644 		uint16_t	offset_and_flags;
23645 		uint16_t	ip_len;
23646 		int		error;
23647 
23648 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23649 		ipha = (ipha_t *)(hdr_ptr + wroff);
23650 		ASSERT(OK_32PTR(ipha));
23651 		*ipha = *ipha_orig;
23652 
23653 		if (ip_data_end - offset > len) {
23654 			offset_and_flags = IPH_MF;
23655 		} else {
23656 			/*
23657 			 * Last frag. Set len to the length of this last piece.
23658 			 */
23659 			len = ip_data_end - offset;
23660 			/* A frag of a frag might have IPH_MF non-zero */
23661 			offset_and_flags =
23662 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23663 			    IPH_MF;
23664 		}
23665 		offset_and_flags |= (uint16_t)(offset >> 3);
23666 		offset_and_flags |= (uint16_t)frag_flag;
23667 		/* Store the offset and flags in the IP header. */
23668 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23669 
23670 		/* Store the length in the IP header. */
23671 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23672 		ipha->ipha_length = htons(ip_len);
23673 
23674 		/*
23675 		 * Set the IP header checksum.  Note that mp is just
23676 		 * the header, so this is easy to pass to ip_csum.
23677 		 */
23678 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23679 
23680 		/*
23681 		 * Record offset and size of header and data of the next packet
23682 		 * in the multidata message.
23683 		 */
23684 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23685 		PDESC_PLD_INIT(&pdi);
23686 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23687 		ASSERT(i1 > 0);
23688 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23689 		if (i1 == len) {
23690 			pld_ptr += len;
23691 		} else {
23692 			i1 = len - i1;
23693 			mp = mp->b_cont;
23694 			ASSERT(mp != NULL);
23695 			ASSERT(MBLKL(mp) >= i1);
23696 			/*
23697 			 * Attach the next payload message block to the
23698 			 * multidata message.
23699 			 */
23700 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23701 				goto pbuf_panic;
23702 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23703 			pld_ptr = mp->b_rptr + i1;
23704 		}
23705 
23706 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23707 		    KM_NOSLEEP)) == NULL) {
23708 			/*
23709 			 * Any failure other than ENOMEM indicates that we
23710 			 * have passed in invalid pdesc info or parameters
23711 			 * to mmd_addpdesc, which must not happen.
23712 			 *
23713 			 * EINVAL is a result of failure on boundary checks
23714 			 * against the pdesc info contents.  It should not
23715 			 * happen, and we panic because either there's
23716 			 * horrible heap corruption, and/or programming
23717 			 * mistake.
23718 			 */
23719 			if (error != ENOMEM) {
23720 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23721 				    "pdesc logic error detected for "
23722 				    "mmd %p pinfo %p (%d)\n",
23723 				    (void *)mmd, (void *)&pdi, error);
23724 				/* NOTREACHED */
23725 			}
23726 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23727 			/* Free unattached payload message blocks as well */
23728 			md_mp->b_cont = mp->b_cont;
23729 			goto free_mmd;
23730 		}
23731 
23732 		/* Advance fragment offset. */
23733 		offset += len;
23734 
23735 		/* Advance to location for next header in the buffer. */
23736 		hdr_ptr += hdr_chunk_len;
23737 
23738 		/* Did we reach the next payload message block? */
23739 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23740 			mp = mp->b_cont;
23741 			/*
23742 			 * Attach the next message block with payload
23743 			 * data to the multidata message.
23744 			 */
23745 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23746 				goto pbuf_panic;
23747 			pld_ptr = mp->b_rptr;
23748 		}
23749 	}
23750 
23751 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23752 	ASSERT(mp->b_wptr == pld_ptr);
23753 
23754 	/* Update IP statistics */
23755 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23756 
23757 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23758 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23759 
23760 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23761 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23762 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23763 
23764 	if (pkt_type == OB_PKT) {
23765 		ire->ire_ob_pkt_count += pkts;
23766 		if (ire->ire_ipif != NULL)
23767 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23768 	} else {
23769 		/* The type is IB_PKT in the forwarding path. */
23770 		ire->ire_ib_pkt_count += pkts;
23771 		ASSERT(!IRE_IS_LOCAL(ire));
23772 		if (ire->ire_type & IRE_BROADCAST) {
23773 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
23774 		} else {
23775 			UPDATE_MIB(ill->ill_ip_mib,
23776 			    ipIfStatsHCOutForwDatagrams, pkts);
23777 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
23778 		}
23779 	}
23780 	ire->ire_last_used_time = lbolt;
23781 	/* Send it down */
23782 	putnext(ire->ire_stq, md_mp);
23783 	return;
23784 
23785 pbuf_panic:
23786 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
23787 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
23788 	    pbuf_idx);
23789 	/* NOTREACHED */
23790 }
23791 
23792 /*
23793  * Outbound IP fragmentation routine.
23794  *
23795  * NOTE : This routine does not ire_refrele the ire that is passed in
23796  * as the argument.
23797  */
23798 static void
23799 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
23800     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
23801 {
23802 	int		i1;
23803 	mblk_t		*ll_hdr_mp;
23804 	int 		ll_hdr_len;
23805 	int		hdr_len;
23806 	mblk_t		*hdr_mp;
23807 	ipha_t		*ipha;
23808 	int		ip_data_end;
23809 	int		len;
23810 	mblk_t		*mp = mp_orig, *mp1;
23811 	int		offset;
23812 	queue_t		*q;
23813 	uint32_t	v_hlen_tos_len;
23814 	mblk_t		*first_mp;
23815 	boolean_t	mctl_present;
23816 	ill_t		*ill;
23817 	ill_t		*out_ill;
23818 	mblk_t		*xmit_mp;
23819 	mblk_t		*carve_mp;
23820 	ire_t		*ire1 = NULL;
23821 	ire_t		*save_ire = NULL;
23822 	mblk_t  	*next_mp = NULL;
23823 	boolean_t	last_frag = B_FALSE;
23824 	boolean_t	multirt_send = B_FALSE;
23825 	ire_t		*first_ire = NULL;
23826 	irb_t		*irb = NULL;
23827 	mib2_ipIfStatsEntry_t *mibptr = NULL;
23828 
23829 	ill = ire_to_ill(ire);
23830 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
23831 
23832 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
23833 
23834 	if (max_frag == 0) {
23835 		ip1dbg(("ip_wput_frag: ire frag size is 0"
23836 		    " -  dropping packet\n"));
23837 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23838 		freemsg(mp);
23839 		return;
23840 	}
23841 
23842 	/*
23843 	 * IPSEC does not allow hw accelerated packets to be fragmented
23844 	 * This check is made in ip_wput_ipsec_out prior to coming here
23845 	 * via ip_wput_ire_fragmentit.
23846 	 *
23847 	 * If at this point we have an ire whose ARP request has not
23848 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
23849 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
23850 	 * This packet and all fragmentable packets for this ire will
23851 	 * continue to get dropped while ire_nce->nce_state remains in
23852 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
23853 	 * ND_REACHABLE, all subsquent large packets for this ire will
23854 	 * get fragemented and sent out by this function.
23855 	 */
23856 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
23857 		/* If nce_state is ND_INITIAL, trigger ARP query */
23858 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
23859 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
23860 		    " -  dropping packet\n"));
23861 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23862 		freemsg(mp);
23863 		return;
23864 	}
23865 
23866 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
23867 	    "ip_wput_frag_start:");
23868 
23869 	if (mp->b_datap->db_type == M_CTL) {
23870 		first_mp = mp;
23871 		mp_orig = mp = mp->b_cont;
23872 		mctl_present = B_TRUE;
23873 	} else {
23874 		first_mp = mp;
23875 		mctl_present = B_FALSE;
23876 	}
23877 
23878 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
23879 	ipha = (ipha_t *)mp->b_rptr;
23880 
23881 	/*
23882 	 * If the Don't Fragment flag is on, generate an ICMP destination
23883 	 * unreachable, fragmentation needed.
23884 	 */
23885 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23886 	if (offset & IPH_DF) {
23887 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23888 		if (is_system_labeled()) {
23889 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
23890 			    ire->ire_max_frag - max_frag, AF_INET);
23891 		}
23892 		/*
23893 		 * Need to compute hdr checksum if called from ip_wput_ire.
23894 		 * Note that ip_rput_forward verifies the checksum before
23895 		 * calling this routine so in that case this is a noop.
23896 		 */
23897 		ipha->ipha_hdr_checksum = 0;
23898 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23899 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
23900 		    ipst);
23901 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23902 		    "ip_wput_frag_end:(%S)",
23903 		    "don't fragment");
23904 		return;
23905 	}
23906 	/*
23907 	 * Labeled systems adjust max_frag if they add a label
23908 	 * to send the correct path mtu.  We need the real mtu since we
23909 	 * are fragmenting the packet after label adjustment.
23910 	 */
23911 	if (is_system_labeled())
23912 		max_frag = ire->ire_max_frag;
23913 	if (mctl_present)
23914 		freeb(first_mp);
23915 	/*
23916 	 * Establish the starting offset.  May not be zero if we are fragging
23917 	 * a fragment that is being forwarded.
23918 	 */
23919 	offset = offset & IPH_OFFSET;
23920 
23921 	/* TODO why is this test needed? */
23922 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
23923 	if (((max_frag - LENGTH) & ~7) < 8) {
23924 		/* TODO: notify ulp somehow */
23925 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23926 		freemsg(mp);
23927 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23928 		    "ip_wput_frag_end:(%S)",
23929 		    "len < 8");
23930 		return;
23931 	}
23932 
23933 	hdr_len = (V_HLEN & 0xF) << 2;
23934 
23935 	ipha->ipha_hdr_checksum = 0;
23936 
23937 	/*
23938 	 * Establish the number of bytes maximum per frag, after putting
23939 	 * in the header.
23940 	 */
23941 	len = (max_frag - hdr_len) & ~7;
23942 
23943 	/* Check if we can use MDT to send out the frags. */
23944 	ASSERT(!IRE_IS_LOCAL(ire));
23945 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
23946 	    ipst->ips_ip_multidata_outbound &&
23947 	    !(ire->ire_flags & RTF_MULTIRT) &&
23948 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
23949 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
23950 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
23951 		ASSERT(ill->ill_mdt_capab != NULL);
23952 		if (!ill->ill_mdt_capab->ill_mdt_on) {
23953 			/*
23954 			 * If MDT has been previously turned off in the past,
23955 			 * and we currently can do MDT (due to IPQoS policy
23956 			 * removal, etc.) then enable it for this interface.
23957 			 */
23958 			ill->ill_mdt_capab->ill_mdt_on = 1;
23959 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
23960 			    ill->ill_name));
23961 		}
23962 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
23963 		    offset);
23964 		return;
23965 	}
23966 
23967 	/* Get a copy of the header for the trailing frags */
23968 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
23969 	if (!hdr_mp) {
23970 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
23971 		freemsg(mp);
23972 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
23973 		    "ip_wput_frag_end:(%S)",
23974 		    "couldn't copy hdr");
23975 		return;
23976 	}
23977 	if (DB_CRED(mp) != NULL)
23978 		mblk_setcred(hdr_mp, DB_CRED(mp));
23979 
23980 	/* Store the starting offset, with the MoreFrags flag. */
23981 	i1 = offset | IPH_MF | frag_flag;
23982 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
23983 
23984 	/* Establish the ending byte offset, based on the starting offset. */
23985 	offset <<= 3;
23986 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
23987 
23988 	/* Store the length of the first fragment in the IP header. */
23989 	i1 = len + hdr_len;
23990 	ASSERT(i1 <= IP_MAXPACKET);
23991 	ipha->ipha_length = htons((uint16_t)i1);
23992 
23993 	/*
23994 	 * Compute the IP header checksum for the first frag.  We have to
23995 	 * watch out that we stop at the end of the header.
23996 	 */
23997 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23998 
23999 	/*
24000 	 * Now carve off the first frag.  Note that this will include the
24001 	 * original IP header.
24002 	 */
24003 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24004 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24005 		freeb(hdr_mp);
24006 		freemsg(mp_orig);
24007 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24008 		    "ip_wput_frag_end:(%S)",
24009 		    "couldn't carve first");
24010 		return;
24011 	}
24012 
24013 	/*
24014 	 * Multirouting case. Each fragment is replicated
24015 	 * via all non-condemned RTF_MULTIRT routes
24016 	 * currently resolved.
24017 	 * We ensure that first_ire is the first RTF_MULTIRT
24018 	 * ire in the bucket.
24019 	 */
24020 	if (ire->ire_flags & RTF_MULTIRT) {
24021 		irb = ire->ire_bucket;
24022 		ASSERT(irb != NULL);
24023 
24024 		multirt_send = B_TRUE;
24025 
24026 		/* Make sure we do not omit any multiroute ire. */
24027 		IRB_REFHOLD(irb);
24028 		for (first_ire = irb->irb_ire;
24029 		    first_ire != NULL;
24030 		    first_ire = first_ire->ire_next) {
24031 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24032 			    (first_ire->ire_addr == ire->ire_addr) &&
24033 			    !(first_ire->ire_marks &
24034 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24035 				break;
24036 			}
24037 		}
24038 
24039 		if (first_ire != NULL) {
24040 			if (first_ire != ire) {
24041 				IRE_REFHOLD(first_ire);
24042 				/*
24043 				 * Do not release the ire passed in
24044 				 * as the argument.
24045 				 */
24046 				ire = first_ire;
24047 			} else {
24048 				first_ire = NULL;
24049 			}
24050 		}
24051 		IRB_REFRELE(irb);
24052 
24053 		/*
24054 		 * Save the first ire; we will need to restore it
24055 		 * for the trailing frags.
24056 		 * We REFHOLD save_ire, as each iterated ire will be
24057 		 * REFRELEd.
24058 		 */
24059 		save_ire = ire;
24060 		IRE_REFHOLD(save_ire);
24061 	}
24062 
24063 	/*
24064 	 * First fragment emission loop.
24065 	 * In most cases, the emission loop below is entered only
24066 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24067 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24068 	 * bucket, and send the fragment through all crossed
24069 	 * RTF_MULTIRT routes.
24070 	 */
24071 	do {
24072 		if (ire->ire_flags & RTF_MULTIRT) {
24073 			/*
24074 			 * We are in a multiple send case, need to get
24075 			 * the next ire and make a copy of the packet.
24076 			 * ire1 holds here the next ire to process in the
24077 			 * bucket. If multirouting is expected,
24078 			 * any non-RTF_MULTIRT ire that has the
24079 			 * right destination address is ignored.
24080 			 *
24081 			 * We have to take into account the MTU of
24082 			 * each walked ire. max_frag is set by the
24083 			 * the caller and generally refers to
24084 			 * the primary ire entry. Here we ensure that
24085 			 * no route with a lower MTU will be used, as
24086 			 * fragments are carved once for all ires,
24087 			 * then replicated.
24088 			 */
24089 			ASSERT(irb != NULL);
24090 			IRB_REFHOLD(irb);
24091 			for (ire1 = ire->ire_next;
24092 			    ire1 != NULL;
24093 			    ire1 = ire1->ire_next) {
24094 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24095 					continue;
24096 				if (ire1->ire_addr != ire->ire_addr)
24097 					continue;
24098 				if (ire1->ire_marks &
24099 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24100 					continue;
24101 				/*
24102 				 * Ensure we do not exceed the MTU
24103 				 * of the next route.
24104 				 */
24105 				if (ire1->ire_max_frag < max_frag) {
24106 					ip_multirt_bad_mtu(ire1, max_frag);
24107 					continue;
24108 				}
24109 
24110 				/* Got one. */
24111 				IRE_REFHOLD(ire1);
24112 				break;
24113 			}
24114 			IRB_REFRELE(irb);
24115 
24116 			if (ire1 != NULL) {
24117 				next_mp = copyb(mp);
24118 				if ((next_mp == NULL) ||
24119 				    ((mp->b_cont != NULL) &&
24120 				    ((next_mp->b_cont =
24121 				    dupmsg(mp->b_cont)) == NULL))) {
24122 					freemsg(next_mp);
24123 					next_mp = NULL;
24124 					ire_refrele(ire1);
24125 					ire1 = NULL;
24126 				}
24127 			}
24128 
24129 			/* Last multiroute ire; don't loop anymore. */
24130 			if (ire1 == NULL) {
24131 				multirt_send = B_FALSE;
24132 			}
24133 		}
24134 
24135 		ll_hdr_len = 0;
24136 		LOCK_IRE_FP_MP(ire);
24137 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24138 		if (ll_hdr_mp != NULL) {
24139 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24140 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24141 		} else {
24142 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24143 		}
24144 
24145 		/* If there is a transmit header, get a copy for this frag. */
24146 		/*
24147 		 * TODO: should check db_ref before calling ip_carve_mp since
24148 		 * it might give us a dup.
24149 		 */
24150 		if (!ll_hdr_mp) {
24151 			/* No xmit header. */
24152 			xmit_mp = mp;
24153 
24154 		/* We have a link-layer header that can fit in our mblk. */
24155 		} else if (mp->b_datap->db_ref == 1 &&
24156 		    ll_hdr_len != 0 &&
24157 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24158 			/* M_DATA fastpath */
24159 			mp->b_rptr -= ll_hdr_len;
24160 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24161 			xmit_mp = mp;
24162 
24163 		/* Corner case if copyb has failed */
24164 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24165 			UNLOCK_IRE_FP_MP(ire);
24166 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24167 			freeb(hdr_mp);
24168 			freemsg(mp);
24169 			freemsg(mp_orig);
24170 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24171 			    "ip_wput_frag_end:(%S)",
24172 			    "discard");
24173 
24174 			if (multirt_send) {
24175 				ASSERT(ire1);
24176 				ASSERT(next_mp);
24177 
24178 				freemsg(next_mp);
24179 				ire_refrele(ire1);
24180 			}
24181 			if (save_ire != NULL)
24182 				IRE_REFRELE(save_ire);
24183 
24184 			if (first_ire != NULL)
24185 				ire_refrele(first_ire);
24186 			return;
24187 
24188 		/*
24189 		 * Case of res_mp OR the fastpath mp can't fit
24190 		 * in the mblk
24191 		 */
24192 		} else {
24193 			xmit_mp->b_cont = mp;
24194 			if (DB_CRED(mp) != NULL)
24195 				mblk_setcred(xmit_mp, DB_CRED(mp));
24196 			/*
24197 			 * Get priority marking, if any.
24198 			 * We propagate the CoS marking from the
24199 			 * original packet that went to QoS processing
24200 			 * in ip_wput_ire to the newly carved mp.
24201 			 */
24202 			if (DB_TYPE(xmit_mp) == M_DATA)
24203 				xmit_mp->b_band = mp->b_band;
24204 		}
24205 		UNLOCK_IRE_FP_MP(ire);
24206 
24207 		q = ire->ire_stq;
24208 		out_ill = (ill_t *)q->q_ptr;
24209 
24210 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24211 
24212 		DTRACE_PROBE4(ip4__physical__out__start,
24213 		    ill_t *, NULL, ill_t *, out_ill,
24214 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24215 
24216 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24217 		    ipst->ips_ipv4firewall_physical_out,
24218 		    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24219 
24220 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24221 
24222 		if (xmit_mp != NULL) {
24223 			putnext(q, xmit_mp);
24224 
24225 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24226 			UPDATE_MIB(out_ill->ill_ip_mib,
24227 			    ipIfStatsHCOutOctets, i1);
24228 
24229 			if (pkt_type != OB_PKT) {
24230 				/*
24231 				 * Update the packet count and MIB stats
24232 				 * of trailing RTF_MULTIRT ires.
24233 				 */
24234 				UPDATE_OB_PKT_COUNT(ire);
24235 				BUMP_MIB(out_ill->ill_ip_mib,
24236 				    ipIfStatsOutFragReqds);
24237 			}
24238 		}
24239 
24240 		if (multirt_send) {
24241 			/*
24242 			 * We are in a multiple send case; look for
24243 			 * the next ire and re-enter the loop.
24244 			 */
24245 			ASSERT(ire1);
24246 			ASSERT(next_mp);
24247 			/* REFRELE the current ire before looping */
24248 			ire_refrele(ire);
24249 			ire = ire1;
24250 			ire1 = NULL;
24251 			mp = next_mp;
24252 			next_mp = NULL;
24253 		}
24254 	} while (multirt_send);
24255 
24256 	ASSERT(ire1 == NULL);
24257 
24258 	/* Restore the original ire; we need it for the trailing frags */
24259 	if (save_ire != NULL) {
24260 		/* REFRELE the last iterated ire */
24261 		ire_refrele(ire);
24262 		/* save_ire has been REFHOLDed */
24263 		ire = save_ire;
24264 		save_ire = NULL;
24265 		q = ire->ire_stq;
24266 	}
24267 
24268 	if (pkt_type == OB_PKT) {
24269 		UPDATE_OB_PKT_COUNT(ire);
24270 	} else {
24271 		out_ill = (ill_t *)q->q_ptr;
24272 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24273 		UPDATE_IB_PKT_COUNT(ire);
24274 	}
24275 
24276 	/* Advance the offset to the second frag starting point. */
24277 	offset += len;
24278 	/*
24279 	 * Update hdr_len from the copied header - there might be less options
24280 	 * in the later fragments.
24281 	 */
24282 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24283 	/* Loop until done. */
24284 	for (;;) {
24285 		uint16_t	offset_and_flags;
24286 		uint16_t	ip_len;
24287 
24288 		if (ip_data_end - offset > len) {
24289 			/*
24290 			 * Carve off the appropriate amount from the original
24291 			 * datagram.
24292 			 */
24293 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24294 				mp = NULL;
24295 				break;
24296 			}
24297 			/*
24298 			 * More frags after this one.  Get another copy
24299 			 * of the header.
24300 			 */
24301 			if (carve_mp->b_datap->db_ref == 1 &&
24302 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24303 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24304 				/* Inline IP header */
24305 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24306 				    hdr_mp->b_rptr;
24307 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24308 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24309 				mp = carve_mp;
24310 			} else {
24311 				if (!(mp = copyb(hdr_mp))) {
24312 					freemsg(carve_mp);
24313 					break;
24314 				}
24315 				/* Get priority marking, if any. */
24316 				mp->b_band = carve_mp->b_band;
24317 				mp->b_cont = carve_mp;
24318 			}
24319 			ipha = (ipha_t *)mp->b_rptr;
24320 			offset_and_flags = IPH_MF;
24321 		} else {
24322 			/*
24323 			 * Last frag.  Consume the header. Set len to
24324 			 * the length of this last piece.
24325 			 */
24326 			len = ip_data_end - offset;
24327 
24328 			/*
24329 			 * Carve off the appropriate amount from the original
24330 			 * datagram.
24331 			 */
24332 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24333 				mp = NULL;
24334 				break;
24335 			}
24336 			if (carve_mp->b_datap->db_ref == 1 &&
24337 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24338 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24339 				/* Inline IP header */
24340 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24341 				    hdr_mp->b_rptr;
24342 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24343 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24344 				mp = carve_mp;
24345 				freeb(hdr_mp);
24346 				hdr_mp = mp;
24347 			} else {
24348 				mp = hdr_mp;
24349 				/* Get priority marking, if any. */
24350 				mp->b_band = carve_mp->b_band;
24351 				mp->b_cont = carve_mp;
24352 			}
24353 			ipha = (ipha_t *)mp->b_rptr;
24354 			/* A frag of a frag might have IPH_MF non-zero */
24355 			offset_and_flags =
24356 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24357 			    IPH_MF;
24358 		}
24359 		offset_and_flags |= (uint16_t)(offset >> 3);
24360 		offset_and_flags |= (uint16_t)frag_flag;
24361 		/* Store the offset and flags in the IP header. */
24362 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24363 
24364 		/* Store the length in the IP header. */
24365 		ip_len = (uint16_t)(len + hdr_len);
24366 		ipha->ipha_length = htons(ip_len);
24367 
24368 		/*
24369 		 * Set the IP header checksum.	Note that mp is just
24370 		 * the header, so this is easy to pass to ip_csum.
24371 		 */
24372 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24373 
24374 		/* Attach a transmit header, if any, and ship it. */
24375 		if (pkt_type == OB_PKT) {
24376 			UPDATE_OB_PKT_COUNT(ire);
24377 		} else {
24378 			out_ill = (ill_t *)q->q_ptr;
24379 			BUMP_MIB(out_ill->ill_ip_mib,
24380 			    ipIfStatsHCOutForwDatagrams);
24381 			UPDATE_IB_PKT_COUNT(ire);
24382 		}
24383 
24384 		if (ire->ire_flags & RTF_MULTIRT) {
24385 			irb = ire->ire_bucket;
24386 			ASSERT(irb != NULL);
24387 
24388 			multirt_send = B_TRUE;
24389 
24390 			/*
24391 			 * Save the original ire; we will need to restore it
24392 			 * for the tailing frags.
24393 			 */
24394 			save_ire = ire;
24395 			IRE_REFHOLD(save_ire);
24396 		}
24397 		/*
24398 		 * Emission loop for this fragment, similar
24399 		 * to what is done for the first fragment.
24400 		 */
24401 		do {
24402 			if (multirt_send) {
24403 				/*
24404 				 * We are in a multiple send case, need to get
24405 				 * the next ire and make a copy of the packet.
24406 				 */
24407 				ASSERT(irb != NULL);
24408 				IRB_REFHOLD(irb);
24409 				for (ire1 = ire->ire_next;
24410 				    ire1 != NULL;
24411 				    ire1 = ire1->ire_next) {
24412 					if (!(ire1->ire_flags & RTF_MULTIRT))
24413 						continue;
24414 					if (ire1->ire_addr != ire->ire_addr)
24415 						continue;
24416 					if (ire1->ire_marks &
24417 					    (IRE_MARK_CONDEMNED|
24418 					    IRE_MARK_HIDDEN)) {
24419 						continue;
24420 					}
24421 					/*
24422 					 * Ensure we do not exceed the MTU
24423 					 * of the next route.
24424 					 */
24425 					if (ire1->ire_max_frag < max_frag) {
24426 						ip_multirt_bad_mtu(ire1,
24427 						    max_frag);
24428 						continue;
24429 					}
24430 
24431 					/* Got one. */
24432 					IRE_REFHOLD(ire1);
24433 					break;
24434 				}
24435 				IRB_REFRELE(irb);
24436 
24437 				if (ire1 != NULL) {
24438 					next_mp = copyb(mp);
24439 					if ((next_mp == NULL) ||
24440 					    ((mp->b_cont != NULL) &&
24441 					    ((next_mp->b_cont =
24442 					    dupmsg(mp->b_cont)) == NULL))) {
24443 						freemsg(next_mp);
24444 						next_mp = NULL;
24445 						ire_refrele(ire1);
24446 						ire1 = NULL;
24447 					}
24448 				}
24449 
24450 				/* Last multiroute ire; don't loop anymore. */
24451 				if (ire1 == NULL) {
24452 					multirt_send = B_FALSE;
24453 				}
24454 			}
24455 
24456 			/* Update transmit header */
24457 			ll_hdr_len = 0;
24458 			LOCK_IRE_FP_MP(ire);
24459 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24460 			if (ll_hdr_mp != NULL) {
24461 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24462 				ll_hdr_len = MBLKL(ll_hdr_mp);
24463 			} else {
24464 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24465 			}
24466 
24467 			if (!ll_hdr_mp) {
24468 				xmit_mp = mp;
24469 
24470 			/*
24471 			 * We have link-layer header that can fit in
24472 			 * our mblk.
24473 			 */
24474 			} else if (mp->b_datap->db_ref == 1 &&
24475 			    ll_hdr_len != 0 &&
24476 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24477 				/* M_DATA fastpath */
24478 				mp->b_rptr -= ll_hdr_len;
24479 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24480 				    ll_hdr_len);
24481 				xmit_mp = mp;
24482 
24483 			/*
24484 			 * Case of res_mp OR the fastpath mp can't fit
24485 			 * in the mblk
24486 			 */
24487 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24488 				xmit_mp->b_cont = mp;
24489 				if (DB_CRED(mp) != NULL)
24490 					mblk_setcred(xmit_mp, DB_CRED(mp));
24491 				/* Get priority marking, if any. */
24492 				if (DB_TYPE(xmit_mp) == M_DATA)
24493 					xmit_mp->b_band = mp->b_band;
24494 
24495 			/* Corner case if copyb failed */
24496 			} else {
24497 				/*
24498 				 * Exit both the replication and
24499 				 * fragmentation loops.
24500 				 */
24501 				UNLOCK_IRE_FP_MP(ire);
24502 				goto drop_pkt;
24503 			}
24504 			UNLOCK_IRE_FP_MP(ire);
24505 
24506 			mp1 = mp;
24507 			out_ill = (ill_t *)q->q_ptr;
24508 
24509 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24510 
24511 			DTRACE_PROBE4(ip4__physical__out__start,
24512 			    ill_t *, NULL, ill_t *, out_ill,
24513 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24514 
24515 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24516 			    ipst->ips_ipv4firewall_physical_out,
24517 			    NULL, out_ill, ipha, xmit_mp, mp, ipst);
24518 
24519 			DTRACE_PROBE1(ip4__physical__out__end,
24520 			    mblk_t *, xmit_mp);
24521 
24522 			if (mp != mp1 && hdr_mp == mp1)
24523 				hdr_mp = mp;
24524 			if (mp != mp1 && mp_orig == mp1)
24525 				mp_orig = mp;
24526 
24527 			if (xmit_mp != NULL) {
24528 				putnext(q, xmit_mp);
24529 
24530 				BUMP_MIB(out_ill->ill_ip_mib,
24531 				    ipIfStatsHCOutTransmits);
24532 				UPDATE_MIB(out_ill->ill_ip_mib,
24533 				    ipIfStatsHCOutOctets, ip_len);
24534 
24535 				if (pkt_type != OB_PKT) {
24536 					/*
24537 					 * Update the packet count of trailing
24538 					 * RTF_MULTIRT ires.
24539 					 */
24540 					UPDATE_OB_PKT_COUNT(ire);
24541 				}
24542 			}
24543 
24544 			/* All done if we just consumed the hdr_mp. */
24545 			if (mp == hdr_mp) {
24546 				last_frag = B_TRUE;
24547 				BUMP_MIB(out_ill->ill_ip_mib,
24548 				    ipIfStatsOutFragOKs);
24549 			}
24550 
24551 			if (multirt_send) {
24552 				/*
24553 				 * We are in a multiple send case; look for
24554 				 * the next ire and re-enter the loop.
24555 				 */
24556 				ASSERT(ire1);
24557 				ASSERT(next_mp);
24558 				/* REFRELE the current ire before looping */
24559 				ire_refrele(ire);
24560 				ire = ire1;
24561 				ire1 = NULL;
24562 				q = ire->ire_stq;
24563 				mp = next_mp;
24564 				next_mp = NULL;
24565 			}
24566 		} while (multirt_send);
24567 		/*
24568 		 * Restore the original ire; we need it for the
24569 		 * trailing frags
24570 		 */
24571 		if (save_ire != NULL) {
24572 			ASSERT(ire1 == NULL);
24573 			/* REFRELE the last iterated ire */
24574 			ire_refrele(ire);
24575 			/* save_ire has been REFHOLDed */
24576 			ire = save_ire;
24577 			q = ire->ire_stq;
24578 			save_ire = NULL;
24579 		}
24580 
24581 		if (last_frag) {
24582 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24583 			    "ip_wput_frag_end:(%S)",
24584 			    "consumed hdr_mp");
24585 
24586 			if (first_ire != NULL)
24587 				ire_refrele(first_ire);
24588 			return;
24589 		}
24590 		/* Otherwise, advance and loop. */
24591 		offset += len;
24592 	}
24593 
24594 drop_pkt:
24595 	/* Clean up following allocation failure. */
24596 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24597 	freemsg(mp);
24598 	if (mp != hdr_mp)
24599 		freeb(hdr_mp);
24600 	if (mp != mp_orig)
24601 		freemsg(mp_orig);
24602 
24603 	if (save_ire != NULL)
24604 		IRE_REFRELE(save_ire);
24605 	if (first_ire != NULL)
24606 		ire_refrele(first_ire);
24607 
24608 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24609 	    "ip_wput_frag_end:(%S)",
24610 	    "end--alloc failure");
24611 }
24612 
24613 /*
24614  * Copy the header plus those options which have the copy bit set
24615  */
24616 static mblk_t *
24617 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24618 {
24619 	mblk_t	*mp;
24620 	uchar_t	*up;
24621 
24622 	/*
24623 	 * Quick check if we need to look for options without the copy bit
24624 	 * set
24625 	 */
24626 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24627 	if (!mp)
24628 		return (mp);
24629 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24630 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24631 		bcopy(rptr, mp->b_rptr, hdr_len);
24632 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24633 		return (mp);
24634 	}
24635 	up  = mp->b_rptr;
24636 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24637 	up += IP_SIMPLE_HDR_LENGTH;
24638 	rptr += IP_SIMPLE_HDR_LENGTH;
24639 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24640 	while (hdr_len > 0) {
24641 		uint32_t optval;
24642 		uint32_t optlen;
24643 
24644 		optval = *rptr;
24645 		if (optval == IPOPT_EOL)
24646 			break;
24647 		if (optval == IPOPT_NOP)
24648 			optlen = 1;
24649 		else
24650 			optlen = rptr[1];
24651 		if (optval & IPOPT_COPY) {
24652 			bcopy(rptr, up, optlen);
24653 			up += optlen;
24654 		}
24655 		rptr += optlen;
24656 		hdr_len -= optlen;
24657 	}
24658 	/*
24659 	 * Make sure that we drop an even number of words by filling
24660 	 * with EOL to the next word boundary.
24661 	 */
24662 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24663 	    hdr_len & 0x3; hdr_len++)
24664 		*up++ = IPOPT_EOL;
24665 	mp->b_wptr = up;
24666 	/* Update header length */
24667 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24668 	return (mp);
24669 }
24670 
24671 /*
24672  * Delivery to local recipients including fanout to multiple recipients.
24673  * Does not do checksumming of UDP/TCP.
24674  * Note: q should be the read side queue for either the ill or conn.
24675  * Note: rq should be the read side q for the lower (ill) stream.
24676  * We don't send packets to IPPF processing, thus the last argument
24677  * to all the fanout calls are B_FALSE.
24678  */
24679 void
24680 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24681     int fanout_flags, zoneid_t zoneid)
24682 {
24683 	uint32_t	protocol;
24684 	mblk_t		*first_mp;
24685 	boolean_t	mctl_present;
24686 	int		ire_type;
24687 #define	rptr	((uchar_t *)ipha)
24688 	ip_stack_t	*ipst = ill->ill_ipst;
24689 
24690 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24691 	    "ip_wput_local_start: q %p", q);
24692 
24693 	if (ire != NULL) {
24694 		ire_type = ire->ire_type;
24695 	} else {
24696 		/*
24697 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24698 		 * packet is not multicast, we can't tell the ire type.
24699 		 */
24700 		ASSERT(CLASSD(ipha->ipha_dst));
24701 		ire_type = IRE_BROADCAST;
24702 	}
24703 
24704 	first_mp = mp;
24705 	if (first_mp->b_datap->db_type == M_CTL) {
24706 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24707 		if (!io->ipsec_out_secure) {
24708 			/*
24709 			 * This ipsec_out_t was allocated in ip_wput
24710 			 * for multicast packets to store the ill_index.
24711 			 * As this is being delivered locally, we don't
24712 			 * need this anymore.
24713 			 */
24714 			mp = first_mp->b_cont;
24715 			freeb(first_mp);
24716 			first_mp = mp;
24717 			mctl_present = B_FALSE;
24718 		} else {
24719 			/*
24720 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24721 			 * security properties for the looped-back packet.
24722 			 */
24723 			mctl_present = B_TRUE;
24724 			mp = first_mp->b_cont;
24725 			ASSERT(mp != NULL);
24726 			ipsec_out_to_in(first_mp);
24727 		}
24728 	} else {
24729 		mctl_present = B_FALSE;
24730 	}
24731 
24732 	DTRACE_PROBE4(ip4__loopback__in__start,
24733 	    ill_t *, ill, ill_t *, NULL,
24734 	    ipha_t *, ipha, mblk_t *, first_mp);
24735 
24736 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24737 	    ipst->ips_ipv4firewall_loopback_in,
24738 	    ill, NULL, ipha, first_mp, mp, ipst);
24739 
24740 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24741 
24742 	if (first_mp == NULL)
24743 		return;
24744 
24745 	ipst->ips_loopback_packets++;
24746 
24747 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24748 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24749 	if (!IS_SIMPLE_IPH(ipha)) {
24750 		ip_wput_local_options(ipha, ipst);
24751 	}
24752 
24753 	protocol = ipha->ipha_protocol;
24754 	switch (protocol) {
24755 	case IPPROTO_ICMP: {
24756 		ire_t		*ire_zone;
24757 		ilm_t		*ilm;
24758 		mblk_t		*mp1;
24759 		zoneid_t	last_zoneid;
24760 
24761 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24762 			ASSERT(ire_type == IRE_BROADCAST);
24763 			/*
24764 			 * In the multicast case, applications may have joined
24765 			 * the group from different zones, so we need to deliver
24766 			 * the packet to each of them. Loop through the
24767 			 * multicast memberships structures (ilm) on the receive
24768 			 * ill and send a copy of the packet up each matching
24769 			 * one. However, we don't do this for multicasts sent on
24770 			 * the loopback interface (PHYI_LOOPBACK flag set) as
24771 			 * they must stay in the sender's zone.
24772 			 *
24773 			 * ilm_add_v6() ensures that ilms in the same zone are
24774 			 * contiguous in the ill_ilm list. We use this property
24775 			 * to avoid sending duplicates needed when two
24776 			 * applications in the same zone join the same group on
24777 			 * different logical interfaces: we ignore the ilm if
24778 			 * it's zoneid is the same as the last matching one.
24779 			 * In addition, the sending of the packet for
24780 			 * ire_zoneid is delayed until all of the other ilms
24781 			 * have been exhausted.
24782 			 */
24783 			last_zoneid = -1;
24784 			ILM_WALKER_HOLD(ill);
24785 			for (ilm = ill->ill_ilm; ilm != NULL;
24786 			    ilm = ilm->ilm_next) {
24787 				if ((ilm->ilm_flags & ILM_DELETED) ||
24788 				    ipha->ipha_dst != ilm->ilm_addr ||
24789 				    ilm->ilm_zoneid == last_zoneid ||
24790 				    ilm->ilm_zoneid == zoneid ||
24791 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
24792 					continue;
24793 				mp1 = ip_copymsg(first_mp);
24794 				if (mp1 == NULL)
24795 					continue;
24796 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24797 				    mctl_present, B_FALSE, ill,
24798 				    ilm->ilm_zoneid);
24799 				last_zoneid = ilm->ilm_zoneid;
24800 			}
24801 			ILM_WALKER_RELE(ill);
24802 			/*
24803 			 * Loopback case: the sending endpoint has
24804 			 * IP_MULTICAST_LOOP disabled, therefore we don't
24805 			 * dispatch the multicast packet to the sending zone.
24806 			 */
24807 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
24808 				freemsg(first_mp);
24809 				return;
24810 			}
24811 		} else if (ire_type == IRE_BROADCAST) {
24812 			/*
24813 			 * In the broadcast case, there may be many zones
24814 			 * which need a copy of the packet delivered to them.
24815 			 * There is one IRE_BROADCAST per broadcast address
24816 			 * and per zone; we walk those using a helper function.
24817 			 * In addition, the sending of the packet for zoneid is
24818 			 * delayed until all of the other ires have been
24819 			 * processed.
24820 			 */
24821 			IRB_REFHOLD(ire->ire_bucket);
24822 			ire_zone = NULL;
24823 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
24824 			    ire)) != NULL) {
24825 				mp1 = ip_copymsg(first_mp);
24826 				if (mp1 == NULL)
24827 					continue;
24828 
24829 				UPDATE_IB_PKT_COUNT(ire_zone);
24830 				ire_zone->ire_last_used_time = lbolt;
24831 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
24832 				    mctl_present, B_FALSE, ill,
24833 				    ire_zone->ire_zoneid);
24834 			}
24835 			IRB_REFRELE(ire->ire_bucket);
24836 		}
24837 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
24838 		    0, mctl_present, B_FALSE, ill, zoneid);
24839 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24840 		    "ip_wput_local_end: q %p (%S)",
24841 		    q, "icmp");
24842 		return;
24843 	}
24844 	case IPPROTO_IGMP:
24845 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
24846 			/* Bad packet - discarded by igmp_input */
24847 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24848 			    "ip_wput_local_end: q %p (%S)",
24849 			    q, "igmp_input--bad packet");
24850 			if (mctl_present)
24851 				freeb(first_mp);
24852 			return;
24853 		}
24854 		/*
24855 		 * igmp_input() may have returned the pulled up message.
24856 		 * So first_mp and ipha need to be reinitialized.
24857 		 */
24858 		ipha = (ipha_t *)mp->b_rptr;
24859 		if (mctl_present)
24860 			first_mp->b_cont = mp;
24861 		else
24862 			first_mp = mp;
24863 		/* deliver to local raw users */
24864 		break;
24865 	case IPPROTO_ENCAP:
24866 		/*
24867 		 * This case is covered by either ip_fanout_proto, or by
24868 		 * the above security processing for self-tunneled packets.
24869 		 */
24870 		break;
24871 	case IPPROTO_UDP: {
24872 		uint16_t	*up;
24873 		uint32_t	ports;
24874 
24875 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
24876 		    UDP_PORTS_OFFSET);
24877 		/* Force a 'valid' checksum. */
24878 		up[3] = 0;
24879 
24880 		ports = *(uint32_t *)up;
24881 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
24882 		    (ire_type == IRE_BROADCAST),
24883 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24884 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
24885 		    ill, zoneid);
24886 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24887 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
24888 		return;
24889 	}
24890 	case IPPROTO_TCP: {
24891 
24892 		/*
24893 		 * For TCP, discard broadcast packets.
24894 		 */
24895 		if ((ushort_t)ire_type == IRE_BROADCAST) {
24896 			freemsg(first_mp);
24897 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
24898 			ip2dbg(("ip_wput_local: discard broadcast\n"));
24899 			return;
24900 		}
24901 
24902 		if (mp->b_datap->db_type == M_DATA) {
24903 			/*
24904 			 * M_DATA mblk, so init mblk (chain) for no struio().
24905 			 */
24906 			mblk_t	*mp1 = mp;
24907 
24908 			do {
24909 				mp1->b_datap->db_struioflag = 0;
24910 			} while ((mp1 = mp1->b_cont) != NULL);
24911 		}
24912 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
24913 		    <= mp->b_wptr);
24914 		ip_fanout_tcp(q, first_mp, ill, ipha,
24915 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24916 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
24917 		    mctl_present, B_FALSE, zoneid);
24918 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24919 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
24920 		return;
24921 	}
24922 	case IPPROTO_SCTP:
24923 	{
24924 		uint32_t	ports;
24925 
24926 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
24927 		ip_fanout_sctp(first_mp, ill, ipha, ports,
24928 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
24929 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
24930 		return;
24931 	}
24932 
24933 	default:
24934 		break;
24935 	}
24936 	/*
24937 	 * Find a client for some other protocol.  We give
24938 	 * copies to multiple clients, if more than one is
24939 	 * bound.
24940 	 */
24941 	ip_fanout_proto(q, first_mp, ill, ipha,
24942 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
24943 	    mctl_present, B_FALSE, ill, zoneid);
24944 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
24945 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
24946 #undef	rptr
24947 }
24948 
24949 /*
24950  * Update any source route, record route, or timestamp options.
24951  * Check that we are at end of strict source route.
24952  * The options have been sanity checked by ip_wput_options().
24953  */
24954 static void
24955 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
24956 {
24957 	ipoptp_t	opts;
24958 	uchar_t		*opt;
24959 	uint8_t		optval;
24960 	uint8_t		optlen;
24961 	ipaddr_t	dst;
24962 	uint32_t	ts;
24963 	ire_t		*ire;
24964 	timestruc_t	now;
24965 
24966 	ip2dbg(("ip_wput_local_options\n"));
24967 	for (optval = ipoptp_first(&opts, ipha);
24968 	    optval != IPOPT_EOL;
24969 	    optval = ipoptp_next(&opts)) {
24970 		opt = opts.ipoptp_cur;
24971 		optlen = opts.ipoptp_len;
24972 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
24973 		switch (optval) {
24974 			uint32_t off;
24975 		case IPOPT_SSRR:
24976 		case IPOPT_LSRR:
24977 			off = opt[IPOPT_OFFSET];
24978 			off--;
24979 			if (optlen < IP_ADDR_LEN ||
24980 			    off > optlen - IP_ADDR_LEN) {
24981 				/* End of source route */
24982 				break;
24983 			}
24984 			/*
24985 			 * This will only happen if two consecutive entries
24986 			 * in the source route contains our address or if
24987 			 * it is a packet with a loose source route which
24988 			 * reaches us before consuming the whole source route
24989 			 */
24990 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
24991 			if (optval == IPOPT_SSRR) {
24992 				return;
24993 			}
24994 			/*
24995 			 * Hack: instead of dropping the packet truncate the
24996 			 * source route to what has been used by filling the
24997 			 * rest with IPOPT_NOP.
24998 			 */
24999 			opt[IPOPT_OLEN] = (uint8_t)off;
25000 			while (off < optlen) {
25001 				opt[off++] = IPOPT_NOP;
25002 			}
25003 			break;
25004 		case IPOPT_RR:
25005 			off = opt[IPOPT_OFFSET];
25006 			off--;
25007 			if (optlen < IP_ADDR_LEN ||
25008 			    off > optlen - IP_ADDR_LEN) {
25009 				/* No more room - ignore */
25010 				ip1dbg((
25011 				    "ip_wput_forward_options: end of RR\n"));
25012 				break;
25013 			}
25014 			dst = htonl(INADDR_LOOPBACK);
25015 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25016 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25017 			break;
25018 		case IPOPT_TS:
25019 			/* Insert timestamp if there is romm */
25020 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25021 			case IPOPT_TS_TSONLY:
25022 				off = IPOPT_TS_TIMELEN;
25023 				break;
25024 			case IPOPT_TS_PRESPEC:
25025 			case IPOPT_TS_PRESPEC_RFC791:
25026 				/* Verify that the address matched */
25027 				off = opt[IPOPT_OFFSET] - 1;
25028 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25029 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25030 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25031 				    ipst);
25032 				if (ire == NULL) {
25033 					/* Not for us */
25034 					break;
25035 				}
25036 				ire_refrele(ire);
25037 				/* FALLTHRU */
25038 			case IPOPT_TS_TSANDADDR:
25039 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25040 				break;
25041 			default:
25042 				/*
25043 				 * ip_*put_options should have already
25044 				 * dropped this packet.
25045 				 */
25046 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25047 				    "unknown IT - bug in ip_wput_options?\n");
25048 				return;	/* Keep "lint" happy */
25049 			}
25050 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25051 				/* Increase overflow counter */
25052 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25053 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25054 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25055 				    (off << 4);
25056 				break;
25057 			}
25058 			off = opt[IPOPT_OFFSET] - 1;
25059 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25060 			case IPOPT_TS_PRESPEC:
25061 			case IPOPT_TS_PRESPEC_RFC791:
25062 			case IPOPT_TS_TSANDADDR:
25063 				dst = htonl(INADDR_LOOPBACK);
25064 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25065 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25066 				/* FALLTHRU */
25067 			case IPOPT_TS_TSONLY:
25068 				off = opt[IPOPT_OFFSET] - 1;
25069 				/* Compute # of milliseconds since midnight */
25070 				gethrestime(&now);
25071 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25072 				    now.tv_nsec / (NANOSEC / MILLISEC);
25073 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25074 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25075 				break;
25076 			}
25077 			break;
25078 		}
25079 	}
25080 }
25081 
25082 /*
25083  * Send out a multicast packet on interface ipif.
25084  * The sender does not have an conn.
25085  * Caller verifies that this isn't a PHYI_LOOPBACK.
25086  */
25087 void
25088 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25089 {
25090 	ipha_t	*ipha;
25091 	ire_t	*ire;
25092 	ipaddr_t	dst;
25093 	mblk_t		*first_mp;
25094 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25095 
25096 	/* igmp_sendpkt always allocates a ipsec_out_t */
25097 	ASSERT(mp->b_datap->db_type == M_CTL);
25098 	ASSERT(!ipif->ipif_isv6);
25099 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25100 
25101 	first_mp = mp;
25102 	mp = first_mp->b_cont;
25103 	ASSERT(mp->b_datap->db_type == M_DATA);
25104 	ipha = (ipha_t *)mp->b_rptr;
25105 
25106 	/*
25107 	 * Find an IRE which matches the destination and the outgoing
25108 	 * queue (i.e. the outgoing interface.)
25109 	 */
25110 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25111 		dst = ipif->ipif_pp_dst_addr;
25112 	else
25113 		dst = ipha->ipha_dst;
25114 	/*
25115 	 * The source address has already been initialized by the
25116 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25117 	 * be sufficient rather than MATCH_IRE_IPIF.
25118 	 *
25119 	 * This function is used for sending IGMP packets. We need
25120 	 * to make sure that we send the packet out of the interface
25121 	 * (ipif->ipif_ill) where we joined the group. This is to
25122 	 * prevent from switches doing IGMP snooping to send us multicast
25123 	 * packets for a given group on the interface we have joined.
25124 	 * If we can't find an ire, igmp_sendpkt has already initialized
25125 	 * ipsec_out_attach_if so that this will not be load spread in
25126 	 * ip_newroute_ipif.
25127 	 */
25128 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25129 	    MATCH_IRE_ILL, ipst);
25130 	if (!ire) {
25131 		/*
25132 		 * Mark this packet to make it be delivered to
25133 		 * ip_wput_ire after the new ire has been
25134 		 * created.
25135 		 */
25136 		mp->b_prev = NULL;
25137 		mp->b_next = NULL;
25138 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25139 		    zoneid, &zero_info);
25140 		return;
25141 	}
25142 
25143 	/*
25144 	 * Honor the RTF_SETSRC flag; this is the only case
25145 	 * where we force this addr whatever the current src addr is,
25146 	 * because this address is set by igmp_sendpkt(), and
25147 	 * cannot be specified by any user.
25148 	 */
25149 	if (ire->ire_flags & RTF_SETSRC) {
25150 		ipha->ipha_src = ire->ire_src_addr;
25151 	}
25152 
25153 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25154 }
25155 
25156 /*
25157  * NOTE : This function does not ire_refrele the ire argument passed in.
25158  *
25159  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25160  * failure. The nce_fp_mp can vanish any time in the case of
25161  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25162  * the ire_lock to access the nce_fp_mp in this case.
25163  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25164  * prepending a fastpath message IPQoS processing must precede it, we also set
25165  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25166  * (IPQoS might have set the b_band for CoS marking).
25167  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25168  * must follow it so that IPQoS can mark the dl_priority field for CoS
25169  * marking, if needed.
25170  */
25171 static mblk_t *
25172 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25173 {
25174 	uint_t	hlen;
25175 	ipha_t *ipha;
25176 	mblk_t *mp1;
25177 	boolean_t qos_done = B_FALSE;
25178 	uchar_t	*ll_hdr;
25179 	ip_stack_t	*ipst = ire->ire_ipst;
25180 
25181 #define	rptr	((uchar_t *)ipha)
25182 
25183 	ipha = (ipha_t *)mp->b_rptr;
25184 	hlen = 0;
25185 	LOCK_IRE_FP_MP(ire);
25186 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25187 		ASSERT(DB_TYPE(mp1) == M_DATA);
25188 		/* Initiate IPPF processing */
25189 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25190 			UNLOCK_IRE_FP_MP(ire);
25191 			ip_process(proc, &mp, ill_index);
25192 			if (mp == NULL)
25193 				return (NULL);
25194 
25195 			ipha = (ipha_t *)mp->b_rptr;
25196 			LOCK_IRE_FP_MP(ire);
25197 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25198 				qos_done = B_TRUE;
25199 				goto no_fp_mp;
25200 			}
25201 			ASSERT(DB_TYPE(mp1) == M_DATA);
25202 		}
25203 		hlen = MBLKL(mp1);
25204 		/*
25205 		 * Check if we have enough room to prepend fastpath
25206 		 * header
25207 		 */
25208 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25209 			ll_hdr = rptr - hlen;
25210 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25211 			/*
25212 			 * Set the b_rptr to the start of the link layer
25213 			 * header
25214 			 */
25215 			mp->b_rptr = ll_hdr;
25216 			mp1 = mp;
25217 		} else {
25218 			mp1 = copyb(mp1);
25219 			if (mp1 == NULL)
25220 				goto unlock_err;
25221 			mp1->b_band = mp->b_band;
25222 			mp1->b_cont = mp;
25223 			/*
25224 			 * certain system generated traffic may not
25225 			 * have cred/label in ip header block. This
25226 			 * is true even for a labeled system. But for
25227 			 * labeled traffic, inherit the label in the
25228 			 * new header.
25229 			 */
25230 			if (DB_CRED(mp) != NULL)
25231 				mblk_setcred(mp1, DB_CRED(mp));
25232 			/*
25233 			 * XXX disable ICK_VALID and compute checksum
25234 			 * here; can happen if nce_fp_mp changes and
25235 			 * it can't be copied now due to insufficient
25236 			 * space. (unlikely, fp mp can change, but it
25237 			 * does not increase in length)
25238 			 */
25239 		}
25240 		UNLOCK_IRE_FP_MP(ire);
25241 	} else {
25242 no_fp_mp:
25243 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25244 		if (mp1 == NULL) {
25245 unlock_err:
25246 			UNLOCK_IRE_FP_MP(ire);
25247 			freemsg(mp);
25248 			return (NULL);
25249 		}
25250 		UNLOCK_IRE_FP_MP(ire);
25251 		mp1->b_cont = mp;
25252 		/*
25253 		 * certain system generated traffic may not
25254 		 * have cred/label in ip header block. This
25255 		 * is true even for a labeled system. But for
25256 		 * labeled traffic, inherit the label in the
25257 		 * new header.
25258 		 */
25259 		if (DB_CRED(mp) != NULL)
25260 			mblk_setcred(mp1, DB_CRED(mp));
25261 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25262 			ip_process(proc, &mp1, ill_index);
25263 			if (mp1 == NULL)
25264 				return (NULL);
25265 		}
25266 	}
25267 	return (mp1);
25268 #undef rptr
25269 }
25270 
25271 /*
25272  * Finish the outbound IPsec processing for an IPv6 packet. This function
25273  * is called from ipsec_out_process() if the IPsec packet was processed
25274  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25275  * asynchronously.
25276  */
25277 void
25278 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25279     ire_t *ire_arg)
25280 {
25281 	in6_addr_t *v6dstp;
25282 	ire_t *ire;
25283 	mblk_t *mp;
25284 	ip6_t *ip6h1;
25285 	uint_t	ill_index;
25286 	ipsec_out_t *io;
25287 	boolean_t attach_if, hwaccel;
25288 	uint32_t flags = IP6_NO_IPPOLICY;
25289 	int match_flags;
25290 	zoneid_t zoneid;
25291 	boolean_t ill_need_rele = B_FALSE;
25292 	boolean_t ire_need_rele = B_FALSE;
25293 	ip_stack_t	*ipst;
25294 
25295 	mp = ipsec_mp->b_cont;
25296 	ip6h1 = (ip6_t *)mp->b_rptr;
25297 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25298 	ASSERT(io->ipsec_out_ns != NULL);
25299 	ipst = io->ipsec_out_ns->netstack_ip;
25300 	ill_index = io->ipsec_out_ill_index;
25301 	if (io->ipsec_out_reachable) {
25302 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25303 	}
25304 	attach_if = io->ipsec_out_attach_if;
25305 	hwaccel = io->ipsec_out_accelerated;
25306 	zoneid = io->ipsec_out_zoneid;
25307 	ASSERT(zoneid != ALL_ZONES);
25308 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25309 	/* Multicast addresses should have non-zero ill_index. */
25310 	v6dstp = &ip6h->ip6_dst;
25311 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25312 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25313 	ASSERT(!attach_if || ill_index != 0);
25314 	if (ill_index != 0) {
25315 		if (ill == NULL) {
25316 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25317 			    B_TRUE, ipst);
25318 
25319 			/* Failure case frees things for us. */
25320 			if (ill == NULL)
25321 				return;
25322 
25323 			ill_need_rele = B_TRUE;
25324 		}
25325 		/*
25326 		 * If this packet needs to go out on a particular interface
25327 		 * honor it.
25328 		 */
25329 		if (attach_if) {
25330 			match_flags = MATCH_IRE_ILL;
25331 
25332 			/*
25333 			 * Check if we need an ire that will not be
25334 			 * looked up by anybody else i.e. HIDDEN.
25335 			 */
25336 			if (ill_is_probeonly(ill)) {
25337 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25338 			}
25339 		}
25340 	}
25341 	ASSERT(mp != NULL);
25342 
25343 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25344 		boolean_t unspec_src;
25345 		ipif_t	*ipif;
25346 
25347 		/*
25348 		 * Use the ill_index to get the right ill.
25349 		 */
25350 		unspec_src = io->ipsec_out_unspec_src;
25351 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25352 		if (ipif == NULL) {
25353 			if (ill_need_rele)
25354 				ill_refrele(ill);
25355 			freemsg(ipsec_mp);
25356 			return;
25357 		}
25358 
25359 		if (ire_arg != NULL) {
25360 			ire = ire_arg;
25361 		} else {
25362 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25363 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25364 			ire_need_rele = B_TRUE;
25365 		}
25366 		if (ire != NULL) {
25367 			ipif_refrele(ipif);
25368 			/*
25369 			 * XXX Do the multicast forwarding now, as the IPSEC
25370 			 * processing has been done.
25371 			 */
25372 			goto send;
25373 		}
25374 
25375 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25376 		mp->b_prev = NULL;
25377 		mp->b_next = NULL;
25378 
25379 		/*
25380 		 * If the IPsec packet was processed asynchronously,
25381 		 * drop it now.
25382 		 */
25383 		if (q == NULL) {
25384 			if (ill_need_rele)
25385 				ill_refrele(ill);
25386 			freemsg(ipsec_mp);
25387 			return;
25388 		}
25389 
25390 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25391 		    unspec_src, zoneid);
25392 		ipif_refrele(ipif);
25393 	} else {
25394 		if (attach_if) {
25395 			ipif_t	*ipif;
25396 
25397 			ipif = ipif_get_next_ipif(NULL, ill);
25398 			if (ipif == NULL) {
25399 				if (ill_need_rele)
25400 					ill_refrele(ill);
25401 				freemsg(ipsec_mp);
25402 				return;
25403 			}
25404 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25405 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25406 			ire_need_rele = B_TRUE;
25407 			ipif_refrele(ipif);
25408 		} else {
25409 			if (ire_arg != NULL) {
25410 				ire = ire_arg;
25411 			} else {
25412 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25413 				    ipst);
25414 				ire_need_rele = B_TRUE;
25415 			}
25416 		}
25417 		if (ire != NULL)
25418 			goto send;
25419 		/*
25420 		 * ire disappeared underneath.
25421 		 *
25422 		 * What we need to do here is the ip_newroute
25423 		 * logic to get the ire without doing the IPSEC
25424 		 * processing. Follow the same old path. But this
25425 		 * time, ip_wput or ire_add_then_send will call us
25426 		 * directly as all the IPSEC operations are done.
25427 		 */
25428 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25429 		mp->b_prev = NULL;
25430 		mp->b_next = NULL;
25431 
25432 		/*
25433 		 * If the IPsec packet was processed asynchronously,
25434 		 * drop it now.
25435 		 */
25436 		if (q == NULL) {
25437 			if (ill_need_rele)
25438 				ill_refrele(ill);
25439 			freemsg(ipsec_mp);
25440 			return;
25441 		}
25442 
25443 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25444 		    zoneid, ipst);
25445 	}
25446 	if (ill != NULL && ill_need_rele)
25447 		ill_refrele(ill);
25448 	return;
25449 send:
25450 	if (ill != NULL && ill_need_rele)
25451 		ill_refrele(ill);
25452 
25453 	/* Local delivery */
25454 	if (ire->ire_stq == NULL) {
25455 		ill_t	*out_ill;
25456 		ASSERT(q != NULL);
25457 
25458 		/* PFHooks: LOOPBACK_OUT */
25459 		out_ill = ire->ire_ipif->ipif_ill;
25460 
25461 		DTRACE_PROBE4(ip6__loopback__out__start,
25462 		    ill_t *, NULL, ill_t *, out_ill,
25463 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25464 
25465 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25466 		    ipst->ips_ipv6firewall_loopback_out,
25467 		    NULL, out_ill, ip6h1, ipsec_mp, mp, ipst);
25468 
25469 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25470 
25471 		if (ipsec_mp != NULL)
25472 			ip_wput_local_v6(RD(q), out_ill,
25473 			    ip6h, ipsec_mp, ire, 0);
25474 		if (ire_need_rele)
25475 			ire_refrele(ire);
25476 		return;
25477 	}
25478 	/*
25479 	 * Everything is done. Send it out on the wire.
25480 	 * We force the insertion of a fragment header using the
25481 	 * IPH_FRAG_HDR flag in two cases:
25482 	 * - after reception of an ICMPv6 "packet too big" message
25483 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25484 	 * - for multirouted IPv6 packets, so that the receiver can
25485 	 *   discard duplicates according to their fragment identifier
25486 	 */
25487 	/* XXX fix flow control problems. */
25488 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25489 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25490 		if (hwaccel) {
25491 			/*
25492 			 * hardware acceleration does not handle these
25493 			 * "slow path" cases.
25494 			 */
25495 			/* IPsec KSTATS: should bump bean counter here. */
25496 			if (ire_need_rele)
25497 				ire_refrele(ire);
25498 			freemsg(ipsec_mp);
25499 			return;
25500 		}
25501 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25502 		    (mp->b_cont ? msgdsize(mp) :
25503 		    mp->b_wptr - (uchar_t *)ip6h)) {
25504 			/* IPsec KSTATS: should bump bean counter here. */
25505 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25506 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25507 			    msgdsize(mp)));
25508 			if (ire_need_rele)
25509 				ire_refrele(ire);
25510 			freemsg(ipsec_mp);
25511 			return;
25512 		}
25513 		ASSERT(mp->b_prev == NULL);
25514 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25515 		    ntohs(ip6h->ip6_plen) +
25516 		    IPV6_HDR_LEN, ire->ire_max_frag));
25517 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25518 		    ire->ire_max_frag);
25519 	} else {
25520 		UPDATE_OB_PKT_COUNT(ire);
25521 		ire->ire_last_used_time = lbolt;
25522 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25523 	}
25524 	if (ire_need_rele)
25525 		ire_refrele(ire);
25526 	freeb(ipsec_mp);
25527 }
25528 
25529 void
25530 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25531 {
25532 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25533 	da_ipsec_t *hada;	/* data attributes */
25534 	ill_t *ill = (ill_t *)q->q_ptr;
25535 
25536 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25537 
25538 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25539 		/* IPsec KSTATS: Bump lose counter here! */
25540 		freemsg(mp);
25541 		return;
25542 	}
25543 
25544 	/*
25545 	 * It's an IPsec packet that must be
25546 	 * accelerated by the Provider, and the
25547 	 * outbound ill is IPsec acceleration capable.
25548 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25549 	 * to the ill.
25550 	 * IPsec KSTATS: should bump packet counter here.
25551 	 */
25552 
25553 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25554 	if (hada_mp == NULL) {
25555 		/* IPsec KSTATS: should bump packet counter here. */
25556 		freemsg(mp);
25557 		return;
25558 	}
25559 
25560 	hada_mp->b_datap->db_type = M_CTL;
25561 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25562 	hada_mp->b_cont = mp;
25563 
25564 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25565 	bzero(hada, sizeof (da_ipsec_t));
25566 	hada->da_type = IPHADA_M_CTL;
25567 
25568 	putnext(q, hada_mp);
25569 }
25570 
25571 /*
25572  * Finish the outbound IPsec processing. This function is called from
25573  * ipsec_out_process() if the IPsec packet was processed
25574  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25575  * asynchronously.
25576  */
25577 void
25578 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25579     ire_t *ire_arg)
25580 {
25581 	uint32_t v_hlen_tos_len;
25582 	ipaddr_t	dst;
25583 	ipif_t	*ipif = NULL;
25584 	ire_t *ire;
25585 	ire_t *ire1 = NULL;
25586 	mblk_t *next_mp = NULL;
25587 	uint32_t max_frag;
25588 	boolean_t multirt_send = B_FALSE;
25589 	mblk_t *mp;
25590 	mblk_t *mp1;
25591 	ipha_t *ipha1;
25592 	uint_t	ill_index;
25593 	ipsec_out_t *io;
25594 	boolean_t attach_if;
25595 	int match_flags, offset;
25596 	irb_t *irb = NULL;
25597 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25598 	zoneid_t zoneid;
25599 	uint32_t cksum;
25600 	uint16_t *up;
25601 	ipxmit_state_t	pktxmit_state;
25602 	ip_stack_t	*ipst;
25603 
25604 #ifdef	_BIG_ENDIAN
25605 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25606 #else
25607 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25608 #endif
25609 
25610 	mp = ipsec_mp->b_cont;
25611 	ipha1 = (ipha_t *)mp->b_rptr;
25612 	ASSERT(mp != NULL);
25613 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25614 	dst = ipha->ipha_dst;
25615 
25616 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25617 	ill_index = io->ipsec_out_ill_index;
25618 	attach_if = io->ipsec_out_attach_if;
25619 	zoneid = io->ipsec_out_zoneid;
25620 	ASSERT(zoneid != ALL_ZONES);
25621 	ipst = io->ipsec_out_ns->netstack_ip;
25622 	ASSERT(io->ipsec_out_ns != NULL);
25623 
25624 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25625 	if (ill_index != 0) {
25626 		if (ill == NULL) {
25627 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25628 			    ill_index, B_FALSE, ipst);
25629 
25630 			/* Failure case frees things for us. */
25631 			if (ill == NULL)
25632 				return;
25633 
25634 			ill_need_rele = B_TRUE;
25635 		}
25636 		/*
25637 		 * If this packet needs to go out on a particular interface
25638 		 * honor it.
25639 		 */
25640 		if (attach_if) {
25641 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25642 
25643 			/*
25644 			 * Check if we need an ire that will not be
25645 			 * looked up by anybody else i.e. HIDDEN.
25646 			 */
25647 			if (ill_is_probeonly(ill)) {
25648 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25649 			}
25650 		}
25651 	}
25652 
25653 	if (CLASSD(dst)) {
25654 		boolean_t conn_dontroute;
25655 		/*
25656 		 * Use the ill_index to get the right ipif.
25657 		 */
25658 		conn_dontroute = io->ipsec_out_dontroute;
25659 		if (ill_index == 0)
25660 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25661 		else
25662 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25663 		if (ipif == NULL) {
25664 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25665 			    " multicast\n"));
25666 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25667 			freemsg(ipsec_mp);
25668 			goto done;
25669 		}
25670 		/*
25671 		 * ipha_src has already been intialized with the
25672 		 * value of the ipif in ip_wput. All we need now is
25673 		 * an ire to send this downstream.
25674 		 */
25675 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25676 		    MBLK_GETLABEL(mp), match_flags, ipst);
25677 		if (ire != NULL) {
25678 			ill_t *ill1;
25679 			/*
25680 			 * Do the multicast forwarding now, as the IPSEC
25681 			 * processing has been done.
25682 			 */
25683 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25684 			    (ill1 = ire_to_ill(ire))) {
25685 				if (ip_mforward(ill1, ipha, mp)) {
25686 					freemsg(ipsec_mp);
25687 					ip1dbg(("ip_wput_ipsec_out: mforward "
25688 					    "failed\n"));
25689 					ire_refrele(ire);
25690 					goto done;
25691 				}
25692 			}
25693 			goto send;
25694 		}
25695 
25696 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25697 		mp->b_prev = NULL;
25698 		mp->b_next = NULL;
25699 
25700 		/*
25701 		 * If the IPsec packet was processed asynchronously,
25702 		 * drop it now.
25703 		 */
25704 		if (q == NULL) {
25705 			freemsg(ipsec_mp);
25706 			goto done;
25707 		}
25708 
25709 		/*
25710 		 * We may be using a wrong ipif to create the ire.
25711 		 * But it is okay as the source address is assigned
25712 		 * for the packet already. Next outbound packet would
25713 		 * create the IRE with the right IPIF in ip_wput.
25714 		 *
25715 		 * Also handle RTF_MULTIRT routes.
25716 		 */
25717 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25718 		    zoneid, &zero_info);
25719 	} else {
25720 		if (attach_if) {
25721 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25722 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25723 		} else {
25724 			if (ire_arg != NULL) {
25725 				ire = ire_arg;
25726 				ire_need_rele = B_FALSE;
25727 			} else {
25728 				ire = ire_cache_lookup(dst, zoneid,
25729 				    MBLK_GETLABEL(mp), ipst);
25730 			}
25731 		}
25732 		if (ire != NULL) {
25733 			goto send;
25734 		}
25735 
25736 		/*
25737 		 * ire disappeared underneath.
25738 		 *
25739 		 * What we need to do here is the ip_newroute
25740 		 * logic to get the ire without doing the IPSEC
25741 		 * processing. Follow the same old path. But this
25742 		 * time, ip_wput or ire_add_then_put will call us
25743 		 * directly as all the IPSEC operations are done.
25744 		 */
25745 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25746 		mp->b_prev = NULL;
25747 		mp->b_next = NULL;
25748 
25749 		/*
25750 		 * If the IPsec packet was processed asynchronously,
25751 		 * drop it now.
25752 		 */
25753 		if (q == NULL) {
25754 			freemsg(ipsec_mp);
25755 			goto done;
25756 		}
25757 
25758 		/*
25759 		 * Since we're going through ip_newroute() again, we
25760 		 * need to make sure we don't:
25761 		 *
25762 		 *	1.) Trigger the ASSERT() with the ipha_ident
25763 		 *	    overloading.
25764 		 *	2.) Redo transport-layer checksumming, since we've
25765 		 *	    already done all that to get this far.
25766 		 *
25767 		 * The easiest way not do either of the above is to set
25768 		 * the ipha_ident field to IP_HDR_INCLUDED.
25769 		 */
25770 		ipha->ipha_ident = IP_HDR_INCLUDED;
25771 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25772 		    zoneid, ipst);
25773 	}
25774 	goto done;
25775 send:
25776 	if (ipha->ipha_protocol == IPPROTO_UDP &&
25777 	    udp_compute_checksum(ipst->ips_netstack)) {
25778 		/*
25779 		 * ESP NAT-Traversal packet.
25780 		 *
25781 		 * Just do software checksum for now.
25782 		 */
25783 
25784 		offset = IP_SIMPLE_HDR_LENGTH + UDP_CHECKSUM_OFFSET;
25785 		IP_STAT(ipst, ip_out_sw_cksum);
25786 		IP_STAT_UPDATE(ipst, ip_udp_out_sw_cksum_bytes,
25787 		    ntohs(htons(ipha->ipha_length) - IP_SIMPLE_HDR_LENGTH));
25788 #define	iphs	((uint16_t *)ipha)
25789 		cksum = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
25790 		    iphs[9] + ntohs(htons(ipha->ipha_length) -
25791 		    IP_SIMPLE_HDR_LENGTH);
25792 #undef iphs
25793 		cksum = IP_CSUM(mp, IP_SIMPLE_HDR_LENGTH, cksum);
25794 		for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont)
25795 			if (mp1->b_wptr - mp1->b_rptr >=
25796 			    offset + sizeof (uint16_t)) {
25797 				up = (uint16_t *)(mp1->b_rptr + offset);
25798 				*up = cksum;
25799 				break;	/* out of for loop */
25800 			} else {
25801 				offset -= (mp->b_wptr - mp->b_rptr);
25802 			}
25803 	} /* Otherwise, just keep the all-zero checksum. */
25804 
25805 	if (ire->ire_stq == NULL) {
25806 		ill_t	*out_ill;
25807 		/*
25808 		 * Loopbacks go through ip_wput_local except for one case.
25809 		 * We come here if we generate a icmp_frag_needed message
25810 		 * after IPSEC processing is over. When this function calls
25811 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
25812 		 * icmp_frag_needed. The message generated comes back here
25813 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
25814 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
25815 		 * source address as it is usually set in ip_wput_ire. As
25816 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
25817 		 * and we end up here. We can't enter ip_wput_ire once the
25818 		 * IPSEC processing is over and hence we need to do it here.
25819 		 */
25820 		ASSERT(q != NULL);
25821 		UPDATE_OB_PKT_COUNT(ire);
25822 		ire->ire_last_used_time = lbolt;
25823 		if (ipha->ipha_src == 0)
25824 			ipha->ipha_src = ire->ire_src_addr;
25825 
25826 		/* PFHooks: LOOPBACK_OUT */
25827 		out_ill = ire->ire_ipif->ipif_ill;
25828 
25829 		DTRACE_PROBE4(ip4__loopback__out__start,
25830 		    ill_t *, NULL, ill_t *, out_ill,
25831 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
25832 
25833 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
25834 		    ipst->ips_ipv4firewall_loopback_out,
25835 		    NULL, out_ill, ipha1, ipsec_mp, mp, ipst);
25836 
25837 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
25838 
25839 		if (ipsec_mp != NULL)
25840 			ip_wput_local(RD(q), out_ill,
25841 			    ipha, ipsec_mp, ire, 0, zoneid);
25842 		if (ire_need_rele)
25843 			ire_refrele(ire);
25844 		goto done;
25845 	}
25846 
25847 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
25848 		/*
25849 		 * We are through with IPSEC processing.
25850 		 * Fragment this and send it on the wire.
25851 		 */
25852 		if (io->ipsec_out_accelerated) {
25853 			/*
25854 			 * The packet has been accelerated but must
25855 			 * be fragmented. This should not happen
25856 			 * since AH and ESP must not accelerate
25857 			 * packets that need fragmentation, however
25858 			 * the configuration could have changed
25859 			 * since the AH or ESP processing.
25860 			 * Drop packet.
25861 			 * IPsec KSTATS: bump bean counter here.
25862 			 */
25863 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
25864 			    "fragmented accelerated packet!\n"));
25865 			freemsg(ipsec_mp);
25866 		} else {
25867 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
25868 		}
25869 		if (ire_need_rele)
25870 			ire_refrele(ire);
25871 		goto done;
25872 	}
25873 
25874 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
25875 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
25876 	    (void *)ire->ire_ipif, (void *)ipif));
25877 
25878 	/*
25879 	 * Multiroute the secured packet, unless IPsec really
25880 	 * requires the packet to go out only through a particular
25881 	 * interface.
25882 	 */
25883 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
25884 		ire_t *first_ire;
25885 		irb = ire->ire_bucket;
25886 		ASSERT(irb != NULL);
25887 		/*
25888 		 * This ire has been looked up as the one that
25889 		 * goes through the given ipif;
25890 		 * make sure we do not omit any other multiroute ire
25891 		 * that may be present in the bucket before this one.
25892 		 */
25893 		IRB_REFHOLD(irb);
25894 		for (first_ire = irb->irb_ire;
25895 		    first_ire != NULL;
25896 		    first_ire = first_ire->ire_next) {
25897 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
25898 			    (first_ire->ire_addr == ire->ire_addr) &&
25899 			    !(first_ire->ire_marks &
25900 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
25901 				break;
25902 			}
25903 		}
25904 
25905 		if ((first_ire != NULL) && (first_ire != ire)) {
25906 			/*
25907 			 * Don't change the ire if the packet must
25908 			 * be fragmented if sent via this new one.
25909 			 */
25910 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
25911 				IRE_REFHOLD(first_ire);
25912 				if (ire_need_rele)
25913 					ire_refrele(ire);
25914 				else
25915 					ire_need_rele = B_TRUE;
25916 				ire = first_ire;
25917 			}
25918 		}
25919 		IRB_REFRELE(irb);
25920 
25921 		multirt_send = B_TRUE;
25922 		max_frag = ire->ire_max_frag;
25923 	} else {
25924 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
25925 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
25926 			    "flag, attach_if %d\n", attach_if));
25927 		}
25928 	}
25929 
25930 	/*
25931 	 * In most cases, the emission loop below is entered only once.
25932 	 * Only in the case where the ire holds the RTF_MULTIRT
25933 	 * flag, we loop to process all RTF_MULTIRT ires in the
25934 	 * bucket, and send the packet through all crossed
25935 	 * RTF_MULTIRT routes.
25936 	 */
25937 	do {
25938 		if (multirt_send) {
25939 			/*
25940 			 * ire1 holds here the next ire to process in the
25941 			 * bucket. If multirouting is expected,
25942 			 * any non-RTF_MULTIRT ire that has the
25943 			 * right destination address is ignored.
25944 			 */
25945 			ASSERT(irb != NULL);
25946 			IRB_REFHOLD(irb);
25947 			for (ire1 = ire->ire_next;
25948 			    ire1 != NULL;
25949 			    ire1 = ire1->ire_next) {
25950 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
25951 					continue;
25952 				if (ire1->ire_addr != ire->ire_addr)
25953 					continue;
25954 				if (ire1->ire_marks &
25955 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
25956 					continue;
25957 				/* No loopback here */
25958 				if (ire1->ire_stq == NULL)
25959 					continue;
25960 				/*
25961 				 * Ensure we do not exceed the MTU
25962 				 * of the next route.
25963 				 */
25964 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
25965 					ip_multirt_bad_mtu(ire1, max_frag);
25966 					continue;
25967 				}
25968 
25969 				IRE_REFHOLD(ire1);
25970 				break;
25971 			}
25972 			IRB_REFRELE(irb);
25973 			if (ire1 != NULL) {
25974 				/*
25975 				 * We are in a multiple send case, need to
25976 				 * make a copy of the packet.
25977 				 */
25978 				next_mp = copymsg(ipsec_mp);
25979 				if (next_mp == NULL) {
25980 					ire_refrele(ire1);
25981 					ire1 = NULL;
25982 				}
25983 			}
25984 		}
25985 		/*
25986 		 * Everything is done. Send it out on the wire
25987 		 *
25988 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
25989 		 * either send it on the wire or, in the case of
25990 		 * HW acceleration, call ipsec_hw_putnext.
25991 		 */
25992 		if (ire->ire_nce &&
25993 		    ire->ire_nce->nce_state != ND_REACHABLE) {
25994 			DTRACE_PROBE2(ip__wput__ipsec__bail,
25995 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
25996 			/*
25997 			 * If ire's link-layer is unresolved (this
25998 			 * would only happen if the incomplete ire
25999 			 * was added to cachetable via forwarding path)
26000 			 * don't bother going to ip_xmit_v4. Just drop the
26001 			 * packet.
26002 			 * There is a slight risk here, in that, if we
26003 			 * have the forwarding path create an incomplete
26004 			 * IRE, then until the IRE is completed, any
26005 			 * transmitted IPSEC packets will be dropped
26006 			 * instead of being queued waiting for resolution.
26007 			 *
26008 			 * But the likelihood of a forwarding packet and a wput
26009 			 * packet sending to the same dst at the same time
26010 			 * and there not yet be an ARP entry for it is small.
26011 			 * Furthermore, if this actually happens, it might
26012 			 * be likely that wput would generate multiple
26013 			 * packets (and forwarding would also have a train
26014 			 * of packets) for that destination. If this is
26015 			 * the case, some of them would have been dropped
26016 			 * anyway, since ARP only queues a few packets while
26017 			 * waiting for resolution
26018 			 *
26019 			 * NOTE: We should really call ip_xmit_v4,
26020 			 * and let it queue the packet and send the
26021 			 * ARP query and have ARP come back thus:
26022 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26023 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26024 			 * hw accel work. But it's too complex to get
26025 			 * the IPsec hw  acceleration approach to fit
26026 			 * well with ip_xmit_v4 doing ARP without
26027 			 * doing IPSEC simplification. For now, we just
26028 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26029 			 * that we can continue with the send on the next
26030 			 * attempt.
26031 			 *
26032 			 * XXX THis should be revisited, when
26033 			 * the IPsec/IP interaction is cleaned up
26034 			 */
26035 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26036 			    " - dropping packet\n"));
26037 			freemsg(ipsec_mp);
26038 			/*
26039 			 * Call ip_xmit_v4() to trigger ARP query
26040 			 * in case the nce_state is ND_INITIAL
26041 			 */
26042 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26043 			goto drop_pkt;
26044 		}
26045 
26046 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26047 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26048 		    mblk_t *, ipsec_mp);
26049 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26050 		    ipst->ips_ipv4firewall_physical_out,
26051 		    NULL, ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, ipst);
26052 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26053 		if (ipsec_mp == NULL)
26054 			goto drop_pkt;
26055 
26056 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26057 		pktxmit_state = ip_xmit_v4(mp, ire,
26058 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26059 
26060 		if ((pktxmit_state ==  SEND_FAILED) ||
26061 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26062 
26063 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26064 drop_pkt:
26065 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26066 			    ipIfStatsOutDiscards);
26067 			if (ire_need_rele)
26068 				ire_refrele(ire);
26069 			if (ire1 != NULL) {
26070 				ire_refrele(ire1);
26071 				freemsg(next_mp);
26072 			}
26073 			goto done;
26074 		}
26075 
26076 		freeb(ipsec_mp);
26077 		if (ire_need_rele)
26078 			ire_refrele(ire);
26079 
26080 		if (ire1 != NULL) {
26081 			ire = ire1;
26082 			ire_need_rele = B_TRUE;
26083 			ASSERT(next_mp);
26084 			ipsec_mp = next_mp;
26085 			mp = ipsec_mp->b_cont;
26086 			ire1 = NULL;
26087 			next_mp = NULL;
26088 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26089 		} else {
26090 			multirt_send = B_FALSE;
26091 		}
26092 	} while (multirt_send);
26093 done:
26094 	if (ill != NULL && ill_need_rele)
26095 		ill_refrele(ill);
26096 	if (ipif != NULL)
26097 		ipif_refrele(ipif);
26098 }
26099 
26100 /*
26101  * Get the ill corresponding to the specified ire, and compare its
26102  * capabilities with the protocol and algorithms specified by the
26103  * the SA obtained from ipsec_out. If they match, annotate the
26104  * ipsec_out structure to indicate that the packet needs acceleration.
26105  *
26106  *
26107  * A packet is eligible for outbound hardware acceleration if the
26108  * following conditions are satisfied:
26109  *
26110  * 1. the packet will not be fragmented
26111  * 2. the provider supports the algorithm
26112  * 3. there is no pending control message being exchanged
26113  * 4. snoop is not attached
26114  * 5. the destination address is not a broadcast or multicast address.
26115  *
26116  * Rationale:
26117  *	- Hardware drivers do not support fragmentation with
26118  *	  the current interface.
26119  *	- snoop, multicast, and broadcast may result in exposure of
26120  *	  a cleartext datagram.
26121  * We check all five of these conditions here.
26122  *
26123  * XXX would like to nuke "ire_t *" parameter here; problem is that
26124  * IRE is only way to figure out if a v4 address is a broadcast and
26125  * thus ineligible for acceleration...
26126  */
26127 static void
26128 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26129 {
26130 	ipsec_out_t *io;
26131 	mblk_t *data_mp;
26132 	uint_t plen, overhead;
26133 	ip_stack_t	*ipst;
26134 
26135 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26136 		return;
26137 
26138 	if (ill == NULL)
26139 		return;
26140 	ipst = ill->ill_ipst;
26141 	/*
26142 	 * Destination address is a broadcast or multicast.  Punt.
26143 	 */
26144 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26145 	    IRE_LOCAL)))
26146 		return;
26147 
26148 	data_mp = ipsec_mp->b_cont;
26149 
26150 	if (ill->ill_isv6) {
26151 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26152 
26153 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26154 			return;
26155 
26156 		plen = ip6h->ip6_plen;
26157 	} else {
26158 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26159 
26160 		if (CLASSD(ipha->ipha_dst))
26161 			return;
26162 
26163 		plen = ipha->ipha_length;
26164 	}
26165 	/*
26166 	 * Is there a pending DLPI control message being exchanged
26167 	 * between IP/IPsec and the DLS Provider? If there is, it
26168 	 * could be a SADB update, and the state of the DLS Provider
26169 	 * SADB might not be in sync with the SADB maintained by
26170 	 * IPsec. To avoid dropping packets or using the wrong keying
26171 	 * material, we do not accelerate this packet.
26172 	 */
26173 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26174 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26175 		    "ill_dlpi_pending! don't accelerate packet\n"));
26176 		return;
26177 	}
26178 
26179 	/*
26180 	 * Is the Provider in promiscous mode? If it does, we don't
26181 	 * accelerate the packet since it will bounce back up to the
26182 	 * listeners in the clear.
26183 	 */
26184 	if (ill->ill_promisc_on_phys) {
26185 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26186 		    "ill in promiscous mode, don't accelerate packet\n"));
26187 		return;
26188 	}
26189 
26190 	/*
26191 	 * Will the packet require fragmentation?
26192 	 */
26193 
26194 	/*
26195 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26196 	 * as is used elsewhere.
26197 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26198 	 *	+ 2-byte trailer
26199 	 */
26200 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26201 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26202 
26203 	if ((plen + overhead) > ill->ill_max_mtu)
26204 		return;
26205 
26206 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26207 
26208 	/*
26209 	 * Can the ill accelerate this IPsec protocol and algorithm
26210 	 * specified by the SA?
26211 	 */
26212 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26213 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26214 		return;
26215 	}
26216 
26217 	/*
26218 	 * Tell AH or ESP that the outbound ill is capable of
26219 	 * accelerating this packet.
26220 	 */
26221 	io->ipsec_out_is_capab_ill = B_TRUE;
26222 }
26223 
26224 /*
26225  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26226  *
26227  * If this function returns B_TRUE, the requested SA's have been filled
26228  * into the ipsec_out_*_sa pointers.
26229  *
26230  * If the function returns B_FALSE, the packet has been "consumed", most
26231  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26232  *
26233  * The SA references created by the protocol-specific "select"
26234  * function will be released when the ipsec_mp is freed, thanks to the
26235  * ipsec_out_free destructor -- see spd.c.
26236  */
26237 static boolean_t
26238 ipsec_out_select_sa(mblk_t *ipsec_mp)
26239 {
26240 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26241 	ipsec_out_t *io;
26242 	ipsec_policy_t *pp;
26243 	ipsec_action_t *ap;
26244 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26245 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26246 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26247 
26248 	if (!io->ipsec_out_secure) {
26249 		/*
26250 		 * We came here by mistake.
26251 		 * Don't bother with ipsec processing
26252 		 * We should "discourage" this path in the future.
26253 		 */
26254 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26255 		return (B_FALSE);
26256 	}
26257 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26258 	ASSERT((io->ipsec_out_policy != NULL) ||
26259 	    (io->ipsec_out_act != NULL));
26260 
26261 	ASSERT(io->ipsec_out_failed == B_FALSE);
26262 
26263 	/*
26264 	 * IPSEC processing has started.
26265 	 */
26266 	io->ipsec_out_proc_begin = B_TRUE;
26267 	ap = io->ipsec_out_act;
26268 	if (ap == NULL) {
26269 		pp = io->ipsec_out_policy;
26270 		ASSERT(pp != NULL);
26271 		ap = pp->ipsp_act;
26272 		ASSERT(ap != NULL);
26273 	}
26274 
26275 	/*
26276 	 * We have an action.  now, let's select SA's.
26277 	 * (In the future, we can cache this in the conn_t..)
26278 	 */
26279 	if (ap->ipa_want_esp) {
26280 		if (io->ipsec_out_esp_sa == NULL) {
26281 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26282 			    IPPROTO_ESP);
26283 		}
26284 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26285 	}
26286 
26287 	if (ap->ipa_want_ah) {
26288 		if (io->ipsec_out_ah_sa == NULL) {
26289 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26290 			    IPPROTO_AH);
26291 		}
26292 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26293 		/*
26294 		 * The ESP and AH processing order needs to be preserved
26295 		 * when both protocols are required (ESP should be applied
26296 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26297 		 * when both ESP and AH are required, and an AH ACQUIRE
26298 		 * is needed.
26299 		 */
26300 		if (ap->ipa_want_esp && need_ah_acquire)
26301 			need_esp_acquire = B_TRUE;
26302 	}
26303 
26304 	/*
26305 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26306 	 * Release SAs that got referenced, but will not be used until we
26307 	 * acquire _all_ of the SAs we need.
26308 	 */
26309 	if (need_ah_acquire || need_esp_acquire) {
26310 		if (io->ipsec_out_ah_sa != NULL) {
26311 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26312 			io->ipsec_out_ah_sa = NULL;
26313 		}
26314 		if (io->ipsec_out_esp_sa != NULL) {
26315 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26316 			io->ipsec_out_esp_sa = NULL;
26317 		}
26318 
26319 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26320 		return (B_FALSE);
26321 	}
26322 
26323 	return (B_TRUE);
26324 }
26325 
26326 /*
26327  * Process an IPSEC_OUT message and see what you can
26328  * do with it.
26329  * IPQoS Notes:
26330  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26331  * IPSec.
26332  * XXX would like to nuke ire_t.
26333  * XXX ill_index better be "real"
26334  */
26335 void
26336 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26337 {
26338 	ipsec_out_t *io;
26339 	ipsec_policy_t *pp;
26340 	ipsec_action_t *ap;
26341 	ipha_t *ipha;
26342 	ip6_t *ip6h;
26343 	mblk_t *mp;
26344 	ill_t *ill;
26345 	zoneid_t zoneid;
26346 	ipsec_status_t ipsec_rc;
26347 	boolean_t ill_need_rele = B_FALSE;
26348 	ip_stack_t	*ipst;
26349 	ipsec_stack_t	*ipss;
26350 
26351 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26352 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26353 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26354 	ipst = io->ipsec_out_ns->netstack_ip;
26355 	mp = ipsec_mp->b_cont;
26356 
26357 	/*
26358 	 * Initiate IPPF processing. We do it here to account for packets
26359 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26360 	 * We can check for ipsec_out_proc_begin even for such packets, as
26361 	 * they will always be false (asserted below).
26362 	 */
26363 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26364 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26365 		    io->ipsec_out_ill_index : ill_index);
26366 		if (mp == NULL) {
26367 			ip2dbg(("ipsec_out_process: packet dropped "\
26368 			    "during IPPF processing\n"));
26369 			freeb(ipsec_mp);
26370 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26371 			return;
26372 		}
26373 	}
26374 
26375 	if (!io->ipsec_out_secure) {
26376 		/*
26377 		 * We came here by mistake.
26378 		 * Don't bother with ipsec processing
26379 		 * Should "discourage" this path in the future.
26380 		 */
26381 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26382 		goto done;
26383 	}
26384 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26385 	ASSERT((io->ipsec_out_policy != NULL) ||
26386 	    (io->ipsec_out_act != NULL));
26387 	ASSERT(io->ipsec_out_failed == B_FALSE);
26388 
26389 	ipss = ipst->ips_netstack->netstack_ipsec;
26390 	if (!ipsec_loaded(ipss)) {
26391 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26392 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26393 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26394 		} else {
26395 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26396 		}
26397 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26398 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26399 		    &ipss->ipsec_dropper);
26400 		return;
26401 	}
26402 
26403 	/*
26404 	 * IPSEC processing has started.
26405 	 */
26406 	io->ipsec_out_proc_begin = B_TRUE;
26407 	ap = io->ipsec_out_act;
26408 	if (ap == NULL) {
26409 		pp = io->ipsec_out_policy;
26410 		ASSERT(pp != NULL);
26411 		ap = pp->ipsp_act;
26412 		ASSERT(ap != NULL);
26413 	}
26414 
26415 	/*
26416 	 * Save the outbound ill index. When the packet comes back
26417 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26418 	 * before sending it the accelerated packet.
26419 	 */
26420 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26421 		int ifindex;
26422 		ill = ire_to_ill(ire);
26423 		ifindex = ill->ill_phyint->phyint_ifindex;
26424 		io->ipsec_out_capab_ill_index = ifindex;
26425 	}
26426 
26427 	/*
26428 	 * The order of processing is first insert a IP header if needed.
26429 	 * Then insert the ESP header and then the AH header.
26430 	 */
26431 	if ((io->ipsec_out_se_done == B_FALSE) &&
26432 	    (ap->ipa_want_se)) {
26433 		/*
26434 		 * First get the outer IP header before sending
26435 		 * it to ESP.
26436 		 */
26437 		ipha_t *oipha, *iipha;
26438 		mblk_t *outer_mp, *inner_mp;
26439 
26440 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26441 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26442 			    "ipsec_out_process: "
26443 			    "Self-Encapsulation failed: Out of memory\n");
26444 			freemsg(ipsec_mp);
26445 			if (ill != NULL) {
26446 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26447 			} else {
26448 				BUMP_MIB(&ipst->ips_ip_mib,
26449 				    ipIfStatsOutDiscards);
26450 			}
26451 			return;
26452 		}
26453 		inner_mp = ipsec_mp->b_cont;
26454 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26455 		oipha = (ipha_t *)outer_mp->b_rptr;
26456 		iipha = (ipha_t *)inner_mp->b_rptr;
26457 		*oipha = *iipha;
26458 		outer_mp->b_wptr += sizeof (ipha_t);
26459 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26460 		    sizeof (ipha_t));
26461 		oipha->ipha_protocol = IPPROTO_ENCAP;
26462 		oipha->ipha_version_and_hdr_length =
26463 		    IP_SIMPLE_HDR_VERSION;
26464 		oipha->ipha_hdr_checksum = 0;
26465 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26466 		outer_mp->b_cont = inner_mp;
26467 		ipsec_mp->b_cont = outer_mp;
26468 
26469 		io->ipsec_out_se_done = B_TRUE;
26470 		io->ipsec_out_tunnel = B_TRUE;
26471 	}
26472 
26473 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26474 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26475 	    !ipsec_out_select_sa(ipsec_mp))
26476 		return;
26477 
26478 	/*
26479 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26480 	 * to do the heavy lifting.
26481 	 */
26482 	zoneid = io->ipsec_out_zoneid;
26483 	ASSERT(zoneid != ALL_ZONES);
26484 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26485 		ASSERT(io->ipsec_out_esp_sa != NULL);
26486 		io->ipsec_out_esp_done = B_TRUE;
26487 		/*
26488 		 * Note that since hw accel can only apply one transform,
26489 		 * not two, we skip hw accel for ESP if we also have AH
26490 		 * This is an design limitation of the interface
26491 		 * which should be revisited.
26492 		 */
26493 		ASSERT(ire != NULL);
26494 		if (io->ipsec_out_ah_sa == NULL) {
26495 			ill = (ill_t *)ire->ire_stq->q_ptr;
26496 			ipsec_out_is_accelerated(ipsec_mp,
26497 			    io->ipsec_out_esp_sa, ill, ire);
26498 		}
26499 
26500 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26501 		switch (ipsec_rc) {
26502 		case IPSEC_STATUS_SUCCESS:
26503 			break;
26504 		case IPSEC_STATUS_FAILED:
26505 			if (ill != NULL) {
26506 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26507 			} else {
26508 				BUMP_MIB(&ipst->ips_ip_mib,
26509 				    ipIfStatsOutDiscards);
26510 			}
26511 			/* FALLTHRU */
26512 		case IPSEC_STATUS_PENDING:
26513 			return;
26514 		}
26515 	}
26516 
26517 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26518 		ASSERT(io->ipsec_out_ah_sa != NULL);
26519 		io->ipsec_out_ah_done = B_TRUE;
26520 		if (ire == NULL) {
26521 			int idx = io->ipsec_out_capab_ill_index;
26522 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26523 			    NULL, NULL, NULL, NULL, ipst);
26524 			ill_need_rele = B_TRUE;
26525 		} else {
26526 			ill = (ill_t *)ire->ire_stq->q_ptr;
26527 		}
26528 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26529 		    ire);
26530 
26531 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26532 		switch (ipsec_rc) {
26533 		case IPSEC_STATUS_SUCCESS:
26534 			break;
26535 		case IPSEC_STATUS_FAILED:
26536 			if (ill != NULL) {
26537 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26538 			} else {
26539 				BUMP_MIB(&ipst->ips_ip_mib,
26540 				    ipIfStatsOutDiscards);
26541 			}
26542 			/* FALLTHRU */
26543 		case IPSEC_STATUS_PENDING:
26544 			if (ill != NULL && ill_need_rele)
26545 				ill_refrele(ill);
26546 			return;
26547 		}
26548 	}
26549 	/*
26550 	 * We are done with IPSEC processing. Send it over
26551 	 * the wire.
26552 	 */
26553 done:
26554 	mp = ipsec_mp->b_cont;
26555 	ipha = (ipha_t *)mp->b_rptr;
26556 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26557 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26558 	} else {
26559 		ip6h = (ip6_t *)ipha;
26560 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26561 	}
26562 	if (ill != NULL && ill_need_rele)
26563 		ill_refrele(ill);
26564 }
26565 
26566 /* ARGSUSED */
26567 void
26568 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26569 {
26570 	opt_restart_t	*or;
26571 	int	err;
26572 	conn_t	*connp;
26573 
26574 	ASSERT(CONN_Q(q));
26575 	connp = Q_TO_CONN(q);
26576 
26577 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26578 	or = (opt_restart_t *)first_mp->b_rptr;
26579 	/*
26580 	 * We don't need to pass any credentials here since this is just
26581 	 * a restart. The credentials are passed in when svr4_optcom_req
26582 	 * is called the first time (from ip_wput_nondata).
26583 	 */
26584 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26585 		err = svr4_optcom_req(q, first_mp, NULL,
26586 		    &ip_opt_obj);
26587 	} else {
26588 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26589 		err = tpi_optcom_req(q, first_mp, NULL,
26590 		    &ip_opt_obj);
26591 	}
26592 	if (err != EINPROGRESS) {
26593 		/* operation is done */
26594 		CONN_OPER_PENDING_DONE(connp);
26595 	}
26596 }
26597 
26598 /*
26599  * ioctls that go through a down/up sequence may need to wait for the down
26600  * to complete. This involves waiting for the ire and ipif refcnts to go down
26601  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26602  */
26603 /* ARGSUSED */
26604 void
26605 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26606 {
26607 	struct iocblk *iocp;
26608 	mblk_t *mp1;
26609 	ip_ioctl_cmd_t *ipip;
26610 	int err;
26611 	sin_t	*sin;
26612 	struct lifreq *lifr;
26613 	struct ifreq *ifr;
26614 
26615 	iocp = (struct iocblk *)mp->b_rptr;
26616 	ASSERT(ipsq != NULL);
26617 	/* Existence of mp1 verified in ip_wput_nondata */
26618 	mp1 = mp->b_cont->b_cont;
26619 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26620 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26621 		/*
26622 		 * Special case where ipsq_current_ipif is not set:
26623 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26624 		 * ill could also have become part of a ipmp group in the
26625 		 * process, we are here as were not able to complete the
26626 		 * operation in ipif_set_values because we could not become
26627 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26628 		 * will not be set so we need to set it.
26629 		 */
26630 		ill_t *ill = q->q_ptr;
26631 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26632 	}
26633 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26634 
26635 	if (ipip->ipi_cmd_type == IF_CMD) {
26636 		/* This a old style SIOC[GS]IF* command */
26637 		ifr = (struct ifreq *)mp1->b_rptr;
26638 		sin = (sin_t *)&ifr->ifr_addr;
26639 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26640 		/* This a new style SIOC[GS]LIF* command */
26641 		lifr = (struct lifreq *)mp1->b_rptr;
26642 		sin = (sin_t *)&lifr->lifr_addr;
26643 	} else {
26644 		sin = NULL;
26645 	}
26646 
26647 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26648 	    ipip, mp1->b_rptr);
26649 
26650 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26651 }
26652 
26653 /*
26654  * ioctl processing
26655  *
26656  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26657  * the ioctl command in the ioctl tables, determines the copyin data size
26658  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26659  *
26660  * ioctl processing then continues when the M_IOCDATA makes its way down to
26661  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26662  * associated 'conn' is refheld till the end of the ioctl and the general
26663  * ioctl processing function ip_process_ioctl() is called to extract the
26664  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26665  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26666  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26667  * is used to extract the ioctl's arguments.
26668  *
26669  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26670  * so goes thru the serialization primitive ipsq_try_enter. Then the
26671  * appropriate function to handle the ioctl is called based on the entry in
26672  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26673  * which also refreleases the 'conn' that was refheld at the start of the
26674  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26675  *
26676  * Many exclusive ioctls go thru an internal down up sequence as part of
26677  * the operation. For example an attempt to change the IP address of an
26678  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26679  * does all the cleanup such as deleting all ires that use this address.
26680  * Then we need to wait till all references to the interface go away.
26681  */
26682 void
26683 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26684 {
26685 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26686 	ip_ioctl_cmd_t *ipip = arg;
26687 	ip_extract_func_t *extract_funcp;
26688 	cmd_info_t ci;
26689 	int err;
26690 	boolean_t entered_ipsq = B_FALSE;
26691 
26692 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26693 
26694 	if (ipip == NULL)
26695 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26696 
26697 	/*
26698 	 * SIOCLIFADDIF needs to go thru a special path since the
26699 	 * ill may not exist yet. This happens in the case of lo0
26700 	 * which is created using this ioctl.
26701 	 */
26702 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26703 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26704 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26705 		return;
26706 	}
26707 
26708 	ci.ci_ipif = NULL;
26709 	if (ipip->ipi_cmd_type == MISC_CMD) {
26710 		/*
26711 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26712 		 */
26713 		if (ipip->ipi_cmd == IF_UNITSEL) {
26714 			/* ioctl comes down the ill */
26715 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26716 			ipif_refhold(ci.ci_ipif);
26717 		}
26718 		err = 0;
26719 		ci.ci_sin = NULL;
26720 		ci.ci_sin6 = NULL;
26721 		ci.ci_lifr = NULL;
26722 	} else {
26723 		switch (ipip->ipi_cmd_type) {
26724 		case IF_CMD:
26725 		case LIF_CMD:
26726 			extract_funcp = ip_extract_lifreq;
26727 			break;
26728 
26729 		case ARP_CMD:
26730 		case XARP_CMD:
26731 			extract_funcp = ip_extract_arpreq;
26732 			break;
26733 
26734 		case TUN_CMD:
26735 			extract_funcp = ip_extract_tunreq;
26736 			break;
26737 
26738 		case MSFILT_CMD:
26739 			extract_funcp = ip_extract_msfilter;
26740 			break;
26741 
26742 		default:
26743 			ASSERT(0);
26744 		}
26745 
26746 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26747 		if (err != 0) {
26748 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26749 			return;
26750 		}
26751 
26752 		/*
26753 		 * All of the extraction functions return a refheld ipif.
26754 		 */
26755 		ASSERT(ci.ci_ipif != NULL);
26756 	}
26757 
26758 	/*
26759 	 * If ipsq is non-null, we are already being called exclusively
26760 	 */
26761 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26762 	if (!(ipip->ipi_flags & IPI_WR)) {
26763 		/*
26764 		 * A return value of EINPROGRESS means the ioctl is
26765 		 * either queued and waiting for some reason or has
26766 		 * already completed.
26767 		 */
26768 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26769 		    ci.ci_lifr);
26770 		if (ci.ci_ipif != NULL)
26771 			ipif_refrele(ci.ci_ipif);
26772 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26773 		return;
26774 	}
26775 
26776 	ASSERT(ci.ci_ipif != NULL);
26777 
26778 	if (ipsq == NULL) {
26779 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26780 		    ip_process_ioctl, NEW_OP, B_TRUE);
26781 		entered_ipsq = B_TRUE;
26782 	}
26783 	/*
26784 	 * Release the ipif so that ipif_down and friends that wait for
26785 	 * references to go away are not misled about the current ipif_refcnt
26786 	 * values. We are writer so we can access the ipif even after releasing
26787 	 * the ipif.
26788 	 */
26789 	ipif_refrele(ci.ci_ipif);
26790 	if (ipsq == NULL)
26791 		return;
26792 
26793 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26794 
26795 	/*
26796 	 * For most set ioctls that come here, this serves as a single point
26797 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26798 	 * be any new references to the ipif. This helps functions that go
26799 	 * through this path and end up trying to wait for the refcnts
26800 	 * associated with the ipif to go down to zero. Some exceptions are
26801 	 * Failover, Failback, and Groupname commands that operate on more than
26802 	 * just the ci.ci_ipif. These commands internally determine the
26803 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
26804 	 * flags on that set. Another exception is the Removeif command that
26805 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
26806 	 * ipif to operate on.
26807 	 */
26808 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
26809 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
26810 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
26811 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
26812 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
26813 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
26814 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
26815 
26816 	/*
26817 	 * A return value of EINPROGRESS means the ioctl is
26818 	 * either queued and waiting for some reason or has
26819 	 * already completed.
26820 	 */
26821 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
26822 
26823 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26824 
26825 	if (entered_ipsq)
26826 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
26827 }
26828 
26829 /*
26830  * Complete the ioctl. Typically ioctls use the mi package and need to
26831  * do mi_copyout/mi_copy_done.
26832  */
26833 void
26834 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
26835 {
26836 	conn_t	*connp = NULL;
26837 
26838 	if (err == EINPROGRESS)
26839 		return;
26840 
26841 	if (CONN_Q(q)) {
26842 		connp = Q_TO_CONN(q);
26843 		ASSERT(connp->conn_ref >= 2);
26844 	}
26845 
26846 	switch (mode) {
26847 	case COPYOUT:
26848 		if (err == 0)
26849 			mi_copyout(q, mp);
26850 		else
26851 			mi_copy_done(q, mp, err);
26852 		break;
26853 
26854 	case NO_COPYOUT:
26855 		mi_copy_done(q, mp, err);
26856 		break;
26857 
26858 	default:
26859 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
26860 		break;
26861 	}
26862 
26863 	/*
26864 	 * The refhold placed at the start of the ioctl is released here.
26865 	 */
26866 	if (connp != NULL)
26867 		CONN_OPER_PENDING_DONE(connp);
26868 
26869 	if (ipsq != NULL)
26870 		ipsq_current_finish(ipsq);
26871 }
26872 
26873 /*
26874  * This is called from ip_wput_nondata to resume a deferred TCP bind.
26875  */
26876 /* ARGSUSED */
26877 void
26878 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
26879 {
26880 	conn_t *connp = arg;
26881 	tcp_t	*tcp;
26882 
26883 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
26884 	tcp = connp->conn_tcp;
26885 
26886 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
26887 		freemsg(mp);
26888 	else
26889 		tcp_rput_other(tcp, mp);
26890 	CONN_OPER_PENDING_DONE(connp);
26891 }
26892 
26893 /* Called from ip_wput for all non data messages */
26894 /* ARGSUSED */
26895 void
26896 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26897 {
26898 	mblk_t		*mp1;
26899 	ire_t		*ire, *fake_ire;
26900 	ill_t		*ill;
26901 	struct iocblk	*iocp;
26902 	ip_ioctl_cmd_t	*ipip;
26903 	cred_t		*cr;
26904 	conn_t		*connp;
26905 	int		err;
26906 	nce_t		*nce;
26907 	ipif_t		*ipif;
26908 	ip_stack_t	*ipst;
26909 	char		*proto_str;
26910 
26911 	if (CONN_Q(q)) {
26912 		connp = Q_TO_CONN(q);
26913 		ipst = connp->conn_netstack->netstack_ip;
26914 	} else {
26915 		connp = NULL;
26916 		ipst = ILLQ_TO_IPST(q);
26917 	}
26918 
26919 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
26920 
26921 	/* Check if it is a queue to /dev/sctp. */
26922 	if (connp != NULL && connp->conn_ulp == IPPROTO_SCTP &&
26923 	    connp->conn_rq == NULL) {
26924 		sctp_wput(q, mp);
26925 		return;
26926 	}
26927 
26928 	switch (DB_TYPE(mp)) {
26929 	case M_IOCTL:
26930 		/*
26931 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
26932 		 * will arrange to copy in associated control structures.
26933 		 */
26934 		ip_sioctl_copyin_setup(q, mp);
26935 		return;
26936 	case M_IOCDATA:
26937 		/*
26938 		 * Ensure that this is associated with one of our trans-
26939 		 * parent ioctls.  If it's not ours, discard it if we're
26940 		 * running as a driver, or pass it on if we're a module.
26941 		 */
26942 		iocp = (struct iocblk *)mp->b_rptr;
26943 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26944 		if (ipip == NULL) {
26945 			if (q->q_next == NULL) {
26946 				goto nak;
26947 			} else {
26948 				putnext(q, mp);
26949 			}
26950 			return;
26951 		}
26952 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
26953 			/*
26954 			 * the ioctl is one we recognise, but is not
26955 			 * consumed by IP as a module, pass M_IOCDATA
26956 			 * for processing downstream, but only for
26957 			 * common Streams ioctls.
26958 			 */
26959 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
26960 				putnext(q, mp);
26961 				return;
26962 			} else {
26963 				goto nak;
26964 			}
26965 		}
26966 
26967 		/* IOCTL continuation following copyin or copyout. */
26968 		if (mi_copy_state(q, mp, NULL) == -1) {
26969 			/*
26970 			 * The copy operation failed.  mi_copy_state already
26971 			 * cleaned up, so we're out of here.
26972 			 */
26973 			return;
26974 		}
26975 		/*
26976 		 * If we just completed a copy in, we become writer and
26977 		 * continue processing in ip_sioctl_copyin_done.  If it
26978 		 * was a copy out, we call mi_copyout again.  If there is
26979 		 * nothing more to copy out, it will complete the IOCTL.
26980 		 */
26981 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
26982 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
26983 				mi_copy_done(q, mp, EPROTO);
26984 				return;
26985 			}
26986 			/*
26987 			 * Check for cases that need more copying.  A return
26988 			 * value of 0 means a second copyin has been started,
26989 			 * so we return; a return value of 1 means no more
26990 			 * copying is needed, so we continue.
26991 			 */
26992 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
26993 			    MI_COPY_COUNT(mp) == 1) {
26994 				if (ip_copyin_msfilter(q, mp) == 0)
26995 					return;
26996 			}
26997 			/*
26998 			 * Refhold the conn, till the ioctl completes. This is
26999 			 * needed in case the ioctl ends up in the pending mp
27000 			 * list. Every mp in the ill_pending_mp list and
27001 			 * the ipsq_pending_mp must have a refhold on the conn
27002 			 * to resume processing. The refhold is released when
27003 			 * the ioctl completes. (normally or abnormally)
27004 			 * In all cases ip_ioctl_finish is called to finish
27005 			 * the ioctl.
27006 			 */
27007 			if (connp != NULL) {
27008 				/* This is not a reentry */
27009 				ASSERT(ipsq == NULL);
27010 				CONN_INC_REF(connp);
27011 			} else {
27012 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27013 					mi_copy_done(q, mp, EINVAL);
27014 					return;
27015 				}
27016 			}
27017 
27018 			ip_process_ioctl(ipsq, q, mp, ipip);
27019 
27020 		} else {
27021 			mi_copyout(q, mp);
27022 		}
27023 		return;
27024 nak:
27025 		iocp->ioc_error = EINVAL;
27026 		mp->b_datap->db_type = M_IOCNAK;
27027 		iocp->ioc_count = 0;
27028 		qreply(q, mp);
27029 		return;
27030 
27031 	case M_IOCNAK:
27032 		/*
27033 		 * The only way we could get here is if a resolver didn't like
27034 		 * an IOCTL we sent it.	 This shouldn't happen.
27035 		 */
27036 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27037 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27038 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27039 		freemsg(mp);
27040 		return;
27041 	case M_IOCACK:
27042 		/* /dev/ip shouldn't see this */
27043 		if (CONN_Q(q))
27044 			goto nak;
27045 
27046 		/* Finish socket ioctls passed through to ARP. */
27047 		ip_sioctl_iocack(q, mp);
27048 		return;
27049 	case M_FLUSH:
27050 		if (*mp->b_rptr & FLUSHW)
27051 			flushq(q, FLUSHALL);
27052 		if (q->q_next) {
27053 			putnext(q, mp);
27054 			return;
27055 		}
27056 		if (*mp->b_rptr & FLUSHR) {
27057 			*mp->b_rptr &= ~FLUSHW;
27058 			qreply(q, mp);
27059 			return;
27060 		}
27061 		freemsg(mp);
27062 		return;
27063 	case IRE_DB_REQ_TYPE:
27064 		if (connp == NULL) {
27065 			proto_str = "IRE_DB_REQ_TYPE";
27066 			goto protonak;
27067 		}
27068 		/* An Upper Level Protocol wants a copy of an IRE. */
27069 		ip_ire_req(q, mp);
27070 		return;
27071 	case M_CTL:
27072 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27073 			break;
27074 
27075 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27076 		    TUN_HELLO) {
27077 			ASSERT(connp != NULL);
27078 			connp->conn_flags |= IPCL_IPTUN;
27079 			freeb(mp);
27080 			return;
27081 		}
27082 
27083 		if (connp != NULL && *(uint32_t *)mp->b_rptr ==
27084 		    IP_ULP_OUT_LABELED) {
27085 			out_labeled_t *olp;
27086 
27087 			if (mp->b_wptr - mp->b_rptr != sizeof (*olp))
27088 				break;
27089 			olp = (out_labeled_t *)mp->b_rptr;
27090 			connp->conn_ulp_labeled = olp->out_qnext == q;
27091 			freemsg(mp);
27092 			return;
27093 		}
27094 
27095 		/* M_CTL messages are used by ARP to tell us things. */
27096 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27097 			break;
27098 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27099 		case AR_ENTRY_SQUERY:
27100 			ip_wput_ctl(q, mp);
27101 			return;
27102 		case AR_CLIENT_NOTIFY:
27103 			ip_arp_news(q, mp);
27104 			return;
27105 		case AR_DLPIOP_DONE:
27106 			ASSERT(q->q_next != NULL);
27107 			ill = (ill_t *)q->q_ptr;
27108 			/* qwriter_ip releases the refhold */
27109 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27110 			ill_refhold(ill);
27111 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27112 			return;
27113 		case AR_ARP_CLOSING:
27114 			/*
27115 			 * ARP (above us) is closing. If no ARP bringup is
27116 			 * currently pending, ack the message so that ARP
27117 			 * can complete its close. Also mark ill_arp_closing
27118 			 * so that new ARP bringups will fail. If any
27119 			 * ARP bringup is currently in progress, we will
27120 			 * ack this when the current ARP bringup completes.
27121 			 */
27122 			ASSERT(q->q_next != NULL);
27123 			ill = (ill_t *)q->q_ptr;
27124 			mutex_enter(&ill->ill_lock);
27125 			ill->ill_arp_closing = 1;
27126 			if (!ill->ill_arp_bringup_pending) {
27127 				mutex_exit(&ill->ill_lock);
27128 				qreply(q, mp);
27129 			} else {
27130 				mutex_exit(&ill->ill_lock);
27131 				freemsg(mp);
27132 			}
27133 			return;
27134 		case AR_ARP_EXTEND:
27135 			/*
27136 			 * The ARP module above us is capable of duplicate
27137 			 * address detection.  Old ATM drivers will not send
27138 			 * this message.
27139 			 */
27140 			ASSERT(q->q_next != NULL);
27141 			ill = (ill_t *)q->q_ptr;
27142 			ill->ill_arp_extend = B_TRUE;
27143 			freemsg(mp);
27144 			return;
27145 		default:
27146 			break;
27147 		}
27148 		break;
27149 	case M_PROTO:
27150 	case M_PCPROTO:
27151 		/*
27152 		 * The only PROTO messages we expect are ULP binds and
27153 		 * copies of option negotiation acknowledgements.
27154 		 */
27155 		switch (((union T_primitives *)mp->b_rptr)->type) {
27156 		case O_T_BIND_REQ:
27157 		case T_BIND_REQ: {
27158 			/* Request can get queued in bind */
27159 			if (connp == NULL) {
27160 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27161 				goto protonak;
27162 			}
27163 			/*
27164 			 * Both TCP and UDP call ip_bind_{v4,v6}() directly
27165 			 * instead of going through this path.  We only get
27166 			 * here in the following cases:
27167 			 *
27168 			 * a. Bind retries, where ipsq is non-NULL.
27169 			 * b. T_BIND_REQ is issued from non TCP/UDP
27170 			 *    transport, e.g. icmp for raw socket,
27171 			 *    in which case ipsq will be NULL.
27172 			 */
27173 			ASSERT(ipsq != NULL ||
27174 			    (!IPCL_IS_TCP(connp) && !IPCL_IS_UDP(connp)));
27175 
27176 			/* Don't increment refcnt if this is a re-entry */
27177 			if (ipsq == NULL)
27178 				CONN_INC_REF(connp);
27179 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27180 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27181 			if (mp == NULL)
27182 				return;
27183 			if (IPCL_IS_TCP(connp)) {
27184 				/*
27185 				 * In the case of TCP endpoint we
27186 				 * come here only for bind retries
27187 				 */
27188 				ASSERT(ipsq != NULL);
27189 				CONN_INC_REF(connp);
27190 				squeue_fill(connp->conn_sqp, mp,
27191 				    ip_resume_tcp_bind, connp,
27192 				    SQTAG_BIND_RETRY);
27193 				return;
27194 			} else if (IPCL_IS_UDP(connp)) {
27195 				/*
27196 				 * In the case of UDP endpoint we
27197 				 * come here only for bind retries
27198 				 */
27199 				ASSERT(ipsq != NULL);
27200 				udp_resume_bind(connp, mp);
27201 				return;
27202 			}
27203 			qreply(q, mp);
27204 			CONN_OPER_PENDING_DONE(connp);
27205 			return;
27206 		}
27207 		case T_SVR4_OPTMGMT_REQ:
27208 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27209 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27210 
27211 			if (connp == NULL) {
27212 				proto_str = "T_SVR4_OPTMGMT_REQ";
27213 				goto protonak;
27214 			}
27215 
27216 			if (!snmpcom_req(q, mp, ip_snmp_set,
27217 			    ip_snmp_get, cr)) {
27218 				/*
27219 				 * Call svr4_optcom_req so that it can
27220 				 * generate the ack. We don't come here
27221 				 * if this operation is being restarted.
27222 				 * ip_restart_optmgmt will drop the conn ref.
27223 				 * In the case of ipsec option after the ipsec
27224 				 * load is complete conn_restart_ipsec_waiter
27225 				 * drops the conn ref.
27226 				 */
27227 				ASSERT(ipsq == NULL);
27228 				CONN_INC_REF(connp);
27229 				if (ip_check_for_ipsec_opt(q, mp))
27230 					return;
27231 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj);
27232 				if (err != EINPROGRESS) {
27233 					/* Operation is done */
27234 					CONN_OPER_PENDING_DONE(connp);
27235 				}
27236 			}
27237 			return;
27238 		case T_OPTMGMT_REQ:
27239 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27240 			/*
27241 			 * Note: No snmpcom_req support through new
27242 			 * T_OPTMGMT_REQ.
27243 			 * Call tpi_optcom_req so that it can
27244 			 * generate the ack.
27245 			 */
27246 			if (connp == NULL) {
27247 				proto_str = "T_OPTMGMT_REQ";
27248 				goto protonak;
27249 			}
27250 
27251 			ASSERT(ipsq == NULL);
27252 			/*
27253 			 * We don't come here for restart. ip_restart_optmgmt
27254 			 * will drop the conn ref. In the case of ipsec option
27255 			 * after the ipsec load is complete
27256 			 * conn_restart_ipsec_waiter drops the conn ref.
27257 			 */
27258 			CONN_INC_REF(connp);
27259 			if (ip_check_for_ipsec_opt(q, mp))
27260 				return;
27261 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj);
27262 			if (err != EINPROGRESS) {
27263 				/* Operation is done */
27264 				CONN_OPER_PENDING_DONE(connp);
27265 			}
27266 			return;
27267 		case T_UNBIND_REQ:
27268 			if (connp == NULL) {
27269 				proto_str = "T_UNBIND_REQ";
27270 				goto protonak;
27271 			}
27272 			mp = ip_unbind(q, mp);
27273 			qreply(q, mp);
27274 			return;
27275 		default:
27276 			/*
27277 			 * Have to drop any DLPI messages coming down from
27278 			 * arp (such as an info_req which would cause ip
27279 			 * to receive an extra info_ack if it was passed
27280 			 * through.
27281 			 */
27282 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27283 			    (int)*(uint_t *)mp->b_rptr));
27284 			freemsg(mp);
27285 			return;
27286 		}
27287 		/* NOTREACHED */
27288 	case IRE_DB_TYPE: {
27289 		nce_t		*nce;
27290 		ill_t		*ill;
27291 		in6_addr_t	gw_addr_v6;
27292 
27293 
27294 		/*
27295 		 * This is a response back from a resolver.  It
27296 		 * consists of a message chain containing:
27297 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27298 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27299 		 * The LL_HDR_MBLK is the DLPI header to use to get
27300 		 * the attached packet, and subsequent ones for the
27301 		 * same destination, transmitted.
27302 		 */
27303 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27304 			break;
27305 		/*
27306 		 * First, check to make sure the resolution succeeded.
27307 		 * If it failed, the second mblk will be empty.
27308 		 * If it is, free the chain, dropping the packet.
27309 		 * (We must ire_delete the ire; that frees the ire mblk)
27310 		 * We're doing this now to support PVCs for ATM; it's
27311 		 * a partial xresolv implementation. When we fully implement
27312 		 * xresolv interfaces, instead of freeing everything here
27313 		 * we'll initiate neighbor discovery.
27314 		 *
27315 		 * For v4 (ARP and other external resolvers) the resolver
27316 		 * frees the message, so no check is needed. This check
27317 		 * is required, though, for a full xresolve implementation.
27318 		 * Including this code here now both shows how external
27319 		 * resolvers can NACK a resolution request using an
27320 		 * existing design that has no specific provisions for NACKs,
27321 		 * and also takes into account that the current non-ARP
27322 		 * external resolver has been coded to use this method of
27323 		 * NACKing for all IPv6 (xresolv) cases,
27324 		 * whether our xresolv implementation is complete or not.
27325 		 *
27326 		 */
27327 		ire = (ire_t *)mp->b_rptr;
27328 		ill = ire_to_ill(ire);
27329 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27330 		if (mp1->b_rptr == mp1->b_wptr) {
27331 			if (ire->ire_ipversion == IPV6_VERSION) {
27332 				/*
27333 				 * XRESOLV interface.
27334 				 */
27335 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27336 				mutex_enter(&ire->ire_lock);
27337 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27338 				mutex_exit(&ire->ire_lock);
27339 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27340 					nce = ndp_lookup_v6(ill,
27341 					    &ire->ire_addr_v6, B_FALSE);
27342 				} else {
27343 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27344 					    B_FALSE);
27345 				}
27346 				if (nce != NULL) {
27347 					nce_resolv_failed(nce);
27348 					ndp_delete(nce);
27349 					NCE_REFRELE(nce);
27350 				}
27351 			}
27352 			mp->b_cont = NULL;
27353 			freemsg(mp1);		/* frees the pkt as well */
27354 			ASSERT(ire->ire_nce == NULL);
27355 			ire_delete((ire_t *)mp->b_rptr);
27356 			return;
27357 		}
27358 
27359 		/*
27360 		 * Split them into IRE_MBLK and pkt and feed it into
27361 		 * ire_add_then_send. Then in ire_add_then_send
27362 		 * the IRE will be added, and then the packet will be
27363 		 * run back through ip_wput. This time it will make
27364 		 * it to the wire.
27365 		 */
27366 		mp->b_cont = NULL;
27367 		mp = mp1->b_cont;		/* now, mp points to pkt */
27368 		mp1->b_cont = NULL;
27369 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27370 		if (ire->ire_ipversion == IPV6_VERSION) {
27371 			/*
27372 			 * XRESOLV interface. Find the nce and put a copy
27373 			 * of the dl_unitdata_req in nce_res_mp
27374 			 */
27375 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27376 			mutex_enter(&ire->ire_lock);
27377 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27378 			mutex_exit(&ire->ire_lock);
27379 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27380 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27381 				    B_FALSE);
27382 			} else {
27383 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27384 			}
27385 			if (nce != NULL) {
27386 				/*
27387 				 * We have to protect nce_res_mp here
27388 				 * from being accessed by other threads
27389 				 * while we change the mblk pointer.
27390 				 * Other functions will also lock the nce when
27391 				 * accessing nce_res_mp.
27392 				 *
27393 				 * The reason we change the mblk pointer
27394 				 * here rather than copying the resolved address
27395 				 * into the template is that, unlike with
27396 				 * ethernet, we have no guarantee that the
27397 				 * resolved address length will be
27398 				 * smaller than or equal to the lla length
27399 				 * with which the template was allocated,
27400 				 * (for ethernet, they're equal)
27401 				 * so we have to use the actual resolved
27402 				 * address mblk - which holds the real
27403 				 * dl_unitdata_req with the resolved address.
27404 				 *
27405 				 * Doing this is the same behavior as was
27406 				 * previously used in the v4 ARP case.
27407 				 */
27408 				mutex_enter(&nce->nce_lock);
27409 				if (nce->nce_res_mp != NULL)
27410 					freemsg(nce->nce_res_mp);
27411 				nce->nce_res_mp = mp1;
27412 				mutex_exit(&nce->nce_lock);
27413 				/*
27414 				 * We do a fastpath probe here because
27415 				 * we have resolved the address without
27416 				 * using Neighbor Discovery.
27417 				 * In the non-XRESOLV v6 case, the fastpath
27418 				 * probe is done right after neighbor
27419 				 * discovery completes.
27420 				 */
27421 				if (nce->nce_res_mp != NULL) {
27422 					int res;
27423 					nce_fastpath_list_add(nce);
27424 					res = ill_fastpath_probe(ill,
27425 					    nce->nce_res_mp);
27426 					if (res != 0 && res != EAGAIN)
27427 						nce_fastpath_list_delete(nce);
27428 				}
27429 
27430 				ire_add_then_send(q, ire, mp);
27431 				/*
27432 				 * Now we have to clean out any packets
27433 				 * that may have been queued on the nce
27434 				 * while it was waiting for address resolution
27435 				 * to complete.
27436 				 */
27437 				mutex_enter(&nce->nce_lock);
27438 				mp1 = nce->nce_qd_mp;
27439 				nce->nce_qd_mp = NULL;
27440 				mutex_exit(&nce->nce_lock);
27441 				while (mp1 != NULL) {
27442 					mblk_t *nxt_mp;
27443 					queue_t *fwdq = NULL;
27444 					ill_t   *inbound_ill;
27445 					uint_t ifindex;
27446 
27447 					nxt_mp = mp1->b_next;
27448 					mp1->b_next = NULL;
27449 					/*
27450 					 * Retrieve ifindex stored in
27451 					 * ip_rput_data_v6()
27452 					 */
27453 					ifindex =
27454 					    (uint_t)(uintptr_t)mp1->b_prev;
27455 					inbound_ill =
27456 					    ill_lookup_on_ifindex(ifindex,
27457 					    B_TRUE, NULL, NULL, NULL,
27458 					    NULL, ipst);
27459 					mp1->b_prev = NULL;
27460 					if (inbound_ill != NULL)
27461 						fwdq = inbound_ill->ill_rq;
27462 
27463 					if (fwdq != NULL) {
27464 						put(fwdq, mp1);
27465 						ill_refrele(inbound_ill);
27466 					} else
27467 						put(WR(ill->ill_rq), mp1);
27468 					mp1 = nxt_mp;
27469 				}
27470 				NCE_REFRELE(nce);
27471 			} else {	/* nce is NULL; clean up */
27472 				ire_delete(ire);
27473 				freemsg(mp);
27474 				freemsg(mp1);
27475 				return;
27476 			}
27477 		} else {
27478 			nce_t *arpce;
27479 			/*
27480 			 * Link layer resolution succeeded. Recompute the
27481 			 * ire_nce.
27482 			 */
27483 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27484 			if ((arpce = ndp_lookup_v4(ill,
27485 			    (ire->ire_gateway_addr != INADDR_ANY ?
27486 			    &ire->ire_gateway_addr : &ire->ire_addr),
27487 			    B_FALSE)) == NULL) {
27488 				freeb(ire->ire_mp);
27489 				freeb(mp1);
27490 				freemsg(mp);
27491 				return;
27492 			}
27493 			mutex_enter(&arpce->nce_lock);
27494 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27495 			if (arpce->nce_state == ND_REACHABLE) {
27496 				/*
27497 				 * Someone resolved this before us;
27498 				 * cleanup the res_mp. Since ire has
27499 				 * not been added yet, the call to ire_add_v4
27500 				 * from ire_add_then_send (when a dup is
27501 				 * detected) will clean up the ire.
27502 				 */
27503 				freeb(mp1);
27504 			} else {
27505 				ASSERT(arpce->nce_res_mp == NULL);
27506 				arpce->nce_res_mp = mp1;
27507 				arpce->nce_state = ND_REACHABLE;
27508 			}
27509 			mutex_exit(&arpce->nce_lock);
27510 			if (ire->ire_marks & IRE_MARK_NOADD) {
27511 				/*
27512 				 * this ire will not be added to the ire
27513 				 * cache table, so we can set the ire_nce
27514 				 * here, as there are no atomicity constraints.
27515 				 */
27516 				ire->ire_nce = arpce;
27517 				/*
27518 				 * We are associating this nce with the ire
27519 				 * so change the nce ref taken in
27520 				 * ndp_lookup_v4() from
27521 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27522 				 */
27523 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27524 			} else {
27525 				NCE_REFRELE(arpce);
27526 			}
27527 			ire_add_then_send(q, ire, mp);
27528 		}
27529 		return;	/* All is well, the packet has been sent. */
27530 	}
27531 	case IRE_ARPRESOLVE_TYPE: {
27532 
27533 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27534 			break;
27535 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27536 		mp->b_cont = NULL;
27537 		/*
27538 		 * First, check to make sure the resolution succeeded.
27539 		 * If it failed, the second mblk will be empty.
27540 		 */
27541 		if (mp1->b_rptr == mp1->b_wptr) {
27542 			/* cleanup  the incomplete ire, free queued packets */
27543 			freemsg(mp); /* fake ire */
27544 			freeb(mp1);  /* dl_unitdata response */
27545 			return;
27546 		}
27547 
27548 		/*
27549 		 * update any incomplete nce_t found. we lookup the ctable
27550 		 * and find the nce from the ire->ire_nce because we need
27551 		 * to pass the ire to ip_xmit_v4 later, and can find both
27552 		 * ire and nce in one lookup from the ctable.
27553 		 */
27554 		fake_ire = (ire_t *)mp->b_rptr;
27555 		/*
27556 		 * By the time we come back here from ARP
27557 		 * the logical outgoing interface  of the incomplete ire
27558 		 * we added in ire_forward could have disappeared,
27559 		 * causing the incomplete ire to also have
27560 		 * dissapeared. So we need to retreive the
27561 		 * proper ipif for the ire  before looking
27562 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27563 		 */
27564 		ill = q->q_ptr;
27565 
27566 		/* Get the outgoing ipif */
27567 		mutex_enter(&ill->ill_lock);
27568 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27569 			mutex_exit(&ill->ill_lock);
27570 			freemsg(mp); /* fake ire */
27571 			freeb(mp1);  /* dl_unitdata response */
27572 			return;
27573 		}
27574 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27575 
27576 		if (ipif == NULL) {
27577 			mutex_exit(&ill->ill_lock);
27578 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27579 			freemsg(mp);
27580 			freeb(mp1);
27581 			return;
27582 		}
27583 		ipif_refhold_locked(ipif);
27584 		mutex_exit(&ill->ill_lock);
27585 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27586 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27587 		    ipif, fake_ire->ire_zoneid, NULL,
27588 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27589 		ipif_refrele(ipif);
27590 		if (ire == NULL) {
27591 			/*
27592 			 * no ire was found; check if there is an nce
27593 			 * for this lookup; if it has no ire's pointing at it
27594 			 * cleanup.
27595 			 */
27596 			if ((nce = ndp_lookup_v4(ill,
27597 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27598 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27599 			    B_FALSE)) != NULL) {
27600 				/*
27601 				 * cleanup:
27602 				 * We check for refcnt 2 (one for the nce
27603 				 * hash list + 1 for the ref taken by
27604 				 * ndp_lookup_v4) to check that there are
27605 				 * no ire's pointing at the nce.
27606 				 */
27607 				if (nce->nce_refcnt == 2)
27608 					ndp_delete(nce);
27609 				NCE_REFRELE(nce);
27610 			}
27611 			freeb(mp1);  /* dl_unitdata response */
27612 			freemsg(mp); /* fake ire */
27613 			return;
27614 		}
27615 		nce = ire->ire_nce;
27616 		DTRACE_PROBE2(ire__arpresolve__type,
27617 		    ire_t *, ire, nce_t *, nce);
27618 		ASSERT(nce->nce_state != ND_INITIAL);
27619 		mutex_enter(&nce->nce_lock);
27620 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27621 		if (nce->nce_state == ND_REACHABLE) {
27622 			/*
27623 			 * Someone resolved this before us;
27624 			 * our response is not needed any more.
27625 			 */
27626 			mutex_exit(&nce->nce_lock);
27627 			freeb(mp1);  /* dl_unitdata response */
27628 		} else {
27629 			ASSERT(nce->nce_res_mp == NULL);
27630 			nce->nce_res_mp = mp1;
27631 			nce->nce_state = ND_REACHABLE;
27632 			mutex_exit(&nce->nce_lock);
27633 			nce_fastpath(nce);
27634 		}
27635 		/*
27636 		 * The cached nce_t has been updated to be reachable;
27637 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27638 		 */
27639 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27640 		freemsg(mp);
27641 		/*
27642 		 * send out queued packets.
27643 		 */
27644 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27645 
27646 		IRE_REFRELE(ire);
27647 		return;
27648 	}
27649 	default:
27650 		break;
27651 	}
27652 	if (q->q_next) {
27653 		putnext(q, mp);
27654 	} else
27655 		freemsg(mp);
27656 	return;
27657 
27658 protonak:
27659 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27660 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27661 		qreply(q, mp);
27662 }
27663 
27664 /*
27665  * Process IP options in an outbound packet.  Modify the destination if there
27666  * is a source route option.
27667  * Returns non-zero if something fails in which case an ICMP error has been
27668  * sent and mp freed.
27669  */
27670 static int
27671 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27672     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27673 {
27674 	ipoptp_t	opts;
27675 	uchar_t		*opt;
27676 	uint8_t		optval;
27677 	uint8_t		optlen;
27678 	ipaddr_t	dst;
27679 	intptr_t	code = 0;
27680 	mblk_t		*mp;
27681 	ire_t		*ire = NULL;
27682 
27683 	ip2dbg(("ip_wput_options\n"));
27684 	mp = ipsec_mp;
27685 	if (mctl_present) {
27686 		mp = ipsec_mp->b_cont;
27687 	}
27688 
27689 	dst = ipha->ipha_dst;
27690 	for (optval = ipoptp_first(&opts, ipha);
27691 	    optval != IPOPT_EOL;
27692 	    optval = ipoptp_next(&opts)) {
27693 		opt = opts.ipoptp_cur;
27694 		optlen = opts.ipoptp_len;
27695 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27696 		    optval, optlen));
27697 		switch (optval) {
27698 			uint32_t off;
27699 		case IPOPT_SSRR:
27700 		case IPOPT_LSRR:
27701 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27702 				ip1dbg((
27703 				    "ip_wput_options: bad option offset\n"));
27704 				code = (char *)&opt[IPOPT_OLEN] -
27705 				    (char *)ipha;
27706 				goto param_prob;
27707 			}
27708 			off = opt[IPOPT_OFFSET];
27709 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27710 			    ntohl(dst)));
27711 			/*
27712 			 * For strict: verify that dst is directly
27713 			 * reachable.
27714 			 */
27715 			if (optval == IPOPT_SSRR) {
27716 				ire = ire_ftable_lookup(dst, 0, 0,
27717 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27718 				    MBLK_GETLABEL(mp),
27719 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27720 				if (ire == NULL) {
27721 					ip1dbg(("ip_wput_options: SSRR not"
27722 					    " directly reachable: 0x%x\n",
27723 					    ntohl(dst)));
27724 					goto bad_src_route;
27725 				}
27726 				ire_refrele(ire);
27727 			}
27728 			break;
27729 		case IPOPT_RR:
27730 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27731 				ip1dbg((
27732 				    "ip_wput_options: bad option offset\n"));
27733 				code = (char *)&opt[IPOPT_OLEN] -
27734 				    (char *)ipha;
27735 				goto param_prob;
27736 			}
27737 			break;
27738 		case IPOPT_TS:
27739 			/*
27740 			 * Verify that length >=5 and that there is either
27741 			 * room for another timestamp or that the overflow
27742 			 * counter is not maxed out.
27743 			 */
27744 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27745 			if (optlen < IPOPT_MINLEN_IT) {
27746 				goto param_prob;
27747 			}
27748 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27749 				ip1dbg((
27750 				    "ip_wput_options: bad option offset\n"));
27751 				code = (char *)&opt[IPOPT_OFFSET] -
27752 				    (char *)ipha;
27753 				goto param_prob;
27754 			}
27755 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27756 			case IPOPT_TS_TSONLY:
27757 				off = IPOPT_TS_TIMELEN;
27758 				break;
27759 			case IPOPT_TS_TSANDADDR:
27760 			case IPOPT_TS_PRESPEC:
27761 			case IPOPT_TS_PRESPEC_RFC791:
27762 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27763 				break;
27764 			default:
27765 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27766 				    (char *)ipha;
27767 				goto param_prob;
27768 			}
27769 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27770 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27771 				/*
27772 				 * No room and the overflow counter is 15
27773 				 * already.
27774 				 */
27775 				goto param_prob;
27776 			}
27777 			break;
27778 		}
27779 	}
27780 
27781 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27782 		return (0);
27783 
27784 	ip1dbg(("ip_wput_options: error processing IP options."));
27785 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27786 
27787 param_prob:
27788 	/*
27789 	 * Since ip_wput() isn't close to finished, we fill
27790 	 * in enough of the header for credible error reporting.
27791 	 */
27792 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27793 		/* Failed */
27794 		freemsg(ipsec_mp);
27795 		return (-1);
27796 	}
27797 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27798 	return (-1);
27799 
27800 bad_src_route:
27801 	/*
27802 	 * Since ip_wput() isn't close to finished, we fill
27803 	 * in enough of the header for credible error reporting.
27804 	 */
27805 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27806 		/* Failed */
27807 		freemsg(ipsec_mp);
27808 		return (-1);
27809 	}
27810 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27811 	return (-1);
27812 }
27813 
27814 /*
27815  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
27816  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
27817  * thru /etc/system.
27818  */
27819 #define	CONN_MAXDRAINCNT	64
27820 
27821 static void
27822 conn_drain_init(ip_stack_t *ipst)
27823 {
27824 	int i;
27825 
27826 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
27827 
27828 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
27829 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
27830 		/*
27831 		 * Default value of the number of drainers is the
27832 		 * number of cpus, subject to maximum of 8 drainers.
27833 		 */
27834 		if (boot_max_ncpus != -1)
27835 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
27836 		else
27837 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
27838 	}
27839 
27840 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
27841 	    sizeof (idl_t), KM_SLEEP);
27842 
27843 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
27844 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
27845 		    MUTEX_DEFAULT, NULL);
27846 	}
27847 }
27848 
27849 static void
27850 conn_drain_fini(ip_stack_t *ipst)
27851 {
27852 	int i;
27853 
27854 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
27855 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
27856 	kmem_free(ipst->ips_conn_drain_list,
27857 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
27858 	ipst->ips_conn_drain_list = NULL;
27859 }
27860 
27861 /*
27862  * Note: For an overview of how flowcontrol is handled in IP please see the
27863  * IP Flowcontrol notes at the top of this file.
27864  *
27865  * Flow control has blocked us from proceeding. Insert the given conn in one
27866  * of the conn drain lists. These conn wq's will be qenabled later on when
27867  * STREAMS flow control does a backenable. conn_walk_drain will enable
27868  * the first conn in each of these drain lists. Each of these qenabled conns
27869  * in turn enables the next in the list, after it runs, or when it closes,
27870  * thus sustaining the drain process.
27871  *
27872  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
27873  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
27874  * running at any time, on a given conn, since there can be only 1 service proc
27875  * running on a queue at any time.
27876  */
27877 void
27878 conn_drain_insert(conn_t *connp)
27879 {
27880 	idl_t	*idl;
27881 	uint_t	index;
27882 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
27883 
27884 	mutex_enter(&connp->conn_lock);
27885 	if (connp->conn_state_flags & CONN_CLOSING) {
27886 		/*
27887 		 * The conn is closing as a result of which CONN_CLOSING
27888 		 * is set. Return.
27889 		 */
27890 		mutex_exit(&connp->conn_lock);
27891 		return;
27892 	} else if (connp->conn_idl == NULL) {
27893 		/*
27894 		 * Assign the next drain list round robin. We dont' use
27895 		 * a lock, and thus it may not be strictly round robin.
27896 		 * Atomicity of load/stores is enough to make sure that
27897 		 * conn_drain_list_index is always within bounds.
27898 		 */
27899 		index = ipst->ips_conn_drain_list_index;
27900 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
27901 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
27902 		index++;
27903 		if (index == ipst->ips_conn_drain_list_cnt)
27904 			index = 0;
27905 		ipst->ips_conn_drain_list_index = index;
27906 	}
27907 	mutex_exit(&connp->conn_lock);
27908 
27909 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27910 	if ((connp->conn_drain_prev != NULL) ||
27911 	    (connp->conn_state_flags & CONN_CLOSING)) {
27912 		/*
27913 		 * The conn is already in the drain list, OR
27914 		 * the conn is closing. We need to check again for
27915 		 * the closing case again since close can happen
27916 		 * after we drop the conn_lock, and before we
27917 		 * acquire the CONN_DRAIN_LIST_LOCK.
27918 		 */
27919 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27920 		return;
27921 	} else {
27922 		idl = connp->conn_idl;
27923 	}
27924 
27925 	/*
27926 	 * The conn is not in the drain list. Insert it at the
27927 	 * tail of the drain list. The drain list is circular
27928 	 * and doubly linked. idl_conn points to the 1st element
27929 	 * in the list.
27930 	 */
27931 	if (idl->idl_conn == NULL) {
27932 		idl->idl_conn = connp;
27933 		connp->conn_drain_next = connp;
27934 		connp->conn_drain_prev = connp;
27935 	} else {
27936 		conn_t *head = idl->idl_conn;
27937 
27938 		connp->conn_drain_next = head;
27939 		connp->conn_drain_prev = head->conn_drain_prev;
27940 		head->conn_drain_prev->conn_drain_next = connp;
27941 		head->conn_drain_prev = connp;
27942 	}
27943 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27944 }
27945 
27946 /*
27947  * This conn is closing, and we are called from ip_close. OR
27948  * This conn has been serviced by ip_wsrv, and we need to do the tail
27949  * processing.
27950  * If this conn is part of the drain list, we may need to sustain the drain
27951  * process by qenabling the next conn in the drain list. We may also need to
27952  * remove this conn from the list, if it is done.
27953  */
27954 static void
27955 conn_drain_tail(conn_t *connp, boolean_t closing)
27956 {
27957 	idl_t *idl;
27958 
27959 	/*
27960 	 * connp->conn_idl is stable at this point, and no lock is needed
27961 	 * to check it. If we are called from ip_close, close has already
27962 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
27963 	 * called us only because conn_idl is non-null. If we are called thru
27964 	 * service, conn_idl could be null, but it cannot change because
27965 	 * service is single-threaded per queue, and there cannot be another
27966 	 * instance of service trying to call conn_drain_insert on this conn
27967 	 * now.
27968 	 */
27969 	ASSERT(!closing || (connp->conn_idl != NULL));
27970 
27971 	/*
27972 	 * If connp->conn_idl is null, the conn has not been inserted into any
27973 	 * drain list even once since creation of the conn. Just return.
27974 	 */
27975 	if (connp->conn_idl == NULL)
27976 		return;
27977 
27978 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
27979 
27980 	if (connp->conn_drain_prev == NULL) {
27981 		/* This conn is currently not in the drain list.  */
27982 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
27983 		return;
27984 	}
27985 	idl = connp->conn_idl;
27986 	if (idl->idl_conn_draining == connp) {
27987 		/*
27988 		 * This conn is the current drainer. If this is the last conn
27989 		 * in the drain list, we need to do more checks, in the 'if'
27990 		 * below. Otherwwise we need to just qenable the next conn,
27991 		 * to sustain the draining, and is handled in the 'else'
27992 		 * below.
27993 		 */
27994 		if (connp->conn_drain_next == idl->idl_conn) {
27995 			/*
27996 			 * This conn is the last in this list. This round
27997 			 * of draining is complete. If idl_repeat is set,
27998 			 * it means another flow enabling has happened from
27999 			 * the driver/streams and we need to another round
28000 			 * of draining.
28001 			 * If there are more than 2 conns in the drain list,
28002 			 * do a left rotate by 1, so that all conns except the
28003 			 * conn at the head move towards the head by 1, and the
28004 			 * the conn at the head goes to the tail. This attempts
28005 			 * a more even share for all queues that are being
28006 			 * drained.
28007 			 */
28008 			if ((connp->conn_drain_next != connp) &&
28009 			    (idl->idl_conn->conn_drain_next != connp)) {
28010 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28011 			}
28012 			if (idl->idl_repeat) {
28013 				qenable(idl->idl_conn->conn_wq);
28014 				idl->idl_conn_draining = idl->idl_conn;
28015 				idl->idl_repeat = 0;
28016 			} else {
28017 				idl->idl_conn_draining = NULL;
28018 			}
28019 		} else {
28020 			/*
28021 			 * If the next queue that we are now qenable'ing,
28022 			 * is closing, it will remove itself from this list
28023 			 * and qenable the subsequent queue in ip_close().
28024 			 * Serialization is acheived thru idl_lock.
28025 			 */
28026 			qenable(connp->conn_drain_next->conn_wq);
28027 			idl->idl_conn_draining = connp->conn_drain_next;
28028 		}
28029 	}
28030 	if (!connp->conn_did_putbq || closing) {
28031 		/*
28032 		 * Remove ourself from the drain list, if we did not do
28033 		 * a putbq, or if the conn is closing.
28034 		 * Note: It is possible that q->q_first is non-null. It means
28035 		 * that these messages landed after we did a enableok() in
28036 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28037 		 * service them.
28038 		 */
28039 		if (connp->conn_drain_next == connp) {
28040 			/* Singleton in the list */
28041 			ASSERT(connp->conn_drain_prev == connp);
28042 			idl->idl_conn = NULL;
28043 			idl->idl_conn_draining = NULL;
28044 		} else {
28045 			connp->conn_drain_prev->conn_drain_next =
28046 			    connp->conn_drain_next;
28047 			connp->conn_drain_next->conn_drain_prev =
28048 			    connp->conn_drain_prev;
28049 			if (idl->idl_conn == connp)
28050 				idl->idl_conn = connp->conn_drain_next;
28051 			ASSERT(idl->idl_conn_draining != connp);
28052 
28053 		}
28054 		connp->conn_drain_next = NULL;
28055 		connp->conn_drain_prev = NULL;
28056 	}
28057 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28058 }
28059 
28060 /*
28061  * Write service routine. Shared perimeter entry point.
28062  * ip_wsrv can be called in any of the following ways.
28063  * 1. The device queue's messages has fallen below the low water mark
28064  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28065  *    the drain lists and backenable the first conn in each list.
28066  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28067  *    qenabled non-tcp upper layers. We start dequeing messages and call
28068  *    ip_wput for each message.
28069  */
28070 
28071 void
28072 ip_wsrv(queue_t *q)
28073 {
28074 	conn_t	*connp;
28075 	ill_t	*ill;
28076 	mblk_t	*mp;
28077 
28078 	if (q->q_next) {
28079 		ill = (ill_t *)q->q_ptr;
28080 		if (ill->ill_state_flags == 0) {
28081 			/*
28082 			 * The device flow control has opened up.
28083 			 * Walk through conn drain lists and qenable the
28084 			 * first conn in each list. This makes sense only
28085 			 * if the stream is fully plumbed and setup.
28086 			 * Hence the if check above.
28087 			 */
28088 			ip1dbg(("ip_wsrv: walking\n"));
28089 			conn_walk_drain(ill->ill_ipst);
28090 		}
28091 		return;
28092 	}
28093 
28094 	connp = Q_TO_CONN(q);
28095 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28096 
28097 	/*
28098 	 * 1. Set conn_draining flag to signal that service is active.
28099 	 *
28100 	 * 2. ip_output determines whether it has been called from service,
28101 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28102 	 *    has been called from service.
28103 	 *
28104 	 * 3. Message ordering is preserved by the following logic.
28105 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28106 	 *    the message at the tail, if conn_draining is set (i.e. service
28107 	 *    is running) or if q->q_first is non-null.
28108 	 *
28109 	 *    ii. If ip_output is called from service, and if ip_output cannot
28110 	 *    putnext due to flow control, it does a putbq.
28111 	 *
28112 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28113 	 *    (causing an infinite loop).
28114 	 */
28115 	ASSERT(!connp->conn_did_putbq);
28116 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28117 		connp->conn_draining = 1;
28118 		noenable(q);
28119 		while ((mp = getq(q)) != NULL) {
28120 			ASSERT(CONN_Q(q));
28121 
28122 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28123 			if (connp->conn_did_putbq) {
28124 				/* ip_wput did a putbq */
28125 				break;
28126 			}
28127 		}
28128 		/*
28129 		 * At this point, a thread coming down from top, calling
28130 		 * ip_wput, may end up queueing the message. We have not yet
28131 		 * enabled the queue, so ip_wsrv won't be called again.
28132 		 * To avoid this race, check q->q_first again (in the loop)
28133 		 * If the other thread queued the message before we call
28134 		 * enableok(), we will catch it in the q->q_first check.
28135 		 * If the other thread queues the message after we call
28136 		 * enableok(), ip_wsrv will be called again by STREAMS.
28137 		 */
28138 		connp->conn_draining = 0;
28139 		enableok(q);
28140 	}
28141 
28142 	/* Enable the next conn for draining */
28143 	conn_drain_tail(connp, B_FALSE);
28144 
28145 	connp->conn_did_putbq = 0;
28146 }
28147 
28148 /*
28149  * Walk the list of all conn's calling the function provided with the
28150  * specified argument for each.	 Note that this only walks conn's that
28151  * have been bound.
28152  * Applies to both IPv4 and IPv6.
28153  */
28154 static void
28155 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28156 {
28157 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28158 	    ipst->ips_ipcl_udp_fanout_size,
28159 	    func, arg, zoneid);
28160 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28161 	    ipst->ips_ipcl_conn_fanout_size,
28162 	    func, arg, zoneid);
28163 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28164 	    ipst->ips_ipcl_bind_fanout_size,
28165 	    func, arg, zoneid);
28166 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28167 	    IPPROTO_MAX, func, arg, zoneid);
28168 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28169 	    IPPROTO_MAX, func, arg, zoneid);
28170 }
28171 
28172 /*
28173  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28174  * of conns that need to be drained, check if drain is already in progress.
28175  * If so set the idl_repeat bit, indicating that the last conn in the list
28176  * needs to reinitiate the drain once again, for the list. If drain is not
28177  * in progress for the list, initiate the draining, by qenabling the 1st
28178  * conn in the list. The drain is self-sustaining, each qenabled conn will
28179  * in turn qenable the next conn, when it is done/blocked/closing.
28180  */
28181 static void
28182 conn_walk_drain(ip_stack_t *ipst)
28183 {
28184 	int i;
28185 	idl_t *idl;
28186 
28187 	IP_STAT(ipst, ip_conn_walk_drain);
28188 
28189 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28190 		idl = &ipst->ips_conn_drain_list[i];
28191 		mutex_enter(&idl->idl_lock);
28192 		if (idl->idl_conn == NULL) {
28193 			mutex_exit(&idl->idl_lock);
28194 			continue;
28195 		}
28196 		/*
28197 		 * If this list is not being drained currently by
28198 		 * an ip_wsrv thread, start the process.
28199 		 */
28200 		if (idl->idl_conn_draining == NULL) {
28201 			ASSERT(idl->idl_repeat == 0);
28202 			qenable(idl->idl_conn->conn_wq);
28203 			idl->idl_conn_draining = idl->idl_conn;
28204 		} else {
28205 			idl->idl_repeat = 1;
28206 		}
28207 		mutex_exit(&idl->idl_lock);
28208 	}
28209 }
28210 
28211 /*
28212  * Walk an conn hash table of `count' buckets, calling func for each entry.
28213  */
28214 static void
28215 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28216     zoneid_t zoneid)
28217 {
28218 	conn_t	*connp;
28219 
28220 	while (count-- > 0) {
28221 		mutex_enter(&connfp->connf_lock);
28222 		for (connp = connfp->connf_head; connp != NULL;
28223 		    connp = connp->conn_next) {
28224 			if (zoneid == GLOBAL_ZONEID ||
28225 			    zoneid == connp->conn_zoneid) {
28226 				CONN_INC_REF(connp);
28227 				mutex_exit(&connfp->connf_lock);
28228 				(*func)(connp, arg);
28229 				mutex_enter(&connfp->connf_lock);
28230 				CONN_DEC_REF(connp);
28231 			}
28232 		}
28233 		mutex_exit(&connfp->connf_lock);
28234 		connfp++;
28235 	}
28236 }
28237 
28238 /* ipcl_walk routine invoked for ip_conn_report for each conn. */
28239 static void
28240 conn_report1(conn_t *connp, void *mp)
28241 {
28242 	char	buf1[INET6_ADDRSTRLEN];
28243 	char	buf2[INET6_ADDRSTRLEN];
28244 	uint_t	print_len, buf_len;
28245 
28246 	ASSERT(connp != NULL);
28247 
28248 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28249 	if (buf_len <= 0)
28250 		return;
28251 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28252 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28253 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28254 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28255 	    "%5d %s/%05d %s/%05d\n",
28256 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28257 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28258 	    buf1, connp->conn_lport,
28259 	    buf2, connp->conn_fport);
28260 	if (print_len < buf_len) {
28261 		((mblk_t *)mp)->b_wptr += print_len;
28262 	} else {
28263 		((mblk_t *)mp)->b_wptr += buf_len;
28264 	}
28265 }
28266 
28267 /*
28268  * Named Dispatch routine to produce a formatted report on all conns
28269  * that are listed in one of the fanout tables.
28270  * This report is accessed by using the ndd utility to "get" ND variable
28271  * "ip_conn_status".
28272  */
28273 /* ARGSUSED */
28274 static int
28275 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28276 {
28277 	conn_t *connp = Q_TO_CONN(q);
28278 
28279 	(void) mi_mpprintf(mp,
28280 	    "CONN      " MI_COL_HDRPAD_STR
28281 	    "rfq      " MI_COL_HDRPAD_STR
28282 	    "stq      " MI_COL_HDRPAD_STR
28283 	    " zone local                 remote");
28284 
28285 	/*
28286 	 * Because of the ndd constraint, at most we can have 64K buffer
28287 	 * to put in all conn info.  So to be more efficient, just
28288 	 * allocate a 64K buffer here, assuming we need that large buffer.
28289 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28290 	 */
28291 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28292 		/* The following may work even if we cannot get a large buf. */
28293 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28294 		return (0);
28295 	}
28296 
28297 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28298 	    connp->conn_netstack->netstack_ip);
28299 	return (0);
28300 }
28301 
28302 /*
28303  * Determine if the ill and multicast aspects of that packets
28304  * "matches" the conn.
28305  */
28306 boolean_t
28307 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28308     zoneid_t zoneid)
28309 {
28310 	ill_t *in_ill;
28311 	boolean_t found;
28312 	ipif_t *ipif;
28313 	ire_t *ire;
28314 	ipaddr_t dst, src;
28315 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28316 
28317 	dst = ipha->ipha_dst;
28318 	src = ipha->ipha_src;
28319 
28320 	/*
28321 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28322 	 * unicast, broadcast and multicast reception to
28323 	 * conn_incoming_ill. conn_wantpacket itself is called
28324 	 * only for BROADCAST and multicast.
28325 	 *
28326 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28327 	 *    is part of a group. Hence, we should be receiving
28328 	 *    just one copy of broadcast for the whole group.
28329 	 *    Thus, if it is part of the group the packet could
28330 	 *    come on any ill of the group and hence we need a
28331 	 *    match on the group. Otherwise, match on ill should
28332 	 *    be sufficient.
28333 	 *
28334 	 * 2) ip_rput does not suppress duplicate multicast packets.
28335 	 *    If there are two interfaces in a ill group and we have
28336 	 *    2 applications (conns) joined a multicast group G on
28337 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28338 	 *    will give us two packets because we join G on both the
28339 	 *    interfaces rather than nominating just one interface
28340 	 *    for receiving multicast like broadcast above. So,
28341 	 *    we have to call ilg_lookup_ill to filter out duplicate
28342 	 *    copies, if ill is part of a group.
28343 	 */
28344 	in_ill = connp->conn_incoming_ill;
28345 	if (in_ill != NULL) {
28346 		if (in_ill->ill_group == NULL) {
28347 			if (in_ill != ill)
28348 				return (B_FALSE);
28349 		} else if (in_ill->ill_group != ill->ill_group) {
28350 			return (B_FALSE);
28351 		}
28352 	}
28353 
28354 	if (!CLASSD(dst)) {
28355 		if (IPCL_ZONE_MATCH(connp, zoneid))
28356 			return (B_TRUE);
28357 		/*
28358 		 * The conn is in a different zone; we need to check that this
28359 		 * broadcast address is configured in the application's zone and
28360 		 * on one ill in the group.
28361 		 */
28362 		ipif = ipif_get_next_ipif(NULL, ill);
28363 		if (ipif == NULL)
28364 			return (B_FALSE);
28365 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28366 		    connp->conn_zoneid, NULL,
28367 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28368 		ipif_refrele(ipif);
28369 		if (ire != NULL) {
28370 			ire_refrele(ire);
28371 			return (B_TRUE);
28372 		} else {
28373 			return (B_FALSE);
28374 		}
28375 	}
28376 
28377 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28378 	    connp->conn_zoneid == zoneid) {
28379 		/*
28380 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28381 		 * disabled, therefore we don't dispatch the multicast packet to
28382 		 * the sending zone.
28383 		 */
28384 		return (B_FALSE);
28385 	}
28386 
28387 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28388 		/*
28389 		 * Multicast packet on the loopback interface: we only match
28390 		 * conns who joined the group in the specified zone.
28391 		 */
28392 		return (B_FALSE);
28393 	}
28394 
28395 	if (connp->conn_multi_router) {
28396 		/* multicast packet and multicast router socket: send up */
28397 		return (B_TRUE);
28398 	}
28399 
28400 	mutex_enter(&connp->conn_lock);
28401 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28402 	mutex_exit(&connp->conn_lock);
28403 	return (found);
28404 }
28405 
28406 /*
28407  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28408  */
28409 /* ARGSUSED */
28410 static void
28411 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28412 {
28413 	ill_t *ill = (ill_t *)q->q_ptr;
28414 	mblk_t	*mp1, *mp2;
28415 	ipif_t  *ipif;
28416 	int err = 0;
28417 	conn_t *connp = NULL;
28418 	ipsq_t	*ipsq;
28419 	arc_t	*arc;
28420 
28421 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28422 
28423 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28424 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28425 
28426 	ASSERT(IAM_WRITER_ILL(ill));
28427 	mp2 = mp->b_cont;
28428 	mp->b_cont = NULL;
28429 
28430 	/*
28431 	 * We have now received the arp bringup completion message
28432 	 * from ARP. Mark the arp bringup as done. Also if the arp
28433 	 * stream has already started closing, send up the AR_ARP_CLOSING
28434 	 * ack now since ARP is waiting in close for this ack.
28435 	 */
28436 	mutex_enter(&ill->ill_lock);
28437 	ill->ill_arp_bringup_pending = 0;
28438 	if (ill->ill_arp_closing) {
28439 		mutex_exit(&ill->ill_lock);
28440 		/* Let's reuse the mp for sending the ack */
28441 		arc = (arc_t *)mp->b_rptr;
28442 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28443 		arc->arc_cmd = AR_ARP_CLOSING;
28444 		qreply(q, mp);
28445 	} else {
28446 		mutex_exit(&ill->ill_lock);
28447 		freeb(mp);
28448 	}
28449 
28450 	ipsq = ill->ill_phyint->phyint_ipsq;
28451 	ipif = ipsq->ipsq_pending_ipif;
28452 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28453 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28454 	if (mp1 == NULL) {
28455 		/* bringup was aborted by the user */
28456 		freemsg(mp2);
28457 		return;
28458 	}
28459 
28460 	/*
28461 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28462 	 * must have an associated conn_t.  Otherwise, we're bringing this
28463 	 * interface back up as part of handling an asynchronous event (e.g.,
28464 	 * physical address change).
28465 	 */
28466 	if (ipsq->ipsq_current_ioctl != 0) {
28467 		ASSERT(connp != NULL);
28468 		q = CONNP_TO_WQ(connp);
28469 	} else {
28470 		ASSERT(connp == NULL);
28471 		q = ill->ill_rq;
28472 	}
28473 
28474 	/*
28475 	 * If the DL_BIND_REQ fails, it is noted
28476 	 * in arc_name_offset.
28477 	 */
28478 	err = *((int *)mp2->b_rptr);
28479 	if (err == 0) {
28480 		if (ipif->ipif_isv6) {
28481 			if ((err = ipif_up_done_v6(ipif)) != 0)
28482 				ip0dbg(("ip_arp_done: init failed\n"));
28483 		} else {
28484 			if ((err = ipif_up_done(ipif)) != 0)
28485 				ip0dbg(("ip_arp_done: init failed\n"));
28486 		}
28487 	} else {
28488 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28489 	}
28490 
28491 	freemsg(mp2);
28492 
28493 	if ((err == 0) && (ill->ill_up_ipifs)) {
28494 		err = ill_up_ipifs(ill, q, mp1);
28495 		if (err == EINPROGRESS)
28496 			return;
28497 	}
28498 
28499 	if (ill->ill_up_ipifs)
28500 		ill_group_cleanup(ill);
28501 
28502 	/*
28503 	 * The operation must complete without EINPROGRESS since
28504 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28505 	 * Otherwise, the operation will be stuck forever in the ipsq.
28506 	 */
28507 	ASSERT(err != EINPROGRESS);
28508 	if (ipsq->ipsq_current_ioctl != 0)
28509 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28510 	else
28511 		ipsq_current_finish(ipsq);
28512 }
28513 
28514 /* Allocate the private structure */
28515 static int
28516 ip_priv_alloc(void **bufp)
28517 {
28518 	void	*buf;
28519 
28520 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28521 		return (ENOMEM);
28522 
28523 	*bufp = buf;
28524 	return (0);
28525 }
28526 
28527 /* Function to delete the private structure */
28528 void
28529 ip_priv_free(void *buf)
28530 {
28531 	ASSERT(buf != NULL);
28532 	kmem_free(buf, sizeof (ip_priv_t));
28533 }
28534 
28535 /*
28536  * The entry point for IPPF processing.
28537  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28538  * routine just returns.
28539  *
28540  * When called, ip_process generates an ipp_packet_t structure
28541  * which holds the state information for this packet and invokes the
28542  * the classifier (via ipp_packet_process). The classification, depending on
28543  * configured filters, results in a list of actions for this packet. Invoking
28544  * an action may cause the packet to be dropped, in which case the resulting
28545  * mblk (*mpp) is NULL. proc indicates the callout position for
28546  * this packet and ill_index is the interface this packet on or will leave
28547  * on (inbound and outbound resp.).
28548  */
28549 void
28550 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28551 {
28552 	mblk_t		*mp;
28553 	ip_priv_t	*priv;
28554 	ipp_action_id_t	aid;
28555 	int		rc = 0;
28556 	ipp_packet_t	*pp;
28557 #define	IP_CLASS	"ip"
28558 
28559 	/* If the classifier is not loaded, return  */
28560 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28561 		return;
28562 	}
28563 
28564 	mp = *mpp;
28565 	ASSERT(mp != NULL);
28566 
28567 	/* Allocate the packet structure */
28568 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28569 	if (rc != 0) {
28570 		*mpp = NULL;
28571 		freemsg(mp);
28572 		return;
28573 	}
28574 
28575 	/* Allocate the private structure */
28576 	rc = ip_priv_alloc((void **)&priv);
28577 	if (rc != 0) {
28578 		*mpp = NULL;
28579 		freemsg(mp);
28580 		ipp_packet_free(pp);
28581 		return;
28582 	}
28583 	priv->proc = proc;
28584 	priv->ill_index = ill_index;
28585 	ipp_packet_set_private(pp, priv, ip_priv_free);
28586 	ipp_packet_set_data(pp, mp);
28587 
28588 	/* Invoke the classifier */
28589 	rc = ipp_packet_process(&pp);
28590 	if (pp != NULL) {
28591 		mp = ipp_packet_get_data(pp);
28592 		ipp_packet_free(pp);
28593 		if (rc != 0) {
28594 			freemsg(mp);
28595 			*mpp = NULL;
28596 		}
28597 	} else {
28598 		*mpp = NULL;
28599 	}
28600 #undef	IP_CLASS
28601 }
28602 
28603 /*
28604  * Propagate a multicast group membership operation (add/drop) on
28605  * all the interfaces crossed by the related multirt routes.
28606  * The call is considered successful if the operation succeeds
28607  * on at least one interface.
28608  */
28609 static int
28610 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28611     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28612     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28613     mblk_t *first_mp)
28614 {
28615 	ire_t		*ire_gw;
28616 	irb_t		*irb;
28617 	int		error = 0;
28618 	opt_restart_t	*or;
28619 	ip_stack_t	*ipst = ire->ire_ipst;
28620 
28621 	irb = ire->ire_bucket;
28622 	ASSERT(irb != NULL);
28623 
28624 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28625 
28626 	or = (opt_restart_t *)first_mp->b_rptr;
28627 	IRB_REFHOLD(irb);
28628 	for (; ire != NULL; ire = ire->ire_next) {
28629 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28630 			continue;
28631 		if (ire->ire_addr != group)
28632 			continue;
28633 
28634 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28635 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28636 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28637 		/* No resolver exists for the gateway; skip this ire. */
28638 		if (ire_gw == NULL)
28639 			continue;
28640 
28641 		/*
28642 		 * This function can return EINPROGRESS. If so the operation
28643 		 * will be restarted from ip_restart_optmgmt which will
28644 		 * call ip_opt_set and option processing will restart for
28645 		 * this option. So we may end up calling 'fn' more than once.
28646 		 * This requires that 'fn' is idempotent except for the
28647 		 * return value. The operation is considered a success if
28648 		 * it succeeds at least once on any one interface.
28649 		 */
28650 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28651 		    NULL, fmode, src, first_mp);
28652 		if (error == 0)
28653 			or->or_private = CGTP_MCAST_SUCCESS;
28654 
28655 		if (ip_debug > 0) {
28656 			ulong_t	off;
28657 			char	*ksym;
28658 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28659 			ip2dbg(("ip_multirt_apply_membership: "
28660 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28661 			    "error %d [success %u]\n",
28662 			    ksym ? ksym : "?",
28663 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28664 			    error, or->or_private));
28665 		}
28666 
28667 		ire_refrele(ire_gw);
28668 		if (error == EINPROGRESS) {
28669 			IRB_REFRELE(irb);
28670 			return (error);
28671 		}
28672 	}
28673 	IRB_REFRELE(irb);
28674 	/*
28675 	 * Consider the call as successful if we succeeded on at least
28676 	 * one interface. Otherwise, return the last encountered error.
28677 	 */
28678 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28679 }
28680 
28681 
28682 /*
28683  * Issue a warning regarding a route crossing an interface with an
28684  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28685  * amount of time is logged.
28686  */
28687 static void
28688 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28689 {
28690 	hrtime_t	current = gethrtime();
28691 	char		buf[INET_ADDRSTRLEN];
28692 	ip_stack_t	*ipst = ire->ire_ipst;
28693 
28694 	/* Convert interval in ms to hrtime in ns */
28695 	if (ipst->ips_multirt_bad_mtu_last_time +
28696 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28697 	    current) {
28698 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28699 		    "to %s, incorrect MTU %u (expected %u)\n",
28700 		    ip_dot_addr(ire->ire_addr, buf),
28701 		    ire->ire_max_frag, max_frag);
28702 
28703 		ipst->ips_multirt_bad_mtu_last_time = current;
28704 	}
28705 }
28706 
28707 
28708 /*
28709  * Get the CGTP (multirouting) filtering status.
28710  * If 0, the CGTP hooks are transparent.
28711  */
28712 /* ARGSUSED */
28713 static int
28714 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28715 {
28716 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28717 
28718 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28719 	return (0);
28720 }
28721 
28722 
28723 /*
28724  * Set the CGTP (multirouting) filtering status.
28725  * If the status is changed from active to transparent
28726  * or from transparent to active, forward the new status
28727  * to the filtering module (if loaded).
28728  */
28729 /* ARGSUSED */
28730 static int
28731 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28732     cred_t *ioc_cr)
28733 {
28734 	long		new_value;
28735 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28736 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28737 
28738 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28739 		return (EPERM);
28740 
28741 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28742 	    new_value < 0 || new_value > 1) {
28743 		return (EINVAL);
28744 	}
28745 
28746 	if ((!*ip_cgtp_filter_value) && new_value) {
28747 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28748 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28749 		    " (module not loaded)" : "");
28750 	}
28751 	if (*ip_cgtp_filter_value && (!new_value)) {
28752 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28753 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28754 		    " (module not loaded)" : "");
28755 	}
28756 
28757 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28758 		int	res;
28759 		netstackid_t stackid;
28760 
28761 		stackid = ipst->ips_netstack->netstack_stackid;
28762 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28763 		    new_value);
28764 		if (res)
28765 			return (res);
28766 	}
28767 
28768 	*ip_cgtp_filter_value = (boolean_t)new_value;
28769 
28770 	return (0);
28771 }
28772 
28773 
28774 /*
28775  * Return the expected CGTP hooks version number.
28776  */
28777 int
28778 ip_cgtp_filter_supported(void)
28779 {
28780 	return (ip_cgtp_filter_rev);
28781 }
28782 
28783 
28784 /*
28785  * CGTP hooks can be registered by invoking this function.
28786  * Checks that the version number matches.
28787  */
28788 int
28789 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28790 {
28791 	netstack_t *ns;
28792 	ip_stack_t *ipst;
28793 
28794 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28795 		return (ENOTSUP);
28796 
28797 	ns = netstack_find_by_stackid(stackid);
28798 	if (ns == NULL)
28799 		return (EINVAL);
28800 	ipst = ns->netstack_ip;
28801 	ASSERT(ipst != NULL);
28802 
28803 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28804 		netstack_rele(ns);
28805 		return (EALREADY);
28806 	}
28807 
28808 	ipst->ips_ip_cgtp_filter_ops = ops;
28809 	netstack_rele(ns);
28810 	return (0);
28811 }
28812 
28813 /*
28814  * CGTP hooks can be unregistered by invoking this function.
28815  * Returns ENXIO if there was no registration.
28816  * Returns EBUSY if the ndd variable has not been turned off.
28817  */
28818 int
28819 ip_cgtp_filter_unregister(netstackid_t stackid)
28820 {
28821 	netstack_t *ns;
28822 	ip_stack_t *ipst;
28823 
28824 	ns = netstack_find_by_stackid(stackid);
28825 	if (ns == NULL)
28826 		return (EINVAL);
28827 	ipst = ns->netstack_ip;
28828 	ASSERT(ipst != NULL);
28829 
28830 	if (ipst->ips_ip_cgtp_filter) {
28831 		netstack_rele(ns);
28832 		return (EBUSY);
28833 	}
28834 
28835 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
28836 		netstack_rele(ns);
28837 		return (ENXIO);
28838 	}
28839 	ipst->ips_ip_cgtp_filter_ops = NULL;
28840 	netstack_rele(ns);
28841 	return (0);
28842 }
28843 
28844 /*
28845  * Check whether there is a CGTP filter registration.
28846  * Returns non-zero if there is a registration, otherwise returns zero.
28847  * Note: returns zero if bad stackid.
28848  */
28849 int
28850 ip_cgtp_filter_is_registered(netstackid_t stackid)
28851 {
28852 	netstack_t *ns;
28853 	ip_stack_t *ipst;
28854 	int ret;
28855 
28856 	ns = netstack_find_by_stackid(stackid);
28857 	if (ns == NULL)
28858 		return (0);
28859 	ipst = ns->netstack_ip;
28860 	ASSERT(ipst != NULL);
28861 
28862 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
28863 		ret = 1;
28864 	else
28865 		ret = 0;
28866 
28867 	netstack_rele(ns);
28868 	return (ret);
28869 }
28870 
28871 static squeue_func_t
28872 ip_squeue_switch(int val)
28873 {
28874 	squeue_func_t rval = squeue_fill;
28875 
28876 	switch (val) {
28877 	case IP_SQUEUE_ENTER_NODRAIN:
28878 		rval = squeue_enter_nodrain;
28879 		break;
28880 	case IP_SQUEUE_ENTER:
28881 		rval = squeue_enter;
28882 		break;
28883 	default:
28884 		break;
28885 	}
28886 	return (rval);
28887 }
28888 
28889 /* ARGSUSED */
28890 static int
28891 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
28892     caddr_t addr, cred_t *cr)
28893 {
28894 	int *v = (int *)addr;
28895 	long new_value;
28896 
28897 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28898 		return (EPERM);
28899 
28900 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28901 		return (EINVAL);
28902 
28903 	ip_input_proc = ip_squeue_switch(new_value);
28904 	*v = new_value;
28905 	return (0);
28906 }
28907 
28908 /* ARGSUSED */
28909 static int
28910 ip_int_set(queue_t *q, mblk_t *mp, char *value,
28911     caddr_t addr, cred_t *cr)
28912 {
28913 	int *v = (int *)addr;
28914 	long new_value;
28915 
28916 	if (secpolicy_net_config(cr, B_FALSE) != 0)
28917 		return (EPERM);
28918 
28919 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
28920 		return (EINVAL);
28921 
28922 	*v = new_value;
28923 	return (0);
28924 }
28925 
28926 /*
28927  * Handle changes to ipmp_hook_emulation ndd variable.
28928  * Need to update phyint_hook_ifindex.
28929  * Also generate a nic plumb event should a new ifidex be assigned to a group.
28930  */
28931 static void
28932 ipmp_hook_emulation_changed(ip_stack_t *ipst)
28933 {
28934 	phyint_t *phyi;
28935 	phyint_t *phyi_tmp;
28936 	char *groupname;
28937 	int namelen;
28938 	ill_t	*ill;
28939 	boolean_t new_group;
28940 
28941 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
28942 	/*
28943 	 * Group indicies are stored in the phyint - a common structure
28944 	 * to both IPv4 and IPv6.
28945 	 */
28946 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
28947 	for (; phyi != NULL;
28948 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
28949 	    phyi, AVL_AFTER)) {
28950 		/* Ignore the ones that do not have a group */
28951 		if (phyi->phyint_groupname_len == 0)
28952 			continue;
28953 
28954 		/*
28955 		 * Look for other phyint in group.
28956 		 * Clear name/namelen so the lookup doesn't find ourselves.
28957 		 */
28958 		namelen = phyi->phyint_groupname_len;
28959 		groupname = phyi->phyint_groupname;
28960 		phyi->phyint_groupname_len = 0;
28961 		phyi->phyint_groupname = NULL;
28962 
28963 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
28964 		/* Restore */
28965 		phyi->phyint_groupname_len = namelen;
28966 		phyi->phyint_groupname = groupname;
28967 
28968 		new_group = B_FALSE;
28969 		if (ipst->ips_ipmp_hook_emulation) {
28970 			/*
28971 			 * If the group already exists and has already
28972 			 * been assigned a group ifindex, we use the existing
28973 			 * group_ifindex, otherwise we pick a new group_ifindex
28974 			 * here.
28975 			 */
28976 			if (phyi_tmp != NULL &&
28977 			    phyi_tmp->phyint_group_ifindex != 0) {
28978 				phyi->phyint_group_ifindex =
28979 				    phyi_tmp->phyint_group_ifindex;
28980 			} else {
28981 				/* XXX We need a recovery strategy here. */
28982 				if (!ip_assign_ifindex(
28983 				    &phyi->phyint_group_ifindex, ipst))
28984 					cmn_err(CE_PANIC,
28985 					    "ip_assign_ifindex() failed");
28986 				new_group = B_TRUE;
28987 			}
28988 		} else {
28989 			phyi->phyint_group_ifindex = 0;
28990 		}
28991 		if (ipst->ips_ipmp_hook_emulation)
28992 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
28993 		else
28994 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
28995 
28996 		/*
28997 		 * For IP Filter to find out the relationship between
28998 		 * names and interface indicies, we need to generate
28999 		 * a NE_PLUMB event when a new group can appear.
29000 		 * We always generate events when a new interface appears
29001 		 * (even when ipmp_hook_emulation is set) so there
29002 		 * is no need to generate NE_PLUMB events when
29003 		 * ipmp_hook_emulation is turned off.
29004 		 * And since it isn't critical for IP Filter to get
29005 		 * the NE_UNPLUMB events we skip those here.
29006 		 */
29007 		if (new_group) {
29008 			/*
29009 			 * First phyint in group - generate group PLUMB event.
29010 			 * Since we are not running inside the ipsq we do
29011 			 * the dispatch immediately.
29012 			 */
29013 			if (phyi->phyint_illv4 != NULL)
29014 				ill = phyi->phyint_illv4;
29015 			else
29016 				ill = phyi->phyint_illv6;
29017 
29018 			if (ill != NULL) {
29019 				mutex_enter(&ill->ill_lock);
29020 				ill_nic_info_plumb(ill, B_TRUE);
29021 				ill_nic_info_dispatch(ill);
29022 				mutex_exit(&ill->ill_lock);
29023 			}
29024 		}
29025 	}
29026 	rw_exit(&ipst->ips_ill_g_lock);
29027 }
29028 
29029 /* ARGSUSED */
29030 static int
29031 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29032     caddr_t addr, cred_t *cr)
29033 {
29034 	int *v = (int *)addr;
29035 	long new_value;
29036 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29037 
29038 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29039 		return (EINVAL);
29040 
29041 	if (*v != new_value) {
29042 		*v = new_value;
29043 		ipmp_hook_emulation_changed(ipst);
29044 	}
29045 	return (0);
29046 }
29047 
29048 static void *
29049 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29050 {
29051 	kstat_t *ksp;
29052 
29053 	ip_stat_t template = {
29054 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29055 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29056 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29057 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29058 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29059 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29060 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29061 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29062 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29063 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29064 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29065 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29066 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29067 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29068 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29069 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29070 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29071 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29072 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29073 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29074 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29075 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29076 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29077 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29078 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29079 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29080 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29081 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29082 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29083 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29084 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29085 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29086 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29087 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29088 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29089 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29090 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29091 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29092 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29093 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29094 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29095 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29096 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29097 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29098 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29099 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29100 	};
29101 
29102 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29103 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29104 	    KSTAT_FLAG_VIRTUAL, stackid);
29105 
29106 	if (ksp == NULL)
29107 		return (NULL);
29108 
29109 	bcopy(&template, ip_statisticsp, sizeof (template));
29110 	ksp->ks_data = (void *)ip_statisticsp;
29111 	ksp->ks_private = (void *)(uintptr_t)stackid;
29112 
29113 	kstat_install(ksp);
29114 	return (ksp);
29115 }
29116 
29117 static void
29118 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29119 {
29120 	if (ksp != NULL) {
29121 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29122 		kstat_delete_netstack(ksp, stackid);
29123 	}
29124 }
29125 
29126 static void *
29127 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29128 {
29129 	kstat_t	*ksp;
29130 
29131 	ip_named_kstat_t template = {
29132 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29133 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29134 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29135 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29136 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29137 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29138 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29139 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29140 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29141 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29142 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29143 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29144 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29145 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29146 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29147 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29148 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29149 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29150 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29151 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29152 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29153 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29154 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29155 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29156 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29157 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29158 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29159 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29160 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29161 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29162 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29163 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29164 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29165 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29166 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29167 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29168 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29169 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29170 	};
29171 
29172 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29173 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29174 	if (ksp == NULL || ksp->ks_data == NULL)
29175 		return (NULL);
29176 
29177 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29178 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29179 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29180 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29181 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29182 
29183 	template.netToMediaEntrySize.value.i32 =
29184 	    sizeof (mib2_ipNetToMediaEntry_t);
29185 
29186 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29187 
29188 	bcopy(&template, ksp->ks_data, sizeof (template));
29189 	ksp->ks_update = ip_kstat_update;
29190 	ksp->ks_private = (void *)(uintptr_t)stackid;
29191 
29192 	kstat_install(ksp);
29193 	return (ksp);
29194 }
29195 
29196 static void
29197 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29198 {
29199 	if (ksp != NULL) {
29200 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29201 		kstat_delete_netstack(ksp, stackid);
29202 	}
29203 }
29204 
29205 static int
29206 ip_kstat_update(kstat_t *kp, int rw)
29207 {
29208 	ip_named_kstat_t *ipkp;
29209 	mib2_ipIfStatsEntry_t ipmib;
29210 	ill_walk_context_t ctx;
29211 	ill_t *ill;
29212 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29213 	netstack_t	*ns;
29214 	ip_stack_t	*ipst;
29215 
29216 	if (kp == NULL || kp->ks_data == NULL)
29217 		return (EIO);
29218 
29219 	if (rw == KSTAT_WRITE)
29220 		return (EACCES);
29221 
29222 	ns = netstack_find_by_stackid(stackid);
29223 	if (ns == NULL)
29224 		return (-1);
29225 	ipst = ns->netstack_ip;
29226 	if (ipst == NULL) {
29227 		netstack_rele(ns);
29228 		return (-1);
29229 	}
29230 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29231 
29232 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29233 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29234 	ill = ILL_START_WALK_V4(&ctx, ipst);
29235 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29236 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29237 	rw_exit(&ipst->ips_ill_g_lock);
29238 
29239 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29240 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29241 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29242 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29243 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29244 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29245 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29246 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29247 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29248 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29249 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29250 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29251 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29252 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29253 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29254 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29255 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29256 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29257 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29258 
29259 	ipkp->routingDiscards.value.ui32 =	0;
29260 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29261 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29262 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29263 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29264 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29265 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29266 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29267 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29268 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29269 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29270 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29271 
29272 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29273 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29274 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29275 
29276 	netstack_rele(ns);
29277 
29278 	return (0);
29279 }
29280 
29281 static void *
29282 icmp_kstat_init(netstackid_t stackid)
29283 {
29284 	kstat_t	*ksp;
29285 
29286 	icmp_named_kstat_t template = {
29287 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29288 		{ "inErrors",		KSTAT_DATA_UINT32 },
29289 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29290 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29291 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29292 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29293 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29294 		{ "inEchos",		KSTAT_DATA_UINT32 },
29295 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29296 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29297 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29298 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29299 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29300 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29301 		{ "outErrors",		KSTAT_DATA_UINT32 },
29302 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29303 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29304 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29305 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29306 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29307 		{ "outEchos",		KSTAT_DATA_UINT32 },
29308 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29309 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29310 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29311 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29312 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29313 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29314 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29315 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29316 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29317 		{ "outDrops",		KSTAT_DATA_UINT32 },
29318 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29319 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29320 	};
29321 
29322 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29323 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29324 	if (ksp == NULL || ksp->ks_data == NULL)
29325 		return (NULL);
29326 
29327 	bcopy(&template, ksp->ks_data, sizeof (template));
29328 
29329 	ksp->ks_update = icmp_kstat_update;
29330 	ksp->ks_private = (void *)(uintptr_t)stackid;
29331 
29332 	kstat_install(ksp);
29333 	return (ksp);
29334 }
29335 
29336 static void
29337 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29338 {
29339 	if (ksp != NULL) {
29340 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29341 		kstat_delete_netstack(ksp, stackid);
29342 	}
29343 }
29344 
29345 static int
29346 icmp_kstat_update(kstat_t *kp, int rw)
29347 {
29348 	icmp_named_kstat_t *icmpkp;
29349 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29350 	netstack_t	*ns;
29351 	ip_stack_t	*ipst;
29352 
29353 	if ((kp == NULL) || (kp->ks_data == NULL))
29354 		return (EIO);
29355 
29356 	if (rw == KSTAT_WRITE)
29357 		return (EACCES);
29358 
29359 	ns = netstack_find_by_stackid(stackid);
29360 	if (ns == NULL)
29361 		return (-1);
29362 	ipst = ns->netstack_ip;
29363 	if (ipst == NULL) {
29364 		netstack_rele(ns);
29365 		return (-1);
29366 	}
29367 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29368 
29369 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29370 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29371 	icmpkp->inDestUnreachs.value.ui32 =
29372 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29373 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29374 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29375 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29376 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29377 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29378 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29379 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29380 	icmpkp->inTimestampReps.value.ui32 =
29381 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29382 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29383 	icmpkp->inAddrMaskReps.value.ui32 =
29384 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29385 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29386 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29387 	icmpkp->outDestUnreachs.value.ui32 =
29388 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29389 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29390 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29391 	icmpkp->outSrcQuenchs.value.ui32 =
29392 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29393 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29394 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29395 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29396 	icmpkp->outTimestamps.value.ui32 =
29397 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29398 	icmpkp->outTimestampReps.value.ui32 =
29399 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29400 	icmpkp->outAddrMasks.value.ui32 =
29401 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29402 	icmpkp->outAddrMaskReps.value.ui32 =
29403 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29404 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29405 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29406 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29407 	icmpkp->outFragNeeded.value.ui32 =
29408 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29409 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29410 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29411 	icmpkp->inBadRedirects.value.ui32 =
29412 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29413 
29414 	netstack_rele(ns);
29415 	return (0);
29416 }
29417 
29418 /*
29419  * This is the fanout function for raw socket opened for SCTP.  Note
29420  * that it is called after SCTP checks that there is no socket which
29421  * wants a packet.  Then before SCTP handles this out of the blue packet,
29422  * this function is called to see if there is any raw socket for SCTP.
29423  * If there is and it is bound to the correct address, the packet will
29424  * be sent to that socket.  Note that only one raw socket can be bound to
29425  * a port.  This is assured in ipcl_sctp_hash_insert();
29426  */
29427 void
29428 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29429     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29430     zoneid_t zoneid)
29431 {
29432 	conn_t		*connp;
29433 	queue_t		*rq;
29434 	mblk_t		*first_mp;
29435 	boolean_t	secure;
29436 	ip6_t		*ip6h;
29437 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29438 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29439 
29440 	first_mp = mp;
29441 	if (mctl_present) {
29442 		mp = first_mp->b_cont;
29443 		secure = ipsec_in_is_secure(first_mp);
29444 		ASSERT(mp != NULL);
29445 	} else {
29446 		secure = B_FALSE;
29447 	}
29448 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29449 
29450 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29451 	if (connp == NULL) {
29452 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29453 		return;
29454 	}
29455 	rq = connp->conn_rq;
29456 	if (!canputnext(rq)) {
29457 		CONN_DEC_REF(connp);
29458 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29459 		freemsg(first_mp);
29460 		return;
29461 	}
29462 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29463 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29464 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29465 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29466 		if (first_mp == NULL) {
29467 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29468 			CONN_DEC_REF(connp);
29469 			return;
29470 		}
29471 	}
29472 	/*
29473 	 * We probably should not send M_CTL message up to
29474 	 * raw socket.
29475 	 */
29476 	if (mctl_present)
29477 		freeb(first_mp);
29478 
29479 	/* Initiate IPPF processing here if needed. */
29480 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29481 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29482 		ip_process(IPP_LOCAL_IN, &mp,
29483 		    recv_ill->ill_phyint->phyint_ifindex);
29484 		if (mp == NULL) {
29485 			CONN_DEC_REF(connp);
29486 			return;
29487 		}
29488 	}
29489 
29490 	if (connp->conn_recvif || connp->conn_recvslla ||
29491 	    ((connp->conn_ip_recvpktinfo ||
29492 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29493 	    (flags & IP_FF_IPINFO))) {
29494 		int in_flags = 0;
29495 
29496 		/*
29497 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29498 		 * IPF_RECVIF.
29499 		 */
29500 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29501 			in_flags = IPF_RECVIF;
29502 		}
29503 		if (connp->conn_recvslla) {
29504 			in_flags |= IPF_RECVSLLA;
29505 		}
29506 		if (isv4) {
29507 			mp = ip_add_info(mp, recv_ill, in_flags,
29508 			    IPCL_ZONEID(connp), ipst);
29509 		} else {
29510 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29511 			if (mp == NULL) {
29512 				BUMP_MIB(recv_ill->ill_ip_mib,
29513 				    ipIfStatsInDiscards);
29514 				CONN_DEC_REF(connp);
29515 				return;
29516 			}
29517 		}
29518 	}
29519 
29520 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29521 	/*
29522 	 * We are sending the IPSEC_IN message also up. Refer
29523 	 * to comments above this function.
29524 	 */
29525 	putnext(rq, mp);
29526 	CONN_DEC_REF(connp);
29527 }
29528 
29529 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29530 {									\
29531 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29532 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29533 }
29534 /*
29535  * This function should be called only if all packet processing
29536  * including fragmentation is complete. Callers of this function
29537  * must set mp->b_prev to one of these values:
29538  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29539  * prior to handing over the mp as first argument to this function.
29540  *
29541  * If the ire passed by caller is incomplete, this function
29542  * queues the packet and if necessary, sends ARP request and bails.
29543  * If the ire passed is fully resolved, we simply prepend
29544  * the link-layer header to the packet, do ipsec hw acceleration
29545  * work if necessary, and send the packet out on the wire.
29546  *
29547  * NOTE: IPSEC will only call this function with fully resolved
29548  * ires if hw acceleration is involved.
29549  * TODO list :
29550  * 	a Handle M_MULTIDATA so that
29551  *	  tcp_multisend->tcp_multisend_data can
29552  *	  call ip_xmit_v4 directly
29553  *	b Handle post-ARP work for fragments so that
29554  *	  ip_wput_frag can call this function.
29555  */
29556 ipxmit_state_t
29557 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29558 {
29559 	nce_t		*arpce;
29560 	queue_t		*q;
29561 	int		ill_index;
29562 	mblk_t		*nxt_mp, *first_mp;
29563 	boolean_t	xmit_drop = B_FALSE;
29564 	ip_proc_t	proc;
29565 	ill_t		*out_ill;
29566 	int		pkt_len;
29567 
29568 	arpce = ire->ire_nce;
29569 	ASSERT(arpce != NULL);
29570 
29571 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29572 
29573 	mutex_enter(&arpce->nce_lock);
29574 	switch (arpce->nce_state) {
29575 	case ND_REACHABLE:
29576 		/* If there are other queued packets, queue this packet */
29577 		if (arpce->nce_qd_mp != NULL) {
29578 			if (mp != NULL)
29579 				nce_queue_mp_common(arpce, mp, B_FALSE);
29580 			mp = arpce->nce_qd_mp;
29581 		}
29582 		arpce->nce_qd_mp = NULL;
29583 		mutex_exit(&arpce->nce_lock);
29584 
29585 		/*
29586 		 * Flush the queue.  In the common case, where the
29587 		 * ARP is already resolved,  it will go through the
29588 		 * while loop only once.
29589 		 */
29590 		while (mp != NULL) {
29591 
29592 			nxt_mp = mp->b_next;
29593 			mp->b_next = NULL;
29594 			ASSERT(mp->b_datap->db_type != M_CTL);
29595 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29596 			/*
29597 			 * This info is needed for IPQOS to do COS marking
29598 			 * in ip_wput_attach_llhdr->ip_process.
29599 			 */
29600 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29601 			mp->b_prev = NULL;
29602 
29603 			/* set up ill index for outbound qos processing */
29604 			out_ill = ire->ire_ipif->ipif_ill;
29605 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29606 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29607 			    ill_index);
29608 			if (first_mp == NULL) {
29609 				xmit_drop = B_TRUE;
29610 				BUMP_MIB(out_ill->ill_ip_mib,
29611 				    ipIfStatsOutDiscards);
29612 				goto next_mp;
29613 			}
29614 			/* non-ipsec hw accel case */
29615 			if (io == NULL || !io->ipsec_out_accelerated) {
29616 				/* send it */
29617 				q = ire->ire_stq;
29618 				if (proc == IPP_FWD_OUT) {
29619 					UPDATE_IB_PKT_COUNT(ire);
29620 				} else {
29621 					UPDATE_OB_PKT_COUNT(ire);
29622 				}
29623 				ire->ire_last_used_time = lbolt;
29624 
29625 				if (flow_ctl_enabled || canputnext(q)) {
29626 					if (proc == IPP_FWD_OUT) {
29627 
29628 					BUMP_MIB(out_ill->ill_ip_mib,
29629 					    ipIfStatsHCOutForwDatagrams);
29630 
29631 					}
29632 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29633 					    pkt_len);
29634 
29635 					putnext(q, first_mp);
29636 				} else {
29637 					BUMP_MIB(out_ill->ill_ip_mib,
29638 					    ipIfStatsOutDiscards);
29639 					xmit_drop = B_TRUE;
29640 					freemsg(first_mp);
29641 				}
29642 			} else {
29643 				/*
29644 				 * Safety Pup says: make sure this
29645 				 *  is going to the right interface!
29646 				 */
29647 				ill_t *ill1 =
29648 				    (ill_t *)ire->ire_stq->q_ptr;
29649 				int ifindex =
29650 				    ill1->ill_phyint->phyint_ifindex;
29651 				if (ifindex !=
29652 				    io->ipsec_out_capab_ill_index) {
29653 					xmit_drop = B_TRUE;
29654 					freemsg(mp);
29655 				} else {
29656 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29657 					    pkt_len);
29658 					ipsec_hw_putnext(ire->ire_stq, mp);
29659 				}
29660 			}
29661 next_mp:
29662 			mp = nxt_mp;
29663 		} /* while (mp != NULL) */
29664 		if (xmit_drop)
29665 			return (SEND_FAILED);
29666 		else
29667 			return (SEND_PASSED);
29668 
29669 	case ND_INITIAL:
29670 	case ND_INCOMPLETE:
29671 
29672 		/*
29673 		 * While we do send off packets to dests that
29674 		 * use fully-resolved CGTP routes, we do not
29675 		 * handle unresolved CGTP routes.
29676 		 */
29677 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29678 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29679 
29680 		if (mp != NULL) {
29681 			/* queue the packet */
29682 			nce_queue_mp_common(arpce, mp, B_FALSE);
29683 		}
29684 
29685 		if (arpce->nce_state == ND_INCOMPLETE) {
29686 			mutex_exit(&arpce->nce_lock);
29687 			DTRACE_PROBE3(ip__xmit__incomplete,
29688 			    (ire_t *), ire, (mblk_t *), mp,
29689 			    (ipsec_out_t *), io);
29690 			return (LOOKUP_IN_PROGRESS);
29691 		}
29692 
29693 		arpce->nce_state = ND_INCOMPLETE;
29694 		mutex_exit(&arpce->nce_lock);
29695 		/*
29696 		 * Note that ire_add() (called from ire_forward())
29697 		 * holds a ref on the ire until ARP is completed.
29698 		 */
29699 
29700 		ire_arpresolve(ire, ire_to_ill(ire));
29701 		return (LOOKUP_IN_PROGRESS);
29702 	default:
29703 		ASSERT(0);
29704 		mutex_exit(&arpce->nce_lock);
29705 		return (LLHDR_RESLV_FAILED);
29706 	}
29707 }
29708 
29709 #undef	UPDATE_IP_MIB_OB_COUNTERS
29710 
29711 /*
29712  * Return B_TRUE if the buffers differ in length or content.
29713  * This is used for comparing extension header buffers.
29714  * Note that an extension header would be declared different
29715  * even if all that changed was the next header value in that header i.e.
29716  * what really changed is the next extension header.
29717  */
29718 boolean_t
29719 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29720     uint_t blen)
29721 {
29722 	if (!b_valid)
29723 		blen = 0;
29724 
29725 	if (alen != blen)
29726 		return (B_TRUE);
29727 	if (alen == 0)
29728 		return (B_FALSE);	/* Both zero length */
29729 	return (bcmp(abuf, bbuf, alen));
29730 }
29731 
29732 /*
29733  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29734  * Return B_FALSE if memory allocation fails - don't change any state!
29735  */
29736 boolean_t
29737 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29738     const void *src, uint_t srclen)
29739 {
29740 	void *dst;
29741 
29742 	if (!src_valid)
29743 		srclen = 0;
29744 
29745 	ASSERT(*dstlenp == 0);
29746 	if (src != NULL && srclen != 0) {
29747 		dst = mi_alloc(srclen, BPRI_MED);
29748 		if (dst == NULL)
29749 			return (B_FALSE);
29750 	} else {
29751 		dst = NULL;
29752 	}
29753 	if (*dstp != NULL)
29754 		mi_free(*dstp);
29755 	*dstp = dst;
29756 	*dstlenp = dst == NULL ? 0 : srclen;
29757 	return (B_TRUE);
29758 }
29759 
29760 /*
29761  * Replace what is in *dst, *dstlen with the source.
29762  * Assumes ip_allocbuf has already been called.
29763  */
29764 void
29765 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29766     const void *src, uint_t srclen)
29767 {
29768 	if (!src_valid)
29769 		srclen = 0;
29770 
29771 	ASSERT(*dstlenp == srclen);
29772 	if (src != NULL && srclen != 0)
29773 		bcopy(src, *dstp, srclen);
29774 }
29775 
29776 /*
29777  * Free the storage pointed to by the members of an ip6_pkt_t.
29778  */
29779 void
29780 ip6_pkt_free(ip6_pkt_t *ipp)
29781 {
29782 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29783 
29784 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29785 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29786 		ipp->ipp_hopopts = NULL;
29787 		ipp->ipp_hopoptslen = 0;
29788 	}
29789 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29790 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29791 		ipp->ipp_rtdstopts = NULL;
29792 		ipp->ipp_rtdstoptslen = 0;
29793 	}
29794 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
29795 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
29796 		ipp->ipp_dstopts = NULL;
29797 		ipp->ipp_dstoptslen = 0;
29798 	}
29799 	if (ipp->ipp_fields & IPPF_RTHDR) {
29800 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
29801 		ipp->ipp_rthdr = NULL;
29802 		ipp->ipp_rthdrlen = 0;
29803 	}
29804 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
29805 	    IPPF_RTHDR);
29806 }
29807