xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision ae5b046d8f8cec187d40041c4b74b43f561d5ac7)
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 2008 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 <sys/mac.h>
60 #include <net/if.h>
61 #include <net/if_arp.h>
62 #include <net/route.h>
63 #include <sys/sockio.h>
64 #include <netinet/in.h>
65 #include <net/if_dl.h>
66 
67 #include <inet/common.h>
68 #include <inet/mi.h>
69 #include <inet/mib2.h>
70 #include <inet/nd.h>
71 #include <inet/arp.h>
72 #include <inet/snmpcom.h>
73 #include <inet/optcom.h>
74 #include <inet/kstatcom.h>
75 
76 #include <netinet/igmp_var.h>
77 #include <netinet/ip6.h>
78 #include <netinet/icmp6.h>
79 #include <netinet/sctp.h>
80 
81 #include <inet/ip.h>
82 #include <inet/ip_impl.h>
83 #include <inet/ip6.h>
84 #include <inet/ip6_asp.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <inet/ip_multi.h>
88 #include <inet/ip_if.h>
89 #include <inet/ip_ire.h>
90 #include <inet/ip_ftable.h>
91 #include <inet/ip_rts.h>
92 #include <inet/ip_ndp.h>
93 #include <inet/ip_listutils.h>
94 #include <netinet/igmp.h>
95 #include <netinet/ip_mroute.h>
96 #include <inet/ipp_common.h>
97 
98 #include <net/pfkeyv2.h>
99 #include <inet/ipsec_info.h>
100 #include <inet/sadb.h>
101 #include <inet/ipsec_impl.h>
102 #include <sys/iphada.h>
103 #include <inet/tun.h>
104 #include <inet/ipdrop.h>
105 #include <inet/ip_netinfo.h>
106 
107 #include <sys/ethernet.h>
108 #include <net/if_types.h>
109 #include <sys/cpuvar.h>
110 
111 #include <ipp/ipp.h>
112 #include <ipp/ipp_impl.h>
113 #include <ipp/ipgpc/ipgpc.h>
114 
115 #include <sys/multidata.h>
116 #include <sys/pattr.h>
117 
118 #include <inet/ipclassifier.h>
119 #include <inet/sctp_ip.h>
120 #include <inet/sctp/sctp_impl.h>
121 #include <inet/udp_impl.h>
122 #include <inet/rawip_impl.h>
123 #include <inet/rts_impl.h>
124 #include <sys/sunddi.h>
125 
126 #include <sys/tsol/label.h>
127 #include <sys/tsol/tnet.h>
128 
129 #include <rpc/pmap_prot.h>
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
134  * IP_SQUEUE_ENTER: squeue_enter
135  * IP_SQUEUE_FILL: squeue_fill
136  */
137 int ip_squeue_enter = 2;	/* Setable in /etc/system */
138 
139 squeue_func_t ip_input_proc;
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 /*
143  * Setable in /etc/system
144  */
145 int ip_poll_normal_ms = 100;
146 int ip_poll_normal_ticks = 0;
147 int ip_modclose_ackwait_ms = 3000;
148 
149 /*
150  * It would be nice to have these present only in DEBUG systems, but the
151  * current design of the global symbol checking logic requires them to be
152  * unconditionally present.
153  */
154 uint_t ip_thread_data;			/* TSD key for debug support */
155 krwlock_t ip_thread_rwlock;
156 list_t	ip_thread_list;
157 
158 /*
159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
160  */
161 
162 struct listptr_s {
163 	mblk_t	*lp_head;	/* pointer to the head of the list */
164 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
165 };
166 
167 typedef struct listptr_s listptr_t;
168 
169 /*
170  * This is used by ip_snmp_get_mib2_ip_route_media and
171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
172  */
173 typedef struct iproutedata_s {
174 	uint_t		ird_idx;
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
199     uint8_t *laddrp, uint8_t *faddrp) = NULL;
200 
201 /*
202  * Synchronization notes:
203  *
204  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
205  * MT level protection given by STREAMS. IP uses a combination of its own
206  * internal serialization mechanism and standard Solaris locking techniques.
207  * The internal serialization is per phyint (no IPMP) or per IPMP group.
208  * This is used to serialize plumbing operations, IPMP operations, certain
209  * multicast operations, most set ioctls, igmp/mld timers etc.
210  *
211  * Plumbing is a long sequence of operations involving message
212  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
213  * involved in plumbing operations. A natural model is to serialize these
214  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
215  * parallel without any interference. But various set ioctls on hme0 are best
216  * serialized. However if the system uses IPMP, the operations are easier if
217  * they are serialized on a per IPMP group basis since IPMP operations
218  * happen across ill's of a group. Thus the lowest common denominator is to
219  * serialize most set ioctls, multicast join/leave operations, IPMP operations
220  * igmp/mld timer operations, and processing of DLPI control messages received
221  * from drivers on a per IPMP group basis. If the system does not employ
222  * IPMP the serialization is on a per phyint basis. This serialization is
223  * provided by the ipsq_t and primitives operating on this. Details can
224  * be found in ip_if.c above the core primitives operating on ipsq_t.
225  *
226  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
227  * Simiarly lookup of an ire by a thread also returns a refheld ire.
228  * In addition ipif's and ill's referenced by the ire are also indirectly
229  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
230  * the ipif's address or netmask change as long as an ipif is refheld
231  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
232  * address of an ipif has to go through the ipsq_t. This ensures that only
233  * 1 such exclusive operation proceeds at any time on the ipif. It then
234  * deletes all ires associated with this ipif, and waits for all refcnts
235  * associated with this ipif to come down to zero. The address is changed
236  * only after the ipif has been quiesced. Then the ipif is brought up again.
237  * More details are described above the comment in ip_sioctl_flags.
238  *
239  * Packet processing is based mostly on IREs and are fully multi-threaded
240  * using standard Solaris MT techniques.
241  *
242  * There are explicit locks in IP to handle:
243  * - The ip_g_head list maintained by mi_open_link() and friends.
244  *
245  * - The reassembly data structures (one lock per hash bucket)
246  *
247  * - conn_lock is meant to protect conn_t fields. The fields actually
248  *   protected by conn_lock are documented in the conn_t definition.
249  *
250  * - ire_lock to protect some of the fields of the ire, IRE tables
251  *   (one lock per hash bucket). Refer to ip_ire.c for details.
252  *
253  * - ndp_g_lock and nce_lock for protecting NCEs.
254  *
255  * - ill_lock protects fields of the ill and ipif. Details in ip.h
256  *
257  * - ill_g_lock: This is a global reader/writer lock. Protects the following
258  *	* The AVL tree based global multi list of all ills.
259  *	* The linked list of all ipifs of an ill
260  *	* The <ill-ipsq> mapping
261  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
262  *	* The illgroup list threaded by ill_group_next.
263  *	* <ill-phyint> association
264  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
265  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
266  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
267  *   will all have to hold the ill_g_lock as writer for the actual duration
268  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
269  *   may be found in the IPMP section.
270  *
271  * - ill_lock:  This is a per ill mutex.
272  *   It protects some members of the ill and is documented below.
273  *   It also protects the <ill-ipsq> mapping
274  *   It also protects the illgroup list threaded by ill_group_next.
275  *   It also protects the <ill-phyint> assoc.
276  *   It also protects the list of ipifs hanging off the ill.
277  *
278  * - ipsq_lock: This is a per ipsq_t mutex lock.
279  *   This protects all the other members of the ipsq struct except
280  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
281  *
282  * - illgrp_lock: This is a per ill_group mutex lock.
283  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
284  *   which dictates which is the next ill in an ill_group that is to be chosen
285  *   for sending outgoing packets, through creation of an IRE_CACHE that
286  *   references this ill.
287  *
288  * - phyint_lock: This is a per phyint mutex lock. Protects just the
289  *   phyint_flags
290  *
291  * - ip_g_nd_lock: This is a global reader/writer lock.
292  *   Any call to nd_load to load a new parameter to the ND table must hold the
293  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
294  *   as reader.
295  *
296  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
297  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
298  *   uniqueness check also done atomically.
299  *
300  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
301  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
302  *   as a writer when adding or deleting elements from these lists, and
303  *   as a reader when walking these lists to send a SADB update to the
304  *   IPsec capable ills.
305  *
306  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
307  *   group list linked by ill_usesrc_grp_next. It also protects the
308  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
309  *   group is being added or deleted.  This lock is taken as a reader when
310  *   walking the list/group(eg: to get the number of members in a usesrc group).
311  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
312  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
313  *   example, it is not necessary to take this lock in the initial portion
314  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
315  *   ip_sioctl_flags since the these operations are executed exclusively and
316  *   that ensures that the "usesrc group state" cannot change. The "usesrc
317  *   group state" change can happen only in the latter part of
318  *   ip_sioctl_slifusesrc and in ill_delete.
319  *
320  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
321  *
322  * To change the <ill-phyint> association, the ill_g_lock must be held
323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
324  * must be held.
325  *
326  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
327  * and the ill_lock of the ill in question must be held.
328  *
329  * To change the <ill-illgroup> association the ill_g_lock must be held as
330  * writer and the ill_lock of the ill in question must be held.
331  *
332  * To add or delete an ipif from the list of ipifs hanging off the ill,
333  * ill_g_lock (writer) and ill_lock must be held and the thread must be
334  * a writer on the associated ipsq,.
335  *
336  * To add or delete an ill to the system, the ill_g_lock must be held as
337  * writer and the thread must be a writer on the associated ipsq.
338  *
339  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
340  * must be a writer on the associated ipsq.
341  *
342  * Lock hierarchy
343  *
344  * Some lock hierarchy scenarios are listed below.
345  *
346  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
347  * ill_g_lock -> illgrp_lock -> ill_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  *
354  * When more than 1 ill lock is needed to be held, all ill lock addresses
355  * are sorted on address and locked starting from highest addressed lock
356  * downward.
357  *
358  * IPsec scenarios
359  *
360  * ipsa_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
362  * ipsec_capab_ills_lock -> ipsa_lock
363  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
364  *
365  * Trusted Solaris scenarios
366  *
367  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
368  * igsa_lock -> gcdb_lock
369  * gcgrp_rwlock -> ire_lock
370  * gcgrp_rwlock -> gcdb_lock
371  *
372  *
373  * Routing/forwarding table locking notes:
374  *
375  * Lock acquisition order: Radix tree lock, irb_lock.
376  * Requirements:
377  * i.  Walker must not hold any locks during the walker callback.
378  * ii  Walker must not see a truncated tree during the walk because of any node
379  *     deletion.
380  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
381  *     in many places in the code to walk the irb list. Thus even if all the
382  *     ires in a bucket have been deleted, we still can't free the radix node
383  *     until the ires have actually been inactive'd (freed).
384  *
385  * Tree traversal - Need to hold the global tree lock in read mode.
386  * Before dropping the global tree lock, need to either increment the ire_refcnt
387  * to ensure that the radix node can't be deleted.
388  *
389  * Tree add - Need to hold the global tree lock in write mode to add a
390  * radix node. To prevent the node from being deleted, increment the
391  * irb_refcnt, after the node is added to the tree. The ire itself is
392  * added later while holding the irb_lock, but not the tree lock.
393  *
394  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
395  * All associated ires must be inactive (i.e. freed), and irb_refcnt
396  * must be zero.
397  *
398  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
399  * global tree lock (read mode) for traversal.
400  *
401  * IPsec notes :
402  *
403  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
404  * in front of the actual packet. For outbound datagrams, the M_CTL
405  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
406  * information used by the IPsec code for applying the right level of
407  * protection. The information initialized by IP in the ipsec_out_t
408  * is determined by the per-socket policy or global policy in the system.
409  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
410  * ipsec_info.h) which starts out with nothing in it. It gets filled
411  * with the right information if it goes through the AH/ESP code, which
412  * happens if the incoming packet is secure. The information initialized
413  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
414  * the policy requirements needed by per-socket policy or global policy
415  * is met or not.
416  *
417  * If there is both per-socket policy (set using setsockopt) and there
418  * is also global policy match for the 5 tuples of the socket,
419  * ipsec_override_policy() makes the decision of which one to use.
420  *
421  * For fully connected sockets i.e dst, src [addr, port] is known,
422  * conn_policy_cached is set indicating that policy has been cached.
423  * conn_in_enforce_policy may or may not be set depending on whether
424  * there is a global policy match or per-socket policy match.
425  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
426  * Once the right policy is set on the conn_t, policy cannot change for
427  * this socket. This makes life simpler for TCP (UDP ?) where
428  * re-transmissions go out with the same policy. For symmetry, policy
429  * is cached for fully connected UDP sockets also. Thus if policy is cached,
430  * it also implies that policy is latched i.e policy cannot change
431  * on these sockets. As we have the right policy on the conn, we don't
432  * have to lookup global policy for every outbound and inbound datagram
433  * and thus serving as an optimization. Note that a global policy change
434  * does not affect fully connected sockets if they have policy. If fully
435  * connected sockets did not have any policy associated with it, global
436  * policy change may affect them.
437  *
438  * IP Flow control notes:
439  *
440  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
441  * cannot be sent down to the driver by IP, because of a canput failure, IP
442  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
443  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
444  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
445  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
446  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
447  * the queued messages, and removes the conn from the drain list, if all
448  * messages were drained. It also qenables the next conn in the drain list to
449  * continue the drain process.
450  *
451  * In reality the drain list is not a single list, but a configurable number
452  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
453  * list. If the ip_wsrv of the next qenabled conn does not run, because the
454  * stream closes, ip_close takes responsibility to qenable the next conn in
455  * the drain list. The directly called ip_wput path always does a putq, if
456  * it cannot putnext. Thus synchronization problems are handled between
457  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
458  * functions that manipulate this drain list. Furthermore conn_drain_insert
459  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
460  * running on a queue at any time. conn_drain_tail can be simultaneously called
461  * from both ip_wsrv and ip_close.
462  *
463  * IPQOS notes:
464  *
465  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
466  * and IPQoS modules. IPPF includes hooks in IP at different control points
467  * (callout positions) which direct packets to IPQoS modules for policy
468  * processing. Policies, if present, are global.
469  *
470  * The callout positions are located in the following paths:
471  *		o local_in (packets destined for this host)
472  *		o local_out (packets orginating from this host )
473  *		o fwd_in  (packets forwarded by this m/c - inbound)
474  *		o fwd_out (packets forwarded by this m/c - outbound)
475  * Hooks at these callout points can be enabled/disabled using the ndd variable
476  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
477  * By default all the callout positions are enabled.
478  *
479  * Outbound (local_out)
480  * Hooks are placed in ip_wput_ire and ipsec_out_process.
481  *
482  * Inbound (local_in)
483  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
484  * TCP and UDP fanout routines.
485  *
486  * Forwarding (in and out)
487  * Hooks are placed in ip_rput_forward.
488  *
489  * IP Policy Framework processing (IPPF processing)
490  * Policy processing for a packet is initiated by ip_process, which ascertains
491  * that the classifier (ipgpc) is loaded and configured, failing which the
492  * packet resumes normal processing in IP. If the clasifier is present, the
493  * packet is acted upon by one or more IPQoS modules (action instances), per
494  * filters configured in ipgpc and resumes normal IP processing thereafter.
495  * An action instance can drop a packet in course of its processing.
496  *
497  * A boolean variable, ip_policy, is used in all the fanout routines that can
498  * invoke ip_process for a packet. This variable indicates if the packet should
499  * to be sent for policy processing. The variable is set to B_TRUE by default,
500  * i.e. when the routines are invoked in the normal ip procesing path for a
501  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
502  * ip_policy is set to B_FALSE for all the routines called in these two
503  * functions because, in the former case,  we don't process loopback traffic
504  * currently while in the latter, the packets have already been processed in
505  * icmp_inbound.
506  *
507  * Zones notes:
508  *
509  * The partitioning rules for networking are as follows:
510  * 1) Packets coming from a zone must have a source address belonging to that
511  * zone.
512  * 2) Packets coming from a zone can only be sent on a physical interface on
513  * which the zone has an IP address.
514  * 3) Between two zones on the same machine, packet delivery is only allowed if
515  * there's a matching route for the destination and zone in the forwarding
516  * table.
517  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
518  * different zones can bind to the same port with the wildcard address
519  * (INADDR_ANY).
520  *
521  * The granularity of interface partitioning is at the logical interface level.
522  * Therefore, every zone has its own IP addresses, and incoming packets can be
523  * attributed to a zone unambiguously. A logical interface is placed into a zone
524  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
525  * structure. Rule (1) is implemented by modifying the source address selection
526  * algorithm so that the list of eligible addresses is filtered based on the
527  * sending process zone.
528  *
529  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
530  * across all zones, depending on their type. Here is the break-up:
531  *
532  * IRE type				Shared/exclusive
533  * --------				----------------
534  * IRE_BROADCAST			Exclusive
535  * IRE_DEFAULT (default routes)		Shared (*)
536  * IRE_LOCAL				Exclusive (x)
537  * IRE_LOOPBACK				Exclusive
538  * IRE_PREFIX (net routes)		Shared (*)
539  * IRE_CACHE				Exclusive
540  * IRE_IF_NORESOLVER (interface routes)	Exclusive
541  * IRE_IF_RESOLVER (interface routes)	Exclusive
542  * IRE_HOST (host routes)		Shared (*)
543  *
544  * (*) A zone can only use a default or off-subnet route if the gateway is
545  * directly reachable from the zone, that is, if the gateway's address matches
546  * one of the zone's logical interfaces.
547  *
548  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
549  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
550  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
551  * address of the zone itself (the destination). Since IRE_LOCAL is used
552  * for communication between zones, ip_wput_ire has special logic to set
553  * the right source address when sending using an IRE_LOCAL.
554  *
555  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
556  * ire_cache_lookup restricts loopback using an IRE_LOCAL
557  * between zone to the case when L2 would have conceptually looped the packet
558  * back, i.e. the loopback which is required since neither Ethernet drivers
559  * nor Ethernet hardware loops them back. This is the case when the normal
560  * routes (ignoring IREs with different zoneids) would send out the packet on
561  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
562  * associated.
563  *
564  * Multiple zones can share a common broadcast address; typically all zones
565  * share the 255.255.255.255 address. Incoming as well as locally originated
566  * broadcast packets must be dispatched to all the zones on the broadcast
567  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
568  * since some zones may not be on the 10.16.72/24 network. To handle this, each
569  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
570  * sent to every zone that has an IRE_BROADCAST entry for the destination
571  * address on the input ill, see conn_wantpacket().
572  *
573  * Applications in different zones can join the same multicast group address.
574  * For IPv4, group memberships are per-logical interface, so they're already
575  * inherently part of a zone. For IPv6, group memberships are per-physical
576  * interface, so we distinguish IPv6 group memberships based on group address,
577  * interface and zoneid. In both cases, received multicast packets are sent to
578  * every zone for which a group membership entry exists. On IPv6 we need to
579  * check that the target zone still has an address on the receiving physical
580  * interface; it could have been removed since the application issued the
581  * IPV6_JOIN_GROUP.
582  */
583 
584 /*
585  * Squeue Fanout flags:
586  *	0: No fanout.
587  *	1: Fanout across all squeues
588  */
589 boolean_t	ip_squeue_fanout = 0;
590 
591 /*
592  * Maximum dups allowed per packet.
593  */
594 uint_t ip_max_frag_dups = 10;
595 
596 #define	IS_SIMPLE_IPH(ipha)						\
597 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
598 
599 /* RFC1122 Conformance */
600 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
601 
602 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
603 
604 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
605 
606 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
607 		    cred_t *credp, boolean_t isv6);
608 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
609 
610 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
611 		    ip_stack_t *);
612 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
613 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
614 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
615 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
616 		    mblk_t *, int, ip_stack_t *);
617 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
618 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
619 		    ill_t *, zoneid_t);
620 static void	icmp_options_update(ipha_t *);
621 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
622 		    ip_stack_t *);
623 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
624 		    zoneid_t zoneid, ip_stack_t *);
625 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
626 static void	icmp_redirect(ill_t *, mblk_t *);
627 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
628 		    ip_stack_t *);
629 
630 static void	ip_arp_news(queue_t *, mblk_t *);
631 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
632 		    ip_stack_t *);
633 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
634 char		*ip_dot_addr(ipaddr_t, char *);
635 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
636 int		ip_close(queue_t *, int);
637 static char	*ip_dot_saddr(uchar_t *, char *);
638 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
639 		    boolean_t, boolean_t, ill_t *, zoneid_t);
640 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, zoneid_t);
642 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
643 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
644 static void	ip_lrput(queue_t *, mblk_t *);
645 ipaddr_t	ip_net_mask(ipaddr_t);
646 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
647 		    ip_stack_t *);
648 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
649 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
650 char		*ip_nv_lookup(nv_t *, int);
651 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
652 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
654 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
655     ipndp_t *, size_t);
656 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
657 void	ip_rput(queue_t *, mblk_t *);
658 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
659 		    void *dummy_arg);
660 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
661 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
662     ip_stack_t *);
663 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
664 			    ire_t *, ip_stack_t *);
665 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
666 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
667 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
668     ip_stack_t *);
669 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
670 		    uint16_t *);
671 int		ip_snmp_get(queue_t *, mblk_t *, int);
672 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
673 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
674 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
675 		    ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
682 		    ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
684 		    ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
702 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
703 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
704 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
705 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
706 static boolean_t	ip_source_route_included(ipha_t *);
707 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
708 
709 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
710 		    zoneid_t, ip_stack_t *);
711 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
712 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
713 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
714 		    zoneid_t, ip_stack_t *);
715 
716 static void	conn_drain_init(ip_stack_t *);
717 static void	conn_drain_fini(ip_stack_t *);
718 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
719 
720 static void	conn_walk_drain(ip_stack_t *);
721 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
722     zoneid_t);
723 
724 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
725 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
726 static void	ip_stack_fini(netstackid_t stackid, void *arg);
727 
728 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
729     zoneid_t);
730 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
731     void *dummy_arg);
732 
733 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
734 
735 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
736     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
737     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
738 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
739 
740 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
741 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
742     caddr_t, cred_t *);
743 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
748     caddr_t cp, cred_t *cr);
749 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
750     cred_t *);
751 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
752     cred_t *);
753 static squeue_func_t ip_squeue_switch(int);
754 
755 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
756 static void	ip_kstat_fini(netstackid_t, kstat_t *);
757 static int	ip_kstat_update(kstat_t *kp, int rw);
758 static void	*icmp_kstat_init(netstackid_t);
759 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
760 static int	icmp_kstat_update(kstat_t *kp, int rw);
761 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
762 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
763 
764 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
765 
766 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
767     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
768 
769 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
770     ipha_t *, ill_t *, boolean_t);
771 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
772 
773 /* How long, in seconds, we allow frags to hang around. */
774 #define	IP_FRAG_TIMEOUT	60
775 
776 /*
777  * Threshold which determines whether MDT should be used when
778  * generating IP fragments; payload size must be greater than
779  * this threshold for MDT to take place.
780  */
781 #define	IP_WPUT_FRAG_MDT_MIN	32768
782 
783 /* Setable in /etc/system only */
784 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
785 
786 static long ip_rput_pullups;
787 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
788 
789 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
790 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
791 
792 int	ip_debug;
793 
794 #ifdef DEBUG
795 uint32_t ipsechw_debug = 0;
796 #endif
797 
798 /*
799  * Multirouting/CGTP stuff
800  */
801 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
802 
803 /*
804  * XXX following really should only be in a header. Would need more
805  * header and .c clean up first.
806  */
807 extern optdb_obj_t	ip_opt_obj;
808 
809 ulong_t ip_squeue_enter_unbound = 0;
810 
811 /*
812  * Named Dispatch Parameter Table.
813  * All of these are alterable, within the min/max values given, at run time.
814  */
815 static ipparam_t	lcl_param_arr[] = {
816 	/* min	max	value	name */
817 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
818 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
819 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
820 	{  0,	1,	0,	"ip_respond_to_timestamp"},
821 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
822 	{  0,	1,	1,	"ip_send_redirects"},
823 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
824 	{  0,	10,	0,	"ip_mrtdebug"},
825 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
826 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
827 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
828 	{  1,	255,	255,	"ip_def_ttl" },
829 	{  0,	1,	0,	"ip_forward_src_routed"},
830 	{  0,	256,	32,	"ip_wroff_extra" },
831 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
832 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
833 	{  0,	1,	1,	"ip_path_mtu_discovery" },
834 	{  0,	240,	30,	"ip_ignore_delete_time" },
835 	{  0,	1,	0,	"ip_ignore_redirect" },
836 	{  0,	1,	1,	"ip_output_queue" },
837 	{  1,	254,	1,	"ip_broadcast_ttl" },
838 	{  0,	99999,	100,	"ip_icmp_err_interval" },
839 	{  1,	99999,	10,	"ip_icmp_err_burst" },
840 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
841 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
842 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
843 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
844 	{  0,	1,	1,	"icmp_accept_clear_messages" },
845 	{  0,	1,	1,	"igmp_accept_clear_messages" },
846 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
847 				"ip_ndp_delay_first_probe_time"},
848 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
849 				"ip_ndp_max_unicast_solicit"},
850 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
851 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
852 	{  0,	1,	0,	"ip6_forward_src_routed"},
853 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
854 	{  0,	1,	1,	"ip6_send_redirects"},
855 	{  0,	1,	0,	"ip6_ignore_redirect" },
856 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
857 
858 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
859 
860 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
861 
862 	{  0,	1,	1,	"pim_accept_clear_messages" },
863 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
864 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
865 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
866 	{  0,	15,	0,	"ip_policy_mask" },
867 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
868 	{  0,	255,	1,	"ip_multirt_ttl" },
869 	{  0,	1,	1,	"ip_multidata_outbound" },
870 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
871 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
872 	{  0,	1000,	1,	"ip_max_temp_defend" },
873 	{  0,	1000,	3,	"ip_max_defend" },
874 	{  0,	999999,	30,	"ip_defend_interval" },
875 	{  0,	3600000, 300000, "ip_dup_recovery" },
876 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
877 	{  0,	1,	1,	"ip_lso_outbound" },
878 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
879 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
880 #ifdef DEBUG
881 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
882 #else
883 	{  0,	0,	0,	"" },
884 #endif
885 };
886 
887 /*
888  * Extended NDP table
889  * The addresses for the first two are filled in to be ips_ip_g_forward
890  * and ips_ipv6_forward at init time.
891  */
892 static ipndp_t	lcl_ndp_arr[] = {
893 	/* getf			setf		data			name */
894 #define	IPNDP_IP_FORWARDING_OFFSET	0
895 	{  ip_param_generic_get,	ip_forward_set,	NULL,
896 	    "ip_forwarding" },
897 #define	IPNDP_IP6_FORWARDING_OFFSET	1
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip6_forwarding" },
900 	{  ip_ill_report,	NULL,		NULL,
901 	    "ip_ill_status" },
902 	{  ip_ipif_report,	NULL,		NULL,
903 	    "ip_ipif_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 	{  ip_srcid_report,	NULL,		NULL,
909 	    "ip_srcid_status" },
910 	{ ip_param_generic_get, ip_squeue_profile_set,
911 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
912 	{ ip_param_generic_get, ip_squeue_bind_set,
913 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
914 	{ ip_param_generic_get, ip_input_proc_set,
915 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
916 	{ ip_param_generic_get, ip_int_set,
917 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
918 #define	IPNDP_CGTP_FILTER_OFFSET	11
919 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
920 	    "ip_cgtp_filter" },
921 	{ ip_param_generic_get, ip_int_set,
922 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
923 #define	IPNDP_IPMP_HOOK_OFFSET	13
924 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
925 	    "ipmp_hook_emulation" },
926 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
927 	    "ip_debug" },
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 	/* SIOCSENABLESDP is handled by SDP */
1296 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1297 };
1298 
1299 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1300 
1301 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1302 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1303 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1304 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1305 		TUN_CMD, ip_sioctl_tunparam, NULL },
1306 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1307 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1313 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1314 		MISC_CMD, mrt_ioctl},
1315 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1316 		MISC_CMD, mrt_ioctl},
1317 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1318 		MISC_CMD, mrt_ioctl}
1319 };
1320 
1321 int ip_misc_ioctl_count =
1322     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1323 
1324 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1325 					/* Settable in /etc/system */
1326 /* Defined in ip_ire.c */
1327 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1328 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1329 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1330 
1331 static nv_t	ire_nv_arr[] = {
1332 	{ IRE_BROADCAST, "BROADCAST" },
1333 	{ IRE_LOCAL, "LOCAL" },
1334 	{ IRE_LOOPBACK, "LOOPBACK" },
1335 	{ IRE_CACHE, "CACHE" },
1336 	{ IRE_DEFAULT, "DEFAULT" },
1337 	{ IRE_PREFIX, "PREFIX" },
1338 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1339 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1340 	{ IRE_HOST, "HOST" },
1341 	{ 0 }
1342 };
1343 
1344 nv_t	*ire_nv_tbl = ire_nv_arr;
1345 
1346 /* Simple ICMP IP Header Template */
1347 static ipha_t icmp_ipha = {
1348 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1349 };
1350 
1351 struct module_info ip_mod_info = {
1352 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1353 };
1354 
1355 /*
1356  * Duplicate static symbols within a module confuses mdb; so we avoid the
1357  * problem by making the symbols here distinct from those in udp.c.
1358  */
1359 
1360 /*
1361  * Entry points for IP as a device and as a module.
1362  * FIXME: down the road we might want a separate module and driver qinit.
1363  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1364  */
1365 static struct qinit iprinitv4 = {
1366 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1367 	&ip_mod_info
1368 };
1369 
1370 struct qinit iprinitv6 = {
1371 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1372 	&ip_mod_info
1373 };
1374 
1375 static struct qinit ipwinitv4 = {
1376 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1377 	&ip_mod_info
1378 };
1379 
1380 struct qinit ipwinitv6 = {
1381 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1382 	&ip_mod_info
1383 };
1384 
1385 static struct qinit iplrinit = {
1386 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1387 	&ip_mod_info
1388 };
1389 
1390 static struct qinit iplwinit = {
1391 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1392 	&ip_mod_info
1393 };
1394 
1395 /* For AF_INET aka /dev/ip */
1396 struct streamtab ipinfov4 = {
1397 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1398 };
1399 
1400 /* For AF_INET6 aka /dev/ip6 */
1401 struct streamtab ipinfov6 = {
1402 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1403 };
1404 
1405 #ifdef	DEBUG
1406 static boolean_t skip_sctp_cksum = B_FALSE;
1407 #endif
1408 
1409 /*
1410  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1411  * ip_rput_v6(), ip_output(), etc.  If the message
1412  * block already has a M_CTL at the front of it, then simply set the zoneid
1413  * appropriately.
1414  */
1415 mblk_t *
1416 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1417 {
1418 	mblk_t		*first_mp;
1419 	ipsec_out_t	*io;
1420 
1421 	ASSERT(zoneid != ALL_ZONES);
1422 	if (mp->b_datap->db_type == M_CTL) {
1423 		io = (ipsec_out_t *)mp->b_rptr;
1424 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1425 		io->ipsec_out_zoneid = zoneid;
1426 		return (mp);
1427 	}
1428 
1429 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1430 	if (first_mp == NULL)
1431 		return (NULL);
1432 	io = (ipsec_out_t *)first_mp->b_rptr;
1433 	/* This is not a secure packet */
1434 	io->ipsec_out_secure = B_FALSE;
1435 	io->ipsec_out_zoneid = zoneid;
1436 	first_mp->b_cont = mp;
1437 	return (first_mp);
1438 }
1439 
1440 /*
1441  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1442  */
1443 mblk_t *
1444 ip_copymsg(mblk_t *mp)
1445 {
1446 	mblk_t *nmp;
1447 	ipsec_info_t *in;
1448 
1449 	if (mp->b_datap->db_type != M_CTL)
1450 		return (copymsg(mp));
1451 
1452 	in = (ipsec_info_t *)mp->b_rptr;
1453 
1454 	/*
1455 	 * Note that M_CTL is also used for delivering ICMP error messages
1456 	 * upstream to transport layers.
1457 	 */
1458 	if (in->ipsec_info_type != IPSEC_OUT &&
1459 	    in->ipsec_info_type != IPSEC_IN)
1460 		return (copymsg(mp));
1461 
1462 	nmp = copymsg(mp->b_cont);
1463 
1464 	if (in->ipsec_info_type == IPSEC_OUT) {
1465 		return (ipsec_out_tag(mp, nmp,
1466 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1467 	} else {
1468 		return (ipsec_in_tag(mp, nmp,
1469 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1470 	}
1471 }
1472 
1473 /* Generate an ICMP fragmentation needed message. */
1474 static void
1475 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1476     ip_stack_t *ipst)
1477 {
1478 	icmph_t	icmph;
1479 	mblk_t *first_mp;
1480 	boolean_t mctl_present;
1481 
1482 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1483 
1484 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1485 		if (mctl_present)
1486 			freeb(first_mp);
1487 		return;
1488 	}
1489 
1490 	bzero(&icmph, sizeof (icmph_t));
1491 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1492 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1493 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1494 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1495 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1496 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1497 	    ipst);
1498 }
1499 
1500 /*
1501  * icmp_inbound deals with ICMP messages in the following ways.
1502  *
1503  * 1) It needs to send a reply back and possibly delivering it
1504  *    to the "interested" upper clients.
1505  * 2) It needs to send it to the upper clients only.
1506  * 3) It needs to change some values in IP only.
1507  * 4) It needs to change some values in IP and upper layers e.g TCP.
1508  *
1509  * We need to accomodate icmp messages coming in clear until we get
1510  * everything secure from the wire. If icmp_accept_clear_messages
1511  * is zero we check with the global policy and act accordingly. If
1512  * it is non-zero, we accept the message without any checks. But
1513  * *this does not mean* that this will be delivered to the upper
1514  * clients. By accepting we might send replies back, change our MTU
1515  * value etc. but delivery to the ULP/clients depends on their policy
1516  * dispositions.
1517  *
1518  * We handle the above 4 cases in the context of IPsec in the
1519  * following way :
1520  *
1521  * 1) Send the reply back in the same way as the request came in.
1522  *    If it came in encrypted, it goes out encrypted. If it came in
1523  *    clear, it goes out in clear. Thus, this will prevent chosen
1524  *    plain text attack.
1525  * 2) The client may or may not expect things to come in secure.
1526  *    If it comes in secure, the policy constraints are checked
1527  *    before delivering it to the upper layers. If it comes in
1528  *    clear, ipsec_inbound_accept_clear will decide whether to
1529  *    accept this in clear or not. In both the cases, if the returned
1530  *    message (IP header + 8 bytes) that caused the icmp message has
1531  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1532  *    sending up. If there are only 8 bytes of returned message, then
1533  *    upper client will not be notified.
1534  * 3) Check with global policy to see whether it matches the constaints.
1535  *    But this will be done only if icmp_accept_messages_in_clear is
1536  *    zero.
1537  * 4) If we need to change both in IP and ULP, then the decision taken
1538  *    while affecting the values in IP and while delivering up to TCP
1539  *    should be the same.
1540  *
1541  * 	There are two cases.
1542  *
1543  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1544  *	   failed), we will not deliver it to the ULP, even though they
1545  *	   are *willing* to accept in *clear*. This is fine as our global
1546  *	   disposition to icmp messages asks us reject the datagram.
1547  *
1548  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1549  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1550  *	   to deliver it to ULP (policy failed), it can lead to
1551  *	   consistency problems. The cases known at this time are
1552  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1553  *	   values :
1554  *
1555  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1556  *	     and Upper layer rejects. Then the communication will
1557  *	     come to a stop. This is solved by making similar decisions
1558  *	     at both levels. Currently, when we are unable to deliver
1559  *	     to the Upper Layer (due to policy failures) while IP has
1560  *	     adjusted ire_max_frag, the next outbound datagram would
1561  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1562  *	     will be with the right level of protection. Thus the right
1563  *	     value will be communicated even if we are not able to
1564  *	     communicate when we get from the wire initially. But this
1565  *	     assumes there would be at least one outbound datagram after
1566  *	     IP has adjusted its ire_max_frag value. To make things
1567  *	     simpler, we accept in clear after the validation of
1568  *	     AH/ESP headers.
1569  *
1570  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1571  *	     upper layer depending on the level of protection the upper
1572  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1573  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1574  *	     should be accepted in clear when the Upper layer expects secure.
1575  *	     Thus the communication may get aborted by some bad ICMP
1576  *	     packets.
1577  *
1578  * IPQoS Notes:
1579  * The only instance when a packet is sent for processing is when there
1580  * isn't an ICMP client and if we are interested in it.
1581  * If there is a client, IPPF processing will take place in the
1582  * ip_fanout_proto routine.
1583  *
1584  * Zones notes:
1585  * The packet is only processed in the context of the specified zone: typically
1586  * only this zone will reply to an echo request, and only interested clients in
1587  * this zone will receive a copy of the packet. This means that the caller must
1588  * call icmp_inbound() for each relevant zone.
1589  */
1590 static void
1591 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1592     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1593     ill_t *recv_ill, zoneid_t zoneid)
1594 {
1595 	icmph_t	*icmph;
1596 	ipha_t	*ipha;
1597 	int	iph_hdr_length;
1598 	int	hdr_length;
1599 	boolean_t	interested;
1600 	uint32_t	ts;
1601 	uchar_t	*wptr;
1602 	ipif_t	*ipif;
1603 	mblk_t *first_mp;
1604 	ipsec_in_t *ii;
1605 	ire_t *src_ire;
1606 	boolean_t onlink;
1607 	timestruc_t now;
1608 	uint32_t ill_index;
1609 	ip_stack_t *ipst;
1610 
1611 	ASSERT(ill != NULL);
1612 	ipst = ill->ill_ipst;
1613 
1614 	first_mp = mp;
1615 	if (mctl_present) {
1616 		mp = first_mp->b_cont;
1617 		ASSERT(mp != NULL);
1618 	}
1619 
1620 	ipha = (ipha_t *)mp->b_rptr;
1621 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1622 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1623 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1624 		if (first_mp == NULL)
1625 			return;
1626 	}
1627 
1628 	/*
1629 	 * On a labeled system, we have to check whether the zone itself is
1630 	 * permitted to receive raw traffic.
1631 	 */
1632 	if (is_system_labeled()) {
1633 		if (zoneid == ALL_ZONES)
1634 			zoneid = tsol_packet_to_zoneid(mp);
1635 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1636 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1637 			    zoneid));
1638 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1639 			freemsg(first_mp);
1640 			return;
1641 		}
1642 	}
1643 
1644 	/*
1645 	 * We have accepted the ICMP message. It means that we will
1646 	 * respond to the packet if needed. It may not be delivered
1647 	 * to the upper client depending on the policy constraints
1648 	 * and the disposition in ipsec_inbound_accept_clear.
1649 	 */
1650 
1651 	ASSERT(ill != NULL);
1652 
1653 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1654 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1655 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1656 		/* Last chance to get real. */
1657 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1658 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1659 			freemsg(first_mp);
1660 			return;
1661 		}
1662 		/* Refresh iph following the pullup. */
1663 		ipha = (ipha_t *)mp->b_rptr;
1664 	}
1665 	/* ICMP header checksum, including checksum field, should be zero. */
1666 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1667 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1668 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1669 		freemsg(first_mp);
1670 		return;
1671 	}
1672 	/* The IP header will always be a multiple of four bytes */
1673 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1674 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1675 	    icmph->icmph_code));
1676 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1677 	/* We will set "interested" to "true" if we want a copy */
1678 	interested = B_FALSE;
1679 	switch (icmph->icmph_type) {
1680 	case ICMP_ECHO_REPLY:
1681 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1682 		break;
1683 	case ICMP_DEST_UNREACHABLE:
1684 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1685 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1686 		interested = B_TRUE;	/* Pass up to transport */
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1688 		break;
1689 	case ICMP_SOURCE_QUENCH:
1690 		interested = B_TRUE;	/* Pass up to transport */
1691 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1692 		break;
1693 	case ICMP_REDIRECT:
1694 		if (!ipst->ips_ip_ignore_redirect)
1695 			interested = B_TRUE;
1696 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1697 		break;
1698 	case ICMP_ECHO_REQUEST:
1699 		/*
1700 		 * Whether to respond to echo requests that come in as IP
1701 		 * broadcasts or as IP multicast is subject to debate
1702 		 * (what isn't?).  We aim to please, you pick it.
1703 		 * Default is do it.
1704 		 */
1705 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1706 			/* unicast: always respond */
1707 			interested = B_TRUE;
1708 		} else if (CLASSD(ipha->ipha_dst)) {
1709 			/* multicast: respond based on tunable */
1710 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1711 		} else if (broadcast) {
1712 			/* broadcast: respond based on tunable */
1713 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1714 		}
1715 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1716 		break;
1717 	case ICMP_ROUTER_ADVERTISEMENT:
1718 	case ICMP_ROUTER_SOLICITATION:
1719 		break;
1720 	case ICMP_TIME_EXCEEDED:
1721 		interested = B_TRUE;	/* Pass up to transport */
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1723 		break;
1724 	case ICMP_PARAM_PROBLEM:
1725 		interested = B_TRUE;	/* Pass up to transport */
1726 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1727 		break;
1728 	case ICMP_TIME_STAMP_REQUEST:
1729 		/* Response to Time Stamp Requests is local policy. */
1730 		if (ipst->ips_ip_g_resp_to_timestamp &&
1731 		    /* So is whether to respond if it was an IP broadcast. */
1732 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1733 			int tstamp_len = 3 * sizeof (uint32_t);
1734 
1735 			if (wptr +  tstamp_len > mp->b_wptr) {
1736 				if (!pullupmsg(mp, wptr + tstamp_len -
1737 				    mp->b_rptr)) {
1738 					BUMP_MIB(ill->ill_ip_mib,
1739 					    ipIfStatsInDiscards);
1740 					freemsg(first_mp);
1741 					return;
1742 				}
1743 				/* Refresh ipha following the pullup. */
1744 				ipha = (ipha_t *)mp->b_rptr;
1745 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1746 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1747 			}
1748 			interested = B_TRUE;
1749 		}
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1751 		break;
1752 	case ICMP_TIME_STAMP_REPLY:
1753 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1754 		break;
1755 	case ICMP_INFO_REQUEST:
1756 		/* Per RFC 1122 3.2.2.7, ignore this. */
1757 	case ICMP_INFO_REPLY:
1758 		break;
1759 	case ICMP_ADDRESS_MASK_REQUEST:
1760 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1761 		    !broadcast) &&
1762 		    /* TODO m_pullup of complete header? */
1763 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1764 			interested = B_TRUE;
1765 		}
1766 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1767 		break;
1768 	case ICMP_ADDRESS_MASK_REPLY:
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1770 		break;
1771 	default:
1772 		interested = B_TRUE;	/* Pass up to transport */
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1774 		break;
1775 	}
1776 	/* See if there is an ICMP client. */
1777 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1778 		/* If there is an ICMP client and we want one too, copy it. */
1779 		mblk_t *first_mp1;
1780 
1781 		if (!interested) {
1782 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1783 			    ip_policy, recv_ill, zoneid);
1784 			return;
1785 		}
1786 		first_mp1 = ip_copymsg(first_mp);
1787 		if (first_mp1 != NULL) {
1788 			ip_fanout_proto(q, first_mp1, ill, ipha,
1789 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1790 		}
1791 	} else if (!interested) {
1792 		freemsg(first_mp);
1793 		return;
1794 	} else {
1795 		/*
1796 		 * Initiate policy processing for this packet if ip_policy
1797 		 * is true.
1798 		 */
1799 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1800 			ill_index = ill->ill_phyint->phyint_ifindex;
1801 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1802 			if (mp == NULL) {
1803 				if (mctl_present) {
1804 					freeb(first_mp);
1805 				}
1806 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1807 				return;
1808 			}
1809 		}
1810 	}
1811 	/* We want to do something with it. */
1812 	/* Check db_ref to make sure we can modify the packet. */
1813 	if (mp->b_datap->db_ref > 1) {
1814 		mblk_t	*first_mp1;
1815 
1816 		first_mp1 = ip_copymsg(first_mp);
1817 		freemsg(first_mp);
1818 		if (!first_mp1) {
1819 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1820 			return;
1821 		}
1822 		first_mp = first_mp1;
1823 		if (mctl_present) {
1824 			mp = first_mp->b_cont;
1825 			ASSERT(mp != NULL);
1826 		} else {
1827 			mp = first_mp;
1828 		}
1829 		ipha = (ipha_t *)mp->b_rptr;
1830 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1831 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1832 	}
1833 	switch (icmph->icmph_type) {
1834 	case ICMP_ADDRESS_MASK_REQUEST:
1835 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1836 		if (ipif == NULL) {
1837 			freemsg(first_mp);
1838 			return;
1839 		}
1840 		/*
1841 		 * outging interface must be IPv4
1842 		 */
1843 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1844 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1845 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1846 		ipif_refrele(ipif);
1847 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1848 		break;
1849 	case ICMP_ECHO_REQUEST:
1850 		icmph->icmph_type = ICMP_ECHO_REPLY;
1851 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1852 		break;
1853 	case ICMP_TIME_STAMP_REQUEST: {
1854 		uint32_t *tsp;
1855 
1856 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1857 		tsp = (uint32_t *)wptr;
1858 		tsp++;		/* Skip past 'originate time' */
1859 		/* Compute # of milliseconds since midnight */
1860 		gethrestime(&now);
1861 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1862 		    now.tv_nsec / (NANOSEC / MILLISEC);
1863 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1864 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1865 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1866 		break;
1867 	}
1868 	default:
1869 		ipha = (ipha_t *)&icmph[1];
1870 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1871 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1872 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1873 				freemsg(first_mp);
1874 				return;
1875 			}
1876 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1877 			ipha = (ipha_t *)&icmph[1];
1878 		}
1879 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1880 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1881 			freemsg(first_mp);
1882 			return;
1883 		}
1884 		hdr_length = IPH_HDR_LENGTH(ipha);
1885 		if (hdr_length < sizeof (ipha_t)) {
1886 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1887 			freemsg(first_mp);
1888 			return;
1889 		}
1890 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1891 			if (!pullupmsg(mp,
1892 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1893 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1894 				freemsg(first_mp);
1895 				return;
1896 			}
1897 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 			ipha = (ipha_t *)&icmph[1];
1899 		}
1900 		switch (icmph->icmph_type) {
1901 		case ICMP_REDIRECT:
1902 			/*
1903 			 * As there is no upper client to deliver, we don't
1904 			 * need the first_mp any more.
1905 			 */
1906 			if (mctl_present) {
1907 				freeb(first_mp);
1908 			}
1909 			icmp_redirect(ill, mp);
1910 			return;
1911 		case ICMP_DEST_UNREACHABLE:
1912 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1913 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1914 				    zoneid, mp, iph_hdr_length, ipst)) {
1915 					freemsg(first_mp);
1916 					return;
1917 				}
1918 				/*
1919 				 * icmp_inbound_too_big() may alter mp.
1920 				 * Resynch ipha and icmph accordingly.
1921 				 */
1922 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1923 				ipha = (ipha_t *)&icmph[1];
1924 			}
1925 			/* FALLTHRU */
1926 		default :
1927 			/*
1928 			 * IPQoS notes: Since we have already done IPQoS
1929 			 * processing we don't want to do it again in
1930 			 * the fanout routines called by
1931 			 * icmp_inbound_error_fanout, hence the last
1932 			 * argument, ip_policy, is B_FALSE.
1933 			 */
1934 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1935 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1936 			    B_FALSE, recv_ill, zoneid);
1937 		}
1938 		return;
1939 	}
1940 	/* Send out an ICMP packet */
1941 	icmph->icmph_checksum = 0;
1942 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1943 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1944 		ipif_t	*ipif_chosen;
1945 		/*
1946 		 * Make it look like it was directed to us, so we don't look
1947 		 * like a fool with a broadcast or multicast source address.
1948 		 */
1949 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1950 		/*
1951 		 * Make sure that we haven't grabbed an interface that's DOWN.
1952 		 */
1953 		if (ipif != NULL) {
1954 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1955 			    ipha->ipha_src, zoneid);
1956 			if (ipif_chosen != NULL) {
1957 				ipif_refrele(ipif);
1958 				ipif = ipif_chosen;
1959 			}
1960 		}
1961 		if (ipif == NULL) {
1962 			ip0dbg(("icmp_inbound: "
1963 			    "No source for broadcast/multicast:\n"
1964 			    "\tsrc 0x%x dst 0x%x ill %p "
1965 			    "ipif_lcl_addr 0x%x\n",
1966 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1967 			    (void *)ill,
1968 			    ill->ill_ipif->ipif_lcl_addr));
1969 			freemsg(first_mp);
1970 			return;
1971 		}
1972 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1973 		ipha->ipha_dst = ipif->ipif_src_addr;
1974 		ipif_refrele(ipif);
1975 	}
1976 	/* Reset time to live. */
1977 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1978 	{
1979 		/* Swap source and destination addresses */
1980 		ipaddr_t tmp;
1981 
1982 		tmp = ipha->ipha_src;
1983 		ipha->ipha_src = ipha->ipha_dst;
1984 		ipha->ipha_dst = tmp;
1985 	}
1986 	ipha->ipha_ident = 0;
1987 	if (!IS_SIMPLE_IPH(ipha))
1988 		icmp_options_update(ipha);
1989 
1990 	/*
1991 	 * ICMP echo replies should go out on the same interface
1992 	 * the request came on as probes used by in.mpathd for detecting
1993 	 * NIC failures are ECHO packets. We turn-off load spreading
1994 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1995 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1996 	 * function. This is in turn handled by ip_wput and ip_newroute
1997 	 * to make sure that the packet goes out on the interface it came
1998 	 * in on. If we don't turnoff load spreading, the packets might get
1999 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2000 	 * to go out and in.mpathd would wrongly detect a failure or
2001 	 * mis-detect a NIC failure for link failure. As load spreading
2002 	 * can happen only if ill_group is not NULL, we do only for
2003 	 * that case and this does not affect the normal case.
2004 	 *
2005 	 * We turn off load spreading only on echo packets that came from
2006 	 * on-link hosts. If the interface route has been deleted, this will
2007 	 * not be enforced as we can't do much. For off-link hosts, as the
2008 	 * default routes in IPv4 does not typically have an ire_ipif
2009 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2010 	 * Moreover, expecting a default route through this interface may
2011 	 * not be correct. We use ipha_dst because of the swap above.
2012 	 */
2013 	onlink = B_FALSE;
2014 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2015 		/*
2016 		 * First, we need to make sure that it is not one of our
2017 		 * local addresses. If we set onlink when it is one of
2018 		 * our local addresses, we will end up creating IRE_CACHES
2019 		 * for one of our local addresses. Then, we will never
2020 		 * accept packets for them afterwards.
2021 		 */
2022 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2023 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2024 		if (src_ire == NULL) {
2025 			ipif = ipif_get_next_ipif(NULL, ill);
2026 			if (ipif == NULL) {
2027 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2028 				freemsg(mp);
2029 				return;
2030 			}
2031 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2032 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2033 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2034 			ipif_refrele(ipif);
2035 			if (src_ire != NULL) {
2036 				onlink = B_TRUE;
2037 				ire_refrele(src_ire);
2038 			}
2039 		} else {
2040 			ire_refrele(src_ire);
2041 		}
2042 	}
2043 	if (!mctl_present) {
2044 		/*
2045 		 * This packet should go out the same way as it
2046 		 * came in i.e in clear. To make sure that global
2047 		 * policy will not be applied to this in ip_wput_ire,
2048 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2049 		 */
2050 		ASSERT(first_mp == mp);
2051 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2052 		if (first_mp == NULL) {
2053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2054 			freemsg(mp);
2055 			return;
2056 		}
2057 		ii = (ipsec_in_t *)first_mp->b_rptr;
2058 
2059 		/* This is not a secure packet */
2060 		ii->ipsec_in_secure = B_FALSE;
2061 		if (onlink) {
2062 			ii->ipsec_in_attach_if = B_TRUE;
2063 			ii->ipsec_in_ill_index =
2064 			    ill->ill_phyint->phyint_ifindex;
2065 			ii->ipsec_in_rill_index =
2066 			    recv_ill->ill_phyint->phyint_ifindex;
2067 		}
2068 		first_mp->b_cont = mp;
2069 	} else if (onlink) {
2070 		ii = (ipsec_in_t *)first_mp->b_rptr;
2071 		ii->ipsec_in_attach_if = B_TRUE;
2072 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2073 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2074 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2075 	} else {
2076 		ii = (ipsec_in_t *)first_mp->b_rptr;
2077 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2078 	}
2079 	ii->ipsec_in_zoneid = zoneid;
2080 	ASSERT(zoneid != ALL_ZONES);
2081 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2082 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2083 		return;
2084 	}
2085 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2086 	put(WR(q), first_mp);
2087 }
2088 
2089 static ipaddr_t
2090 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2091 {
2092 	conn_t *connp;
2093 	connf_t *connfp;
2094 	ipaddr_t nexthop_addr = INADDR_ANY;
2095 	int hdr_length = IPH_HDR_LENGTH(ipha);
2096 	uint16_t *up;
2097 	uint32_t ports;
2098 	ip_stack_t *ipst = ill->ill_ipst;
2099 
2100 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2101 	switch (ipha->ipha_protocol) {
2102 		case IPPROTO_TCP:
2103 		{
2104 			tcph_t *tcph;
2105 
2106 			/* do a reverse lookup */
2107 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2108 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2109 			    TCPS_LISTEN, ipst);
2110 			break;
2111 		}
2112 		case IPPROTO_UDP:
2113 		{
2114 			uint32_t dstport, srcport;
2115 
2116 			((uint16_t *)&ports)[0] = up[1];
2117 			((uint16_t *)&ports)[1] = up[0];
2118 
2119 			/* Extract ports in net byte order */
2120 			dstport = htons(ntohl(ports) & 0xFFFF);
2121 			srcport = htons(ntohl(ports) >> 16);
2122 
2123 			connfp = &ipst->ips_ipcl_udp_fanout[
2124 			    IPCL_UDP_HASH(dstport, ipst)];
2125 			mutex_enter(&connfp->connf_lock);
2126 			connp = connfp->connf_head;
2127 
2128 			/* do a reverse lookup */
2129 			while ((connp != NULL) &&
2130 			    (!IPCL_UDP_MATCH(connp, dstport,
2131 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2132 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2133 				connp = connp->conn_next;
2134 			}
2135 			if (connp != NULL)
2136 				CONN_INC_REF(connp);
2137 			mutex_exit(&connfp->connf_lock);
2138 			break;
2139 		}
2140 		case IPPROTO_SCTP:
2141 		{
2142 			in6_addr_t map_src, map_dst;
2143 
2144 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2146 			((uint16_t *)&ports)[0] = up[1];
2147 			((uint16_t *)&ports)[1] = up[0];
2148 
2149 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2150 			    zoneid, ipst->ips_netstack->netstack_sctp);
2151 			if (connp == NULL) {
2152 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2153 				    zoneid, ports, ipha, ipst);
2154 			} else {
2155 				CONN_INC_REF(connp);
2156 				SCTP_REFRELE(CONN2SCTP(connp));
2157 			}
2158 			break;
2159 		}
2160 		default:
2161 		{
2162 			ipha_t ripha;
2163 
2164 			ripha.ipha_src = ipha->ipha_dst;
2165 			ripha.ipha_dst = ipha->ipha_src;
2166 			ripha.ipha_protocol = ipha->ipha_protocol;
2167 
2168 			connfp = &ipst->ips_ipcl_proto_fanout[
2169 			    ipha->ipha_protocol];
2170 			mutex_enter(&connfp->connf_lock);
2171 			connp = connfp->connf_head;
2172 			for (connp = connfp->connf_head; connp != NULL;
2173 			    connp = connp->conn_next) {
2174 				if (IPCL_PROTO_MATCH(connp,
2175 				    ipha->ipha_protocol, &ripha, ill,
2176 				    0, zoneid)) {
2177 					CONN_INC_REF(connp);
2178 					break;
2179 				}
2180 			}
2181 			mutex_exit(&connfp->connf_lock);
2182 		}
2183 	}
2184 	if (connp != NULL) {
2185 		if (connp->conn_nexthop_set)
2186 			nexthop_addr = connp->conn_nexthop_v4;
2187 		CONN_DEC_REF(connp);
2188 	}
2189 	return (nexthop_addr);
2190 }
2191 
2192 /* Table from RFC 1191 */
2193 static int icmp_frag_size_table[] =
2194 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2195 
2196 /*
2197  * Process received ICMP Packet too big.
2198  * After updating any IRE it does the fanout to any matching transport streams.
2199  * Assumes the message has been pulled up till the IP header that caused
2200  * the error.
2201  *
2202  * Returns B_FALSE on failure and B_TRUE on success.
2203  */
2204 static boolean_t
2205 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2206     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2207     ip_stack_t *ipst)
2208 {
2209 	ire_t	*ire, *first_ire;
2210 	int	mtu;
2211 	int	hdr_length;
2212 	ipaddr_t nexthop_addr;
2213 
2214 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2215 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2216 	ASSERT(ill != NULL);
2217 
2218 	hdr_length = IPH_HDR_LENGTH(ipha);
2219 
2220 	/* Drop if the original packet contained a source route */
2221 	if (ip_source_route_included(ipha)) {
2222 		return (B_FALSE);
2223 	}
2224 	/*
2225 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2226 	 * header.
2227 	 */
2228 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2229 	    mp->b_wptr) {
2230 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2231 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2232 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2233 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2234 			return (B_FALSE);
2235 		}
2236 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2237 		ipha = (ipha_t *)&icmph[1];
2238 	}
2239 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2240 	if (nexthop_addr != INADDR_ANY) {
2241 		/* nexthop set */
2242 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2243 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2244 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2245 	} else {
2246 		/* nexthop not set */
2247 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2248 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2249 	}
2250 
2251 	if (!first_ire) {
2252 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2253 		    ntohl(ipha->ipha_dst)));
2254 		return (B_FALSE);
2255 	}
2256 	/* Check for MTU discovery advice as described in RFC 1191 */
2257 	mtu = ntohs(icmph->icmph_du_mtu);
2258 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2259 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2260 	    ire = ire->ire_next) {
2261 		/*
2262 		 * Look for the connection to which this ICMP message is
2263 		 * directed. If it has the IP_NEXTHOP option set, then the
2264 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2265 		 * option. Else the search is limited to regular IREs.
2266 		 */
2267 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2268 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2269 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2270 		    (nexthop_addr != INADDR_ANY)))
2271 			continue;
2272 
2273 		mutex_enter(&ire->ire_lock);
2274 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2275 			/* Reduce the IRE max frag value as advised. */
2276 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2277 			    mtu, ire->ire_max_frag));
2278 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2279 		} else {
2280 			uint32_t length;
2281 			int	i;
2282 
2283 			/*
2284 			 * Use the table from RFC 1191 to figure out
2285 			 * the next "plateau" based on the length in
2286 			 * the original IP packet.
2287 			 */
2288 			length = ntohs(ipha->ipha_length);
2289 			if (ire->ire_max_frag <= length &&
2290 			    ire->ire_max_frag >= length - hdr_length) {
2291 				/*
2292 				 * Handle broken BSD 4.2 systems that
2293 				 * return the wrong iph_length in ICMP
2294 				 * errors.
2295 				 */
2296 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2297 				    length, ire->ire_max_frag));
2298 				length -= hdr_length;
2299 			}
2300 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2301 				if (length > icmp_frag_size_table[i])
2302 					break;
2303 			}
2304 			if (i == A_CNT(icmp_frag_size_table)) {
2305 				/* Smaller than 68! */
2306 				ip1dbg(("Too big for packet size %d\n",
2307 				    length));
2308 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2309 				ire->ire_frag_flag = 0;
2310 			} else {
2311 				mtu = icmp_frag_size_table[i];
2312 				ip1dbg(("Calculated mtu %d, packet size %d, "
2313 				    "before %d", mtu, length,
2314 				    ire->ire_max_frag));
2315 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2316 				ip1dbg((", after %d\n", ire->ire_max_frag));
2317 			}
2318 			/* Record the new max frag size for the ULP. */
2319 			icmph->icmph_du_zero = 0;
2320 			icmph->icmph_du_mtu =
2321 			    htons((uint16_t)ire->ire_max_frag);
2322 		}
2323 		mutex_exit(&ire->ire_lock);
2324 	}
2325 	rw_exit(&first_ire->ire_bucket->irb_lock);
2326 	ire_refrele(first_ire);
2327 	return (B_TRUE);
2328 }
2329 
2330 /*
2331  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2332  * calls this function.
2333  */
2334 static mblk_t *
2335 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2336 {
2337 	ipha_t *ipha;
2338 	icmph_t *icmph;
2339 	ipha_t *in_ipha;
2340 	int length;
2341 
2342 	ASSERT(mp->b_datap->db_type == M_DATA);
2343 
2344 	/*
2345 	 * For Self-encapsulated packets, we added an extra IP header
2346 	 * without the options. Inner IP header is the one from which
2347 	 * the outer IP header was formed. Thus, we need to remove the
2348 	 * outer IP header. To do this, we pullup the whole message
2349 	 * and overlay whatever follows the outer IP header over the
2350 	 * outer IP header.
2351 	 */
2352 
2353 	if (!pullupmsg(mp, -1))
2354 		return (NULL);
2355 
2356 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2357 	ipha = (ipha_t *)&icmph[1];
2358 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2359 
2360 	/*
2361 	 * The length that we want to overlay is following the inner
2362 	 * IP header. Subtracting the IP header + icmp header + outer
2363 	 * IP header's length should give us the length that we want to
2364 	 * overlay.
2365 	 */
2366 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2367 	    hdr_length;
2368 	/*
2369 	 * Overlay whatever follows the inner header over the
2370 	 * outer header.
2371 	 */
2372 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2373 
2374 	/* Set the wptr to account for the outer header */
2375 	mp->b_wptr -= hdr_length;
2376 	return (mp);
2377 }
2378 
2379 /*
2380  * Try to pass the ICMP message upstream in case the ULP cares.
2381  *
2382  * If the packet that caused the ICMP error is secure, we send
2383  * it to AH/ESP to make sure that the attached packet has a
2384  * valid association. ipha in the code below points to the
2385  * IP header of the packet that caused the error.
2386  *
2387  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2388  * in the context of IPsec. Normally we tell the upper layer
2389  * whenever we send the ire (including ip_bind), the IPsec header
2390  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2391  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2392  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2393  * same thing. As TCP has the IPsec options size that needs to be
2394  * adjusted, we just pass the MTU unchanged.
2395  *
2396  * IFN could have been generated locally or by some router.
2397  *
2398  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2399  *	    This happens because IP adjusted its value of MTU on an
2400  *	    earlier IFN message and could not tell the upper layer,
2401  *	    the new adjusted value of MTU e.g. Packet was encrypted
2402  *	    or there was not enough information to fanout to upper
2403  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2404  *	    generates the IFN, where IPsec processing has *not* been
2405  *	    done.
2406  *
2407  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2408  *	    could have generated this. This happens because ire_max_frag
2409  *	    value in IP was set to a new value, while the IPsec processing
2410  *	    was being done and after we made the fragmentation check in
2411  *	    ip_wput_ire. Thus on return from IPsec processing,
2412  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2413  *	    and generates the IFN. As IPsec processing is over, we fanout
2414  *	    to AH/ESP to remove the header.
2415  *
2416  *	    In both these cases, ipsec_in_loopback will be set indicating
2417  *	    that IFN was generated locally.
2418  *
2419  * ROUTER : IFN could be secure or non-secure.
2420  *
2421  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2422  *	      packet in error has AH/ESP headers to validate the AH/ESP
2423  *	      headers. AH/ESP will verify whether there is a valid SA or
2424  *	      not and send it back. We will fanout again if we have more
2425  *	      data in the packet.
2426  *
2427  *	      If the packet in error does not have AH/ESP, we handle it
2428  *	      like any other case.
2429  *
2430  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2431  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2432  *	      for validation. AH/ESP will verify whether there is a
2433  *	      valid SA or not and send it back. We will fanout again if
2434  *	      we have more data in the packet.
2435  *
2436  *	      If the packet in error does not have AH/ESP, we handle it
2437  *	      like any other case.
2438  */
2439 static void
2440 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2441     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2442     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2443     zoneid_t zoneid)
2444 {
2445 	uint16_t *up;	/* Pointer to ports in ULP header */
2446 	uint32_t ports;	/* reversed ports for fanout */
2447 	ipha_t ripha;	/* With reversed addresses */
2448 	mblk_t *first_mp;
2449 	ipsec_in_t *ii;
2450 	tcph_t	*tcph;
2451 	conn_t	*connp;
2452 	ip_stack_t *ipst;
2453 
2454 	ASSERT(ill != NULL);
2455 
2456 	ASSERT(recv_ill != NULL);
2457 	ipst = recv_ill->ill_ipst;
2458 
2459 	first_mp = mp;
2460 	if (mctl_present) {
2461 		mp = first_mp->b_cont;
2462 		ASSERT(mp != NULL);
2463 
2464 		ii = (ipsec_in_t *)first_mp->b_rptr;
2465 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2466 	} else {
2467 		ii = NULL;
2468 	}
2469 
2470 	switch (ipha->ipha_protocol) {
2471 	case IPPROTO_UDP:
2472 		/*
2473 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2474 		 * transport header.
2475 		 */
2476 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2477 		    mp->b_wptr) {
2478 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2479 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2480 				goto discard_pkt;
2481 			}
2482 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2483 			ipha = (ipha_t *)&icmph[1];
2484 		}
2485 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2486 
2487 		/*
2488 		 * Attempt to find a client stream based on port.
2489 		 * Note that we do a reverse lookup since the header is
2490 		 * in the form we sent it out.
2491 		 * The ripha header is only used for the IP_UDP_MATCH and we
2492 		 * only set the src and dst addresses and protocol.
2493 		 */
2494 		ripha.ipha_src = ipha->ipha_dst;
2495 		ripha.ipha_dst = ipha->ipha_src;
2496 		ripha.ipha_protocol = ipha->ipha_protocol;
2497 		((uint16_t *)&ports)[0] = up[1];
2498 		((uint16_t *)&ports)[1] = up[0];
2499 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2500 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2501 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2502 		    icmph->icmph_type, icmph->icmph_code));
2503 
2504 		/* Have to change db_type after any pullupmsg */
2505 		DB_TYPE(mp) = M_CTL;
2506 
2507 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2508 		    mctl_present, ip_policy, recv_ill, zoneid);
2509 		return;
2510 
2511 	case IPPROTO_TCP:
2512 		/*
2513 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2514 		 * transport header.
2515 		 */
2516 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2517 		    mp->b_wptr) {
2518 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2519 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2520 				goto discard_pkt;
2521 			}
2522 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2523 			ipha = (ipha_t *)&icmph[1];
2524 		}
2525 		/*
2526 		 * Find a TCP client stream for this packet.
2527 		 * Note that we do a reverse lookup since the header is
2528 		 * in the form we sent it out.
2529 		 */
2530 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2531 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2532 		    ipst);
2533 		if (connp == NULL)
2534 			goto discard_pkt;
2535 
2536 		/* Have to change db_type after any pullupmsg */
2537 		DB_TYPE(mp) = M_CTL;
2538 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2539 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2540 		return;
2541 
2542 	case IPPROTO_SCTP:
2543 		/*
2544 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2545 		 * transport header.
2546 		 */
2547 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2548 		    mp->b_wptr) {
2549 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2550 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2551 				goto discard_pkt;
2552 			}
2553 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2554 			ipha = (ipha_t *)&icmph[1];
2555 		}
2556 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2557 		/*
2558 		 * Find a SCTP client stream for this packet.
2559 		 * Note that we do a reverse lookup since the header is
2560 		 * in the form we sent it out.
2561 		 * The ripha header is only used for the matching and we
2562 		 * only set the src and dst addresses, protocol, and version.
2563 		 */
2564 		ripha.ipha_src = ipha->ipha_dst;
2565 		ripha.ipha_dst = ipha->ipha_src;
2566 		ripha.ipha_protocol = ipha->ipha_protocol;
2567 		ripha.ipha_version_and_hdr_length =
2568 		    ipha->ipha_version_and_hdr_length;
2569 		((uint16_t *)&ports)[0] = up[1];
2570 		((uint16_t *)&ports)[1] = up[0];
2571 
2572 		/* Have to change db_type after any pullupmsg */
2573 		DB_TYPE(mp) = M_CTL;
2574 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2575 		    mctl_present, ip_policy, zoneid);
2576 		return;
2577 
2578 	case IPPROTO_ESP:
2579 	case IPPROTO_AH: {
2580 		int ipsec_rc;
2581 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2582 
2583 		/*
2584 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2585 		 * We will re-use the IPSEC_IN if it is already present as
2586 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2587 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2588 		 * one and attach it in the front.
2589 		 */
2590 		if (ii != NULL) {
2591 			/*
2592 			 * ip_fanout_proto_again converts the ICMP errors
2593 			 * that come back from AH/ESP to M_DATA so that
2594 			 * if it is non-AH/ESP and we do a pullupmsg in
2595 			 * this function, it would work. Convert it back
2596 			 * to M_CTL before we send up as this is a ICMP
2597 			 * error. This could have been generated locally or
2598 			 * by some router. Validate the inner IPsec
2599 			 * headers.
2600 			 *
2601 			 * NOTE : ill_index is used by ip_fanout_proto_again
2602 			 * to locate the ill.
2603 			 */
2604 			ASSERT(ill != NULL);
2605 			ii->ipsec_in_ill_index =
2606 			    ill->ill_phyint->phyint_ifindex;
2607 			ii->ipsec_in_rill_index =
2608 			    recv_ill->ill_phyint->phyint_ifindex;
2609 			DB_TYPE(first_mp->b_cont) = M_CTL;
2610 		} else {
2611 			/*
2612 			 * IPSEC_IN is not present. We attach a ipsec_in
2613 			 * message and send up to IPsec for validating
2614 			 * and removing the IPsec headers. Clear
2615 			 * ipsec_in_secure so that when we return
2616 			 * from IPsec, we don't mistakenly think that this
2617 			 * is a secure packet came from the network.
2618 			 *
2619 			 * NOTE : ill_index is used by ip_fanout_proto_again
2620 			 * to locate the ill.
2621 			 */
2622 			ASSERT(first_mp == mp);
2623 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2624 			if (first_mp == NULL) {
2625 				freemsg(mp);
2626 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2627 				return;
2628 			}
2629 			ii = (ipsec_in_t *)first_mp->b_rptr;
2630 
2631 			/* This is not a secure packet */
2632 			ii->ipsec_in_secure = B_FALSE;
2633 			first_mp->b_cont = mp;
2634 			DB_TYPE(mp) = M_CTL;
2635 			ASSERT(ill != NULL);
2636 			ii->ipsec_in_ill_index =
2637 			    ill->ill_phyint->phyint_ifindex;
2638 			ii->ipsec_in_rill_index =
2639 			    recv_ill->ill_phyint->phyint_ifindex;
2640 		}
2641 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2642 
2643 		if (!ipsec_loaded(ipss)) {
2644 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2645 			return;
2646 		}
2647 
2648 		if (ipha->ipha_protocol == IPPROTO_ESP)
2649 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2650 		else
2651 			ipsec_rc = ipsecah_icmp_error(first_mp);
2652 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2653 			return;
2654 
2655 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2656 		return;
2657 	}
2658 	default:
2659 		/*
2660 		 * The ripha header is only used for the lookup and we
2661 		 * only set the src and dst addresses and protocol.
2662 		 */
2663 		ripha.ipha_src = ipha->ipha_dst;
2664 		ripha.ipha_dst = ipha->ipha_src;
2665 		ripha.ipha_protocol = ipha->ipha_protocol;
2666 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2667 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2668 		    ntohl(ipha->ipha_dst),
2669 		    icmph->icmph_type, icmph->icmph_code));
2670 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2671 			ipha_t *in_ipha;
2672 
2673 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2674 			    mp->b_wptr) {
2675 				if (!pullupmsg(mp, (uchar_t *)ipha +
2676 				    hdr_length + sizeof (ipha_t) -
2677 				    mp->b_rptr)) {
2678 					goto discard_pkt;
2679 				}
2680 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2681 				ipha = (ipha_t *)&icmph[1];
2682 			}
2683 			/*
2684 			 * Caller has verified that length has to be
2685 			 * at least the size of IP header.
2686 			 */
2687 			ASSERT(hdr_length >= sizeof (ipha_t));
2688 			/*
2689 			 * Check the sanity of the inner IP header like
2690 			 * we did for the outer header.
2691 			 */
2692 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2693 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2694 				goto discard_pkt;
2695 			}
2696 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2697 				goto discard_pkt;
2698 			}
2699 			/* Check for Self-encapsulated tunnels */
2700 			if (in_ipha->ipha_src == ipha->ipha_src &&
2701 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2702 
2703 				mp = icmp_inbound_self_encap_error(mp,
2704 				    iph_hdr_length, hdr_length);
2705 				if (mp == NULL)
2706 					goto discard_pkt;
2707 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2708 				ipha = (ipha_t *)&icmph[1];
2709 				hdr_length = IPH_HDR_LENGTH(ipha);
2710 				/*
2711 				 * The packet in error is self-encapsualted.
2712 				 * And we are finding it further encapsulated
2713 				 * which we could not have possibly generated.
2714 				 */
2715 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2716 					goto discard_pkt;
2717 				}
2718 				icmp_inbound_error_fanout(q, ill, first_mp,
2719 				    icmph, ipha, iph_hdr_length, hdr_length,
2720 				    mctl_present, ip_policy, recv_ill, zoneid);
2721 				return;
2722 			}
2723 		}
2724 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2725 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2726 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2727 		    ii != NULL &&
2728 		    ii->ipsec_in_loopback &&
2729 		    ii->ipsec_in_secure) {
2730 			/*
2731 			 * For IP tunnels that get a looped-back
2732 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2733 			 * reported new MTU to take into account the IPsec
2734 			 * headers protecting this configured tunnel.
2735 			 *
2736 			 * This allows the tunnel module (tun.c) to blindly
2737 			 * accept the MTU reported in an ICMP "too big"
2738 			 * message.
2739 			 *
2740 			 * Non-looped back ICMP messages will just be
2741 			 * handled by the security protocols (if needed),
2742 			 * and the first subsequent packet will hit this
2743 			 * path.
2744 			 */
2745 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2746 			    ipsec_in_extra_length(first_mp));
2747 		}
2748 		/* Have to change db_type after any pullupmsg */
2749 		DB_TYPE(mp) = M_CTL;
2750 
2751 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2752 		    ip_policy, recv_ill, zoneid);
2753 		return;
2754 	}
2755 	/* NOTREACHED */
2756 discard_pkt:
2757 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2758 drop_pkt:;
2759 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2760 	freemsg(first_mp);
2761 }
2762 
2763 /*
2764  * Common IP options parser.
2765  *
2766  * Setup routine: fill in *optp with options-parsing state, then
2767  * tail-call ipoptp_next to return the first option.
2768  */
2769 uint8_t
2770 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2771 {
2772 	uint32_t totallen; /* total length of all options */
2773 
2774 	totallen = ipha->ipha_version_and_hdr_length -
2775 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2776 	totallen <<= 2;
2777 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2778 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2779 	optp->ipoptp_flags = 0;
2780 	return (ipoptp_next(optp));
2781 }
2782 
2783 /*
2784  * Common IP options parser: extract next option.
2785  */
2786 uint8_t
2787 ipoptp_next(ipoptp_t *optp)
2788 {
2789 	uint8_t *end = optp->ipoptp_end;
2790 	uint8_t *cur = optp->ipoptp_next;
2791 	uint8_t opt, len, pointer;
2792 
2793 	/*
2794 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2795 	 * has been corrupted.
2796 	 */
2797 	ASSERT(cur <= end);
2798 
2799 	if (cur == end)
2800 		return (IPOPT_EOL);
2801 
2802 	opt = cur[IPOPT_OPTVAL];
2803 
2804 	/*
2805 	 * Skip any NOP options.
2806 	 */
2807 	while (opt == IPOPT_NOP) {
2808 		cur++;
2809 		if (cur == end)
2810 			return (IPOPT_EOL);
2811 		opt = cur[IPOPT_OPTVAL];
2812 	}
2813 
2814 	if (opt == IPOPT_EOL)
2815 		return (IPOPT_EOL);
2816 
2817 	/*
2818 	 * Option requiring a length.
2819 	 */
2820 	if ((cur + 1) >= end) {
2821 		optp->ipoptp_flags |= IPOPTP_ERROR;
2822 		return (IPOPT_EOL);
2823 	}
2824 	len = cur[IPOPT_OLEN];
2825 	if (len < 2) {
2826 		optp->ipoptp_flags |= IPOPTP_ERROR;
2827 		return (IPOPT_EOL);
2828 	}
2829 	optp->ipoptp_cur = cur;
2830 	optp->ipoptp_len = len;
2831 	optp->ipoptp_next = cur + len;
2832 	if (cur + len > end) {
2833 		optp->ipoptp_flags |= IPOPTP_ERROR;
2834 		return (IPOPT_EOL);
2835 	}
2836 
2837 	/*
2838 	 * For the options which require a pointer field, make sure
2839 	 * its there, and make sure it points to either something
2840 	 * inside this option, or the end of the option.
2841 	 */
2842 	switch (opt) {
2843 	case IPOPT_RR:
2844 	case IPOPT_TS:
2845 	case IPOPT_LSRR:
2846 	case IPOPT_SSRR:
2847 		if (len <= IPOPT_OFFSET) {
2848 			optp->ipoptp_flags |= IPOPTP_ERROR;
2849 			return (opt);
2850 		}
2851 		pointer = cur[IPOPT_OFFSET];
2852 		if (pointer - 1 > len) {
2853 			optp->ipoptp_flags |= IPOPTP_ERROR;
2854 			return (opt);
2855 		}
2856 		break;
2857 	}
2858 
2859 	/*
2860 	 * Sanity check the pointer field based on the type of the
2861 	 * option.
2862 	 */
2863 	switch (opt) {
2864 	case IPOPT_RR:
2865 	case IPOPT_SSRR:
2866 	case IPOPT_LSRR:
2867 		if (pointer < IPOPT_MINOFF_SR)
2868 			optp->ipoptp_flags |= IPOPTP_ERROR;
2869 		break;
2870 	case IPOPT_TS:
2871 		if (pointer < IPOPT_MINOFF_IT)
2872 			optp->ipoptp_flags |= IPOPTP_ERROR;
2873 		/*
2874 		 * Note that the Internet Timestamp option also
2875 		 * contains two four bit fields (the Overflow field,
2876 		 * and the Flag field), which follow the pointer
2877 		 * field.  We don't need to check that these fields
2878 		 * fall within the length of the option because this
2879 		 * was implicitely done above.  We've checked that the
2880 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2881 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2882 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2883 		 */
2884 		ASSERT(len > IPOPT_POS_OV_FLG);
2885 		break;
2886 	}
2887 
2888 	return (opt);
2889 }
2890 
2891 /*
2892  * Use the outgoing IP header to create an IP_OPTIONS option the way
2893  * it was passed down from the application.
2894  */
2895 int
2896 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2897 {
2898 	ipoptp_t	opts;
2899 	const uchar_t	*opt;
2900 	uint8_t		optval;
2901 	uint8_t		optlen;
2902 	uint32_t	len = 0;
2903 	uchar_t	*buf1 = buf;
2904 
2905 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2906 	len += IP_ADDR_LEN;
2907 	bzero(buf1, IP_ADDR_LEN);
2908 
2909 	/*
2910 	 * OK to cast away const here, as we don't store through the returned
2911 	 * opts.ipoptp_cur pointer.
2912 	 */
2913 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2914 	    optval != IPOPT_EOL;
2915 	    optval = ipoptp_next(&opts)) {
2916 		int	off;
2917 
2918 		opt = opts.ipoptp_cur;
2919 		optlen = opts.ipoptp_len;
2920 		switch (optval) {
2921 		case IPOPT_SSRR:
2922 		case IPOPT_LSRR:
2923 
2924 			/*
2925 			 * Insert ipha_dst as the first entry in the source
2926 			 * route and move down the entries on step.
2927 			 * The last entry gets placed at buf1.
2928 			 */
2929 			buf[IPOPT_OPTVAL] = optval;
2930 			buf[IPOPT_OLEN] = optlen;
2931 			buf[IPOPT_OFFSET] = optlen;
2932 
2933 			off = optlen - IP_ADDR_LEN;
2934 			if (off < 0) {
2935 				/* No entries in source route */
2936 				break;
2937 			}
2938 			/* Last entry in source route */
2939 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2940 			off -= IP_ADDR_LEN;
2941 
2942 			while (off > 0) {
2943 				bcopy(opt + off,
2944 				    buf + off + IP_ADDR_LEN,
2945 				    IP_ADDR_LEN);
2946 				off -= IP_ADDR_LEN;
2947 			}
2948 			/* ipha_dst into first slot */
2949 			bcopy(&ipha->ipha_dst,
2950 			    buf + off + IP_ADDR_LEN,
2951 			    IP_ADDR_LEN);
2952 			buf += optlen;
2953 			len += optlen;
2954 			break;
2955 
2956 		case IPOPT_COMSEC:
2957 		case IPOPT_SECURITY:
2958 			/* if passing up a label is not ok, then remove */
2959 			if (is_system_labeled())
2960 				break;
2961 			/* FALLTHROUGH */
2962 		default:
2963 			bcopy(opt, buf, optlen);
2964 			buf += optlen;
2965 			len += optlen;
2966 			break;
2967 		}
2968 	}
2969 done:
2970 	/* Pad the resulting options */
2971 	while (len & 0x3) {
2972 		*buf++ = IPOPT_EOL;
2973 		len++;
2974 	}
2975 	return (len);
2976 }
2977 
2978 /*
2979  * Update any record route or timestamp options to include this host.
2980  * Reverse any source route option.
2981  * This routine assumes that the options are well formed i.e. that they
2982  * have already been checked.
2983  */
2984 static void
2985 icmp_options_update(ipha_t *ipha)
2986 {
2987 	ipoptp_t	opts;
2988 	uchar_t		*opt;
2989 	uint8_t		optval;
2990 	ipaddr_t	src;		/* Our local address */
2991 	ipaddr_t	dst;
2992 
2993 	ip2dbg(("icmp_options_update\n"));
2994 	src = ipha->ipha_src;
2995 	dst = ipha->ipha_dst;
2996 
2997 	for (optval = ipoptp_first(&opts, ipha);
2998 	    optval != IPOPT_EOL;
2999 	    optval = ipoptp_next(&opts)) {
3000 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3001 		opt = opts.ipoptp_cur;
3002 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3003 		    optval, opts.ipoptp_len));
3004 		switch (optval) {
3005 			int off1, off2;
3006 		case IPOPT_SSRR:
3007 		case IPOPT_LSRR:
3008 			/*
3009 			 * Reverse the source route.  The first entry
3010 			 * should be the next to last one in the current
3011 			 * source route (the last entry is our address).
3012 			 * The last entry should be the final destination.
3013 			 */
3014 			off1 = IPOPT_MINOFF_SR - 1;
3015 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3016 			if (off2 < 0) {
3017 				/* No entries in source route */
3018 				ip1dbg((
3019 				    "icmp_options_update: bad src route\n"));
3020 				break;
3021 			}
3022 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3023 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3024 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3025 			off2 -= IP_ADDR_LEN;
3026 
3027 			while (off1 < off2) {
3028 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3029 				bcopy((char *)opt + off2, (char *)opt + off1,
3030 				    IP_ADDR_LEN);
3031 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3032 				off1 += IP_ADDR_LEN;
3033 				off2 -= IP_ADDR_LEN;
3034 			}
3035 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3036 			break;
3037 		}
3038 	}
3039 }
3040 
3041 /*
3042  * Process received ICMP Redirect messages.
3043  */
3044 static void
3045 icmp_redirect(ill_t *ill, mblk_t *mp)
3046 {
3047 	ipha_t	*ipha;
3048 	int	iph_hdr_length;
3049 	icmph_t	*icmph;
3050 	ipha_t	*ipha_err;
3051 	ire_t	*ire;
3052 	ire_t	*prev_ire;
3053 	ire_t	*save_ire;
3054 	ipaddr_t  src, dst, gateway;
3055 	iulp_t	ulp_info = { 0 };
3056 	int	error;
3057 	ip_stack_t *ipst;
3058 
3059 	ASSERT(ill != NULL);
3060 	ipst = ill->ill_ipst;
3061 
3062 	ipha = (ipha_t *)mp->b_rptr;
3063 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3064 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3065 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3066 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3067 		freemsg(mp);
3068 		return;
3069 	}
3070 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3071 	ipha_err = (ipha_t *)&icmph[1];
3072 	src = ipha->ipha_src;
3073 	dst = ipha_err->ipha_dst;
3074 	gateway = icmph->icmph_rd_gateway;
3075 	/* Make sure the new gateway is reachable somehow. */
3076 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3077 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3078 	/*
3079 	 * Make sure we had a route for the dest in question and that
3080 	 * that route was pointing to the old gateway (the source of the
3081 	 * redirect packet.)
3082 	 */
3083 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3084 	    NULL, MATCH_IRE_GW, ipst);
3085 	/*
3086 	 * Check that
3087 	 *	the redirect was not from ourselves
3088 	 *	the new gateway and the old gateway are directly reachable
3089 	 */
3090 	if (!prev_ire ||
3091 	    !ire ||
3092 	    ire->ire_type == IRE_LOCAL) {
3093 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3094 		freemsg(mp);
3095 		if (ire != NULL)
3096 			ire_refrele(ire);
3097 		if (prev_ire != NULL)
3098 			ire_refrele(prev_ire);
3099 		return;
3100 	}
3101 
3102 	/*
3103 	 * Should we use the old ULP info to create the new gateway?  From
3104 	 * a user's perspective, we should inherit the info so that it
3105 	 * is a "smooth" transition.  If we do not do that, then new
3106 	 * connections going thru the new gateway will have no route metrics,
3107 	 * which is counter-intuitive to user.  From a network point of
3108 	 * view, this may or may not make sense even though the new gateway
3109 	 * is still directly connected to us so the route metrics should not
3110 	 * change much.
3111 	 *
3112 	 * But if the old ire_uinfo is not initialized, we do another
3113 	 * recursive lookup on the dest using the new gateway.  There may
3114 	 * be a route to that.  If so, use it to initialize the redirect
3115 	 * route.
3116 	 */
3117 	if (prev_ire->ire_uinfo.iulp_set) {
3118 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3119 	} else {
3120 		ire_t *tmp_ire;
3121 		ire_t *sire;
3122 
3123 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3124 		    ALL_ZONES, 0, NULL,
3125 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3126 		    ipst);
3127 		if (sire != NULL) {
3128 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3129 			/*
3130 			 * If sire != NULL, ire_ftable_lookup() should not
3131 			 * return a NULL value.
3132 			 */
3133 			ASSERT(tmp_ire != NULL);
3134 			ire_refrele(tmp_ire);
3135 			ire_refrele(sire);
3136 		} else if (tmp_ire != NULL) {
3137 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3138 			    sizeof (iulp_t));
3139 			ire_refrele(tmp_ire);
3140 		}
3141 	}
3142 	if (prev_ire->ire_type == IRE_CACHE)
3143 		ire_delete(prev_ire);
3144 	ire_refrele(prev_ire);
3145 	/*
3146 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3147 	 * require TOS routing
3148 	 */
3149 	switch (icmph->icmph_code) {
3150 	case 0:
3151 	case 1:
3152 		/* TODO: TOS specificity for cases 2 and 3 */
3153 	case 2:
3154 	case 3:
3155 		break;
3156 	default:
3157 		freemsg(mp);
3158 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3159 		ire_refrele(ire);
3160 		return;
3161 	}
3162 	/*
3163 	 * Create a Route Association.  This will allow us to remember that
3164 	 * someone we believe told us to use the particular gateway.
3165 	 */
3166 	save_ire = ire;
3167 	ire = ire_create(
3168 	    (uchar_t *)&dst,			/* dest addr */
3169 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3170 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3171 	    (uchar_t *)&gateway,		/* gateway addr */
3172 	    &save_ire->ire_max_frag,		/* max frag */
3173 	    NULL,				/* no src nce */
3174 	    NULL,				/* no rfq */
3175 	    NULL,				/* no stq */
3176 	    IRE_HOST,
3177 	    NULL,				/* ipif */
3178 	    0,					/* cmask */
3179 	    0,					/* phandle */
3180 	    0,					/* ihandle */
3181 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3182 	    &ulp_info,
3183 	    NULL,				/* tsol_gc_t */
3184 	    NULL,				/* gcgrp */
3185 	    ipst);
3186 
3187 	if (ire == NULL) {
3188 		freemsg(mp);
3189 		ire_refrele(save_ire);
3190 		return;
3191 	}
3192 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3193 	ire_refrele(save_ire);
3194 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3195 
3196 	if (error == 0) {
3197 		ire_refrele(ire);		/* Held in ire_add_v4 */
3198 		/* tell routing sockets that we received a redirect */
3199 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3200 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3201 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3202 	}
3203 
3204 	/*
3205 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3206 	 * This together with the added IRE has the effect of
3207 	 * modifying an existing redirect.
3208 	 */
3209 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3210 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3211 	if (prev_ire != NULL) {
3212 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3213 			ire_delete(prev_ire);
3214 		ire_refrele(prev_ire);
3215 	}
3216 
3217 	freemsg(mp);
3218 }
3219 
3220 /*
3221  * Generate an ICMP parameter problem message.
3222  */
3223 static void
3224 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3225 	ip_stack_t *ipst)
3226 {
3227 	icmph_t	icmph;
3228 	boolean_t mctl_present;
3229 	mblk_t *first_mp;
3230 
3231 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3232 
3233 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3234 		if (mctl_present)
3235 			freeb(first_mp);
3236 		return;
3237 	}
3238 
3239 	bzero(&icmph, sizeof (icmph_t));
3240 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3241 	icmph.icmph_pp_ptr = ptr;
3242 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3243 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3244 	    ipst);
3245 }
3246 
3247 /*
3248  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3249  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3250  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3251  * an icmp error packet can be sent.
3252  * Assigns an appropriate source address to the packet. If ipha_dst is
3253  * one of our addresses use it for source. Otherwise pick a source based
3254  * on a route lookup back to ipha_src.
3255  * Note that ipha_src must be set here since the
3256  * packet is likely to arrive on an ill queue in ip_wput() which will
3257  * not set a source address.
3258  */
3259 static void
3260 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3261     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3262 {
3263 	ipaddr_t dst;
3264 	icmph_t	*icmph;
3265 	ipha_t	*ipha;
3266 	uint_t	len_needed;
3267 	size_t	msg_len;
3268 	mblk_t	*mp1;
3269 	ipaddr_t src;
3270 	ire_t	*ire;
3271 	mblk_t *ipsec_mp;
3272 	ipsec_out_t	*io = NULL;
3273 
3274 	if (mctl_present) {
3275 		/*
3276 		 * If it is :
3277 		 *
3278 		 * 1) a IPSEC_OUT, then this is caused by outbound
3279 		 *    datagram originating on this host. IPsec processing
3280 		 *    may or may not have been done. Refer to comments above
3281 		 *    icmp_inbound_error_fanout for details.
3282 		 *
3283 		 * 2) a IPSEC_IN if we are generating a icmp_message
3284 		 *    for an incoming datagram destined for us i.e called
3285 		 *    from ip_fanout_send_icmp.
3286 		 */
3287 		ipsec_info_t *in;
3288 		ipsec_mp = mp;
3289 		mp = ipsec_mp->b_cont;
3290 
3291 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3292 		ipha = (ipha_t *)mp->b_rptr;
3293 
3294 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3295 		    in->ipsec_info_type == IPSEC_IN);
3296 
3297 		if (in->ipsec_info_type == IPSEC_IN) {
3298 			/*
3299 			 * Convert the IPSEC_IN to IPSEC_OUT.
3300 			 */
3301 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3302 				BUMP_MIB(&ipst->ips_ip_mib,
3303 				    ipIfStatsOutDiscards);
3304 				return;
3305 			}
3306 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3307 		} else {
3308 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3309 			io = (ipsec_out_t *)in;
3310 			/*
3311 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3312 			 * ire lookup.
3313 			 */
3314 			io->ipsec_out_proc_begin = B_FALSE;
3315 		}
3316 		ASSERT(zoneid == io->ipsec_out_zoneid);
3317 		ASSERT(zoneid != ALL_ZONES);
3318 	} else {
3319 		/*
3320 		 * This is in clear. The icmp message we are building
3321 		 * here should go out in clear.
3322 		 *
3323 		 * Pardon the convolution of it all, but it's easier to
3324 		 * allocate a "use cleartext" IPSEC_IN message and convert
3325 		 * it than it is to allocate a new one.
3326 		 */
3327 		ipsec_in_t *ii;
3328 		ASSERT(DB_TYPE(mp) == M_DATA);
3329 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3330 		if (ipsec_mp == NULL) {
3331 			freemsg(mp);
3332 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3333 			return;
3334 		}
3335 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3336 
3337 		/* This is not a secure packet */
3338 		ii->ipsec_in_secure = B_FALSE;
3339 		/*
3340 		 * For trusted extensions using a shared IP address we can
3341 		 * send using any zoneid.
3342 		 */
3343 		if (zoneid == ALL_ZONES)
3344 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3345 		else
3346 			ii->ipsec_in_zoneid = zoneid;
3347 		ipsec_mp->b_cont = mp;
3348 		ipha = (ipha_t *)mp->b_rptr;
3349 		/*
3350 		 * Convert the IPSEC_IN to IPSEC_OUT.
3351 		 */
3352 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3353 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3354 			return;
3355 		}
3356 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3357 	}
3358 
3359 	/* Remember our eventual destination */
3360 	dst = ipha->ipha_src;
3361 
3362 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3363 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3364 	if (ire != NULL &&
3365 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3366 		src = ipha->ipha_dst;
3367 	} else {
3368 		if (ire != NULL)
3369 			ire_refrele(ire);
3370 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3371 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3372 		    ipst);
3373 		if (ire == NULL) {
3374 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3375 			freemsg(ipsec_mp);
3376 			return;
3377 		}
3378 		src = ire->ire_src_addr;
3379 	}
3380 
3381 	if (ire != NULL)
3382 		ire_refrele(ire);
3383 
3384 	/*
3385 	 * Check if we can send back more then 8 bytes in addition to
3386 	 * the IP header.  We try to send 64 bytes of data and the internal
3387 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3388 	 */
3389 	len_needed = IPH_HDR_LENGTH(ipha);
3390 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3391 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3392 
3393 		if (!pullupmsg(mp, -1)) {
3394 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3395 			freemsg(ipsec_mp);
3396 			return;
3397 		}
3398 		ipha = (ipha_t *)mp->b_rptr;
3399 
3400 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3401 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3402 			    len_needed));
3403 		} else {
3404 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3405 
3406 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3407 			len_needed += ip_hdr_length_v6(mp, ip6h);
3408 		}
3409 	}
3410 	len_needed += ipst->ips_ip_icmp_return;
3411 	msg_len = msgdsize(mp);
3412 	if (msg_len > len_needed) {
3413 		(void) adjmsg(mp, len_needed - msg_len);
3414 		msg_len = len_needed;
3415 	}
3416 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3417 	if (mp1 == NULL) {
3418 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3419 		freemsg(ipsec_mp);
3420 		return;
3421 	}
3422 	mp1->b_cont = mp;
3423 	mp = mp1;
3424 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3425 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3426 	    io->ipsec_out_type == IPSEC_OUT);
3427 	ipsec_mp->b_cont = mp;
3428 
3429 	/*
3430 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3431 	 * node generates be accepted in peace by all on-host destinations.
3432 	 * If we do NOT assume that all on-host destinations trust
3433 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3434 	 * (Look for ipsec_out_icmp_loopback).
3435 	 */
3436 	io->ipsec_out_icmp_loopback = B_TRUE;
3437 
3438 	ipha = (ipha_t *)mp->b_rptr;
3439 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3440 	*ipha = icmp_ipha;
3441 	ipha->ipha_src = src;
3442 	ipha->ipha_dst = dst;
3443 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3444 	msg_len += sizeof (icmp_ipha) + len;
3445 	if (msg_len > IP_MAXPACKET) {
3446 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3447 		msg_len = IP_MAXPACKET;
3448 	}
3449 	ipha->ipha_length = htons((uint16_t)msg_len);
3450 	icmph = (icmph_t *)&ipha[1];
3451 	bcopy(stuff, icmph, len);
3452 	icmph->icmph_checksum = 0;
3453 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3454 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3455 	put(q, ipsec_mp);
3456 }
3457 
3458 /*
3459  * Determine if an ICMP error packet can be sent given the rate limit.
3460  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3461  * in milliseconds) and a burst size. Burst size number of packets can
3462  * be sent arbitrarely closely spaced.
3463  * The state is tracked using two variables to implement an approximate
3464  * token bucket filter:
3465  *	icmp_pkt_err_last - lbolt value when the last burst started
3466  *	icmp_pkt_err_sent - number of packets sent in current burst
3467  */
3468 boolean_t
3469 icmp_err_rate_limit(ip_stack_t *ipst)
3470 {
3471 	clock_t now = TICK_TO_MSEC(lbolt);
3472 	uint_t refilled; /* Number of packets refilled in tbf since last */
3473 	/* Guard against changes by loading into local variable */
3474 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3475 
3476 	if (err_interval == 0)
3477 		return (B_FALSE);
3478 
3479 	if (ipst->ips_icmp_pkt_err_last > now) {
3480 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3481 		ipst->ips_icmp_pkt_err_last = 0;
3482 		ipst->ips_icmp_pkt_err_sent = 0;
3483 	}
3484 	/*
3485 	 * If we are in a burst update the token bucket filter.
3486 	 * Update the "last" time to be close to "now" but make sure
3487 	 * we don't loose precision.
3488 	 */
3489 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3490 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3491 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3492 			ipst->ips_icmp_pkt_err_sent = 0;
3493 		} else {
3494 			ipst->ips_icmp_pkt_err_sent -= refilled;
3495 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3496 		}
3497 	}
3498 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3499 		/* Start of new burst */
3500 		ipst->ips_icmp_pkt_err_last = now;
3501 	}
3502 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3503 		ipst->ips_icmp_pkt_err_sent++;
3504 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3505 		    ipst->ips_icmp_pkt_err_sent));
3506 		return (B_FALSE);
3507 	}
3508 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3509 	return (B_TRUE);
3510 }
3511 
3512 /*
3513  * Check if it is ok to send an IPv4 ICMP error packet in
3514  * response to the IPv4 packet in mp.
3515  * Free the message and return null if no
3516  * ICMP error packet should be sent.
3517  */
3518 static mblk_t *
3519 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3520 {
3521 	icmph_t	*icmph;
3522 	ipha_t	*ipha;
3523 	uint_t	len_needed;
3524 	ire_t	*src_ire;
3525 	ire_t	*dst_ire;
3526 
3527 	if (!mp)
3528 		return (NULL);
3529 	ipha = (ipha_t *)mp->b_rptr;
3530 	if (ip_csum_hdr(ipha)) {
3531 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3532 		freemsg(mp);
3533 		return (NULL);
3534 	}
3535 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3536 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3537 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3538 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3539 	if (src_ire != NULL || dst_ire != NULL ||
3540 	    CLASSD(ipha->ipha_dst) ||
3541 	    CLASSD(ipha->ipha_src) ||
3542 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3543 		/* Note: only errors to the fragment with offset 0 */
3544 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3545 		freemsg(mp);
3546 		if (src_ire != NULL)
3547 			ire_refrele(src_ire);
3548 		if (dst_ire != NULL)
3549 			ire_refrele(dst_ire);
3550 		return (NULL);
3551 	}
3552 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3553 		/*
3554 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3555 		 * errors in response to any ICMP errors.
3556 		 */
3557 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3558 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3559 			if (!pullupmsg(mp, len_needed)) {
3560 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3561 				freemsg(mp);
3562 				return (NULL);
3563 			}
3564 			ipha = (ipha_t *)mp->b_rptr;
3565 		}
3566 		icmph = (icmph_t *)
3567 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3568 		switch (icmph->icmph_type) {
3569 		case ICMP_DEST_UNREACHABLE:
3570 		case ICMP_SOURCE_QUENCH:
3571 		case ICMP_TIME_EXCEEDED:
3572 		case ICMP_PARAM_PROBLEM:
3573 		case ICMP_REDIRECT:
3574 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3575 			freemsg(mp);
3576 			return (NULL);
3577 		default:
3578 			break;
3579 		}
3580 	}
3581 	/*
3582 	 * If this is a labeled system, then check to see if we're allowed to
3583 	 * send a response to this particular sender.  If not, then just drop.
3584 	 */
3585 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3586 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3587 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3588 		freemsg(mp);
3589 		return (NULL);
3590 	}
3591 	if (icmp_err_rate_limit(ipst)) {
3592 		/*
3593 		 * Only send ICMP error packets every so often.
3594 		 * This should be done on a per port/source basis,
3595 		 * but for now this will suffice.
3596 		 */
3597 		freemsg(mp);
3598 		return (NULL);
3599 	}
3600 	return (mp);
3601 }
3602 
3603 /*
3604  * Generate an ICMP redirect message.
3605  */
3606 static void
3607 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3608 {
3609 	icmph_t	icmph;
3610 
3611 	/*
3612 	 * We are called from ip_rput where we could
3613 	 * not have attached an IPSEC_IN.
3614 	 */
3615 	ASSERT(mp->b_datap->db_type == M_DATA);
3616 
3617 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3618 		return;
3619 	}
3620 
3621 	bzero(&icmph, sizeof (icmph_t));
3622 	icmph.icmph_type = ICMP_REDIRECT;
3623 	icmph.icmph_code = 1;
3624 	icmph.icmph_rd_gateway = gateway;
3625 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3626 	/* Redirects sent by router, and router is global zone */
3627 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3628 }
3629 
3630 /*
3631  * Generate an ICMP time exceeded message.
3632  */
3633 void
3634 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3635     ip_stack_t *ipst)
3636 {
3637 	icmph_t	icmph;
3638 	boolean_t mctl_present;
3639 	mblk_t *first_mp;
3640 
3641 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3642 
3643 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3644 		if (mctl_present)
3645 			freeb(first_mp);
3646 		return;
3647 	}
3648 
3649 	bzero(&icmph, sizeof (icmph_t));
3650 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3651 	icmph.icmph_code = code;
3652 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3653 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3654 	    ipst);
3655 }
3656 
3657 /*
3658  * Generate an ICMP unreachable message.
3659  */
3660 void
3661 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3662     ip_stack_t *ipst)
3663 {
3664 	icmph_t	icmph;
3665 	mblk_t *first_mp;
3666 	boolean_t mctl_present;
3667 
3668 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3669 
3670 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3671 		if (mctl_present)
3672 			freeb(first_mp);
3673 		return;
3674 	}
3675 
3676 	bzero(&icmph, sizeof (icmph_t));
3677 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3678 	icmph.icmph_code = code;
3679 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3680 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3681 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3682 	    zoneid, ipst);
3683 }
3684 
3685 /*
3686  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3687  * duplicate.  As long as someone else holds the address, the interface will
3688  * stay down.  When that conflict goes away, the interface is brought back up.
3689  * This is done so that accidental shutdowns of addresses aren't made
3690  * permanent.  Your server will recover from a failure.
3691  *
3692  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3693  * user space process (dhcpagent).
3694  *
3695  * Recovery completes if ARP reports that the address is now ours (via
3696  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3697  *
3698  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3699  */
3700 static void
3701 ipif_dup_recovery(void *arg)
3702 {
3703 	ipif_t *ipif = arg;
3704 	ill_t *ill = ipif->ipif_ill;
3705 	mblk_t *arp_add_mp;
3706 	mblk_t *arp_del_mp;
3707 	area_t *area;
3708 	ip_stack_t *ipst = ill->ill_ipst;
3709 
3710 	ipif->ipif_recovery_id = 0;
3711 
3712 	/*
3713 	 * No lock needed for moving or condemned check, as this is just an
3714 	 * optimization.
3715 	 */
3716 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3717 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3718 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3719 		/* No reason to try to bring this address back. */
3720 		return;
3721 	}
3722 
3723 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3724 		goto alloc_fail;
3725 
3726 	if (ipif->ipif_arp_del_mp == NULL) {
3727 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3728 			goto alloc_fail;
3729 		ipif->ipif_arp_del_mp = arp_del_mp;
3730 	}
3731 
3732 	/* Setting the 'unverified' flag restarts DAD */
3733 	area = (area_t *)arp_add_mp->b_rptr;
3734 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3735 	    ACE_F_UNVERIFIED;
3736 	putnext(ill->ill_rq, arp_add_mp);
3737 	return;
3738 
3739 alloc_fail:
3740 	/*
3741 	 * On allocation failure, just restart the timer.  Note that the ipif
3742 	 * is down here, so no other thread could be trying to start a recovery
3743 	 * timer.  The ill_lock protects the condemned flag and the recovery
3744 	 * timer ID.
3745 	 */
3746 	freemsg(arp_add_mp);
3747 	mutex_enter(&ill->ill_lock);
3748 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3749 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3750 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3751 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3752 	}
3753 	mutex_exit(&ill->ill_lock);
3754 }
3755 
3756 /*
3757  * This is for exclusive changes due to ARP.  Either tear down an interface due
3758  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3759  */
3760 /* ARGSUSED */
3761 static void
3762 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3763 {
3764 	ill_t	*ill = rq->q_ptr;
3765 	arh_t *arh;
3766 	ipaddr_t src;
3767 	ipif_t	*ipif;
3768 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3769 	char hbuf[MAC_STR_LEN];
3770 	char sbuf[INET_ADDRSTRLEN];
3771 	const char *failtype;
3772 	boolean_t bring_up;
3773 	ip_stack_t *ipst = ill->ill_ipst;
3774 
3775 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3776 	case AR_CN_READY:
3777 		failtype = NULL;
3778 		bring_up = B_TRUE;
3779 		break;
3780 	case AR_CN_FAILED:
3781 		failtype = "in use";
3782 		bring_up = B_FALSE;
3783 		break;
3784 	default:
3785 		failtype = "claimed";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	}
3789 
3790 	arh = (arh_t *)mp->b_cont->b_rptr;
3791 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3792 
3793 	/* Handle failures due to probes */
3794 	if (src == 0) {
3795 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3796 		    IP_ADDR_LEN);
3797 	}
3798 
3799 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3800 	    sizeof (hbuf));
3801 	(void) ip_dot_addr(src, sbuf);
3802 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3803 
3804 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3805 		    ipif->ipif_lcl_addr != src) {
3806 			continue;
3807 		}
3808 
3809 		/*
3810 		 * If we failed on a recovery probe, then restart the timer to
3811 		 * try again later.
3812 		 */
3813 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3814 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3815 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3816 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3817 		    ipst->ips_ip_dup_recovery > 0 &&
3818 		    ipif->ipif_recovery_id == 0) {
3819 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3820 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3821 			continue;
3822 		}
3823 
3824 		/*
3825 		 * If what we're trying to do has already been done, then do
3826 		 * nothing.
3827 		 */
3828 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3829 			continue;
3830 
3831 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3832 
3833 		if (failtype == NULL) {
3834 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3835 			    ibuf);
3836 		} else {
3837 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3838 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3839 		}
3840 
3841 		if (bring_up) {
3842 			ASSERT(ill->ill_dl_up);
3843 			/*
3844 			 * Free up the ARP delete message so we can allocate
3845 			 * a fresh one through the normal path.
3846 			 */
3847 			freemsg(ipif->ipif_arp_del_mp);
3848 			ipif->ipif_arp_del_mp = NULL;
3849 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3850 			    EINPROGRESS) {
3851 				ipif->ipif_addr_ready = 1;
3852 				(void) ipif_up_done(ipif);
3853 			}
3854 			continue;
3855 		}
3856 
3857 		mutex_enter(&ill->ill_lock);
3858 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3859 		ipif->ipif_flags |= IPIF_DUPLICATE;
3860 		ill->ill_ipif_dup_count++;
3861 		mutex_exit(&ill->ill_lock);
3862 		/*
3863 		 * Already exclusive on the ill; no need to handle deferred
3864 		 * processing here.
3865 		 */
3866 		(void) ipif_down(ipif, NULL, NULL);
3867 		ipif_down_tail(ipif);
3868 		mutex_enter(&ill->ill_lock);
3869 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3870 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3871 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3872 		    ipst->ips_ip_dup_recovery > 0) {
3873 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3874 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3875 		}
3876 		mutex_exit(&ill->ill_lock);
3877 	}
3878 	freemsg(mp);
3879 }
3880 
3881 /* ARGSUSED */
3882 static void
3883 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3884 {
3885 	ill_t	*ill = rq->q_ptr;
3886 	arh_t *arh;
3887 	ipaddr_t src;
3888 	ipif_t	*ipif;
3889 
3890 	arh = (arh_t *)mp->b_cont->b_rptr;
3891 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3892 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3893 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3894 			(void) ipif_resolver_up(ipif, Res_act_defend);
3895 	}
3896 	freemsg(mp);
3897 }
3898 
3899 /*
3900  * News from ARP.  ARP sends notification of interesting events down
3901  * to its clients using M_CTL messages with the interesting ARP packet
3902  * attached via b_cont.
3903  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3904  * queue as opposed to ARP sending the message to all the clients, i.e. all
3905  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3906  * table if a cache IRE is found to delete all the entries for the address in
3907  * the packet.
3908  */
3909 static void
3910 ip_arp_news(queue_t *q, mblk_t *mp)
3911 {
3912 	arcn_t		*arcn;
3913 	arh_t		*arh;
3914 	ire_t		*ire = NULL;
3915 	char		hbuf[MAC_STR_LEN];
3916 	char		sbuf[INET_ADDRSTRLEN];
3917 	ipaddr_t	src;
3918 	in6_addr_t	v6src;
3919 	boolean_t	isv6 = B_FALSE;
3920 	ipif_t		*ipif;
3921 	ill_t		*ill;
3922 	ip_stack_t	*ipst;
3923 
3924 	if (CONN_Q(q)) {
3925 		conn_t *connp = Q_TO_CONN(q);
3926 
3927 		ipst = connp->conn_netstack->netstack_ip;
3928 	} else {
3929 		ill_t *ill = (ill_t *)q->q_ptr;
3930 
3931 		ipst = ill->ill_ipst;
3932 	}
3933 
3934 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3935 		if (q->q_next) {
3936 			putnext(q, mp);
3937 		} else
3938 			freemsg(mp);
3939 		return;
3940 	}
3941 	arh = (arh_t *)mp->b_cont->b_rptr;
3942 	/* Is it one we are interested in? */
3943 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3944 		isv6 = B_TRUE;
3945 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3946 		    IPV6_ADDR_LEN);
3947 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3948 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3949 		    IP_ADDR_LEN);
3950 	} else {
3951 		freemsg(mp);
3952 		return;
3953 	}
3954 
3955 	ill = q->q_ptr;
3956 
3957 	arcn = (arcn_t *)mp->b_rptr;
3958 	switch (arcn->arcn_code) {
3959 	case AR_CN_BOGON:
3960 		/*
3961 		 * Someone is sending ARP packets with a source protocol
3962 		 * address that we have published and for which we believe our
3963 		 * entry is authoritative and (when ill_arp_extend is set)
3964 		 * verified to be unique on the network.
3965 		 *
3966 		 * The ARP module internally handles the cases where the sender
3967 		 * is just probing (for DAD) and where the hardware address of
3968 		 * a non-authoritative entry has changed.  Thus, these are the
3969 		 * real conflicts, and we have to do resolution.
3970 		 *
3971 		 * We back away quickly from the address if it's from DHCP or
3972 		 * otherwise temporary and hasn't been used recently (or at
3973 		 * all).  We'd like to include "deprecated" addresses here as
3974 		 * well (as there's no real reason to defend something we're
3975 		 * discarding), but IPMP "reuses" this flag to mean something
3976 		 * other than the standard meaning.
3977 		 *
3978 		 * If the ARP module above is not extended (meaning that it
3979 		 * doesn't know how to defend the address), then we just log
3980 		 * the problem as we always did and continue on.  It's not
3981 		 * right, but there's little else we can do, and those old ATM
3982 		 * users are going away anyway.
3983 		 */
3984 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3985 		    hbuf, sizeof (hbuf));
3986 		(void) ip_dot_addr(src, sbuf);
3987 		if (isv6) {
3988 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3989 			    ipst);
3990 		} else {
3991 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3992 		}
3993 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3994 			uint32_t now;
3995 			uint32_t maxage;
3996 			clock_t lused;
3997 			uint_t maxdefense;
3998 			uint_t defs;
3999 
4000 			/*
4001 			 * First, figure out if this address hasn't been used
4002 			 * in a while.  If it hasn't, then it's a better
4003 			 * candidate for abandoning.
4004 			 */
4005 			ipif = ire->ire_ipif;
4006 			ASSERT(ipif != NULL);
4007 			now = gethrestime_sec();
4008 			maxage = now - ire->ire_create_time;
4009 			if (maxage > ipst->ips_ip_max_temp_idle)
4010 				maxage = ipst->ips_ip_max_temp_idle;
4011 			lused = drv_hztousec(ddi_get_lbolt() -
4012 			    ire->ire_last_used_time) / MICROSEC + 1;
4013 			if (lused >= maxage && (ipif->ipif_flags &
4014 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4015 				maxdefense = ipst->ips_ip_max_temp_defend;
4016 			else
4017 				maxdefense = ipst->ips_ip_max_defend;
4018 
4019 			/*
4020 			 * Now figure out how many times we've defended
4021 			 * ourselves.  Ignore defenses that happened long in
4022 			 * the past.
4023 			 */
4024 			mutex_enter(&ire->ire_lock);
4025 			if ((defs = ire->ire_defense_count) > 0 &&
4026 			    now - ire->ire_defense_time >
4027 			    ipst->ips_ip_defend_interval) {
4028 				ire->ire_defense_count = defs = 0;
4029 			}
4030 			ire->ire_defense_count++;
4031 			ire->ire_defense_time = now;
4032 			mutex_exit(&ire->ire_lock);
4033 			ill_refhold(ill);
4034 			ire_refrele(ire);
4035 
4036 			/*
4037 			 * If we've defended ourselves too many times already,
4038 			 * then give up and tear down the interface(s) using
4039 			 * this address.  Otherwise, defend by sending out a
4040 			 * gratuitous ARP.
4041 			 */
4042 			if (defs >= maxdefense && ill->ill_arp_extend) {
4043 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4044 				    B_FALSE);
4045 			} else {
4046 				cmn_err(CE_WARN,
4047 				    "node %s is using our IP address %s on %s",
4048 				    hbuf, sbuf, ill->ill_name);
4049 				/*
4050 				 * If this is an old (ATM) ARP module, then
4051 				 * don't try to defend the address.  Remain
4052 				 * compatible with the old behavior.  Defend
4053 				 * only with new ARP.
4054 				 */
4055 				if (ill->ill_arp_extend) {
4056 					qwriter_ip(ill, q, mp, ip_arp_defend,
4057 					    NEW_OP, B_FALSE);
4058 				} else {
4059 					ill_refrele(ill);
4060 				}
4061 			}
4062 			return;
4063 		}
4064 		cmn_err(CE_WARN,
4065 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4066 		    hbuf, sbuf, ill->ill_name);
4067 		if (ire != NULL)
4068 			ire_refrele(ire);
4069 		break;
4070 	case AR_CN_ANNOUNCE:
4071 		if (isv6) {
4072 			/*
4073 			 * For XRESOLV interfaces.
4074 			 * Delete the IRE cache entry and NCE for this
4075 			 * v6 address
4076 			 */
4077 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4078 			/*
4079 			 * If v6src is a non-zero, it's a router address
4080 			 * as below. Do the same sort of thing to clean
4081 			 * out off-net IRE_CACHE entries that go through
4082 			 * the router.
4083 			 */
4084 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4085 				ire_walk_v6(ire_delete_cache_gw_v6,
4086 				    (char *)&v6src, ALL_ZONES, ipst);
4087 			}
4088 		} else {
4089 			nce_hw_map_t hwm;
4090 
4091 			/*
4092 			 * ARP gives us a copy of any packet where it thinks
4093 			 * the address has changed, so that we can update our
4094 			 * caches.  We're responsible for caching known answers
4095 			 * in the current design.  We check whether the
4096 			 * hardware address really has changed in all of our
4097 			 * entries that have cached this mapping, and if so, we
4098 			 * blow them away.  This way we will immediately pick
4099 			 * up the rare case of a host changing hardware
4100 			 * address.
4101 			 */
4102 			if (src == 0)
4103 				break;
4104 			hwm.hwm_addr = src;
4105 			hwm.hwm_hwlen = arh->arh_hlen;
4106 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4107 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4108 			ndp_walk_common(ipst->ips_ndp4, NULL,
4109 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4110 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4111 		}
4112 		break;
4113 	case AR_CN_READY:
4114 		/* No external v6 resolver has a contract to use this */
4115 		if (isv6)
4116 			break;
4117 		/* If the link is down, we'll retry this later */
4118 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4119 			break;
4120 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4121 		    NULL, NULL, ipst);
4122 		if (ipif != NULL) {
4123 			/*
4124 			 * If this is a duplicate recovery, then we now need to
4125 			 * go exclusive to bring this thing back up.
4126 			 */
4127 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4128 			    IPIF_DUPLICATE) {
4129 				ipif_refrele(ipif);
4130 				ill_refhold(ill);
4131 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4132 				    B_FALSE);
4133 				return;
4134 			}
4135 			/*
4136 			 * If this is the first notice that this address is
4137 			 * ready, then let the user know now.
4138 			 */
4139 			if ((ipif->ipif_flags & IPIF_UP) &&
4140 			    !ipif->ipif_addr_ready) {
4141 				ipif_mask_reply(ipif);
4142 				ip_rts_ifmsg(ipif);
4143 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4144 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4145 			}
4146 			ipif->ipif_addr_ready = 1;
4147 			ipif_refrele(ipif);
4148 		}
4149 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4150 		if (ire != NULL) {
4151 			ire->ire_defense_count = 0;
4152 			ire_refrele(ire);
4153 		}
4154 		break;
4155 	case AR_CN_FAILED:
4156 		/* No external v6 resolver has a contract to use this */
4157 		if (isv6)
4158 			break;
4159 		ill_refhold(ill);
4160 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4161 		return;
4162 	}
4163 	freemsg(mp);
4164 }
4165 
4166 /*
4167  * Create a mblk suitable for carrying the interface index and/or source link
4168  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4169  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4170  * application.
4171  */
4172 mblk_t *
4173 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4174     ip_stack_t *ipst)
4175 {
4176 	mblk_t		*mp;
4177 	ip_pktinfo_t	*pinfo;
4178 	ipha_t *ipha;
4179 	struct ether_header *pether;
4180 
4181 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4182 	if (mp == NULL) {
4183 		ip1dbg(("ip_add_info: allocation failure.\n"));
4184 		return (data_mp);
4185 	}
4186 
4187 	ipha	= (ipha_t *)data_mp->b_rptr;
4188 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4189 	bzero(pinfo, sizeof (ip_pktinfo_t));
4190 	pinfo->ip_pkt_flags = (uchar_t)flags;
4191 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4192 
4193 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4194 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4195 	if (flags & IPF_RECVADDR) {
4196 		ipif_t	*ipif;
4197 		ire_t	*ire;
4198 
4199 		/*
4200 		 * Only valid for V4
4201 		 */
4202 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4203 		    (IPV4_VERSION << 4));
4204 
4205 		ipif = ipif_get_next_ipif(NULL, ill);
4206 		if (ipif != NULL) {
4207 			/*
4208 			 * Since a decision has already been made to deliver the
4209 			 * packet, there is no need to test for SECATTR and
4210 			 * ZONEONLY.
4211 			 * When a multicast packet is transmitted
4212 			 * a cache entry is created for the multicast address.
4213 			 * When delivering a copy of the packet or when new
4214 			 * packets are received we do not want to match on the
4215 			 * cached entry so explicitly match on
4216 			 * IRE_LOCAL and IRE_LOOPBACK
4217 			 */
4218 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4219 			    IRE_LOCAL | IRE_LOOPBACK,
4220 			    ipif, zoneid, NULL,
4221 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4222 			if (ire == NULL) {
4223 				/*
4224 				 * packet must have come on a different
4225 				 * interface.
4226 				 * Since a decision has already been made to
4227 				 * deliver the packet, there is no need to test
4228 				 * for SECATTR and ZONEONLY.
4229 				 * Only match on local and broadcast ire's.
4230 				 * See detailed comment above.
4231 				 */
4232 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4233 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4234 				    NULL, MATCH_IRE_TYPE, ipst);
4235 			}
4236 
4237 			if (ire == NULL) {
4238 				/*
4239 				 * This is either a multicast packet or
4240 				 * the address has been removed since
4241 				 * the packet was received.
4242 				 * Return INADDR_ANY so that normal source
4243 				 * selection occurs for the response.
4244 				 */
4245 
4246 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4247 			} else {
4248 				pinfo->ip_pkt_match_addr.s_addr =
4249 				    ire->ire_src_addr;
4250 				ire_refrele(ire);
4251 			}
4252 			ipif_refrele(ipif);
4253 		} else {
4254 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4255 		}
4256 	}
4257 
4258 	pether = (struct ether_header *)((char *)ipha
4259 	    - sizeof (struct ether_header));
4260 	/*
4261 	 * Make sure the interface is an ethernet type, since this option
4262 	 * is currently supported only on this type of interface. Also make
4263 	 * sure we are pointing correctly above db_base.
4264 	 */
4265 
4266 	if ((flags & IPF_RECVSLLA) &&
4267 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4268 	    (ill->ill_type == IFT_ETHER) &&
4269 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4270 
4271 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4272 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4273 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4274 	} else {
4275 		/*
4276 		 * Clear the bit. Indicate to upper layer that IP is not
4277 		 * sending this ancillary info.
4278 		 */
4279 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4280 	}
4281 
4282 	mp->b_datap->db_type = M_CTL;
4283 	mp->b_wptr += sizeof (ip_pktinfo_t);
4284 	mp->b_cont = data_mp;
4285 
4286 	return (mp);
4287 }
4288 
4289 /*
4290  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4291  * part of the bind request.
4292  */
4293 
4294 boolean_t
4295 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4296 {
4297 	ipsec_in_t *ii;
4298 
4299 	ASSERT(policy_mp != NULL);
4300 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4301 
4302 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4303 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4304 
4305 	connp->conn_policy = ii->ipsec_in_policy;
4306 	ii->ipsec_in_policy = NULL;
4307 
4308 	if (ii->ipsec_in_action != NULL) {
4309 		if (connp->conn_latch == NULL) {
4310 			connp->conn_latch = iplatch_create();
4311 			if (connp->conn_latch == NULL)
4312 				return (B_FALSE);
4313 		}
4314 		ipsec_latch_inbound(connp->conn_latch, ii);
4315 	}
4316 	return (B_TRUE);
4317 }
4318 
4319 /*
4320  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4321  * and to arrange for power-fanout assist.  The ULP is identified by
4322  * adding a single byte at the end of the original bind message.
4323  * A ULP other than UDP or TCP that wishes to be recognized passes
4324  * down a bind with a zero length address.
4325  *
4326  * The binding works as follows:
4327  * - A zero byte address means just bind to the protocol.
4328  * - A four byte address is treated as a request to validate
4329  *   that the address is a valid local address, appropriate for
4330  *   an application to bind to. This does not affect any fanout
4331  *   information in IP.
4332  * - A sizeof sin_t byte address is used to bind to only the local address
4333  *   and port.
4334  * - A sizeof ipa_conn_t byte address contains complete fanout information
4335  *   consisting of local and remote addresses and ports.  In
4336  *   this case, the addresses are both validated as appropriate
4337  *   for this operation, and, if so, the information is retained
4338  *   for use in the inbound fanout.
4339  *
4340  * The ULP (except in the zero-length bind) can append an
4341  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4342  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4343  * a copy of the source or destination IRE (source for local bind;
4344  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4345  * policy information contained should be copied on to the conn.
4346  *
4347  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4348  */
4349 mblk_t *
4350 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4351 {
4352 	ssize_t		len;
4353 	struct T_bind_req	*tbr;
4354 	sin_t		*sin;
4355 	ipa_conn_t	*ac;
4356 	uchar_t		*ucp;
4357 	mblk_t		*mp1;
4358 	boolean_t	ire_requested;
4359 	boolean_t	ipsec_policy_set = B_FALSE;
4360 	int		error = 0;
4361 	int		protocol;
4362 	ipa_conn_x_t	*acx;
4363 
4364 	ASSERT(!connp->conn_af_isv6);
4365 	connp->conn_pkt_isv6 = B_FALSE;
4366 
4367 	len = MBLKL(mp);
4368 	if (len < (sizeof (*tbr) + 1)) {
4369 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4370 		    "ip_bind: bogus msg, len %ld", len);
4371 		/* XXX: Need to return something better */
4372 		goto bad_addr;
4373 	}
4374 	/* Back up and extract the protocol identifier. */
4375 	mp->b_wptr--;
4376 	protocol = *mp->b_wptr & 0xFF;
4377 	tbr = (struct T_bind_req *)mp->b_rptr;
4378 	/* Reset the message type in preparation for shipping it back. */
4379 	DB_TYPE(mp) = M_PCPROTO;
4380 
4381 	connp->conn_ulp = (uint8_t)protocol;
4382 
4383 	/*
4384 	 * Check for a zero length address.  This is from a protocol that
4385 	 * wants to register to receive all packets of its type.
4386 	 */
4387 	if (tbr->ADDR_length == 0) {
4388 		/*
4389 		 * These protocols are now intercepted in ip_bind_v6().
4390 		 * Reject protocol-level binds here for now.
4391 		 *
4392 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4393 		 * so that the protocol type cannot be SCTP.
4394 		 */
4395 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4396 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4397 			goto bad_addr;
4398 		}
4399 
4400 		/*
4401 		 *
4402 		 * The udp module never sends down a zero-length address,
4403 		 * and allowing this on a labeled system will break MLP
4404 		 * functionality.
4405 		 */
4406 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4407 			goto bad_addr;
4408 
4409 		if (connp->conn_mac_exempt)
4410 			goto bad_addr;
4411 
4412 		/* No hash here really.  The table is big enough. */
4413 		connp->conn_srcv6 = ipv6_all_zeros;
4414 
4415 		ipcl_proto_insert(connp, protocol);
4416 
4417 		tbr->PRIM_type = T_BIND_ACK;
4418 		return (mp);
4419 	}
4420 
4421 	/* Extract the address pointer from the message. */
4422 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4423 	    tbr->ADDR_length);
4424 	if (ucp == NULL) {
4425 		ip1dbg(("ip_bind: no address\n"));
4426 		goto bad_addr;
4427 	}
4428 	if (!OK_32PTR(ucp)) {
4429 		ip1dbg(("ip_bind: unaligned address\n"));
4430 		goto bad_addr;
4431 	}
4432 	/*
4433 	 * Check for trailing mps.
4434 	 */
4435 
4436 	mp1 = mp->b_cont;
4437 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4438 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4439 
4440 	switch (tbr->ADDR_length) {
4441 	default:
4442 		ip1dbg(("ip_bind: bad address length %d\n",
4443 		    (int)tbr->ADDR_length));
4444 		goto bad_addr;
4445 
4446 	case IP_ADDR_LEN:
4447 		/* Verification of local address only */
4448 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4449 		    ire_requested, ipsec_policy_set, B_FALSE);
4450 		break;
4451 
4452 	case sizeof (sin_t):
4453 		sin = (sin_t *)ucp;
4454 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4455 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4456 		break;
4457 
4458 	case sizeof (ipa_conn_t):
4459 		ac = (ipa_conn_t *)ucp;
4460 		/* For raw socket, the local port is not set. */
4461 		if (ac->ac_lport == 0)
4462 			ac->ac_lport = connp->conn_lport;
4463 		/* Always verify destination reachability. */
4464 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4465 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4466 		    ipsec_policy_set, B_TRUE, B_TRUE);
4467 		break;
4468 
4469 	case sizeof (ipa_conn_x_t):
4470 		acx = (ipa_conn_x_t *)ucp;
4471 		/*
4472 		 * Whether or not to verify destination reachability depends
4473 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4474 		 */
4475 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4476 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4477 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4478 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4479 		break;
4480 	}
4481 	if (error == EINPROGRESS)
4482 		return (NULL);
4483 	else if (error != 0)
4484 		goto bad_addr;
4485 	/*
4486 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4487 	 * We can't do this in ip_bind_insert_ire because the policy
4488 	 * may not have been inherited at that point in time and hence
4489 	 * conn_out_enforce_policy may not be set.
4490 	 */
4491 	mp1 = mp->b_cont;
4492 	if (ire_requested && connp->conn_out_enforce_policy &&
4493 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4494 		ire_t *ire = (ire_t *)mp1->b_rptr;
4495 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4496 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4497 	}
4498 
4499 	/* Send it home. */
4500 	mp->b_datap->db_type = M_PCPROTO;
4501 	tbr->PRIM_type = T_BIND_ACK;
4502 	return (mp);
4503 
4504 bad_addr:
4505 	/*
4506 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4507 	 * a unix errno.
4508 	 */
4509 	if (error > 0)
4510 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4511 	else
4512 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4513 	return (mp);
4514 }
4515 
4516 /*
4517  * Here address is verified to be a valid local address.
4518  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4519  * address is also considered a valid local address.
4520  * In the case of a broadcast/multicast address, however, the
4521  * upper protocol is expected to reset the src address
4522  * to 0 if it sees a IRE_BROADCAST type returned so that
4523  * no packets are emitted with broadcast/multicast address as
4524  * source address (that violates hosts requirements RFC1122)
4525  * The addresses valid for bind are:
4526  *	(1) - INADDR_ANY (0)
4527  *	(2) - IP address of an UP interface
4528  *	(3) - IP address of a DOWN interface
4529  *	(4) - valid local IP broadcast addresses. In this case
4530  *	the conn will only receive packets destined to
4531  *	the specified broadcast address.
4532  *	(5) - a multicast address. In this case
4533  *	the conn will only receive packets destined to
4534  *	the specified multicast address. Note: the
4535  *	application still has to issue an
4536  *	IP_ADD_MEMBERSHIP socket option.
4537  *
4538  * On error, return -1 for TBADADDR otherwise pass the
4539  * errno with TSYSERR reply.
4540  *
4541  * In all the above cases, the bound address must be valid in the current zone.
4542  * When the address is loopback, multicast or broadcast, there might be many
4543  * matching IREs so bind has to look up based on the zone.
4544  *
4545  * Note: lport is in network byte order.
4546  */
4547 int
4548 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4549     boolean_t ire_requested, boolean_t ipsec_policy_set,
4550     boolean_t fanout_insert)
4551 {
4552 	int		error = 0;
4553 	ire_t		*src_ire;
4554 	mblk_t		*policy_mp;
4555 	ipif_t		*ipif;
4556 	zoneid_t	zoneid;
4557 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4558 
4559 	if (ipsec_policy_set) {
4560 		policy_mp = mp->b_cont;
4561 	}
4562 
4563 	/*
4564 	 * If it was previously connected, conn_fully_bound would have
4565 	 * been set.
4566 	 */
4567 	connp->conn_fully_bound = B_FALSE;
4568 
4569 	src_ire = NULL;
4570 	ipif = NULL;
4571 
4572 	zoneid = IPCL_ZONEID(connp);
4573 
4574 	if (src_addr) {
4575 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4576 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4577 		/*
4578 		 * If an address other than 0.0.0.0 is requested,
4579 		 * we verify that it is a valid address for bind
4580 		 * Note: Following code is in if-else-if form for
4581 		 * readability compared to a condition check.
4582 		 */
4583 		/* LINTED - statement has no consequent */
4584 		if (IRE_IS_LOCAL(src_ire)) {
4585 			/*
4586 			 * (2) Bind to address of local UP interface
4587 			 */
4588 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4589 			/*
4590 			 * (4) Bind to broadcast address
4591 			 * Note: permitted only from transports that
4592 			 * request IRE
4593 			 */
4594 			if (!ire_requested)
4595 				error = EADDRNOTAVAIL;
4596 		} else {
4597 			/*
4598 			 * (3) Bind to address of local DOWN interface
4599 			 * (ipif_lookup_addr() looks up all interfaces
4600 			 * but we do not get here for UP interfaces
4601 			 * - case (2) above)
4602 			 * We put the protocol byte back into the mblk
4603 			 * since we may come back via ip_wput_nondata()
4604 			 * later with this mblk if ipif_lookup_addr chooses
4605 			 * to defer processing.
4606 			 */
4607 			*mp->b_wptr++ = (char)connp->conn_ulp;
4608 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4609 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4610 			    &error, ipst)) != NULL) {
4611 				ipif_refrele(ipif);
4612 			} else if (error == EINPROGRESS) {
4613 				if (src_ire != NULL)
4614 					ire_refrele(src_ire);
4615 				return (EINPROGRESS);
4616 			} else if (CLASSD(src_addr)) {
4617 				error = 0;
4618 				if (src_ire != NULL)
4619 					ire_refrele(src_ire);
4620 				/*
4621 				 * (5) bind to multicast address.
4622 				 * Fake out the IRE returned to upper
4623 				 * layer to be a broadcast IRE.
4624 				 */
4625 				src_ire = ire_ctable_lookup(
4626 				    INADDR_BROADCAST, INADDR_ANY,
4627 				    IRE_BROADCAST, NULL, zoneid, NULL,
4628 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4629 				    ipst);
4630 				if (src_ire == NULL || !ire_requested)
4631 					error = EADDRNOTAVAIL;
4632 			} else {
4633 				/*
4634 				 * Not a valid address for bind
4635 				 */
4636 				error = EADDRNOTAVAIL;
4637 			}
4638 			/*
4639 			 * Just to keep it consistent with the processing in
4640 			 * ip_bind_v4()
4641 			 */
4642 			mp->b_wptr--;
4643 		}
4644 		if (error) {
4645 			/* Red Alert!  Attempting to be a bogon! */
4646 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4647 			    ntohl(src_addr)));
4648 			goto bad_addr;
4649 		}
4650 	}
4651 
4652 	/*
4653 	 * Allow setting new policies. For example, disconnects come
4654 	 * down as ipa_t bind. As we would have set conn_policy_cached
4655 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4656 	 * can change after the disconnect.
4657 	 */
4658 	connp->conn_policy_cached = B_FALSE;
4659 
4660 	/*
4661 	 * If not fanout_insert this was just an address verification
4662 	 */
4663 	if (fanout_insert) {
4664 		/*
4665 		 * The addresses have been verified. Time to insert in
4666 		 * the correct fanout list.
4667 		 */
4668 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4669 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4670 		connp->conn_lport = lport;
4671 		connp->conn_fport = 0;
4672 		/*
4673 		 * Do we need to add a check to reject Multicast packets
4674 		 */
4675 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4676 	}
4677 
4678 	if (error == 0) {
4679 		if (ire_requested) {
4680 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4681 				error = -1;
4682 				/* Falls through to bad_addr */
4683 			}
4684 		} else if (ipsec_policy_set) {
4685 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4686 				error = -1;
4687 				/* Falls through to bad_addr */
4688 			}
4689 		}
4690 	}
4691 bad_addr:
4692 	if (error != 0) {
4693 		if (connp->conn_anon_port) {
4694 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4695 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4696 			    B_FALSE);
4697 		}
4698 		connp->conn_mlp_type = mlptSingle;
4699 	}
4700 	if (src_ire != NULL)
4701 		IRE_REFRELE(src_ire);
4702 	if (ipsec_policy_set) {
4703 		ASSERT(policy_mp == mp->b_cont);
4704 		ASSERT(policy_mp != NULL);
4705 		freeb(policy_mp);
4706 		/*
4707 		 * As of now assume that nothing else accompanies
4708 		 * IPSEC_POLICY_SET.
4709 		 */
4710 		mp->b_cont = NULL;
4711 	}
4712 	return (error);
4713 }
4714 
4715 /*
4716  * Verify that both the source and destination addresses
4717  * are valid.  If verify_dst is false, then the destination address may be
4718  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4719  * destination reachability, while tunnels do not.
4720  * Note that we allow connect to broadcast and multicast
4721  * addresses when ire_requested is set. Thus the ULP
4722  * has to check for IRE_BROADCAST and multicast.
4723  *
4724  * Returns zero if ok.
4725  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4726  * (for use with TSYSERR reply).
4727  *
4728  * Note: lport and fport are in network byte order.
4729  */
4730 int
4731 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4732     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4733     boolean_t ire_requested, boolean_t ipsec_policy_set,
4734     boolean_t fanout_insert, boolean_t verify_dst)
4735 {
4736 	ire_t		*src_ire;
4737 	ire_t		*dst_ire;
4738 	int		error = 0;
4739 	int 		protocol;
4740 	mblk_t		*policy_mp;
4741 	ire_t		*sire = NULL;
4742 	ire_t		*md_dst_ire = NULL;
4743 	ire_t		*lso_dst_ire = NULL;
4744 	ill_t		*ill = NULL;
4745 	zoneid_t	zoneid;
4746 	ipaddr_t	src_addr = *src_addrp;
4747 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4748 
4749 	src_ire = dst_ire = NULL;
4750 	protocol = *mp->b_wptr & 0xFF;
4751 
4752 	/*
4753 	 * If we never got a disconnect before, clear it now.
4754 	 */
4755 	connp->conn_fully_bound = B_FALSE;
4756 
4757 	if (ipsec_policy_set) {
4758 		policy_mp = mp->b_cont;
4759 	}
4760 
4761 	zoneid = IPCL_ZONEID(connp);
4762 
4763 	if (CLASSD(dst_addr)) {
4764 		/* Pick up an IRE_BROADCAST */
4765 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4766 		    NULL, zoneid, MBLK_GETLABEL(mp),
4767 		    (MATCH_IRE_RECURSIVE |
4768 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4769 		    MATCH_IRE_SECATTR), ipst);
4770 	} else {
4771 		/*
4772 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4773 		 * and onlink ipif is not found set ENETUNREACH error.
4774 		 */
4775 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4776 			ipif_t *ipif;
4777 
4778 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4779 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4780 			if (ipif == NULL) {
4781 				error = ENETUNREACH;
4782 				goto bad_addr;
4783 			}
4784 			ipif_refrele(ipif);
4785 		}
4786 
4787 		if (connp->conn_nexthop_set) {
4788 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4789 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4790 			    MATCH_IRE_SECATTR, ipst);
4791 		} else {
4792 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4793 			    &sire, zoneid, MBLK_GETLABEL(mp),
4794 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4795 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4796 			    MATCH_IRE_SECATTR), ipst);
4797 		}
4798 	}
4799 	/*
4800 	 * dst_ire can't be a broadcast when not ire_requested.
4801 	 * We also prevent ire's with src address INADDR_ANY to
4802 	 * be used, which are created temporarily for
4803 	 * sending out packets from endpoints that have
4804 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4805 	 * reachable.  If verify_dst is false, the destination needn't be
4806 	 * reachable.
4807 	 *
4808 	 * If we match on a reject or black hole, then we've got a
4809 	 * local failure.  May as well fail out the connect() attempt,
4810 	 * since it's never going to succeed.
4811 	 */
4812 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4813 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4814 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4815 		/*
4816 		 * If we're verifying destination reachability, we always want
4817 		 * to complain here.
4818 		 *
4819 		 * If we're not verifying destination reachability but the
4820 		 * destination has a route, we still want to fail on the
4821 		 * temporary address and broadcast address tests.
4822 		 */
4823 		if (verify_dst || (dst_ire != NULL)) {
4824 			if (ip_debug > 2) {
4825 				pr_addr_dbg("ip_bind_connected: bad connected "
4826 				    "dst %s\n", AF_INET, &dst_addr);
4827 			}
4828 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4829 				error = ENETUNREACH;
4830 			else
4831 				error = EHOSTUNREACH;
4832 			goto bad_addr;
4833 		}
4834 	}
4835 
4836 	/*
4837 	 * We now know that routing will allow us to reach the destination.
4838 	 * Check whether Trusted Solaris policy allows communication with this
4839 	 * host, and pretend that the destination is unreachable if not.
4840 	 *
4841 	 * This is never a problem for TCP, since that transport is known to
4842 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4843 	 * handling.  If the remote is unreachable, it will be detected at that
4844 	 * point, so there's no reason to check it here.
4845 	 *
4846 	 * Note that for sendto (and other datagram-oriented friends), this
4847 	 * check is done as part of the data path label computation instead.
4848 	 * The check here is just to make non-TCP connect() report the right
4849 	 * error.
4850 	 */
4851 	if (dst_ire != NULL && is_system_labeled() &&
4852 	    !IPCL_IS_TCP(connp) &&
4853 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4854 	    connp->conn_mac_exempt, ipst) != 0) {
4855 		error = EHOSTUNREACH;
4856 		if (ip_debug > 2) {
4857 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4858 			    AF_INET, &dst_addr);
4859 		}
4860 		goto bad_addr;
4861 	}
4862 
4863 	/*
4864 	 * If the app does a connect(), it means that it will most likely
4865 	 * send more than 1 packet to the destination.  It makes sense
4866 	 * to clear the temporary flag.
4867 	 */
4868 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4869 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4870 		irb_t *irb = dst_ire->ire_bucket;
4871 
4872 		rw_enter(&irb->irb_lock, RW_WRITER);
4873 		/*
4874 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4875 		 * the lock to guarantee irb_tmp_ire_cnt.
4876 		 */
4877 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4878 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4879 			irb->irb_tmp_ire_cnt--;
4880 		}
4881 		rw_exit(&irb->irb_lock);
4882 	}
4883 
4884 	/*
4885 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4886 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4887 	 * eligibility tests for passive connects are handled separately
4888 	 * through tcp_adapt_ire().  We do this before the source address
4889 	 * selection, because dst_ire may change after a call to
4890 	 * ipif_select_source().  This is a best-effort check, as the
4891 	 * packet for this connection may not actually go through
4892 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4893 	 * calling ip_newroute().  This is why we further check on the
4894 	 * IRE during LSO/Multidata packet transmission in
4895 	 * tcp_lsosend()/tcp_multisend().
4896 	 */
4897 	if (!ipsec_policy_set && dst_ire != NULL &&
4898 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4899 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4900 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4901 			lso_dst_ire = dst_ire;
4902 			IRE_REFHOLD(lso_dst_ire);
4903 		} else if (ipst->ips_ip_multidata_outbound &&
4904 		    ILL_MDT_CAPABLE(ill)) {
4905 			md_dst_ire = dst_ire;
4906 			IRE_REFHOLD(md_dst_ire);
4907 		}
4908 	}
4909 
4910 	if (dst_ire != NULL &&
4911 	    dst_ire->ire_type == IRE_LOCAL &&
4912 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4913 		/*
4914 		 * If the IRE belongs to a different zone, look for a matching
4915 		 * route in the forwarding table and use the source address from
4916 		 * that route.
4917 		 */
4918 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4919 		    zoneid, 0, NULL,
4920 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4921 		    MATCH_IRE_RJ_BHOLE, ipst);
4922 		if (src_ire == NULL) {
4923 			error = EHOSTUNREACH;
4924 			goto bad_addr;
4925 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4926 			if (!(src_ire->ire_type & IRE_HOST))
4927 				error = ENETUNREACH;
4928 			else
4929 				error = EHOSTUNREACH;
4930 			goto bad_addr;
4931 		}
4932 		if (src_addr == INADDR_ANY)
4933 			src_addr = src_ire->ire_src_addr;
4934 		ire_refrele(src_ire);
4935 		src_ire = NULL;
4936 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4937 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4938 			src_addr = sire->ire_src_addr;
4939 			ire_refrele(dst_ire);
4940 			dst_ire = sire;
4941 			sire = NULL;
4942 		} else {
4943 			/*
4944 			 * Pick a source address so that a proper inbound
4945 			 * load spreading would happen.
4946 			 */
4947 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4948 			ipif_t *src_ipif = NULL;
4949 			ire_t *ipif_ire;
4950 
4951 			/*
4952 			 * Supply a local source address such that inbound
4953 			 * load spreading happens.
4954 			 *
4955 			 * Determine the best source address on this ill for
4956 			 * the destination.
4957 			 *
4958 			 * 1) For broadcast, we should return a broadcast ire
4959 			 *    found above so that upper layers know that the
4960 			 *    destination address is a broadcast address.
4961 			 *
4962 			 * 2) If this is part of a group, select a better
4963 			 *    source address so that better inbound load
4964 			 *    balancing happens. Do the same if the ipif
4965 			 *    is DEPRECATED.
4966 			 *
4967 			 * 3) If the outgoing interface is part of a usesrc
4968 			 *    group, then try selecting a source address from
4969 			 *    the usesrc ILL.
4970 			 */
4971 			if ((dst_ire->ire_zoneid != zoneid &&
4972 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4973 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4974 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4975 			    ((dst_ill->ill_group != NULL) ||
4976 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4977 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4978 				/*
4979 				 * If the destination is reachable via a
4980 				 * given gateway, the selected source address
4981 				 * should be in the same subnet as the gateway.
4982 				 * Otherwise, the destination is not reachable.
4983 				 *
4984 				 * If there are no interfaces on the same subnet
4985 				 * as the destination, ipif_select_source gives
4986 				 * first non-deprecated interface which might be
4987 				 * on a different subnet than the gateway.
4988 				 * This is not desirable. Hence pass the dst_ire
4989 				 * source address to ipif_select_source.
4990 				 * It is sure that the destination is reachable
4991 				 * with the dst_ire source address subnet.
4992 				 * So passing dst_ire source address to
4993 				 * ipif_select_source will make sure that the
4994 				 * selected source will be on the same subnet
4995 				 * as dst_ire source address.
4996 				 */
4997 				ipaddr_t saddr =
4998 				    dst_ire->ire_ipif->ipif_src_addr;
4999 				src_ipif = ipif_select_source(dst_ill,
5000 				    saddr, zoneid);
5001 				if (src_ipif != NULL) {
5002 					if (IS_VNI(src_ipif->ipif_ill)) {
5003 						/*
5004 						 * For VNI there is no
5005 						 * interface route
5006 						 */
5007 						src_addr =
5008 						    src_ipif->ipif_src_addr;
5009 					} else {
5010 						ipif_ire =
5011 						    ipif_to_ire(src_ipif);
5012 						if (ipif_ire != NULL) {
5013 							IRE_REFRELE(dst_ire);
5014 							dst_ire = ipif_ire;
5015 						}
5016 						src_addr =
5017 						    dst_ire->ire_src_addr;
5018 					}
5019 					ipif_refrele(src_ipif);
5020 				} else {
5021 					src_addr = dst_ire->ire_src_addr;
5022 				}
5023 			} else {
5024 				src_addr = dst_ire->ire_src_addr;
5025 			}
5026 		}
5027 	}
5028 
5029 	/*
5030 	 * We do ire_route_lookup() here (and not
5031 	 * interface lookup as we assert that
5032 	 * src_addr should only come from an
5033 	 * UP interface for hard binding.
5034 	 */
5035 	ASSERT(src_ire == NULL);
5036 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5037 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5038 	/* src_ire must be a local|loopback */
5039 	if (!IRE_IS_LOCAL(src_ire)) {
5040 		if (ip_debug > 2) {
5041 			pr_addr_dbg("ip_bind_connected: bad connected "
5042 			    "src %s\n", AF_INET, &src_addr);
5043 		}
5044 		error = EADDRNOTAVAIL;
5045 		goto bad_addr;
5046 	}
5047 
5048 	/*
5049 	 * If the source address is a loopback address, the
5050 	 * destination had best be local or multicast.
5051 	 * The transports that can't handle multicast will reject
5052 	 * those addresses.
5053 	 */
5054 	if (src_ire->ire_type == IRE_LOOPBACK &&
5055 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5056 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5057 		error = -1;
5058 		goto bad_addr;
5059 	}
5060 
5061 	/*
5062 	 * Allow setting new policies. For example, disconnects come
5063 	 * down as ipa_t bind. As we would have set conn_policy_cached
5064 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5065 	 * can change after the disconnect.
5066 	 */
5067 	connp->conn_policy_cached = B_FALSE;
5068 
5069 	/*
5070 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5071 	 * can handle their passed-in conn's.
5072 	 */
5073 
5074 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5075 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5076 	connp->conn_lport = lport;
5077 	connp->conn_fport = fport;
5078 	*src_addrp = src_addr;
5079 
5080 	ASSERT(!(ipsec_policy_set && ire_requested));
5081 	if (ire_requested) {
5082 		iulp_t *ulp_info = NULL;
5083 
5084 		/*
5085 		 * Note that sire will not be NULL if this is an off-link
5086 		 * connection and there is not cache for that dest yet.
5087 		 *
5088 		 * XXX Because of an existing bug, if there are multiple
5089 		 * default routes, the IRE returned now may not be the actual
5090 		 * default route used (default routes are chosen in a
5091 		 * round robin fashion).  So if the metrics for different
5092 		 * default routes are different, we may return the wrong
5093 		 * metrics.  This will not be a problem if the existing
5094 		 * bug is fixed.
5095 		 */
5096 		if (sire != NULL) {
5097 			ulp_info = &(sire->ire_uinfo);
5098 		}
5099 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5100 			error = -1;
5101 			goto bad_addr;
5102 		}
5103 	} else if (ipsec_policy_set) {
5104 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5105 			error = -1;
5106 			goto bad_addr;
5107 		}
5108 	}
5109 
5110 	/*
5111 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5112 	 * we'll cache that.  If we don't, we'll inherit global policy.
5113 	 *
5114 	 * We can't insert until the conn reflects the policy. Note that
5115 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5116 	 * connections where we don't have a policy. This is to prevent
5117 	 * global policy lookups in the inbound path.
5118 	 *
5119 	 * If we insert before we set conn_policy_cached,
5120 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5121 	 * because global policy cound be non-empty. We normally call
5122 	 * ipsec_check_policy() for conn_policy_cached connections only if
5123 	 * ipc_in_enforce_policy is set. But in this case,
5124 	 * conn_policy_cached can get set anytime since we made the
5125 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5126 	 * called, which will make the above assumption false.  Thus, we
5127 	 * need to insert after we set conn_policy_cached.
5128 	 */
5129 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5130 		goto bad_addr;
5131 
5132 	if (fanout_insert) {
5133 		/*
5134 		 * The addresses have been verified. Time to insert in
5135 		 * the correct fanout list.
5136 		 */
5137 		error = ipcl_conn_insert(connp, protocol, src_addr,
5138 		    dst_addr, connp->conn_ports);
5139 	}
5140 
5141 	if (error == 0) {
5142 		connp->conn_fully_bound = B_TRUE;
5143 		/*
5144 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5145 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5146 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5147 		 * ip_xxinfo_return(), which performs further checks
5148 		 * against them and upon success, returns the LSO/MDT info
5149 		 * mblk which we will attach to the bind acknowledgment.
5150 		 */
5151 		if (lso_dst_ire != NULL) {
5152 			mblk_t *lsoinfo_mp;
5153 
5154 			ASSERT(ill->ill_lso_capab != NULL);
5155 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5156 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5157 				linkb(mp, lsoinfo_mp);
5158 		} else if (md_dst_ire != NULL) {
5159 			mblk_t *mdinfo_mp;
5160 
5161 			ASSERT(ill->ill_mdt_capab != NULL);
5162 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5163 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5164 				linkb(mp, mdinfo_mp);
5165 		}
5166 	}
5167 bad_addr:
5168 	if (ipsec_policy_set) {
5169 		ASSERT(policy_mp == mp->b_cont);
5170 		ASSERT(policy_mp != NULL);
5171 		freeb(policy_mp);
5172 		/*
5173 		 * As of now assume that nothing else accompanies
5174 		 * IPSEC_POLICY_SET.
5175 		 */
5176 		mp->b_cont = NULL;
5177 	}
5178 	if (src_ire != NULL)
5179 		IRE_REFRELE(src_ire);
5180 	if (dst_ire != NULL)
5181 		IRE_REFRELE(dst_ire);
5182 	if (sire != NULL)
5183 		IRE_REFRELE(sire);
5184 	if (md_dst_ire != NULL)
5185 		IRE_REFRELE(md_dst_ire);
5186 	if (lso_dst_ire != NULL)
5187 		IRE_REFRELE(lso_dst_ire);
5188 	return (error);
5189 }
5190 
5191 /*
5192  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5193  * Prefers dst_ire over src_ire.
5194  */
5195 static boolean_t
5196 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5197 {
5198 	mblk_t	*mp1;
5199 	ire_t *ret_ire = NULL;
5200 
5201 	mp1 = mp->b_cont;
5202 	ASSERT(mp1 != NULL);
5203 
5204 	if (ire != NULL) {
5205 		/*
5206 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5207 		 * appended mblk. Its <upper protocol>'s
5208 		 * job to make sure there is room.
5209 		 */
5210 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5211 			return (0);
5212 
5213 		mp1->b_datap->db_type = IRE_DB_TYPE;
5214 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5215 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5216 		ret_ire = (ire_t *)mp1->b_rptr;
5217 		/*
5218 		 * Pass the latest setting of the ip_path_mtu_discovery and
5219 		 * copy the ulp info if any.
5220 		 */
5221 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5222 		    IPH_DF : 0;
5223 		if (ulp_info != NULL) {
5224 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5225 			    sizeof (iulp_t));
5226 		}
5227 		ret_ire->ire_mp = mp1;
5228 	} else {
5229 		/*
5230 		 * No IRE was found. Remove IRE mblk.
5231 		 */
5232 		mp->b_cont = mp1->b_cont;
5233 		freeb(mp1);
5234 	}
5235 
5236 	return (1);
5237 }
5238 
5239 /*
5240  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5241  * the final piece where we don't.  Return a pointer to the first mblk in the
5242  * result, and update the pointer to the next mblk to chew on.  If anything
5243  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5244  * NULL pointer.
5245  */
5246 mblk_t *
5247 ip_carve_mp(mblk_t **mpp, ssize_t len)
5248 {
5249 	mblk_t	*mp0;
5250 	mblk_t	*mp1;
5251 	mblk_t	*mp2;
5252 
5253 	if (!len || !mpp || !(mp0 = *mpp))
5254 		return (NULL);
5255 	/* If we aren't going to consume the first mblk, we need a dup. */
5256 	if (mp0->b_wptr - mp0->b_rptr > len) {
5257 		mp1 = dupb(mp0);
5258 		if (mp1) {
5259 			/* Partition the data between the two mblks. */
5260 			mp1->b_wptr = mp1->b_rptr + len;
5261 			mp0->b_rptr = mp1->b_wptr;
5262 			/*
5263 			 * after adjustments if mblk not consumed is now
5264 			 * unaligned, try to align it. If this fails free
5265 			 * all messages and let upper layer recover.
5266 			 */
5267 			if (!OK_32PTR(mp0->b_rptr)) {
5268 				if (!pullupmsg(mp0, -1)) {
5269 					freemsg(mp0);
5270 					freemsg(mp1);
5271 					*mpp = NULL;
5272 					return (NULL);
5273 				}
5274 			}
5275 		}
5276 		return (mp1);
5277 	}
5278 	/* Eat through as many mblks as we need to get len bytes. */
5279 	len -= mp0->b_wptr - mp0->b_rptr;
5280 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5281 		if (mp2->b_wptr - mp2->b_rptr > len) {
5282 			/*
5283 			 * We won't consume the entire last mblk.  Like
5284 			 * above, dup and partition it.
5285 			 */
5286 			mp1->b_cont = dupb(mp2);
5287 			mp1 = mp1->b_cont;
5288 			if (!mp1) {
5289 				/*
5290 				 * Trouble.  Rather than go to a lot of
5291 				 * trouble to clean up, we free the messages.
5292 				 * This won't be any worse than losing it on
5293 				 * the wire.
5294 				 */
5295 				freemsg(mp0);
5296 				freemsg(mp2);
5297 				*mpp = NULL;
5298 				return (NULL);
5299 			}
5300 			mp1->b_wptr = mp1->b_rptr + len;
5301 			mp2->b_rptr = mp1->b_wptr;
5302 			/*
5303 			 * after adjustments if mblk not consumed is now
5304 			 * unaligned, try to align it. If this fails free
5305 			 * all messages and let upper layer recover.
5306 			 */
5307 			if (!OK_32PTR(mp2->b_rptr)) {
5308 				if (!pullupmsg(mp2, -1)) {
5309 					freemsg(mp0);
5310 					freemsg(mp2);
5311 					*mpp = NULL;
5312 					return (NULL);
5313 				}
5314 			}
5315 			*mpp = mp2;
5316 			return (mp0);
5317 		}
5318 		/* Decrement len by the amount we just got. */
5319 		len -= mp2->b_wptr - mp2->b_rptr;
5320 	}
5321 	/*
5322 	 * len should be reduced to zero now.  If not our caller has
5323 	 * screwed up.
5324 	 */
5325 	if (len) {
5326 		/* Shouldn't happen! */
5327 		freemsg(mp0);
5328 		*mpp = NULL;
5329 		return (NULL);
5330 	}
5331 	/*
5332 	 * We consumed up to exactly the end of an mblk.  Detach the part
5333 	 * we are returning from the rest of the chain.
5334 	 */
5335 	mp1->b_cont = NULL;
5336 	*mpp = mp2;
5337 	return (mp0);
5338 }
5339 
5340 /* The ill stream is being unplumbed. Called from ip_close */
5341 int
5342 ip_modclose(ill_t *ill)
5343 {
5344 	boolean_t success;
5345 	ipsq_t	*ipsq;
5346 	ipif_t	*ipif;
5347 	queue_t	*q = ill->ill_rq;
5348 	ip_stack_t	*ipst = ill->ill_ipst;
5349 	clock_t timeout;
5350 
5351 	/*
5352 	 * Wait for the ACKs of all deferred control messages to be processed.
5353 	 * In particular, we wait for a potential capability reset initiated
5354 	 * in ip_sioctl_plink() to complete before proceeding.
5355 	 *
5356 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5357 	 * in case the driver never replies.
5358 	 */
5359 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5360 	mutex_enter(&ill->ill_lock);
5361 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5362 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5363 			/* Timeout */
5364 			break;
5365 		}
5366 	}
5367 	mutex_exit(&ill->ill_lock);
5368 
5369 	/*
5370 	 * Forcibly enter the ipsq after some delay. This is to take
5371 	 * care of the case when some ioctl does not complete because
5372 	 * we sent a control message to the driver and it did not
5373 	 * send us a reply. We want to be able to at least unplumb
5374 	 * and replumb rather than force the user to reboot the system.
5375 	 */
5376 	success = ipsq_enter(ill, B_FALSE);
5377 
5378 	/*
5379 	 * Open/close/push/pop is guaranteed to be single threaded
5380 	 * per stream by STREAMS. FS guarantees that all references
5381 	 * from top are gone before close is called. So there can't
5382 	 * be another close thread that has set CONDEMNED on this ill.
5383 	 * and cause ipsq_enter to return failure.
5384 	 */
5385 	ASSERT(success);
5386 	ipsq = ill->ill_phyint->phyint_ipsq;
5387 
5388 	/*
5389 	 * Mark it condemned. No new reference will be made to this ill.
5390 	 * Lookup functions will return an error. Threads that try to
5391 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5392 	 * that the refcnt will drop down to zero.
5393 	 */
5394 	mutex_enter(&ill->ill_lock);
5395 	ill->ill_state_flags |= ILL_CONDEMNED;
5396 	for (ipif = ill->ill_ipif; ipif != NULL;
5397 	    ipif = ipif->ipif_next) {
5398 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5399 	}
5400 	/*
5401 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5402 	 * returns  error if ILL_CONDEMNED is set
5403 	 */
5404 	cv_broadcast(&ill->ill_cv);
5405 	mutex_exit(&ill->ill_lock);
5406 
5407 	/*
5408 	 * Send all the deferred DLPI messages downstream which came in
5409 	 * during the small window right before ipsq_enter(). We do this
5410 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5411 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5412 	 */
5413 	ill_dlpi_send_deferred(ill);
5414 
5415 	/*
5416 	 * Shut down fragmentation reassembly.
5417 	 * ill_frag_timer won't start a timer again.
5418 	 * Now cancel any existing timer
5419 	 */
5420 	(void) untimeout(ill->ill_frag_timer_id);
5421 	(void) ill_frag_timeout(ill, 0);
5422 
5423 	/*
5424 	 * If MOVE was in progress, clear the
5425 	 * move_in_progress fields also.
5426 	 */
5427 	if (ill->ill_move_in_progress) {
5428 		ILL_CLEAR_MOVE(ill);
5429 	}
5430 
5431 	/*
5432 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5433 	 * this ill. Then wait for the refcnts to drop to zero.
5434 	 * ill_is_freeable checks whether the ill is really quiescent.
5435 	 * Then make sure that threads that are waiting to enter the
5436 	 * ipsq have seen the error returned by ipsq_enter and have
5437 	 * gone away. Then we call ill_delete_tail which does the
5438 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5439 	 */
5440 	ill_delete(ill);
5441 	mutex_enter(&ill->ill_lock);
5442 	while (!ill_is_freeable(ill))
5443 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5444 	while (ill->ill_waiters)
5445 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5446 
5447 	mutex_exit(&ill->ill_lock);
5448 
5449 	/*
5450 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5451 	 * it held until the end of the function since the cleanup
5452 	 * below needs to be able to use the ip_stack_t.
5453 	 */
5454 	netstack_hold(ipst->ips_netstack);
5455 
5456 	/* qprocsoff is called in ill_delete_tail */
5457 	ill_delete_tail(ill);
5458 	ASSERT(ill->ill_ipst == NULL);
5459 
5460 	/*
5461 	 * Walk through all upper (conn) streams and qenable
5462 	 * those that have queued data.
5463 	 * close synchronization needs this to
5464 	 * be done to ensure that all upper layers blocked
5465 	 * due to flow control to the closing device
5466 	 * get unblocked.
5467 	 */
5468 	ip1dbg(("ip_wsrv: walking\n"));
5469 	conn_walk_drain(ipst);
5470 
5471 	mutex_enter(&ipst->ips_ip_mi_lock);
5472 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5473 	mutex_exit(&ipst->ips_ip_mi_lock);
5474 
5475 	/*
5476 	 * credp could be null if the open didn't succeed and ip_modopen
5477 	 * itself calls ip_close.
5478 	 */
5479 	if (ill->ill_credp != NULL)
5480 		crfree(ill->ill_credp);
5481 
5482 	mutex_enter(&ill->ill_lock);
5483 	ill_nic_info_dispatch(ill);
5484 	mutex_exit(&ill->ill_lock);
5485 
5486 	/*
5487 	 * Now we are done with the module close pieces that
5488 	 * need the netstack_t.
5489 	 */
5490 	netstack_rele(ipst->ips_netstack);
5491 
5492 	mi_close_free((IDP)ill);
5493 	q->q_ptr = WR(q)->q_ptr = NULL;
5494 
5495 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5496 
5497 	return (0);
5498 }
5499 
5500 /*
5501  * This is called as part of close() for IP, UDP, ICMP, and RTS
5502  * in order to quiesce the conn.
5503  */
5504 void
5505 ip_quiesce_conn(conn_t *connp)
5506 {
5507 	boolean_t	drain_cleanup_reqd = B_FALSE;
5508 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5509 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5510 	ip_stack_t	*ipst;
5511 
5512 	ASSERT(!IPCL_IS_TCP(connp));
5513 	ipst = connp->conn_netstack->netstack_ip;
5514 
5515 	/*
5516 	 * Mark the conn as closing, and this conn must not be
5517 	 * inserted in future into any list. Eg. conn_drain_insert(),
5518 	 * won't insert this conn into the conn_drain_list.
5519 	 * Similarly ill_pending_mp_add() will not add any mp to
5520 	 * the pending mp list, after this conn has started closing.
5521 	 *
5522 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5523 	 * cannot get set henceforth.
5524 	 */
5525 	mutex_enter(&connp->conn_lock);
5526 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5527 	connp->conn_state_flags |= CONN_CLOSING;
5528 	if (connp->conn_idl != NULL)
5529 		drain_cleanup_reqd = B_TRUE;
5530 	if (connp->conn_oper_pending_ill != NULL)
5531 		conn_ioctl_cleanup_reqd = B_TRUE;
5532 	if (connp->conn_dhcpinit_ill != NULL) {
5533 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5534 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5535 		connp->conn_dhcpinit_ill = NULL;
5536 	}
5537 	if (connp->conn_ilg_inuse != 0)
5538 		ilg_cleanup_reqd = B_TRUE;
5539 	mutex_exit(&connp->conn_lock);
5540 
5541 	if (conn_ioctl_cleanup_reqd)
5542 		conn_ioctl_cleanup(connp);
5543 
5544 	if (is_system_labeled() && connp->conn_anon_port) {
5545 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5546 		    connp->conn_mlp_type, connp->conn_ulp,
5547 		    ntohs(connp->conn_lport), B_FALSE);
5548 		connp->conn_anon_port = 0;
5549 	}
5550 	connp->conn_mlp_type = mlptSingle;
5551 
5552 	/*
5553 	 * Remove this conn from any fanout list it is on.
5554 	 * and then wait for any threads currently operating
5555 	 * on this endpoint to finish
5556 	 */
5557 	ipcl_hash_remove(connp);
5558 
5559 	/*
5560 	 * Remove this conn from the drain list, and do
5561 	 * any other cleanup that may be required.
5562 	 * (Only non-tcp streams may have a non-null conn_idl.
5563 	 * TCP streams are never flow controlled, and
5564 	 * conn_idl will be null)
5565 	 */
5566 	if (drain_cleanup_reqd)
5567 		conn_drain_tail(connp, B_TRUE);
5568 
5569 	if (connp == ipst->ips_ip_g_mrouter)
5570 		(void) ip_mrouter_done(NULL, ipst);
5571 
5572 	if (ilg_cleanup_reqd)
5573 		ilg_delete_all(connp);
5574 
5575 	conn_delete_ire(connp, NULL);
5576 
5577 	/*
5578 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5579 	 * callers from write side can't be there now because close
5580 	 * is in progress. The only other caller is ipcl_walk
5581 	 * which checks for the condemned flag.
5582 	 */
5583 	mutex_enter(&connp->conn_lock);
5584 	connp->conn_state_flags |= CONN_CONDEMNED;
5585 	while (connp->conn_ref != 1)
5586 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5587 	connp->conn_state_flags |= CONN_QUIESCED;
5588 	mutex_exit(&connp->conn_lock);
5589 }
5590 
5591 /* ARGSUSED */
5592 int
5593 ip_close(queue_t *q, int flags)
5594 {
5595 	conn_t		*connp;
5596 
5597 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5598 
5599 	/*
5600 	 * Call the appropriate delete routine depending on whether this is
5601 	 * a module or device.
5602 	 */
5603 	if (WR(q)->q_next != NULL) {
5604 		/* This is a module close */
5605 		return (ip_modclose((ill_t *)q->q_ptr));
5606 	}
5607 
5608 	connp = q->q_ptr;
5609 	ip_quiesce_conn(connp);
5610 
5611 	qprocsoff(q);
5612 
5613 	/*
5614 	 * Now we are truly single threaded on this stream, and can
5615 	 * delete the things hanging off the connp, and finally the connp.
5616 	 * We removed this connp from the fanout list, it cannot be
5617 	 * accessed thru the fanouts, and we already waited for the
5618 	 * conn_ref to drop to 0. We are already in close, so
5619 	 * there cannot be any other thread from the top. qprocsoff
5620 	 * has completed, and service has completed or won't run in
5621 	 * future.
5622 	 */
5623 	ASSERT(connp->conn_ref == 1);
5624 
5625 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5626 
5627 	connp->conn_ref--;
5628 	ipcl_conn_destroy(connp);
5629 
5630 	q->q_ptr = WR(q)->q_ptr = NULL;
5631 	return (0);
5632 }
5633 
5634 /*
5635  * Wapper around putnext() so that ip_rts_request can merely use
5636  * conn_recv.
5637  */
5638 /*ARGSUSED2*/
5639 static void
5640 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5641 {
5642 	conn_t *connp = (conn_t *)arg1;
5643 
5644 	putnext(connp->conn_rq, mp);
5645 }
5646 
5647 /* Return the IP checksum for the IP header at "iph". */
5648 uint16_t
5649 ip_csum_hdr(ipha_t *ipha)
5650 {
5651 	uint16_t	*uph;
5652 	uint32_t	sum;
5653 	int		opt_len;
5654 
5655 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5656 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5657 	uph = (uint16_t *)ipha;
5658 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5659 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5660 	if (opt_len > 0) {
5661 		do {
5662 			sum += uph[10];
5663 			sum += uph[11];
5664 			uph += 2;
5665 		} while (--opt_len);
5666 	}
5667 	sum = (sum & 0xFFFF) + (sum >> 16);
5668 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5669 	if (sum == 0xffff)
5670 		sum = 0;
5671 	return ((uint16_t)sum);
5672 }
5673 
5674 /*
5675  * Called when the module is about to be unloaded
5676  */
5677 void
5678 ip_ddi_destroy(void)
5679 {
5680 	tnet_fini();
5681 
5682 	icmp_ddi_destroy();
5683 	rts_ddi_destroy();
5684 	udp_ddi_destroy();
5685 	sctp_ddi_g_destroy();
5686 	tcp_ddi_g_destroy();
5687 	ipsec_policy_g_destroy();
5688 	ipcl_g_destroy();
5689 	ip_net_g_destroy();
5690 	ip_ire_g_fini();
5691 	inet_minor_destroy(ip_minor_arena_sa);
5692 #if defined(_LP64)
5693 	inet_minor_destroy(ip_minor_arena_la);
5694 #endif
5695 
5696 #ifdef DEBUG
5697 	list_destroy(&ip_thread_list);
5698 	rw_destroy(&ip_thread_rwlock);
5699 	tsd_destroy(&ip_thread_data);
5700 #endif
5701 
5702 	netstack_unregister(NS_IP);
5703 }
5704 
5705 /*
5706  * First step in cleanup.
5707  */
5708 /* ARGSUSED */
5709 static void
5710 ip_stack_shutdown(netstackid_t stackid, void *arg)
5711 {
5712 	ip_stack_t *ipst = (ip_stack_t *)arg;
5713 
5714 #ifdef NS_DEBUG
5715 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5716 #endif
5717 
5718 	/* Get rid of loopback interfaces and their IREs */
5719 	ip_loopback_cleanup(ipst);
5720 }
5721 
5722 /*
5723  * Free the IP stack instance.
5724  */
5725 static void
5726 ip_stack_fini(netstackid_t stackid, void *arg)
5727 {
5728 	ip_stack_t *ipst = (ip_stack_t *)arg;
5729 	int ret;
5730 
5731 #ifdef NS_DEBUG
5732 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5733 #endif
5734 	ipv4_hook_destroy(ipst);
5735 	ipv6_hook_destroy(ipst);
5736 	ip_net_destroy(ipst);
5737 
5738 	rw_destroy(&ipst->ips_srcid_lock);
5739 
5740 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5741 	ipst->ips_ip_mibkp = NULL;
5742 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5743 	ipst->ips_icmp_mibkp = NULL;
5744 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5745 	ipst->ips_ip_kstat = NULL;
5746 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5747 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5748 	ipst->ips_ip6_kstat = NULL;
5749 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5750 
5751 	nd_free(&ipst->ips_ip_g_nd);
5752 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5753 	ipst->ips_param_arr = NULL;
5754 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5755 	ipst->ips_ndp_arr = NULL;
5756 
5757 	ip_mrouter_stack_destroy(ipst);
5758 
5759 	mutex_destroy(&ipst->ips_ip_mi_lock);
5760 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5761 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5762 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5763 
5764 	ret = untimeout(ipst->ips_igmp_timeout_id);
5765 	if (ret == -1) {
5766 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5767 	} else {
5768 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5769 		ipst->ips_igmp_timeout_id = 0;
5770 	}
5771 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5772 	if (ret == -1) {
5773 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5774 	} else {
5775 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5776 		ipst->ips_igmp_slowtimeout_id = 0;
5777 	}
5778 	ret = untimeout(ipst->ips_mld_timeout_id);
5779 	if (ret == -1) {
5780 		ASSERT(ipst->ips_mld_timeout_id == 0);
5781 	} else {
5782 		ASSERT(ipst->ips_mld_timeout_id != 0);
5783 		ipst->ips_mld_timeout_id = 0;
5784 	}
5785 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5786 	if (ret == -1) {
5787 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5788 	} else {
5789 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5790 		ipst->ips_mld_slowtimeout_id = 0;
5791 	}
5792 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5793 	if (ret == -1) {
5794 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5795 	} else {
5796 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5797 		ipst->ips_ip_ire_expire_id = 0;
5798 	}
5799 
5800 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5801 	mutex_destroy(&ipst->ips_mld_timer_lock);
5802 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5803 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5804 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5805 	rw_destroy(&ipst->ips_ill_g_lock);
5806 
5807 	ip_ire_fini(ipst);
5808 	ip6_asp_free(ipst);
5809 	conn_drain_fini(ipst);
5810 	ipcl_destroy(ipst);
5811 
5812 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5813 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5814 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5815 	ipst->ips_ndp4 = NULL;
5816 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5817 	ipst->ips_ndp6 = NULL;
5818 
5819 	if (ipst->ips_loopback_ksp != NULL) {
5820 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5821 		ipst->ips_loopback_ksp = NULL;
5822 	}
5823 
5824 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5825 	ipst->ips_phyint_g_list = NULL;
5826 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5827 	ipst->ips_ill_g_heads = NULL;
5828 
5829 	kmem_free(ipst, sizeof (*ipst));
5830 }
5831 
5832 /*
5833  * This function is called from the TSD destructor, and is used to debug
5834  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5835  * details.
5836  */
5837 static void
5838 ip_thread_exit(void *phash)
5839 {
5840 	th_hash_t *thh = phash;
5841 
5842 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5843 	list_remove(&ip_thread_list, thh);
5844 	rw_exit(&ip_thread_rwlock);
5845 	mod_hash_destroy_hash(thh->thh_hash);
5846 	kmem_free(thh, sizeof (*thh));
5847 }
5848 
5849 /*
5850  * Called when the IP kernel module is loaded into the kernel
5851  */
5852 void
5853 ip_ddi_init(void)
5854 {
5855 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5856 
5857 	/*
5858 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5859 	 * initial devices: ip, ip6, tcp, tcp6.
5860 	 */
5861 	/*
5862 	 * If this is a 64-bit kernel, then create two separate arenas -
5863 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5864 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5865 	 */
5866 	ip_minor_arena_la = NULL;
5867 	ip_minor_arena_sa = NULL;
5868 #if defined(_LP64)
5869 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5870 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5871 		cmn_err(CE_PANIC,
5872 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5873 	}
5874 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5875 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5876 		cmn_err(CE_PANIC,
5877 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5878 	}
5879 #else
5880 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5881 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5882 		cmn_err(CE_PANIC,
5883 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5884 	}
5885 #endif
5886 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5887 
5888 	ipcl_g_init();
5889 	ip_ire_g_init();
5890 	ip_net_g_init();
5891 
5892 #ifdef DEBUG
5893 	tsd_create(&ip_thread_data, ip_thread_exit);
5894 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5895 	list_create(&ip_thread_list, sizeof (th_hash_t),
5896 	    offsetof(th_hash_t, thh_link));
5897 #endif
5898 
5899 	/*
5900 	 * We want to be informed each time a stack is created or
5901 	 * destroyed in the kernel, so we can maintain the
5902 	 * set of udp_stack_t's.
5903 	 */
5904 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5905 	    ip_stack_fini);
5906 
5907 	ipsec_policy_g_init();
5908 	tcp_ddi_g_init();
5909 	sctp_ddi_g_init();
5910 
5911 	tnet_init();
5912 
5913 	udp_ddi_init();
5914 	rts_ddi_init();
5915 	icmp_ddi_init();
5916 }
5917 
5918 /*
5919  * Initialize the IP stack instance.
5920  */
5921 static void *
5922 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5923 {
5924 	ip_stack_t	*ipst;
5925 	ipparam_t	*pa;
5926 	ipndp_t		*na;
5927 
5928 #ifdef NS_DEBUG
5929 	printf("ip_stack_init(stack %d)\n", stackid);
5930 #endif
5931 
5932 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5933 	ipst->ips_netstack = ns;
5934 
5935 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5936 	    KM_SLEEP);
5937 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5938 	    KM_SLEEP);
5939 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5940 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5941 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5942 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5943 
5944 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5945 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5946 	ipst->ips_igmp_deferred_next = INFINITY;
5947 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5948 	ipst->ips_mld_deferred_next = INFINITY;
5949 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5950 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5951 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5952 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5953 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5954 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5955 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5956 
5957 	ipcl_init(ipst);
5958 	ip_ire_init(ipst);
5959 	ip6_asp_init(ipst);
5960 	ipif_init(ipst);
5961 	conn_drain_init(ipst);
5962 	ip_mrouter_stack_init(ipst);
5963 
5964 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5965 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5966 
5967 	ipst->ips_ip_multirt_log_interval = 1000;
5968 
5969 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5970 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5971 	ipst->ips_ill_index = 1;
5972 
5973 	ipst->ips_saved_ip_g_forward = -1;
5974 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5975 
5976 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5977 	ipst->ips_param_arr = pa;
5978 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5979 
5980 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5981 	ipst->ips_ndp_arr = na;
5982 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5983 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5984 	    (caddr_t)&ipst->ips_ip_g_forward;
5985 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5986 	    (caddr_t)&ipst->ips_ipv6_forward;
5987 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5988 	    "ip_cgtp_filter") == 0);
5989 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5990 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5991 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5992 	    "ipmp_hook_emulation") == 0);
5993 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5994 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5995 
5996 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5997 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5998 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5999 
6000 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6001 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6002 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6003 	ipst->ips_ip6_kstat =
6004 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6005 
6006 	ipst->ips_ipmp_enable_failback = B_TRUE;
6007 
6008 	ipst->ips_ip_src_id = 1;
6009 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6010 
6011 	ip_net_init(ipst, ns);
6012 	ipv4_hook_init(ipst);
6013 	ipv6_hook_init(ipst);
6014 
6015 	return (ipst);
6016 }
6017 
6018 /*
6019  * Allocate and initialize a DLPI template of the specified length.  (May be
6020  * called as writer.)
6021  */
6022 mblk_t *
6023 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6024 {
6025 	mblk_t	*mp;
6026 
6027 	mp = allocb(len, BPRI_MED);
6028 	if (!mp)
6029 		return (NULL);
6030 
6031 	/*
6032 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6033 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6034 	 * that other DLPI are M_PROTO.
6035 	 */
6036 	if (prim == DL_INFO_REQ) {
6037 		mp->b_datap->db_type = M_PCPROTO;
6038 	} else {
6039 		mp->b_datap->db_type = M_PROTO;
6040 	}
6041 
6042 	mp->b_wptr = mp->b_rptr + len;
6043 	bzero(mp->b_rptr, len);
6044 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6045 	return (mp);
6046 }
6047 
6048 /*
6049  * Debug formatting routine.  Returns a character string representation of the
6050  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6051  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6052  *
6053  * Once the ndd table-printing interfaces are removed, this can be changed to
6054  * standard dotted-decimal form.
6055  */
6056 char *
6057 ip_dot_addr(ipaddr_t addr, char *buf)
6058 {
6059 	uint8_t *ap = (uint8_t *)&addr;
6060 
6061 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6062 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6063 	return (buf);
6064 }
6065 
6066 /*
6067  * Write the given MAC address as a printable string in the usual colon-
6068  * separated format.
6069  */
6070 const char *
6071 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6072 {
6073 	char *bp;
6074 
6075 	if (alen == 0 || buflen < 4)
6076 		return ("?");
6077 	bp = buf;
6078 	for (;;) {
6079 		/*
6080 		 * If there are more MAC address bytes available, but we won't
6081 		 * have any room to print them, then add "..." to the string
6082 		 * instead.  See below for the 'magic number' explanation.
6083 		 */
6084 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6085 			(void) strcpy(bp, "...");
6086 			break;
6087 		}
6088 		(void) sprintf(bp, "%02x", *addr++);
6089 		bp += 2;
6090 		if (--alen == 0)
6091 			break;
6092 		*bp++ = ':';
6093 		buflen -= 3;
6094 		/*
6095 		 * At this point, based on the first 'if' statement above,
6096 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6097 		 * buflen >= 4.  The first case leaves room for the final "xx"
6098 		 * number and trailing NUL byte.  The second leaves room for at
6099 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6100 		 * that statement.
6101 		 */
6102 	}
6103 	return (buf);
6104 }
6105 
6106 /*
6107  * Send an ICMP error after patching up the packet appropriately.  Returns
6108  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6109  */
6110 static boolean_t
6111 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6112     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6113     zoneid_t zoneid, ip_stack_t *ipst)
6114 {
6115 	ipha_t *ipha;
6116 	mblk_t *first_mp;
6117 	boolean_t secure;
6118 	unsigned char db_type;
6119 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6120 
6121 	first_mp = mp;
6122 	if (mctl_present) {
6123 		mp = mp->b_cont;
6124 		secure = ipsec_in_is_secure(first_mp);
6125 		ASSERT(mp != NULL);
6126 	} else {
6127 		/*
6128 		 * If this is an ICMP error being reported - which goes
6129 		 * up as M_CTLs, we need to convert them to M_DATA till
6130 		 * we finish checking with global policy because
6131 		 * ipsec_check_global_policy() assumes M_DATA as clear
6132 		 * and M_CTL as secure.
6133 		 */
6134 		db_type = DB_TYPE(mp);
6135 		DB_TYPE(mp) = M_DATA;
6136 		secure = B_FALSE;
6137 	}
6138 	/*
6139 	 * We are generating an icmp error for some inbound packet.
6140 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6141 	 * Before we generate an error, check with global policy
6142 	 * to see whether this is allowed to enter the system. As
6143 	 * there is no "conn", we are checking with global policy.
6144 	 */
6145 	ipha = (ipha_t *)mp->b_rptr;
6146 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6147 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6148 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6149 		if (first_mp == NULL)
6150 			return (B_FALSE);
6151 	}
6152 
6153 	if (!mctl_present)
6154 		DB_TYPE(mp) = db_type;
6155 
6156 	if (flags & IP_FF_SEND_ICMP) {
6157 		if (flags & IP_FF_HDR_COMPLETE) {
6158 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6159 				freemsg(first_mp);
6160 				return (B_TRUE);
6161 			}
6162 		}
6163 		if (flags & IP_FF_CKSUM) {
6164 			/*
6165 			 * Have to correct checksum since
6166 			 * the packet might have been
6167 			 * fragmented and the reassembly code in ip_rput
6168 			 * does not restore the IP checksum.
6169 			 */
6170 			ipha->ipha_hdr_checksum = 0;
6171 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6172 		}
6173 		switch (icmp_type) {
6174 		case ICMP_DEST_UNREACHABLE:
6175 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6176 			    ipst);
6177 			break;
6178 		default:
6179 			freemsg(first_mp);
6180 			break;
6181 		}
6182 	} else {
6183 		freemsg(first_mp);
6184 		return (B_FALSE);
6185 	}
6186 
6187 	return (B_TRUE);
6188 }
6189 
6190 /*
6191  * Used to send an ICMP error message when a packet is received for
6192  * a protocol that is not supported. The mblk passed as argument
6193  * is consumed by this function.
6194  */
6195 void
6196 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6197     ip_stack_t *ipst)
6198 {
6199 	mblk_t *mp;
6200 	ipha_t *ipha;
6201 	ill_t *ill;
6202 	ipsec_in_t *ii;
6203 
6204 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6205 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6206 
6207 	mp = ipsec_mp->b_cont;
6208 	ipsec_mp->b_cont = NULL;
6209 	ipha = (ipha_t *)mp->b_rptr;
6210 	/* Get ill from index in ipsec_in_t. */
6211 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6212 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6213 	    ipst);
6214 	if (ill != NULL) {
6215 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6216 			if (ip_fanout_send_icmp(q, mp, flags,
6217 			    ICMP_DEST_UNREACHABLE,
6218 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6219 				BUMP_MIB(ill->ill_ip_mib,
6220 				    ipIfStatsInUnknownProtos);
6221 			}
6222 		} else {
6223 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6224 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6225 			    0, B_FALSE, zoneid, ipst)) {
6226 				BUMP_MIB(ill->ill_ip_mib,
6227 				    ipIfStatsInUnknownProtos);
6228 			}
6229 		}
6230 		ill_refrele(ill);
6231 	} else { /* re-link for the freemsg() below. */
6232 		ipsec_mp->b_cont = mp;
6233 	}
6234 
6235 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6236 	freemsg(ipsec_mp);
6237 }
6238 
6239 /*
6240  * See if the inbound datagram has had IPsec processing applied to it.
6241  */
6242 boolean_t
6243 ipsec_in_is_secure(mblk_t *ipsec_mp)
6244 {
6245 	ipsec_in_t *ii;
6246 
6247 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6248 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6249 
6250 	if (ii->ipsec_in_loopback) {
6251 		return (ii->ipsec_in_secure);
6252 	} else {
6253 		return (ii->ipsec_in_ah_sa != NULL ||
6254 		    ii->ipsec_in_esp_sa != NULL ||
6255 		    ii->ipsec_in_decaps);
6256 	}
6257 }
6258 
6259 /*
6260  * Handle protocols with which IP is less intimate.  There
6261  * can be more than one stream bound to a particular
6262  * protocol.  When this is the case, normally each one gets a copy
6263  * of any incoming packets.
6264  *
6265  * IPsec NOTE :
6266  *
6267  * Don't allow a secure packet going up a non-secure connection.
6268  * We don't allow this because
6269  *
6270  * 1) Reply might go out in clear which will be dropped at
6271  *    the sending side.
6272  * 2) If the reply goes out in clear it will give the
6273  *    adversary enough information for getting the key in
6274  *    most of the cases.
6275  *
6276  * Moreover getting a secure packet when we expect clear
6277  * implies that SA's were added without checking for
6278  * policy on both ends. This should not happen once ISAKMP
6279  * is used to negotiate SAs as SAs will be added only after
6280  * verifying the policy.
6281  *
6282  * NOTE : If the packet was tunneled and not multicast we only send
6283  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6284  * back to delivering packets to AF_INET6 raw sockets.
6285  *
6286  * IPQoS Notes:
6287  * Once we have determined the client, invoke IPPF processing.
6288  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6289  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6290  * ip_policy will be false.
6291  *
6292  * Zones notes:
6293  * Currently only applications in the global zone can create raw sockets for
6294  * protocols other than ICMP. So unlike the broadcast / multicast case of
6295  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6296  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6297  */
6298 static void
6299 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6300     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6301     zoneid_t zoneid)
6302 {
6303 	queue_t	*rq;
6304 	mblk_t	*mp1, *first_mp1;
6305 	uint_t	protocol = ipha->ipha_protocol;
6306 	ipaddr_t dst;
6307 	boolean_t one_only;
6308 	mblk_t *first_mp = mp;
6309 	boolean_t secure;
6310 	uint32_t ill_index;
6311 	conn_t	*connp, *first_connp, *next_connp;
6312 	connf_t	*connfp;
6313 	boolean_t shared_addr;
6314 	mib2_ipIfStatsEntry_t *mibptr;
6315 	ip_stack_t *ipst = recv_ill->ill_ipst;
6316 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6317 
6318 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6319 	if (mctl_present) {
6320 		mp = first_mp->b_cont;
6321 		secure = ipsec_in_is_secure(first_mp);
6322 		ASSERT(mp != NULL);
6323 	} else {
6324 		secure = B_FALSE;
6325 	}
6326 	dst = ipha->ipha_dst;
6327 	/*
6328 	 * If the packet was tunneled and not multicast we only send to it
6329 	 * the first match.
6330 	 */
6331 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6332 	    !CLASSD(dst));
6333 
6334 	shared_addr = (zoneid == ALL_ZONES);
6335 	if (shared_addr) {
6336 		/*
6337 		 * We don't allow multilevel ports for raw IP, so no need to
6338 		 * check for that here.
6339 		 */
6340 		zoneid = tsol_packet_to_zoneid(mp);
6341 	}
6342 
6343 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6344 	mutex_enter(&connfp->connf_lock);
6345 	connp = connfp->connf_head;
6346 	for (connp = connfp->connf_head; connp != NULL;
6347 	    connp = connp->conn_next) {
6348 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6349 		    zoneid) &&
6350 		    (!is_system_labeled() ||
6351 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6352 		    connp))) {
6353 			break;
6354 		}
6355 	}
6356 
6357 	if (connp == NULL || connp->conn_upq == NULL) {
6358 		/*
6359 		 * No one bound to these addresses.  Is
6360 		 * there a client that wants all
6361 		 * unclaimed datagrams?
6362 		 */
6363 		mutex_exit(&connfp->connf_lock);
6364 		/*
6365 		 * Check for IPPROTO_ENCAP...
6366 		 */
6367 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6368 			/*
6369 			 * If an IPsec mblk is here on a multicast
6370 			 * tunnel (using ip_mroute stuff), check policy here,
6371 			 * THEN ship off to ip_mroute_decap().
6372 			 *
6373 			 * BTW,  If I match a configured IP-in-IP
6374 			 * tunnel, this path will not be reached, and
6375 			 * ip_mroute_decap will never be called.
6376 			 */
6377 			first_mp = ipsec_check_global_policy(first_mp, connp,
6378 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6379 			if (first_mp != NULL) {
6380 				if (mctl_present)
6381 					freeb(first_mp);
6382 				ip_mroute_decap(q, mp, ill);
6383 			} /* Else we already freed everything! */
6384 		} else {
6385 			/*
6386 			 * Otherwise send an ICMP protocol unreachable.
6387 			 */
6388 			if (ip_fanout_send_icmp(q, first_mp, flags,
6389 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6390 			    mctl_present, zoneid, ipst)) {
6391 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6392 			}
6393 		}
6394 		return;
6395 	}
6396 	CONN_INC_REF(connp);
6397 	first_connp = connp;
6398 
6399 	/*
6400 	 * Only send message to one tunnel driver by immediately
6401 	 * terminating the loop.
6402 	 */
6403 	connp = one_only ? NULL : connp->conn_next;
6404 
6405 	for (;;) {
6406 		while (connp != NULL) {
6407 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6408 			    flags, zoneid) &&
6409 			    (!is_system_labeled() ||
6410 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6411 			    shared_addr, connp)))
6412 				break;
6413 			connp = connp->conn_next;
6414 		}
6415 
6416 		/*
6417 		 * Copy the packet.
6418 		 */
6419 		if (connp == NULL || connp->conn_upq == NULL ||
6420 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6421 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6422 			/*
6423 			 * No more interested clients or memory
6424 			 * allocation failed
6425 			 */
6426 			connp = first_connp;
6427 			break;
6428 		}
6429 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6430 		CONN_INC_REF(connp);
6431 		mutex_exit(&connfp->connf_lock);
6432 		rq = connp->conn_rq;
6433 		if (!canputnext(rq)) {
6434 			if (flags & IP_FF_RAWIP) {
6435 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6436 			} else {
6437 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6438 			}
6439 
6440 			freemsg(first_mp1);
6441 		} else {
6442 			/*
6443 			 * Don't enforce here if we're an actual tunnel -
6444 			 * let "tun" do it instead.
6445 			 */
6446 			if (!IPCL_IS_IPTUN(connp) &&
6447 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6448 			    secure)) {
6449 				first_mp1 = ipsec_check_inbound_policy
6450 				    (first_mp1, connp, ipha, NULL,
6451 				    mctl_present);
6452 			}
6453 			if (first_mp1 != NULL) {
6454 				int in_flags = 0;
6455 				/*
6456 				 * ip_fanout_proto also gets called from
6457 				 * icmp_inbound_error_fanout, in which case
6458 				 * the msg type is M_CTL.  Don't add info
6459 				 * in this case for the time being. In future
6460 				 * when there is a need for knowing the
6461 				 * inbound iface index for ICMP error msgs,
6462 				 * then this can be changed.
6463 				 */
6464 				if (connp->conn_recvif)
6465 					in_flags = IPF_RECVIF;
6466 				/*
6467 				 * The ULP may support IP_RECVPKTINFO for both
6468 				 * IP v4 and v6 so pass the appropriate argument
6469 				 * based on conn IP version.
6470 				 */
6471 				if (connp->conn_ip_recvpktinfo) {
6472 					if (connp->conn_af_isv6) {
6473 						/*
6474 						 * V6 only needs index
6475 						 */
6476 						in_flags |= IPF_RECVIF;
6477 					} else {
6478 						/*
6479 						 * V4 needs index +
6480 						 * matching address.
6481 						 */
6482 						in_flags |= IPF_RECVADDR;
6483 					}
6484 				}
6485 				if ((in_flags != 0) &&
6486 				    (mp->b_datap->db_type != M_CTL)) {
6487 					/*
6488 					 * the actual data will be
6489 					 * contained in b_cont upon
6490 					 * successful return of the
6491 					 * following call else
6492 					 * original mblk is returned
6493 					 */
6494 					ASSERT(recv_ill != NULL);
6495 					mp1 = ip_add_info(mp1, recv_ill,
6496 					    in_flags, IPCL_ZONEID(connp), ipst);
6497 				}
6498 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6499 				if (mctl_present)
6500 					freeb(first_mp1);
6501 				(connp->conn_recv)(connp, mp1, NULL);
6502 			}
6503 		}
6504 		mutex_enter(&connfp->connf_lock);
6505 		/* Follow the next pointer before releasing the conn. */
6506 		next_connp = connp->conn_next;
6507 		CONN_DEC_REF(connp);
6508 		connp = next_connp;
6509 	}
6510 
6511 	/* Last one.  Send it upstream. */
6512 	mutex_exit(&connfp->connf_lock);
6513 
6514 	/*
6515 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6516 	 * will be set to false.
6517 	 */
6518 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6519 		ill_index = ill->ill_phyint->phyint_ifindex;
6520 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6521 		if (mp == NULL) {
6522 			CONN_DEC_REF(connp);
6523 			if (mctl_present) {
6524 				freeb(first_mp);
6525 			}
6526 			return;
6527 		}
6528 	}
6529 
6530 	rq = connp->conn_rq;
6531 	if (!canputnext(rq)) {
6532 		if (flags & IP_FF_RAWIP) {
6533 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6534 		} else {
6535 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6536 		}
6537 
6538 		freemsg(first_mp);
6539 	} else {
6540 		if (IPCL_IS_IPTUN(connp)) {
6541 			/*
6542 			 * Tunneled packet.  We enforce policy in the tunnel
6543 			 * module itself.
6544 			 *
6545 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6546 			 * a policy check.
6547 			 * FIXME to use conn_recv for tun later.
6548 			 */
6549 			putnext(rq, first_mp);
6550 			CONN_DEC_REF(connp);
6551 			return;
6552 		}
6553 
6554 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6555 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6556 			    ipha, NULL, mctl_present);
6557 		}
6558 
6559 		if (first_mp != NULL) {
6560 			int in_flags = 0;
6561 
6562 			/*
6563 			 * ip_fanout_proto also gets called
6564 			 * from icmp_inbound_error_fanout, in
6565 			 * which case the msg type is M_CTL.
6566 			 * Don't add info in this case for time
6567 			 * being. In future when there is a
6568 			 * need for knowing the inbound iface
6569 			 * index for ICMP error msgs, then this
6570 			 * can be changed
6571 			 */
6572 			if (connp->conn_recvif)
6573 				in_flags = IPF_RECVIF;
6574 			if (connp->conn_ip_recvpktinfo) {
6575 				if (connp->conn_af_isv6) {
6576 					/*
6577 					 * V6 only needs index
6578 					 */
6579 					in_flags |= IPF_RECVIF;
6580 				} else {
6581 					/*
6582 					 * V4 needs index +
6583 					 * matching address.
6584 					 */
6585 					in_flags |= IPF_RECVADDR;
6586 				}
6587 			}
6588 			if ((in_flags != 0) &&
6589 			    (mp->b_datap->db_type != M_CTL)) {
6590 
6591 				/*
6592 				 * the actual data will be contained in
6593 				 * b_cont upon successful return
6594 				 * of the following call else original
6595 				 * mblk is returned
6596 				 */
6597 				ASSERT(recv_ill != NULL);
6598 				mp = ip_add_info(mp, recv_ill,
6599 				    in_flags, IPCL_ZONEID(connp), ipst);
6600 			}
6601 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6602 			(connp->conn_recv)(connp, mp, NULL);
6603 			if (mctl_present)
6604 				freeb(first_mp);
6605 		}
6606 	}
6607 	CONN_DEC_REF(connp);
6608 }
6609 
6610 /*
6611  * Fanout for TCP packets
6612  * The caller puts <fport, lport> in the ports parameter.
6613  *
6614  * IPQoS Notes
6615  * Before sending it to the client, invoke IPPF processing.
6616  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6617  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6618  * ip_policy is false.
6619  */
6620 static void
6621 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6622     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6623 {
6624 	mblk_t  *first_mp;
6625 	boolean_t secure;
6626 	uint32_t ill_index;
6627 	int	ip_hdr_len;
6628 	tcph_t	*tcph;
6629 	boolean_t syn_present = B_FALSE;
6630 	conn_t	*connp;
6631 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6632 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6633 
6634 	ASSERT(recv_ill != NULL);
6635 
6636 	first_mp = mp;
6637 	if (mctl_present) {
6638 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6639 		mp = first_mp->b_cont;
6640 		secure = ipsec_in_is_secure(first_mp);
6641 		ASSERT(mp != NULL);
6642 	} else {
6643 		secure = B_FALSE;
6644 	}
6645 
6646 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6647 
6648 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6649 	    zoneid, ipst)) == NULL) {
6650 		/*
6651 		 * No connected connection or listener. Send a
6652 		 * TH_RST via tcp_xmit_listeners_reset.
6653 		 */
6654 
6655 		/* Initiate IPPf processing, if needed. */
6656 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6657 			uint32_t ill_index;
6658 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6659 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6660 			if (first_mp == NULL)
6661 				return;
6662 		}
6663 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6664 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6665 		    zoneid));
6666 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6667 		    ipst->ips_netstack->netstack_tcp, NULL);
6668 		return;
6669 	}
6670 
6671 	/*
6672 	 * Allocate the SYN for the TCP connection here itself
6673 	 */
6674 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6675 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6676 		if (IPCL_IS_TCP(connp)) {
6677 			squeue_t *sqp;
6678 
6679 			/*
6680 			 * For fused tcp loopback, assign the eager's
6681 			 * squeue to be that of the active connect's.
6682 			 * Note that we don't check for IP_FF_LOOPBACK
6683 			 * here since this routine gets called only
6684 			 * for loopback (unlike the IPv6 counterpart).
6685 			 */
6686 			ASSERT(Q_TO_CONN(q) != NULL);
6687 			if (do_tcp_fusion &&
6688 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6689 			    !secure &&
6690 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6691 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6692 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6693 				sqp = Q_TO_CONN(q)->conn_sqp;
6694 			} else {
6695 				sqp = IP_SQUEUE_GET(lbolt);
6696 			}
6697 
6698 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6699 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6700 			syn_present = B_TRUE;
6701 		}
6702 	}
6703 
6704 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6705 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6706 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6707 		if ((flags & TH_RST) || (flags & TH_URG)) {
6708 			CONN_DEC_REF(connp);
6709 			freemsg(first_mp);
6710 			return;
6711 		}
6712 		if (flags & TH_ACK) {
6713 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6714 			    ipst->ips_netstack->netstack_tcp, connp);
6715 			CONN_DEC_REF(connp);
6716 			return;
6717 		}
6718 
6719 		CONN_DEC_REF(connp);
6720 		freemsg(first_mp);
6721 		return;
6722 	}
6723 
6724 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6725 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6726 		    NULL, mctl_present);
6727 		if (first_mp == NULL) {
6728 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6729 			CONN_DEC_REF(connp);
6730 			return;
6731 		}
6732 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6733 			ASSERT(syn_present);
6734 			if (mctl_present) {
6735 				ASSERT(first_mp != mp);
6736 				first_mp->b_datap->db_struioflag |=
6737 				    STRUIO_POLICY;
6738 			} else {
6739 				ASSERT(first_mp == mp);
6740 				mp->b_datap->db_struioflag &=
6741 				    ~STRUIO_EAGER;
6742 				mp->b_datap->db_struioflag |=
6743 				    STRUIO_POLICY;
6744 			}
6745 		} else {
6746 			/*
6747 			 * Discard first_mp early since we're dealing with a
6748 			 * fully-connected conn_t and tcp doesn't do policy in
6749 			 * this case.
6750 			 */
6751 			if (mctl_present) {
6752 				freeb(first_mp);
6753 				mctl_present = B_FALSE;
6754 			}
6755 			first_mp = mp;
6756 		}
6757 	}
6758 
6759 	/*
6760 	 * Initiate policy processing here if needed. If we get here from
6761 	 * icmp_inbound_error_fanout, ip_policy is false.
6762 	 */
6763 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6764 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6765 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6766 		if (mp == NULL) {
6767 			CONN_DEC_REF(connp);
6768 			if (mctl_present)
6769 				freeb(first_mp);
6770 			return;
6771 		} else if (mctl_present) {
6772 			ASSERT(first_mp != mp);
6773 			first_mp->b_cont = mp;
6774 		} else {
6775 			first_mp = mp;
6776 		}
6777 	}
6778 
6779 
6780 
6781 	/* Handle socket options. */
6782 	if (!syn_present &&
6783 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6784 		/* Add header */
6785 		ASSERT(recv_ill != NULL);
6786 		/*
6787 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6788 		 * IPF_RECVIF.
6789 		 */
6790 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6791 		    ipst);
6792 		if (mp == NULL) {
6793 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6794 			CONN_DEC_REF(connp);
6795 			if (mctl_present)
6796 				freeb(first_mp);
6797 			return;
6798 		} else if (mctl_present) {
6799 			/*
6800 			 * ip_add_info might return a new mp.
6801 			 */
6802 			ASSERT(first_mp != mp);
6803 			first_mp->b_cont = mp;
6804 		} else {
6805 			first_mp = mp;
6806 		}
6807 	}
6808 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6809 	if (IPCL_IS_TCP(connp)) {
6810 		/* do not drain, certain use cases can blow the stack */
6811 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6812 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6813 	} else {
6814 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6815 		(connp->conn_recv)(connp, first_mp, NULL);
6816 		CONN_DEC_REF(connp);
6817 	}
6818 }
6819 
6820 /*
6821  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6822  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6823  * is not consumed.
6824  *
6825  * One of four things can happen, all of which affect the passed-in mblk:
6826  *
6827  * 1.) ICMP messages that go through here just get returned TRUE.
6828  *
6829  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6830  *
6831  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6832  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6833  *
6834  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6835  */
6836 static boolean_t
6837 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6838     ipsec_stack_t *ipss)
6839 {
6840 	int shift, plen, iph_len;
6841 	ipha_t *ipha;
6842 	udpha_t *udpha;
6843 	uint32_t *spi;
6844 	uint8_t *orptr;
6845 	boolean_t udp_pkt, free_ire;
6846 
6847 	if (DB_TYPE(mp) == M_CTL) {
6848 		/*
6849 		 * ICMP message with UDP inside.  Don't bother stripping, just
6850 		 * send it up.
6851 		 *
6852 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6853 		 * to ignore errors set by ICMP anyway ('cause they might be
6854 		 * forged), but that's the app's decision, not ours.
6855 		 */
6856 
6857 		/* Bunch of reality checks for DEBUG kernels... */
6858 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6859 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6860 
6861 		return (B_TRUE);
6862 	}
6863 
6864 	ipha = (ipha_t *)mp->b_rptr;
6865 	iph_len = IPH_HDR_LENGTH(ipha);
6866 	plen = ntohs(ipha->ipha_length);
6867 
6868 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6869 		/*
6870 		 * Most likely a keepalive for the benefit of an intervening
6871 		 * NAT.  These aren't for us, per se, so drop it.
6872 		 *
6873 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6874 		 * byte packets (keepalives are 1-byte), but we'll drop them
6875 		 * also.
6876 		 */
6877 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6878 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6879 		return (B_FALSE);
6880 	}
6881 
6882 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6883 		/* might as well pull it all up - it might be ESP. */
6884 		if (!pullupmsg(mp, -1)) {
6885 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6886 			    DROPPER(ipss, ipds_esp_nomem),
6887 			    &ipss->ipsec_dropper);
6888 			return (B_FALSE);
6889 		}
6890 
6891 		ipha = (ipha_t *)mp->b_rptr;
6892 	}
6893 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6894 	if (*spi == 0) {
6895 		/* UDP packet - remove 0-spi. */
6896 		shift = sizeof (uint32_t);
6897 	} else {
6898 		/* ESP-in-UDP packet - reduce to ESP. */
6899 		ipha->ipha_protocol = IPPROTO_ESP;
6900 		shift = sizeof (udpha_t);
6901 	}
6902 
6903 	/* Fix IP header */
6904 	ipha->ipha_length = htons(plen - shift);
6905 	ipha->ipha_hdr_checksum = 0;
6906 
6907 	orptr = mp->b_rptr;
6908 	mp->b_rptr += shift;
6909 
6910 	if (*spi == 0) {
6911 		ASSERT((uint8_t *)ipha == orptr);
6912 		udpha = (udpha_t *)(orptr + iph_len);
6913 		udpha->uha_length = htons(plen - shift - iph_len);
6914 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6915 		udp_pkt = B_TRUE;
6916 	} else {
6917 		udp_pkt = B_FALSE;
6918 	}
6919 	ovbcopy(orptr, orptr + shift, iph_len);
6920 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6921 		ipha = (ipha_t *)(orptr + shift);
6922 
6923 		free_ire = (ire == NULL);
6924 		if (free_ire) {
6925 			/* Re-acquire ire. */
6926 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6927 			    ipss->ipsec_netstack->netstack_ip);
6928 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6929 				if (ire != NULL)
6930 					ire_refrele(ire);
6931 				/*
6932 				 * Do a regular freemsg(), as this is an IP
6933 				 * error (no local route) not an IPsec one.
6934 				 */
6935 				freemsg(mp);
6936 			}
6937 		}
6938 
6939 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6940 		if (free_ire)
6941 			ire_refrele(ire);
6942 	}
6943 
6944 	return (udp_pkt);
6945 }
6946 
6947 /*
6948  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6949  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6950  * Caller is responsible for dropping references to the conn, and freeing
6951  * first_mp.
6952  *
6953  * IPQoS Notes
6954  * Before sending it to the client, invoke IPPF processing. Policy processing
6955  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6956  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6957  * ip_wput_local, ip_policy is false.
6958  */
6959 static void
6960 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6961     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6962     boolean_t ip_policy)
6963 {
6964 	boolean_t	mctl_present = (first_mp != NULL);
6965 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6966 	uint32_t	ill_index;
6967 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6968 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6969 
6970 	ASSERT(ill != NULL);
6971 
6972 	if (mctl_present)
6973 		first_mp->b_cont = mp;
6974 	else
6975 		first_mp = mp;
6976 
6977 	if (CONN_UDP_FLOWCTLD(connp)) {
6978 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6979 		freemsg(first_mp);
6980 		return;
6981 	}
6982 
6983 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6984 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6985 		    NULL, mctl_present);
6986 		if (first_mp == NULL) {
6987 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6988 			return;	/* Freed by ipsec_check_inbound_policy(). */
6989 		}
6990 	}
6991 	if (mctl_present)
6992 		freeb(first_mp);
6993 
6994 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6995 	if (connp->conn_udp->udp_nat_t_endpoint) {
6996 		if (mctl_present) {
6997 			/* mctl_present *shouldn't* happen. */
6998 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
6999 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7000 			    &ipss->ipsec_dropper);
7001 			return;
7002 		}
7003 
7004 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7005 			return;
7006 	}
7007 
7008 	/* Handle options. */
7009 	if (connp->conn_recvif)
7010 		in_flags = IPF_RECVIF;
7011 	/*
7012 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7013 	 * passed to ip_add_info is based on IP version of connp.
7014 	 */
7015 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7016 		if (connp->conn_af_isv6) {
7017 			/*
7018 			 * V6 only needs index
7019 			 */
7020 			in_flags |= IPF_RECVIF;
7021 		} else {
7022 			/*
7023 			 * V4 needs index + matching address.
7024 			 */
7025 			in_flags |= IPF_RECVADDR;
7026 		}
7027 	}
7028 
7029 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7030 		in_flags |= IPF_RECVSLLA;
7031 
7032 	/*
7033 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7034 	 * freed if the packet is dropped. The caller will do so.
7035 	 */
7036 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7037 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7038 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7039 		if (mp == NULL) {
7040 			return;
7041 		}
7042 	}
7043 	if ((in_flags != 0) &&
7044 	    (mp->b_datap->db_type != M_CTL)) {
7045 		/*
7046 		 * The actual data will be contained in b_cont
7047 		 * upon successful return of the following call
7048 		 * else original mblk is returned
7049 		 */
7050 		ASSERT(recv_ill != NULL);
7051 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7052 		    ipst);
7053 	}
7054 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7055 	/* Send it upstream */
7056 	(connp->conn_recv)(connp, mp, NULL);
7057 }
7058 
7059 /*
7060  * Fanout for UDP packets.
7061  * The caller puts <fport, lport> in the ports parameter.
7062  *
7063  * If SO_REUSEADDR is set all multicast and broadcast packets
7064  * will be delivered to all streams bound to the same port.
7065  *
7066  * Zones notes:
7067  * Multicast and broadcast packets will be distributed to streams in all zones.
7068  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7069  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7070  * packets. To maintain this behavior with multiple zones, the conns are grouped
7071  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7072  * each zone. If unset, all the following conns in the same zone are skipped.
7073  */
7074 static void
7075 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7076     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7077     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7078 {
7079 	uint32_t	dstport, srcport;
7080 	ipaddr_t	dst;
7081 	mblk_t		*first_mp;
7082 	boolean_t	secure;
7083 	in6_addr_t	v6src;
7084 	conn_t		*connp;
7085 	connf_t		*connfp;
7086 	conn_t		*first_connp;
7087 	conn_t		*next_connp;
7088 	mblk_t		*mp1, *first_mp1;
7089 	ipaddr_t	src;
7090 	zoneid_t	last_zoneid;
7091 	boolean_t	reuseaddr;
7092 	boolean_t	shared_addr;
7093 	boolean_t	unlabeled;
7094 	ip_stack_t	*ipst;
7095 
7096 	ASSERT(recv_ill != NULL);
7097 	ipst = recv_ill->ill_ipst;
7098 
7099 	first_mp = mp;
7100 	if (mctl_present) {
7101 		mp = first_mp->b_cont;
7102 		first_mp->b_cont = NULL;
7103 		secure = ipsec_in_is_secure(first_mp);
7104 		ASSERT(mp != NULL);
7105 	} else {
7106 		first_mp = NULL;
7107 		secure = B_FALSE;
7108 	}
7109 
7110 	/* Extract ports in net byte order */
7111 	dstport = htons(ntohl(ports) & 0xFFFF);
7112 	srcport = htons(ntohl(ports) >> 16);
7113 	dst = ipha->ipha_dst;
7114 	src = ipha->ipha_src;
7115 
7116 	unlabeled = B_FALSE;
7117 	if (is_system_labeled())
7118 		/* Cred cannot be null on IPv4 */
7119 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7120 		    TSLF_UNLABELED) != 0;
7121 	shared_addr = (zoneid == ALL_ZONES);
7122 	if (shared_addr) {
7123 		/*
7124 		 * No need to handle exclusive-stack zones since ALL_ZONES
7125 		 * only applies to the shared stack.
7126 		 */
7127 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7128 		/*
7129 		 * If no shared MLP is found, tsol_mlp_findzone returns
7130 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7131 		 * search for the zone based on the packet label.
7132 		 *
7133 		 * If there is such a zone, we prefer to find a
7134 		 * connection in it.  Otherwise, we look for a
7135 		 * MAC-exempt connection in any zone whose label
7136 		 * dominates the default label on the packet.
7137 		 */
7138 		if (zoneid == ALL_ZONES)
7139 			zoneid = tsol_packet_to_zoneid(mp);
7140 		else
7141 			unlabeled = B_FALSE;
7142 	}
7143 
7144 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7145 	mutex_enter(&connfp->connf_lock);
7146 	connp = connfp->connf_head;
7147 	if (!broadcast && !CLASSD(dst)) {
7148 		/*
7149 		 * Not broadcast or multicast. Send to the one (first)
7150 		 * client we find. No need to check conn_wantpacket()
7151 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7152 		 * IPv4 unicast packets.
7153 		 */
7154 		while ((connp != NULL) &&
7155 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7156 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7157 		    !(unlabeled && connp->conn_mac_exempt)))) {
7158 			/*
7159 			 * We keep searching since the conn did not match,
7160 			 * or its zone did not match and it is not either
7161 			 * an allzones conn or a mac exempt conn (if the
7162 			 * sender is unlabeled.)
7163 			 */
7164 			connp = connp->conn_next;
7165 		}
7166 
7167 		if (connp == NULL || connp->conn_upq == NULL)
7168 			goto notfound;
7169 
7170 		if (is_system_labeled() &&
7171 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7172 		    connp))
7173 			goto notfound;
7174 
7175 		CONN_INC_REF(connp);
7176 		mutex_exit(&connfp->connf_lock);
7177 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7178 		    flags, recv_ill, ip_policy);
7179 		IP_STAT(ipst, ip_udp_fannorm);
7180 		CONN_DEC_REF(connp);
7181 		return;
7182 	}
7183 
7184 	/*
7185 	 * Broadcast and multicast case
7186 	 *
7187 	 * Need to check conn_wantpacket().
7188 	 * If SO_REUSEADDR has been set on the first we send the
7189 	 * packet to all clients that have joined the group and
7190 	 * match the port.
7191 	 */
7192 
7193 	while (connp != NULL) {
7194 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7195 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7196 		    (!is_system_labeled() ||
7197 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7198 		    connp)))
7199 			break;
7200 		connp = connp->conn_next;
7201 	}
7202 
7203 	if (connp == NULL || connp->conn_upq == NULL)
7204 		goto notfound;
7205 
7206 	first_connp = connp;
7207 	/*
7208 	 * When SO_REUSEADDR is not set, send the packet only to the first
7209 	 * matching connection in its zone by keeping track of the zoneid.
7210 	 */
7211 	reuseaddr = first_connp->conn_reuseaddr;
7212 	last_zoneid = first_connp->conn_zoneid;
7213 
7214 	CONN_INC_REF(connp);
7215 	connp = connp->conn_next;
7216 	for (;;) {
7217 		while (connp != NULL) {
7218 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7219 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7220 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7221 			    (!is_system_labeled() ||
7222 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7223 			    shared_addr, connp)))
7224 				break;
7225 			connp = connp->conn_next;
7226 		}
7227 		/*
7228 		 * Just copy the data part alone. The mctl part is
7229 		 * needed just for verifying policy and it is never
7230 		 * sent up.
7231 		 */
7232 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7233 		    ((mp1 = copymsg(mp)) == NULL))) {
7234 			/*
7235 			 * No more interested clients or memory
7236 			 * allocation failed
7237 			 */
7238 			connp = first_connp;
7239 			break;
7240 		}
7241 		if (connp->conn_zoneid != last_zoneid) {
7242 			/*
7243 			 * Update the zoneid so that the packet isn't sent to
7244 			 * any more conns in the same zone unless SO_REUSEADDR
7245 			 * is set.
7246 			 */
7247 			reuseaddr = connp->conn_reuseaddr;
7248 			last_zoneid = connp->conn_zoneid;
7249 		}
7250 		if (first_mp != NULL) {
7251 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7252 			    ipsec_info_type == IPSEC_IN);
7253 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7254 			    ipst->ips_netstack);
7255 			if (first_mp1 == NULL) {
7256 				freemsg(mp1);
7257 				connp = first_connp;
7258 				break;
7259 			}
7260 		} else {
7261 			first_mp1 = NULL;
7262 		}
7263 		CONN_INC_REF(connp);
7264 		mutex_exit(&connfp->connf_lock);
7265 		/*
7266 		 * IPQoS notes: We don't send the packet for policy
7267 		 * processing here, will do it for the last one (below).
7268 		 * i.e. we do it per-packet now, but if we do policy
7269 		 * processing per-conn, then we would need to do it
7270 		 * here too.
7271 		 */
7272 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7273 		    ipha, flags, recv_ill, B_FALSE);
7274 		mutex_enter(&connfp->connf_lock);
7275 		/* Follow the next pointer before releasing the conn. */
7276 		next_connp = connp->conn_next;
7277 		IP_STAT(ipst, ip_udp_fanmb);
7278 		CONN_DEC_REF(connp);
7279 		connp = next_connp;
7280 	}
7281 
7282 	/* Last one.  Send it upstream. */
7283 	mutex_exit(&connfp->connf_lock);
7284 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7285 	    recv_ill, ip_policy);
7286 	IP_STAT(ipst, ip_udp_fanmb);
7287 	CONN_DEC_REF(connp);
7288 	return;
7289 
7290 notfound:
7291 
7292 	mutex_exit(&connfp->connf_lock);
7293 	IP_STAT(ipst, ip_udp_fanothers);
7294 	/*
7295 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7296 	 * have already been matched above, since they live in the IPv4
7297 	 * fanout tables. This implies we only need to
7298 	 * check for IPv6 in6addr_any endpoints here.
7299 	 * Thus we compare using ipv6_all_zeros instead of the destination
7300 	 * address, except for the multicast group membership lookup which
7301 	 * uses the IPv4 destination.
7302 	 */
7303 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7304 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7305 	mutex_enter(&connfp->connf_lock);
7306 	connp = connfp->connf_head;
7307 	if (!broadcast && !CLASSD(dst)) {
7308 		while (connp != NULL) {
7309 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7310 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7311 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7312 			    !connp->conn_ipv6_v6only)
7313 				break;
7314 			connp = connp->conn_next;
7315 		}
7316 
7317 		if (connp != NULL && is_system_labeled() &&
7318 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7319 		    connp))
7320 			connp = NULL;
7321 
7322 		if (connp == NULL || connp->conn_upq == NULL) {
7323 			/*
7324 			 * No one bound to this port.  Is
7325 			 * there a client that wants all
7326 			 * unclaimed datagrams?
7327 			 */
7328 			mutex_exit(&connfp->connf_lock);
7329 
7330 			if (mctl_present)
7331 				first_mp->b_cont = mp;
7332 			else
7333 				first_mp = mp;
7334 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7335 			    connf_head != NULL) {
7336 				ip_fanout_proto(q, first_mp, ill, ipha,
7337 				    flags | IP_FF_RAWIP, mctl_present,
7338 				    ip_policy, recv_ill, zoneid);
7339 			} else {
7340 				if (ip_fanout_send_icmp(q, first_mp, flags,
7341 				    ICMP_DEST_UNREACHABLE,
7342 				    ICMP_PORT_UNREACHABLE,
7343 				    mctl_present, zoneid, ipst)) {
7344 					BUMP_MIB(ill->ill_ip_mib,
7345 					    udpIfStatsNoPorts);
7346 				}
7347 			}
7348 			return;
7349 		}
7350 
7351 		CONN_INC_REF(connp);
7352 		mutex_exit(&connfp->connf_lock);
7353 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7354 		    flags, recv_ill, ip_policy);
7355 		CONN_DEC_REF(connp);
7356 		return;
7357 	}
7358 	/*
7359 	 * IPv4 multicast packet being delivered to an AF_INET6
7360 	 * in6addr_any endpoint.
7361 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7362 	 * and not conn_wantpacket_v6() since any multicast membership is
7363 	 * for an IPv4-mapped multicast address.
7364 	 * The packet is sent to all clients in all zones that have joined the
7365 	 * group and match the port.
7366 	 */
7367 	while (connp != NULL) {
7368 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7369 		    srcport, v6src) &&
7370 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7371 		    (!is_system_labeled() ||
7372 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7373 		    connp)))
7374 			break;
7375 		connp = connp->conn_next;
7376 	}
7377 
7378 	if (connp == NULL || connp->conn_upq == NULL) {
7379 		/*
7380 		 * No one bound to this port.  Is
7381 		 * there a client that wants all
7382 		 * unclaimed datagrams?
7383 		 */
7384 		mutex_exit(&connfp->connf_lock);
7385 
7386 		if (mctl_present)
7387 			first_mp->b_cont = mp;
7388 		else
7389 			first_mp = mp;
7390 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7391 		    NULL) {
7392 			ip_fanout_proto(q, first_mp, ill, ipha,
7393 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7394 			    recv_ill, zoneid);
7395 		} else {
7396 			/*
7397 			 * We used to attempt to send an icmp error here, but
7398 			 * since this is known to be a multicast packet
7399 			 * and we don't send icmp errors in response to
7400 			 * multicast, just drop the packet and give up sooner.
7401 			 */
7402 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7403 			freemsg(first_mp);
7404 		}
7405 		return;
7406 	}
7407 
7408 	first_connp = connp;
7409 
7410 	CONN_INC_REF(connp);
7411 	connp = connp->conn_next;
7412 	for (;;) {
7413 		while (connp != NULL) {
7414 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7415 			    ipv6_all_zeros, srcport, v6src) &&
7416 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7417 			    (!is_system_labeled() ||
7418 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7419 			    shared_addr, connp)))
7420 				break;
7421 			connp = connp->conn_next;
7422 		}
7423 		/*
7424 		 * Just copy the data part alone. The mctl part is
7425 		 * needed just for verifying policy and it is never
7426 		 * sent up.
7427 		 */
7428 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7429 		    ((mp1 = copymsg(mp)) == NULL))) {
7430 			/*
7431 			 * No more intested clients or memory
7432 			 * allocation failed
7433 			 */
7434 			connp = first_connp;
7435 			break;
7436 		}
7437 		if (first_mp != NULL) {
7438 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7439 			    ipsec_info_type == IPSEC_IN);
7440 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7441 			    ipst->ips_netstack);
7442 			if (first_mp1 == NULL) {
7443 				freemsg(mp1);
7444 				connp = first_connp;
7445 				break;
7446 			}
7447 		} else {
7448 			first_mp1 = NULL;
7449 		}
7450 		CONN_INC_REF(connp);
7451 		mutex_exit(&connfp->connf_lock);
7452 		/*
7453 		 * IPQoS notes: We don't send the packet for policy
7454 		 * processing here, will do it for the last one (below).
7455 		 * i.e. we do it per-packet now, but if we do policy
7456 		 * processing per-conn, then we would need to do it
7457 		 * here too.
7458 		 */
7459 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7460 		    ipha, flags, recv_ill, B_FALSE);
7461 		mutex_enter(&connfp->connf_lock);
7462 		/* Follow the next pointer before releasing the conn. */
7463 		next_connp = connp->conn_next;
7464 		CONN_DEC_REF(connp);
7465 		connp = next_connp;
7466 	}
7467 
7468 	/* Last one.  Send it upstream. */
7469 	mutex_exit(&connfp->connf_lock);
7470 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7471 	    recv_ill, ip_policy);
7472 	CONN_DEC_REF(connp);
7473 }
7474 
7475 /*
7476  * Complete the ip_wput header so that it
7477  * is possible to generate ICMP
7478  * errors.
7479  */
7480 int
7481 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7482 {
7483 	ire_t *ire;
7484 
7485 	if (ipha->ipha_src == INADDR_ANY) {
7486 		ire = ire_lookup_local(zoneid, ipst);
7487 		if (ire == NULL) {
7488 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7489 			return (1);
7490 		}
7491 		ipha->ipha_src = ire->ire_addr;
7492 		ire_refrele(ire);
7493 	}
7494 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7495 	ipha->ipha_hdr_checksum = 0;
7496 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7497 	return (0);
7498 }
7499 
7500 /*
7501  * Nobody should be sending
7502  * packets up this stream
7503  */
7504 static void
7505 ip_lrput(queue_t *q, mblk_t *mp)
7506 {
7507 	mblk_t *mp1;
7508 
7509 	switch (mp->b_datap->db_type) {
7510 	case M_FLUSH:
7511 		/* Turn around */
7512 		if (*mp->b_rptr & FLUSHW) {
7513 			*mp->b_rptr &= ~FLUSHR;
7514 			qreply(q, mp);
7515 			return;
7516 		}
7517 		break;
7518 	}
7519 	/* Could receive messages that passed through ar_rput */
7520 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7521 		mp1->b_prev = mp1->b_next = NULL;
7522 	freemsg(mp);
7523 }
7524 
7525 /* Nobody should be sending packets down this stream */
7526 /* ARGSUSED */
7527 void
7528 ip_lwput(queue_t *q, mblk_t *mp)
7529 {
7530 	freemsg(mp);
7531 }
7532 
7533 /*
7534  * Move the first hop in any source route to ipha_dst and remove that part of
7535  * the source route.  Called by other protocols.  Errors in option formatting
7536  * are ignored - will be handled by ip_wput_options Return the final
7537  * destination (either ipha_dst or the last entry in a source route.)
7538  */
7539 ipaddr_t
7540 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7541 {
7542 	ipoptp_t	opts;
7543 	uchar_t		*opt;
7544 	uint8_t		optval;
7545 	uint8_t		optlen;
7546 	ipaddr_t	dst;
7547 	int		i;
7548 	ire_t		*ire;
7549 	ip_stack_t	*ipst = ns->netstack_ip;
7550 
7551 	ip2dbg(("ip_massage_options\n"));
7552 	dst = ipha->ipha_dst;
7553 	for (optval = ipoptp_first(&opts, ipha);
7554 	    optval != IPOPT_EOL;
7555 	    optval = ipoptp_next(&opts)) {
7556 		opt = opts.ipoptp_cur;
7557 		switch (optval) {
7558 			uint8_t off;
7559 		case IPOPT_SSRR:
7560 		case IPOPT_LSRR:
7561 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7562 				ip1dbg(("ip_massage_options: bad src route\n"));
7563 				break;
7564 			}
7565 			optlen = opts.ipoptp_len;
7566 			off = opt[IPOPT_OFFSET];
7567 			off--;
7568 		redo_srr:
7569 			if (optlen < IP_ADDR_LEN ||
7570 			    off > optlen - IP_ADDR_LEN) {
7571 				/* End of source route */
7572 				ip1dbg(("ip_massage_options: end of SR\n"));
7573 				break;
7574 			}
7575 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7576 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7577 			    ntohl(dst)));
7578 			/*
7579 			 * Check if our address is present more than
7580 			 * once as consecutive hops in source route.
7581 			 * XXX verify per-interface ip_forwarding
7582 			 * for source route?
7583 			 */
7584 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7585 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7586 			if (ire != NULL) {
7587 				ire_refrele(ire);
7588 				off += IP_ADDR_LEN;
7589 				goto redo_srr;
7590 			}
7591 			if (dst == htonl(INADDR_LOOPBACK)) {
7592 				ip1dbg(("ip_massage_options: loopback addr in "
7593 				    "source route!\n"));
7594 				break;
7595 			}
7596 			/*
7597 			 * Update ipha_dst to be the first hop and remove the
7598 			 * first hop from the source route (by overwriting
7599 			 * part of the option with NOP options).
7600 			 */
7601 			ipha->ipha_dst = dst;
7602 			/* Put the last entry in dst */
7603 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7604 			    3;
7605 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7606 
7607 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7608 			    ntohl(dst)));
7609 			/* Move down and overwrite */
7610 			opt[IP_ADDR_LEN] = opt[0];
7611 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7612 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7613 			for (i = 0; i < IP_ADDR_LEN; i++)
7614 				opt[i] = IPOPT_NOP;
7615 			break;
7616 		}
7617 	}
7618 	return (dst);
7619 }
7620 
7621 /*
7622  * Return the network mask
7623  * associated with the specified address.
7624  */
7625 ipaddr_t
7626 ip_net_mask(ipaddr_t addr)
7627 {
7628 	uchar_t	*up = (uchar_t *)&addr;
7629 	ipaddr_t mask = 0;
7630 	uchar_t	*maskp = (uchar_t *)&mask;
7631 
7632 #if defined(__i386) || defined(__amd64)
7633 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7634 #endif
7635 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7636 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7637 #endif
7638 	if (CLASSD(addr)) {
7639 		maskp[0] = 0xF0;
7640 		return (mask);
7641 	}
7642 
7643 	/* We assume Class E default netmask to be 32 */
7644 	if (CLASSE(addr))
7645 		return (0xffffffffU);
7646 
7647 	if (addr == 0)
7648 		return (0);
7649 	maskp[0] = 0xFF;
7650 	if ((up[0] & 0x80) == 0)
7651 		return (mask);
7652 
7653 	maskp[1] = 0xFF;
7654 	if ((up[0] & 0xC0) == 0x80)
7655 		return (mask);
7656 
7657 	maskp[2] = 0xFF;
7658 	if ((up[0] & 0xE0) == 0xC0)
7659 		return (mask);
7660 
7661 	/* Otherwise return no mask */
7662 	return ((ipaddr_t)0);
7663 }
7664 
7665 /*
7666  * Select an ill for the packet by considering load spreading across
7667  * a different ill in the group if dst_ill is part of some group.
7668  */
7669 ill_t *
7670 ip_newroute_get_dst_ill(ill_t *dst_ill)
7671 {
7672 	ill_t *ill;
7673 
7674 	/*
7675 	 * We schedule irrespective of whether the source address is
7676 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7677 	 */
7678 	ill = illgrp_scheduler(dst_ill);
7679 	if (ill == NULL)
7680 		return (NULL);
7681 
7682 	/*
7683 	 * For groups with names ip_sioctl_groupname ensures that all
7684 	 * ills are of same type. For groups without names, ifgrp_insert
7685 	 * ensures this.
7686 	 */
7687 	ASSERT(dst_ill->ill_type == ill->ill_type);
7688 
7689 	return (ill);
7690 }
7691 
7692 /*
7693  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7694  */
7695 ill_t *
7696 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7697     ip_stack_t *ipst)
7698 {
7699 	ill_t *ret_ill;
7700 
7701 	ASSERT(ifindex != 0);
7702 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7703 	    ipst);
7704 	if (ret_ill == NULL ||
7705 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7706 		if (isv6) {
7707 			if (ill != NULL) {
7708 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7709 			} else {
7710 				BUMP_MIB(&ipst->ips_ip6_mib,
7711 				    ipIfStatsOutDiscards);
7712 			}
7713 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7714 			    "bad ifindex %d.\n", ifindex));
7715 		} else {
7716 			if (ill != NULL) {
7717 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7718 			} else {
7719 				BUMP_MIB(&ipst->ips_ip_mib,
7720 				    ipIfStatsOutDiscards);
7721 			}
7722 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7723 			    "bad ifindex %d.\n", ifindex));
7724 		}
7725 		if (ret_ill != NULL)
7726 			ill_refrele(ret_ill);
7727 		freemsg(first_mp);
7728 		return (NULL);
7729 	}
7730 
7731 	return (ret_ill);
7732 }
7733 
7734 /*
7735  * IPv4 -
7736  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7737  * out a packet to a destination address for which we do not have specific
7738  * (or sufficient) routing information.
7739  *
7740  * NOTE : These are the scopes of some of the variables that point at IRE,
7741  *	  which needs to be followed while making any future modifications
7742  *	  to avoid memory leaks.
7743  *
7744  *	- ire and sire are the entries looked up initially by
7745  *	  ire_ftable_lookup.
7746  *	- ipif_ire is used to hold the interface ire associated with
7747  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7748  *	  it before branching out to error paths.
7749  *	- save_ire is initialized before ire_create, so that ire returned
7750  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7751  *	  before breaking out of the switch.
7752  *
7753  *	Thus on failures, we have to REFRELE only ire and sire, if they
7754  *	are not NULL.
7755  */
7756 void
7757 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7758     zoneid_t zoneid, ip_stack_t *ipst)
7759 {
7760 	areq_t	*areq;
7761 	ipaddr_t gw = 0;
7762 	ire_t	*ire = NULL;
7763 	mblk_t	*res_mp;
7764 	ipaddr_t *addrp;
7765 	ipaddr_t nexthop_addr;
7766 	ipif_t  *src_ipif = NULL;
7767 	ill_t	*dst_ill = NULL;
7768 	ipha_t  *ipha;
7769 	ire_t	*sire = NULL;
7770 	mblk_t	*first_mp;
7771 	ire_t	*save_ire;
7772 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7773 	ushort_t ire_marks = 0;
7774 	boolean_t mctl_present;
7775 	ipsec_out_t *io;
7776 	mblk_t	*saved_mp;
7777 	ire_t	*first_sire = NULL;
7778 	mblk_t	*copy_mp = NULL;
7779 	mblk_t	*xmit_mp = NULL;
7780 	ipaddr_t save_dst;
7781 	uint32_t multirt_flags =
7782 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7783 	boolean_t multirt_is_resolvable;
7784 	boolean_t multirt_resolve_next;
7785 	boolean_t unspec_src;
7786 	boolean_t do_attach_ill = B_FALSE;
7787 	boolean_t ip_nexthop = B_FALSE;
7788 	tsol_ire_gw_secattr_t *attrp = NULL;
7789 	tsol_gcgrp_t *gcgrp = NULL;
7790 	tsol_gcgrp_addr_t ga;
7791 
7792 	if (ip_debug > 2) {
7793 		/* ip1dbg */
7794 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7795 	}
7796 
7797 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7798 	if (mctl_present) {
7799 		io = (ipsec_out_t *)first_mp->b_rptr;
7800 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7801 		ASSERT(zoneid == io->ipsec_out_zoneid);
7802 		ASSERT(zoneid != ALL_ZONES);
7803 	}
7804 
7805 	ipha = (ipha_t *)mp->b_rptr;
7806 
7807 	/* All multicast lookups come through ip_newroute_ipif() */
7808 	if (CLASSD(dst)) {
7809 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7810 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7811 		freemsg(first_mp);
7812 		return;
7813 	}
7814 
7815 	if (mctl_present && io->ipsec_out_attach_if) {
7816 		/* ip_grab_attach_ill returns a held ill */
7817 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7818 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7819 
7820 		/* Failure case frees things for us. */
7821 		if (attach_ill == NULL)
7822 			return;
7823 
7824 		/*
7825 		 * Check if we need an ire that will not be
7826 		 * looked up by anybody else i.e. HIDDEN.
7827 		 */
7828 		if (ill_is_probeonly(attach_ill))
7829 			ire_marks = IRE_MARK_HIDDEN;
7830 	}
7831 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7832 		ip_nexthop = B_TRUE;
7833 		nexthop_addr = io->ipsec_out_nexthop_addr;
7834 	}
7835 	/*
7836 	 * If this IRE is created for forwarding or it is not for
7837 	 * traffic for congestion controlled protocols, mark it as temporary.
7838 	 */
7839 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7840 		ire_marks |= IRE_MARK_TEMPORARY;
7841 
7842 	/*
7843 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7844 	 * chain until it gets the most specific information available.
7845 	 * For example, we know that there is no IRE_CACHE for this dest,
7846 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7847 	 * ire_ftable_lookup will look up the gateway, etc.
7848 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7849 	 * to the destination, of equal netmask length in the forward table,
7850 	 * will be recursively explored. If no information is available
7851 	 * for the final gateway of that route, we force the returned ire
7852 	 * to be equal to sire using MATCH_IRE_PARENT.
7853 	 * At least, in this case we have a starting point (in the buckets)
7854 	 * to look for other routes to the destination in the forward table.
7855 	 * This is actually used only for multirouting, where a list
7856 	 * of routes has to be processed in sequence.
7857 	 *
7858 	 * In the process of coming up with the most specific information,
7859 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7860 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7861 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7862 	 * Two caveats when handling incomplete ire's in ip_newroute:
7863 	 * - we should be careful when accessing its ire_nce (specifically
7864 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7865 	 * - not all legacy code path callers are prepared to handle
7866 	 *   incomplete ire's, so we should not create/add incomplete
7867 	 *   ire_cache entries here. (See discussion about temporary solution
7868 	 *   further below).
7869 	 *
7870 	 * In order to minimize packet dropping, and to preserve existing
7871 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7872 	 * gateway, and instead use the IF_RESOLVER ire to send out
7873 	 * another request to ARP (this is achieved by passing the
7874 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7875 	 * arp response comes back in ip_wput_nondata, we will create
7876 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7877 	 *
7878 	 * Note that this is a temporary solution; the correct solution is
7879 	 * to create an incomplete  per-dst ire_cache entry, and send the
7880 	 * packet out when the gw's nce is resolved. In order to achieve this,
7881 	 * all packet processing must have been completed prior to calling
7882 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7883 	 * to be modified to accomodate this solution.
7884 	 */
7885 	if (ip_nexthop) {
7886 		/*
7887 		 * The first time we come here, we look for an IRE_INTERFACE
7888 		 * entry for the specified nexthop, set the dst to be the
7889 		 * nexthop address and create an IRE_CACHE entry for the
7890 		 * nexthop. The next time around, we are able to find an
7891 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7892 		 * nexthop address and create an IRE_CACHE entry for the
7893 		 * destination address via the specified nexthop.
7894 		 */
7895 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7896 		    MBLK_GETLABEL(mp), ipst);
7897 		if (ire != NULL) {
7898 			gw = nexthop_addr;
7899 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7900 		} else {
7901 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7902 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7903 			    MBLK_GETLABEL(mp),
7904 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7905 			    ipst);
7906 			if (ire != NULL) {
7907 				dst = nexthop_addr;
7908 			}
7909 		}
7910 	} else if (attach_ill == NULL) {
7911 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7912 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7913 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7914 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7915 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7916 		    ipst);
7917 	} else {
7918 		/*
7919 		 * attach_ill is set only for communicating with
7920 		 * on-link hosts. So, don't look for DEFAULT.
7921 		 */
7922 		ipif_t	*attach_ipif;
7923 
7924 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7925 		if (attach_ipif == NULL) {
7926 			ill_refrele(attach_ill);
7927 			goto icmp_err_ret;
7928 		}
7929 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7930 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7931 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7932 		    MATCH_IRE_SECATTR, ipst);
7933 		ipif_refrele(attach_ipif);
7934 	}
7935 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7936 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7937 
7938 	/*
7939 	 * This loop is run only once in most cases.
7940 	 * We loop to resolve further routes only when the destination
7941 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7942 	 */
7943 	do {
7944 		/* Clear the previous iteration's values */
7945 		if (src_ipif != NULL) {
7946 			ipif_refrele(src_ipif);
7947 			src_ipif = NULL;
7948 		}
7949 		if (dst_ill != NULL) {
7950 			ill_refrele(dst_ill);
7951 			dst_ill = NULL;
7952 		}
7953 
7954 		multirt_resolve_next = B_FALSE;
7955 		/*
7956 		 * We check if packets have to be multirouted.
7957 		 * In this case, given the current <ire, sire> couple,
7958 		 * we look for the next suitable <ire, sire>.
7959 		 * This check is done in ire_multirt_lookup(),
7960 		 * which applies various criteria to find the next route
7961 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7962 		 * unchanged if it detects it has not been tried yet.
7963 		 */
7964 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7965 			ip3dbg(("ip_newroute: starting next_resolution "
7966 			    "with first_mp %p, tag %d\n",
7967 			    (void *)first_mp,
7968 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7969 
7970 			ASSERT(sire != NULL);
7971 			multirt_is_resolvable =
7972 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7973 			    MBLK_GETLABEL(mp), ipst);
7974 
7975 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7976 			    "ire %p, sire %p\n",
7977 			    multirt_is_resolvable,
7978 			    (void *)ire, (void *)sire));
7979 
7980 			if (!multirt_is_resolvable) {
7981 				/*
7982 				 * No more multirt route to resolve; give up
7983 				 * (all routes resolved or no more
7984 				 * resolvable routes).
7985 				 */
7986 				if (ire != NULL) {
7987 					ire_refrele(ire);
7988 					ire = NULL;
7989 				}
7990 			} else {
7991 				ASSERT(sire != NULL);
7992 				ASSERT(ire != NULL);
7993 				/*
7994 				 * We simply use first_sire as a flag that
7995 				 * indicates if a resolvable multirt route
7996 				 * has already been found.
7997 				 * If it is not the case, we may have to send
7998 				 * an ICMP error to report that the
7999 				 * destination is unreachable.
8000 				 * We do not IRE_REFHOLD first_sire.
8001 				 */
8002 				if (first_sire == NULL) {
8003 					first_sire = sire;
8004 				}
8005 			}
8006 		}
8007 		if (ire == NULL) {
8008 			if (ip_debug > 3) {
8009 				/* ip2dbg */
8010 				pr_addr_dbg("ip_newroute: "
8011 				    "can't resolve %s\n", AF_INET, &dst);
8012 			}
8013 			ip3dbg(("ip_newroute: "
8014 			    "ire %p, sire %p, first_sire %p\n",
8015 			    (void *)ire, (void *)sire, (void *)first_sire));
8016 
8017 			if (sire != NULL) {
8018 				ire_refrele(sire);
8019 				sire = NULL;
8020 			}
8021 
8022 			if (first_sire != NULL) {
8023 				/*
8024 				 * At least one multirt route has been found
8025 				 * in the same call to ip_newroute();
8026 				 * there is no need to report an ICMP error.
8027 				 * first_sire was not IRE_REFHOLDed.
8028 				 */
8029 				MULTIRT_DEBUG_UNTAG(first_mp);
8030 				freemsg(first_mp);
8031 				return;
8032 			}
8033 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8034 			    RTA_DST, ipst);
8035 			if (attach_ill != NULL)
8036 				ill_refrele(attach_ill);
8037 			goto icmp_err_ret;
8038 		}
8039 
8040 		/*
8041 		 * Verify that the returned IRE does not have either
8042 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8043 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8044 		 */
8045 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8046 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8047 			if (attach_ill != NULL)
8048 				ill_refrele(attach_ill);
8049 			goto icmp_err_ret;
8050 		}
8051 		/*
8052 		 * Increment the ire_ob_pkt_count field for ire if it is an
8053 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8054 		 * increment the same for the parent IRE, sire, if it is some
8055 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8056 		 */
8057 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8058 			UPDATE_OB_PKT_COUNT(ire);
8059 			ire->ire_last_used_time = lbolt;
8060 		}
8061 
8062 		if (sire != NULL) {
8063 			gw = sire->ire_gateway_addr;
8064 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8065 			    IRE_INTERFACE)) == 0);
8066 			UPDATE_OB_PKT_COUNT(sire);
8067 			sire->ire_last_used_time = lbolt;
8068 		}
8069 		/*
8070 		 * We have a route to reach the destination.
8071 		 *
8072 		 * 1) If the interface is part of ill group, try to get a new
8073 		 *    ill taking load spreading into account.
8074 		 *
8075 		 * 2) After selecting the ill, get a source address that
8076 		 *    might create good inbound load spreading.
8077 		 *    ipif_select_source does this for us.
8078 		 *
8079 		 * If the application specified the ill (ifindex), we still
8080 		 * load spread. Only if the packets needs to go out
8081 		 * specifically on a given ill e.g. binding to
8082 		 * IPIF_NOFAILOVER address, then we don't try to use a
8083 		 * different ill for load spreading.
8084 		 */
8085 		if (attach_ill == NULL) {
8086 			/*
8087 			 * Don't perform outbound load spreading in the
8088 			 * case of an RTF_MULTIRT route, as we actually
8089 			 * typically want to replicate outgoing packets
8090 			 * through particular interfaces.
8091 			 */
8092 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8093 				dst_ill = ire->ire_ipif->ipif_ill;
8094 				/* for uniformity */
8095 				ill_refhold(dst_ill);
8096 			} else {
8097 				/*
8098 				 * If we are here trying to create an IRE_CACHE
8099 				 * for an offlink destination and have the
8100 				 * IRE_CACHE for the next hop and the latter is
8101 				 * using virtual IP source address selection i.e
8102 				 * it's ire->ire_ipif is pointing to a virtual
8103 				 * network interface (vni) then
8104 				 * ip_newroute_get_dst_ll() will return the vni
8105 				 * interface as the dst_ill. Since the vni is
8106 				 * virtual i.e not associated with any physical
8107 				 * interface, it cannot be the dst_ill, hence
8108 				 * in such a case call ip_newroute_get_dst_ll()
8109 				 * with the stq_ill instead of the ire_ipif ILL.
8110 				 * The function returns a refheld ill.
8111 				 */
8112 				if ((ire->ire_type == IRE_CACHE) &&
8113 				    IS_VNI(ire->ire_ipif->ipif_ill))
8114 					dst_ill = ip_newroute_get_dst_ill(
8115 					    ire->ire_stq->q_ptr);
8116 				else
8117 					dst_ill = ip_newroute_get_dst_ill(
8118 					    ire->ire_ipif->ipif_ill);
8119 			}
8120 			if (dst_ill == NULL) {
8121 				if (ip_debug > 2) {
8122 					pr_addr_dbg("ip_newroute: "
8123 					    "no dst ill for dst"
8124 					    " %s\n", AF_INET, &dst);
8125 				}
8126 				goto icmp_err_ret;
8127 			}
8128 		} else {
8129 			dst_ill = ire->ire_ipif->ipif_ill;
8130 			/* for uniformity */
8131 			ill_refhold(dst_ill);
8132 			/*
8133 			 * We should have found a route matching ill as we
8134 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8135 			 * Rather than asserting, when there is a mismatch,
8136 			 * we just drop the packet.
8137 			 */
8138 			if (dst_ill != attach_ill) {
8139 				ip0dbg(("ip_newroute: Packet dropped as "
8140 				    "IPIF_NOFAILOVER ill is %s, "
8141 				    "ire->ire_ipif->ipif_ill is %s\n",
8142 				    attach_ill->ill_name,
8143 				    dst_ill->ill_name));
8144 				ill_refrele(attach_ill);
8145 				goto icmp_err_ret;
8146 			}
8147 		}
8148 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8149 		if (attach_ill != NULL) {
8150 			ill_refrele(attach_ill);
8151 			attach_ill = NULL;
8152 			do_attach_ill = B_TRUE;
8153 		}
8154 		ASSERT(dst_ill != NULL);
8155 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8156 
8157 		/*
8158 		 * Pick the best source address from dst_ill.
8159 		 *
8160 		 * 1) If it is part of a multipathing group, we would
8161 		 *    like to spread the inbound packets across different
8162 		 *    interfaces. ipif_select_source picks a random source
8163 		 *    across the different ills in the group.
8164 		 *
8165 		 * 2) If it is not part of a multipathing group, we try
8166 		 *    to pick the source address from the destination
8167 		 *    route. Clustering assumes that when we have multiple
8168 		 *    prefixes hosted on an interface, the prefix of the
8169 		 *    source address matches the prefix of the destination
8170 		 *    route. We do this only if the address is not
8171 		 *    DEPRECATED.
8172 		 *
8173 		 * 3) If the conn is in a different zone than the ire, we
8174 		 *    need to pick a source address from the right zone.
8175 		 *
8176 		 * NOTE : If we hit case (1) above, the prefix of the source
8177 		 *	  address picked may not match the prefix of the
8178 		 *	  destination routes prefix as ipif_select_source
8179 		 *	  does not look at "dst" while picking a source
8180 		 *	  address.
8181 		 *	  If we want the same behavior as (2), we will need
8182 		 *	  to change the behavior of ipif_select_source.
8183 		 */
8184 		ASSERT(src_ipif == NULL);
8185 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8186 			/*
8187 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8188 			 * Check that the ipif matching the requested source
8189 			 * address still exists.
8190 			 */
8191 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8192 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8193 		}
8194 
8195 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8196 
8197 		if (src_ipif == NULL &&
8198 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8199 			ire_marks |= IRE_MARK_USESRC_CHECK;
8200 			if ((dst_ill->ill_group != NULL) ||
8201 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8202 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8203 			    ire->ire_zoneid != ALL_ZONES) ||
8204 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8205 				/*
8206 				 * If the destination is reachable via a
8207 				 * given gateway, the selected source address
8208 				 * should be in the same subnet as the gateway.
8209 				 * Otherwise, the destination is not reachable.
8210 				 *
8211 				 * If there are no interfaces on the same subnet
8212 				 * as the destination, ipif_select_source gives
8213 				 * first non-deprecated interface which might be
8214 				 * on a different subnet than the gateway.
8215 				 * This is not desirable. Hence pass the dst_ire
8216 				 * source address to ipif_select_source.
8217 				 * It is sure that the destination is reachable
8218 				 * with the dst_ire source address subnet.
8219 				 * So passing dst_ire source address to
8220 				 * ipif_select_source will make sure that the
8221 				 * selected source will be on the same subnet
8222 				 * as dst_ire source address.
8223 				 */
8224 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8225 				src_ipif = ipif_select_source(dst_ill, saddr,
8226 				    zoneid);
8227 				if (src_ipif == NULL) {
8228 					if (ip_debug > 2) {
8229 						pr_addr_dbg("ip_newroute: "
8230 						    "no src for dst %s ",
8231 						    AF_INET, &dst);
8232 						printf("through interface %s\n",
8233 						    dst_ill->ill_name);
8234 					}
8235 					goto icmp_err_ret;
8236 				}
8237 			} else {
8238 				src_ipif = ire->ire_ipif;
8239 				ASSERT(src_ipif != NULL);
8240 				/* hold src_ipif for uniformity */
8241 				ipif_refhold(src_ipif);
8242 			}
8243 		}
8244 
8245 		/*
8246 		 * Assign a source address while we have the conn.
8247 		 * We can't have ip_wput_ire pick a source address when the
8248 		 * packet returns from arp since we need to look at
8249 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8250 		 * going through arp.
8251 		 *
8252 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8253 		 *	  it uses ip6i to store this information.
8254 		 */
8255 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8256 			ipha->ipha_src = src_ipif->ipif_src_addr;
8257 
8258 		if (ip_debug > 3) {
8259 			/* ip2dbg */
8260 			pr_addr_dbg("ip_newroute: first hop %s\n",
8261 			    AF_INET, &gw);
8262 		}
8263 		ip2dbg(("\tire type %s (%d)\n",
8264 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8265 
8266 		/*
8267 		 * The TTL of multirouted packets is bounded by the
8268 		 * ip_multirt_ttl ndd variable.
8269 		 */
8270 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8271 			/* Force TTL of multirouted packets */
8272 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8273 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8274 				ip2dbg(("ip_newroute: forcing multirt TTL "
8275 				    "to %d (was %d), dst 0x%08x\n",
8276 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8277 				    ntohl(sire->ire_addr)));
8278 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8279 			}
8280 		}
8281 		/*
8282 		 * At this point in ip_newroute(), ire is either the
8283 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8284 		 * destination or an IRE_INTERFACE type that should be used
8285 		 * to resolve an on-subnet destination or an on-subnet
8286 		 * next-hop gateway.
8287 		 *
8288 		 * In the IRE_CACHE case, we have the following :
8289 		 *
8290 		 * 1) src_ipif - used for getting a source address.
8291 		 *
8292 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8293 		 *    means packets using this IRE_CACHE will go out on
8294 		 *    dst_ill.
8295 		 *
8296 		 * 3) The IRE sire will point to the prefix that is the
8297 		 *    longest  matching route for the destination. These
8298 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8299 		 *
8300 		 *    The newly created IRE_CACHE entry for the off-subnet
8301 		 *    destination is tied to both the prefix route and the
8302 		 *    interface route used to resolve the next-hop gateway
8303 		 *    via the ire_phandle and ire_ihandle fields,
8304 		 *    respectively.
8305 		 *
8306 		 * In the IRE_INTERFACE case, we have the following :
8307 		 *
8308 		 * 1) src_ipif - used for getting a source address.
8309 		 *
8310 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8311 		 *    means packets using the IRE_CACHE that we will build
8312 		 *    here will go out on dst_ill.
8313 		 *
8314 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8315 		 *    to be created will only be tied to the IRE_INTERFACE
8316 		 *    that was derived from the ire_ihandle field.
8317 		 *
8318 		 *    If sire is non-NULL, it means the destination is
8319 		 *    off-link and we will first create the IRE_CACHE for the
8320 		 *    gateway. Next time through ip_newroute, we will create
8321 		 *    the IRE_CACHE for the final destination as described
8322 		 *    above.
8323 		 *
8324 		 * In both cases, after the current resolution has been
8325 		 * completed (or possibly initialised, in the IRE_INTERFACE
8326 		 * case), the loop may be re-entered to attempt the resolution
8327 		 * of another RTF_MULTIRT route.
8328 		 *
8329 		 * When an IRE_CACHE entry for the off-subnet destination is
8330 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8331 		 * for further processing in emission loops.
8332 		 */
8333 		save_ire = ire;
8334 		switch (ire->ire_type) {
8335 		case IRE_CACHE: {
8336 			ire_t	*ipif_ire;
8337 
8338 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8339 			if (gw == 0)
8340 				gw = ire->ire_gateway_addr;
8341 			/*
8342 			 * We need 3 ire's to create a new cache ire for an
8343 			 * off-link destination from the cache ire of the
8344 			 * gateway.
8345 			 *
8346 			 *	1. The prefix ire 'sire' (Note that this does
8347 			 *	   not apply to the conn_nexthop_set case)
8348 			 *	2. The cache ire of the gateway 'ire'
8349 			 *	3. The interface ire 'ipif_ire'
8350 			 *
8351 			 * We have (1) and (2). We lookup (3) below.
8352 			 *
8353 			 * If there is no interface route to the gateway,
8354 			 * it is a race condition, where we found the cache
8355 			 * but the interface route has been deleted.
8356 			 */
8357 			if (ip_nexthop) {
8358 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8359 			} else {
8360 				ipif_ire =
8361 				    ire_ihandle_lookup_offlink(ire, sire);
8362 			}
8363 			if (ipif_ire == NULL) {
8364 				ip1dbg(("ip_newroute: "
8365 				    "ire_ihandle_lookup_offlink failed\n"));
8366 				goto icmp_err_ret;
8367 			}
8368 
8369 			/*
8370 			 * Check cached gateway IRE for any security
8371 			 * attributes; if found, associate the gateway
8372 			 * credentials group to the destination IRE.
8373 			 */
8374 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8375 				mutex_enter(&attrp->igsa_lock);
8376 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8377 					GCGRP_REFHOLD(gcgrp);
8378 				mutex_exit(&attrp->igsa_lock);
8379 			}
8380 
8381 			/*
8382 			 * XXX For the source of the resolver mp,
8383 			 * we are using the same DL_UNITDATA_REQ
8384 			 * (from save_ire->ire_nce->nce_res_mp)
8385 			 * though the save_ire is not pointing at the same ill.
8386 			 * This is incorrect. We need to send it up to the
8387 			 * resolver to get the right res_mp. For ethernets
8388 			 * this may be okay (ill_type == DL_ETHER).
8389 			 */
8390 
8391 			ire = ire_create(
8392 			    (uchar_t *)&dst,		/* dest address */
8393 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8394 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8395 			    (uchar_t *)&gw,		/* gateway address */
8396 			    &save_ire->ire_max_frag,
8397 			    save_ire->ire_nce,		/* src nce */
8398 			    dst_ill->ill_rq,		/* recv-from queue */
8399 			    dst_ill->ill_wq,		/* send-to queue */
8400 			    IRE_CACHE,			/* IRE type */
8401 			    src_ipif,
8402 			    (sire != NULL) ?
8403 			    sire->ire_mask : 0, 	/* Parent mask */
8404 			    (sire != NULL) ?
8405 			    sire->ire_phandle : 0,	/* Parent handle */
8406 			    ipif_ire->ire_ihandle,	/* Interface handle */
8407 			    (sire != NULL) ? (sire->ire_flags &
8408 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8409 			    (sire != NULL) ?
8410 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8411 			    NULL,
8412 			    gcgrp,
8413 			    ipst);
8414 
8415 			if (ire == NULL) {
8416 				if (gcgrp != NULL) {
8417 					GCGRP_REFRELE(gcgrp);
8418 					gcgrp = NULL;
8419 				}
8420 				ire_refrele(ipif_ire);
8421 				ire_refrele(save_ire);
8422 				break;
8423 			}
8424 
8425 			/* reference now held by IRE */
8426 			gcgrp = NULL;
8427 
8428 			ire->ire_marks |= ire_marks;
8429 
8430 			/*
8431 			 * Prevent sire and ipif_ire from getting deleted.
8432 			 * The newly created ire is tied to both of them via
8433 			 * the phandle and ihandle respectively.
8434 			 */
8435 			if (sire != NULL) {
8436 				IRB_REFHOLD(sire->ire_bucket);
8437 				/* Has it been removed already ? */
8438 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8439 					IRB_REFRELE(sire->ire_bucket);
8440 					ire_refrele(ipif_ire);
8441 					ire_refrele(save_ire);
8442 					break;
8443 				}
8444 			}
8445 
8446 			IRB_REFHOLD(ipif_ire->ire_bucket);
8447 			/* Has it been removed already ? */
8448 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8449 				IRB_REFRELE(ipif_ire->ire_bucket);
8450 				if (sire != NULL)
8451 					IRB_REFRELE(sire->ire_bucket);
8452 				ire_refrele(ipif_ire);
8453 				ire_refrele(save_ire);
8454 				break;
8455 			}
8456 
8457 			xmit_mp = first_mp;
8458 			/*
8459 			 * In the case of multirouting, a copy
8460 			 * of the packet is done before its sending.
8461 			 * The copy is used to attempt another
8462 			 * route resolution, in a next loop.
8463 			 */
8464 			if (ire->ire_flags & RTF_MULTIRT) {
8465 				copy_mp = copymsg(first_mp);
8466 				if (copy_mp != NULL) {
8467 					xmit_mp = copy_mp;
8468 					MULTIRT_DEBUG_TAG(first_mp);
8469 				}
8470 			}
8471 			ire_add_then_send(q, ire, xmit_mp);
8472 			ire_refrele(save_ire);
8473 
8474 			/* Assert that sire is not deleted yet. */
8475 			if (sire != NULL) {
8476 				ASSERT(sire->ire_ptpn != NULL);
8477 				IRB_REFRELE(sire->ire_bucket);
8478 			}
8479 
8480 			/* Assert that ipif_ire is not deleted yet. */
8481 			ASSERT(ipif_ire->ire_ptpn != NULL);
8482 			IRB_REFRELE(ipif_ire->ire_bucket);
8483 			ire_refrele(ipif_ire);
8484 
8485 			/*
8486 			 * If copy_mp is not NULL, multirouting was
8487 			 * requested. We loop to initiate a next
8488 			 * route resolution attempt, starting from sire.
8489 			 */
8490 			if (copy_mp != NULL) {
8491 				/*
8492 				 * Search for the next unresolved
8493 				 * multirt route.
8494 				 */
8495 				copy_mp = NULL;
8496 				ipif_ire = NULL;
8497 				ire = NULL;
8498 				multirt_resolve_next = B_TRUE;
8499 				continue;
8500 			}
8501 			if (sire != NULL)
8502 				ire_refrele(sire);
8503 			ipif_refrele(src_ipif);
8504 			ill_refrele(dst_ill);
8505 			return;
8506 		}
8507 		case IRE_IF_NORESOLVER: {
8508 
8509 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8510 			    dst_ill->ill_resolver_mp == NULL) {
8511 				ip1dbg(("ip_newroute: dst_ill %p "
8512 				    "for IRE_IF_NORESOLVER ire %p has "
8513 				    "no ill_resolver_mp\n",
8514 				    (void *)dst_ill, (void *)ire));
8515 				break;
8516 			}
8517 
8518 			/*
8519 			 * TSol note: We are creating the ire cache for the
8520 			 * destination 'dst'. If 'dst' is offlink, going
8521 			 * through the first hop 'gw', the security attributes
8522 			 * of 'dst' must be set to point to the gateway
8523 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8524 			 * is possible that 'dst' is a potential gateway that is
8525 			 * referenced by some route that has some security
8526 			 * attributes. Thus in the former case, we need to do a
8527 			 * gcgrp_lookup of 'gw' while in the latter case we
8528 			 * need to do gcgrp_lookup of 'dst' itself.
8529 			 */
8530 			ga.ga_af = AF_INET;
8531 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8532 			    &ga.ga_addr);
8533 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8534 
8535 			ire = ire_create(
8536 			    (uchar_t *)&dst,		/* dest address */
8537 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8538 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8539 			    (uchar_t *)&gw,		/* gateway address */
8540 			    &save_ire->ire_max_frag,
8541 			    NULL,			/* no src nce */
8542 			    dst_ill->ill_rq,		/* recv-from queue */
8543 			    dst_ill->ill_wq,		/* send-to queue */
8544 			    IRE_CACHE,
8545 			    src_ipif,
8546 			    save_ire->ire_mask,		/* Parent mask */
8547 			    (sire != NULL) ?		/* Parent handle */
8548 			    sire->ire_phandle : 0,
8549 			    save_ire->ire_ihandle,	/* Interface handle */
8550 			    (sire != NULL) ? sire->ire_flags &
8551 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8552 			    &(save_ire->ire_uinfo),
8553 			    NULL,
8554 			    gcgrp,
8555 			    ipst);
8556 
8557 			if (ire == NULL) {
8558 				if (gcgrp != NULL) {
8559 					GCGRP_REFRELE(gcgrp);
8560 					gcgrp = NULL;
8561 				}
8562 				ire_refrele(save_ire);
8563 				break;
8564 			}
8565 
8566 			/* reference now held by IRE */
8567 			gcgrp = NULL;
8568 
8569 			ire->ire_marks |= ire_marks;
8570 
8571 			/* Prevent save_ire from getting deleted */
8572 			IRB_REFHOLD(save_ire->ire_bucket);
8573 			/* Has it been removed already ? */
8574 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8575 				IRB_REFRELE(save_ire->ire_bucket);
8576 				ire_refrele(save_ire);
8577 				break;
8578 			}
8579 
8580 			/*
8581 			 * In the case of multirouting, a copy
8582 			 * of the packet is made before it is sent.
8583 			 * The copy is used in the next
8584 			 * loop to attempt another resolution.
8585 			 */
8586 			xmit_mp = first_mp;
8587 			if ((sire != NULL) &&
8588 			    (sire->ire_flags & RTF_MULTIRT)) {
8589 				copy_mp = copymsg(first_mp);
8590 				if (copy_mp != NULL) {
8591 					xmit_mp = copy_mp;
8592 					MULTIRT_DEBUG_TAG(first_mp);
8593 				}
8594 			}
8595 			ire_add_then_send(q, ire, xmit_mp);
8596 
8597 			/* Assert that it is not deleted yet. */
8598 			ASSERT(save_ire->ire_ptpn != NULL);
8599 			IRB_REFRELE(save_ire->ire_bucket);
8600 			ire_refrele(save_ire);
8601 
8602 			if (copy_mp != NULL) {
8603 				/*
8604 				 * If we found a (no)resolver, we ignore any
8605 				 * trailing top priority IRE_CACHE in further
8606 				 * loops. This ensures that we do not omit any
8607 				 * (no)resolver.
8608 				 * This IRE_CACHE, if any, will be processed
8609 				 * by another thread entering ip_newroute().
8610 				 * IRE_CACHE entries, if any, will be processed
8611 				 * by another thread entering ip_newroute(),
8612 				 * (upon resolver response, for instance).
8613 				 * This aims to force parallel multirt
8614 				 * resolutions as soon as a packet must be sent.
8615 				 * In the best case, after the tx of only one
8616 				 * packet, all reachable routes are resolved.
8617 				 * Otherwise, the resolution of all RTF_MULTIRT
8618 				 * routes would require several emissions.
8619 				 */
8620 				multirt_flags &= ~MULTIRT_CACHEGW;
8621 
8622 				/*
8623 				 * Search for the next unresolved multirt
8624 				 * route.
8625 				 */
8626 				copy_mp = NULL;
8627 				save_ire = NULL;
8628 				ire = NULL;
8629 				multirt_resolve_next = B_TRUE;
8630 				continue;
8631 			}
8632 
8633 			/*
8634 			 * Don't need sire anymore
8635 			 */
8636 			if (sire != NULL)
8637 				ire_refrele(sire);
8638 
8639 			ipif_refrele(src_ipif);
8640 			ill_refrele(dst_ill);
8641 			return;
8642 		}
8643 		case IRE_IF_RESOLVER:
8644 			/*
8645 			 * We can't build an IRE_CACHE yet, but at least we
8646 			 * found a resolver that can help.
8647 			 */
8648 			res_mp = dst_ill->ill_resolver_mp;
8649 			if (!OK_RESOLVER_MP(res_mp))
8650 				break;
8651 
8652 			/*
8653 			 * To be at this point in the code with a non-zero gw
8654 			 * means that dst is reachable through a gateway that
8655 			 * we have never resolved.  By changing dst to the gw
8656 			 * addr we resolve the gateway first.
8657 			 * When ire_add_then_send() tries to put the IP dg
8658 			 * to dst, it will reenter ip_newroute() at which
8659 			 * time we will find the IRE_CACHE for the gw and
8660 			 * create another IRE_CACHE in case IRE_CACHE above.
8661 			 */
8662 			if (gw != INADDR_ANY) {
8663 				/*
8664 				 * The source ipif that was determined above was
8665 				 * relative to the destination address, not the
8666 				 * gateway's. If src_ipif was not taken out of
8667 				 * the IRE_IF_RESOLVER entry, we'll need to call
8668 				 * ipif_select_source() again.
8669 				 */
8670 				if (src_ipif != ire->ire_ipif) {
8671 					ipif_refrele(src_ipif);
8672 					src_ipif = ipif_select_source(dst_ill,
8673 					    gw, zoneid);
8674 					if (src_ipif == NULL) {
8675 						if (ip_debug > 2) {
8676 							pr_addr_dbg(
8677 							    "ip_newroute: no "
8678 							    "src for gw %s ",
8679 							    AF_INET, &gw);
8680 							printf("through "
8681 							    "interface %s\n",
8682 							    dst_ill->ill_name);
8683 						}
8684 						goto icmp_err_ret;
8685 					}
8686 				}
8687 				save_dst = dst;
8688 				dst = gw;
8689 				gw = INADDR_ANY;
8690 			}
8691 
8692 			/*
8693 			 * We obtain a partial IRE_CACHE which we will pass
8694 			 * along with the resolver query.  When the response
8695 			 * comes back it will be there ready for us to add.
8696 			 * The ire_max_frag is atomically set under the
8697 			 * irebucket lock in ire_add_v[46].
8698 			 */
8699 
8700 			ire = ire_create_mp(
8701 			    (uchar_t *)&dst,		/* dest address */
8702 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8703 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8704 			    (uchar_t *)&gw,		/* gateway address */
8705 			    NULL,			/* ire_max_frag */
8706 			    NULL,			/* no src nce */
8707 			    dst_ill->ill_rq,		/* recv-from queue */
8708 			    dst_ill->ill_wq,		/* send-to queue */
8709 			    IRE_CACHE,
8710 			    src_ipif,			/* Interface ipif */
8711 			    save_ire->ire_mask,		/* Parent mask */
8712 			    0,
8713 			    save_ire->ire_ihandle,	/* Interface handle */
8714 			    0,				/* flags if any */
8715 			    &(save_ire->ire_uinfo),
8716 			    NULL,
8717 			    NULL,
8718 			    ipst);
8719 
8720 			if (ire == NULL) {
8721 				ire_refrele(save_ire);
8722 				break;
8723 			}
8724 
8725 			if ((sire != NULL) &&
8726 			    (sire->ire_flags & RTF_MULTIRT)) {
8727 				copy_mp = copymsg(first_mp);
8728 				if (copy_mp != NULL)
8729 					MULTIRT_DEBUG_TAG(copy_mp);
8730 			}
8731 
8732 			ire->ire_marks |= ire_marks;
8733 
8734 			/*
8735 			 * Construct message chain for the resolver
8736 			 * of the form:
8737 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8738 			 * Packet could contain a IPSEC_OUT mp.
8739 			 *
8740 			 * NOTE : ire will be added later when the response
8741 			 * comes back from ARP. If the response does not
8742 			 * come back, ARP frees the packet. For this reason,
8743 			 * we can't REFHOLD the bucket of save_ire to prevent
8744 			 * deletions. We may not be able to REFRELE the bucket
8745 			 * if the response never comes back. Thus, before
8746 			 * adding the ire, ire_add_v4 will make sure that the
8747 			 * interface route does not get deleted. This is the
8748 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8749 			 * where we can always prevent deletions because of
8750 			 * the synchronous nature of adding IRES i.e
8751 			 * ire_add_then_send is called after creating the IRE.
8752 			 */
8753 			ASSERT(ire->ire_mp != NULL);
8754 			ire->ire_mp->b_cont = first_mp;
8755 			/* Have saved_mp handy, for cleanup if canput fails */
8756 			saved_mp = mp;
8757 			mp = copyb(res_mp);
8758 			if (mp == NULL) {
8759 				/* Prepare for cleanup */
8760 				mp = saved_mp; /* pkt */
8761 				ire_delete(ire); /* ire_mp */
8762 				ire = NULL;
8763 				ire_refrele(save_ire);
8764 				if (copy_mp != NULL) {
8765 					MULTIRT_DEBUG_UNTAG(copy_mp);
8766 					freemsg(copy_mp);
8767 					copy_mp = NULL;
8768 				}
8769 				break;
8770 			}
8771 			linkb(mp, ire->ire_mp);
8772 
8773 			/*
8774 			 * Fill in the source and dest addrs for the resolver.
8775 			 * NOTE: this depends on memory layouts imposed by
8776 			 * ill_init().
8777 			 */
8778 			areq = (areq_t *)mp->b_rptr;
8779 			addrp = (ipaddr_t *)((char *)areq +
8780 			    areq->areq_sender_addr_offset);
8781 			if (do_attach_ill) {
8782 				/*
8783 				 * This is bind to no failover case.
8784 				 * arp packet also must go out on attach_ill.
8785 				 */
8786 				ASSERT(ipha->ipha_src != NULL);
8787 				*addrp = ipha->ipha_src;
8788 			} else {
8789 				*addrp = save_ire->ire_src_addr;
8790 			}
8791 
8792 			ire_refrele(save_ire);
8793 			addrp = (ipaddr_t *)((char *)areq +
8794 			    areq->areq_target_addr_offset);
8795 			*addrp = dst;
8796 			/* Up to the resolver. */
8797 			if (canputnext(dst_ill->ill_rq) &&
8798 			    !(dst_ill->ill_arp_closing)) {
8799 				putnext(dst_ill->ill_rq, mp);
8800 				ire = NULL;
8801 				if (copy_mp != NULL) {
8802 					/*
8803 					 * If we found a resolver, we ignore
8804 					 * any trailing top priority IRE_CACHE
8805 					 * in the further loops. This ensures
8806 					 * that we do not omit any resolver.
8807 					 * IRE_CACHE entries, if any, will be
8808 					 * processed next time we enter
8809 					 * ip_newroute().
8810 					 */
8811 					multirt_flags &= ~MULTIRT_CACHEGW;
8812 					/*
8813 					 * Search for the next unresolved
8814 					 * multirt route.
8815 					 */
8816 					first_mp = copy_mp;
8817 					copy_mp = NULL;
8818 					/* Prepare the next resolution loop. */
8819 					mp = first_mp;
8820 					EXTRACT_PKT_MP(mp, first_mp,
8821 					    mctl_present);
8822 					if (mctl_present)
8823 						io = (ipsec_out_t *)
8824 						    first_mp->b_rptr;
8825 					ipha = (ipha_t *)mp->b_rptr;
8826 
8827 					ASSERT(sire != NULL);
8828 
8829 					dst = save_dst;
8830 					multirt_resolve_next = B_TRUE;
8831 					continue;
8832 				}
8833 
8834 				if (sire != NULL)
8835 					ire_refrele(sire);
8836 
8837 				/*
8838 				 * The response will come back in ip_wput
8839 				 * with db_type IRE_DB_TYPE.
8840 				 */
8841 				ipif_refrele(src_ipif);
8842 				ill_refrele(dst_ill);
8843 				return;
8844 			} else {
8845 				/* Prepare for cleanup */
8846 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8847 				    mp);
8848 				mp->b_cont = NULL;
8849 				freeb(mp); /* areq */
8850 				/*
8851 				 * this is an ire that is not added to the
8852 				 * cache. ire_freemblk will handle the release
8853 				 * of any resources associated with the ire.
8854 				 */
8855 				ire_delete(ire); /* ire_mp */
8856 				mp = saved_mp; /* pkt */
8857 				ire = NULL;
8858 				if (copy_mp != NULL) {
8859 					MULTIRT_DEBUG_UNTAG(copy_mp);
8860 					freemsg(copy_mp);
8861 					copy_mp = NULL;
8862 				}
8863 				break;
8864 			}
8865 		default:
8866 			break;
8867 		}
8868 	} while (multirt_resolve_next);
8869 
8870 	ip1dbg(("ip_newroute: dropped\n"));
8871 	/* Did this packet originate externally? */
8872 	if (mp->b_prev) {
8873 		mp->b_next = NULL;
8874 		mp->b_prev = NULL;
8875 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8876 	} else {
8877 		if (dst_ill != NULL) {
8878 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8879 		} else {
8880 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8881 		}
8882 	}
8883 	ASSERT(copy_mp == NULL);
8884 	MULTIRT_DEBUG_UNTAG(first_mp);
8885 	freemsg(first_mp);
8886 	if (ire != NULL)
8887 		ire_refrele(ire);
8888 	if (sire != NULL)
8889 		ire_refrele(sire);
8890 	if (src_ipif != NULL)
8891 		ipif_refrele(src_ipif);
8892 	if (dst_ill != NULL)
8893 		ill_refrele(dst_ill);
8894 	return;
8895 
8896 icmp_err_ret:
8897 	ip1dbg(("ip_newroute: no route\n"));
8898 	if (src_ipif != NULL)
8899 		ipif_refrele(src_ipif);
8900 	if (dst_ill != NULL)
8901 		ill_refrele(dst_ill);
8902 	if (sire != NULL)
8903 		ire_refrele(sire);
8904 	/* Did this packet originate externally? */
8905 	if (mp->b_prev) {
8906 		mp->b_next = NULL;
8907 		mp->b_prev = NULL;
8908 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8909 		q = WR(q);
8910 	} else {
8911 		/*
8912 		 * There is no outgoing ill, so just increment the
8913 		 * system MIB.
8914 		 */
8915 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8916 		/*
8917 		 * Since ip_wput() isn't close to finished, we fill
8918 		 * in enough of the header for credible error reporting.
8919 		 */
8920 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8921 			/* Failed */
8922 			MULTIRT_DEBUG_UNTAG(first_mp);
8923 			freemsg(first_mp);
8924 			if (ire != NULL)
8925 				ire_refrele(ire);
8926 			return;
8927 		}
8928 	}
8929 
8930 	/*
8931 	 * At this point we will have ire only if RTF_BLACKHOLE
8932 	 * or RTF_REJECT flags are set on the IRE. It will not
8933 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8934 	 */
8935 	if (ire != NULL) {
8936 		if (ire->ire_flags & RTF_BLACKHOLE) {
8937 			ire_refrele(ire);
8938 			MULTIRT_DEBUG_UNTAG(first_mp);
8939 			freemsg(first_mp);
8940 			return;
8941 		}
8942 		ire_refrele(ire);
8943 	}
8944 	if (ip_source_routed(ipha, ipst)) {
8945 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8946 		    zoneid, ipst);
8947 		return;
8948 	}
8949 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8950 }
8951 
8952 ip_opt_info_t zero_info;
8953 
8954 /*
8955  * IPv4 -
8956  * ip_newroute_ipif is called by ip_wput_multicast and
8957  * ip_rput_forward_multicast whenever we need to send
8958  * out a packet to a destination address for which we do not have specific
8959  * routing information. It is used when the packet will be sent out
8960  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8961  * socket option is set or icmp error message wants to go out on a particular
8962  * interface for a unicast packet.
8963  *
8964  * In most cases, the destination address is resolved thanks to the ipif
8965  * intrinsic resolver. However, there are some cases where the call to
8966  * ip_newroute_ipif must take into account the potential presence of
8967  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8968  * that uses the interface. This is specified through flags,
8969  * which can be a combination of:
8970  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8971  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8972  *   and flags. Additionally, the packet source address has to be set to
8973  *   the specified address. The caller is thus expected to set this flag
8974  *   if the packet has no specific source address yet.
8975  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8976  *   flag, the resulting ire will inherit the flag. All unresolved routes
8977  *   to the destination must be explored in the same call to
8978  *   ip_newroute_ipif().
8979  */
8980 static void
8981 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8982     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8983 {
8984 	areq_t	*areq;
8985 	ire_t	*ire = NULL;
8986 	mblk_t	*res_mp;
8987 	ipaddr_t *addrp;
8988 	mblk_t *first_mp;
8989 	ire_t	*save_ire = NULL;
8990 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8991 	ipif_t	*src_ipif = NULL;
8992 	ushort_t ire_marks = 0;
8993 	ill_t	*dst_ill = NULL;
8994 	boolean_t mctl_present;
8995 	ipsec_out_t *io;
8996 	ipha_t *ipha;
8997 	int	ihandle = 0;
8998 	mblk_t	*saved_mp;
8999 	ire_t   *fire = NULL;
9000 	mblk_t  *copy_mp = NULL;
9001 	boolean_t multirt_resolve_next;
9002 	boolean_t unspec_src;
9003 	ipaddr_t ipha_dst;
9004 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9005 
9006 	/*
9007 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9008 	 * here for uniformity
9009 	 */
9010 	ipif_refhold(ipif);
9011 
9012 	/*
9013 	 * This loop is run only once in most cases.
9014 	 * We loop to resolve further routes only when the destination
9015 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9016 	 */
9017 	do {
9018 		if (dst_ill != NULL) {
9019 			ill_refrele(dst_ill);
9020 			dst_ill = NULL;
9021 		}
9022 		if (src_ipif != NULL) {
9023 			ipif_refrele(src_ipif);
9024 			src_ipif = NULL;
9025 		}
9026 		multirt_resolve_next = B_FALSE;
9027 
9028 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9029 		    ipif->ipif_ill->ill_name));
9030 
9031 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9032 		if (mctl_present)
9033 			io = (ipsec_out_t *)first_mp->b_rptr;
9034 
9035 		ipha = (ipha_t *)mp->b_rptr;
9036 
9037 		/*
9038 		 * Save the packet destination address, we may need it after
9039 		 * the packet has been consumed.
9040 		 */
9041 		ipha_dst = ipha->ipha_dst;
9042 
9043 		/*
9044 		 * If the interface is a pt-pt interface we look for an
9045 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9046 		 * local_address and the pt-pt destination address. Otherwise
9047 		 * we just match the local address.
9048 		 * NOTE: dst could be different than ipha->ipha_dst in case
9049 		 * of sending igmp multicast packets over a point-to-point
9050 		 * connection.
9051 		 * Thus we must be careful enough to check ipha_dst to be a
9052 		 * multicast address, otherwise it will take xmit_if path for
9053 		 * multicast packets resulting into kernel stack overflow by
9054 		 * repeated calls to ip_newroute_ipif from ire_send().
9055 		 */
9056 		if (CLASSD(ipha_dst) &&
9057 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9058 			goto err_ret;
9059 		}
9060 
9061 		/*
9062 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9063 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9064 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9065 		 * propagate its flags to the new ire.
9066 		 */
9067 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9068 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9069 			ip2dbg(("ip_newroute_ipif: "
9070 			    "ipif_lookup_multi_ire("
9071 			    "ipif %p, dst %08x) = fire %p\n",
9072 			    (void *)ipif, ntohl(dst), (void *)fire));
9073 		}
9074 
9075 		if (mctl_present && io->ipsec_out_attach_if) {
9076 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9077 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9078 
9079 			/* Failure case frees things for us. */
9080 			if (attach_ill == NULL) {
9081 				ipif_refrele(ipif);
9082 				if (fire != NULL)
9083 					ire_refrele(fire);
9084 				return;
9085 			}
9086 
9087 			/*
9088 			 * Check if we need an ire that will not be
9089 			 * looked up by anybody else i.e. HIDDEN.
9090 			 */
9091 			if (ill_is_probeonly(attach_ill)) {
9092 				ire_marks = IRE_MARK_HIDDEN;
9093 			}
9094 			/*
9095 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9096 			 * case.
9097 			 */
9098 			dst_ill = ipif->ipif_ill;
9099 			/* attach_ill has been refheld by ip_grab_attach_ill */
9100 			ASSERT(dst_ill == attach_ill);
9101 		} else {
9102 			/*
9103 			 * If the interface belongs to an interface group,
9104 			 * make sure the next possible interface in the group
9105 			 * is used.  This encourages load spreading among
9106 			 * peers in an interface group.
9107 			 * Note: load spreading is disabled for RTF_MULTIRT
9108 			 * routes.
9109 			 */
9110 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9111 			    (fire->ire_flags & RTF_MULTIRT)) {
9112 				/*
9113 				 * Don't perform outbound load spreading
9114 				 * in the case of an RTF_MULTIRT issued route,
9115 				 * we actually typically want to replicate
9116 				 * outgoing packets through particular
9117 				 * interfaces.
9118 				 */
9119 				dst_ill = ipif->ipif_ill;
9120 				ill_refhold(dst_ill);
9121 			} else {
9122 				dst_ill = ip_newroute_get_dst_ill(
9123 				    ipif->ipif_ill);
9124 			}
9125 			if (dst_ill == NULL) {
9126 				if (ip_debug > 2) {
9127 					pr_addr_dbg("ip_newroute_ipif: "
9128 					    "no dst ill for dst %s\n",
9129 					    AF_INET, &dst);
9130 				}
9131 				goto err_ret;
9132 			}
9133 		}
9134 
9135 		/*
9136 		 * Pick a source address preferring non-deprecated ones.
9137 		 * Unlike ip_newroute, we don't do any source address
9138 		 * selection here since for multicast it really does not help
9139 		 * in inbound load spreading as in the unicast case.
9140 		 */
9141 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9142 		    (fire->ire_flags & RTF_SETSRC)) {
9143 			/*
9144 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9145 			 * on that interface. This ire has RTF_SETSRC flag, so
9146 			 * the source address of the packet must be changed.
9147 			 * Check that the ipif matching the requested source
9148 			 * address still exists.
9149 			 */
9150 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9151 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9152 		}
9153 
9154 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9155 
9156 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9157 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9158 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9159 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9160 		    (src_ipif == NULL) &&
9161 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9162 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9163 			if (src_ipif == NULL) {
9164 				if (ip_debug > 2) {
9165 					/* ip1dbg */
9166 					pr_addr_dbg("ip_newroute_ipif: "
9167 					    "no src for dst %s",
9168 					    AF_INET, &dst);
9169 				}
9170 				ip1dbg((" through interface %s\n",
9171 				    dst_ill->ill_name));
9172 				goto err_ret;
9173 			}
9174 			ipif_refrele(ipif);
9175 			ipif = src_ipif;
9176 			ipif_refhold(ipif);
9177 		}
9178 		if (src_ipif == NULL) {
9179 			src_ipif = ipif;
9180 			ipif_refhold(src_ipif);
9181 		}
9182 
9183 		/*
9184 		 * Assign a source address while we have the conn.
9185 		 * We can't have ip_wput_ire pick a source address when the
9186 		 * packet returns from arp since conn_unspec_src might be set
9187 		 * and we lose the conn when going through arp.
9188 		 */
9189 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9190 			ipha->ipha_src = src_ipif->ipif_src_addr;
9191 
9192 		/*
9193 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9194 		 * that the outgoing interface does not have an interface ire.
9195 		 */
9196 		if (CLASSD(ipha_dst) && (connp == NULL ||
9197 		    connp->conn_outgoing_ill == NULL) &&
9198 		    infop->ip_opt_ill_index == 0) {
9199 			/* ipif_to_ire returns an held ire */
9200 			ire = ipif_to_ire(ipif);
9201 			if (ire == NULL)
9202 				goto err_ret;
9203 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9204 				goto err_ret;
9205 			/*
9206 			 * ihandle is needed when the ire is added to
9207 			 * cache table.
9208 			 */
9209 			save_ire = ire;
9210 			ihandle = save_ire->ire_ihandle;
9211 
9212 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9213 			    "flags %04x\n",
9214 			    (void *)ire, (void *)ipif, flags));
9215 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9216 			    (fire->ire_flags & RTF_MULTIRT)) {
9217 				/*
9218 				 * As requested by flags, an IRE_OFFSUBNET was
9219 				 * looked up on that interface. This ire has
9220 				 * RTF_MULTIRT flag, so the resolution loop will
9221 				 * be re-entered to resolve additional routes on
9222 				 * other interfaces. For that purpose, a copy of
9223 				 * the packet is performed at this point.
9224 				 */
9225 				fire->ire_last_used_time = lbolt;
9226 				copy_mp = copymsg(first_mp);
9227 				if (copy_mp) {
9228 					MULTIRT_DEBUG_TAG(copy_mp);
9229 				}
9230 			}
9231 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9232 			    (fire->ire_flags & RTF_SETSRC)) {
9233 				/*
9234 				 * As requested by flags, an IRE_OFFSUBET was
9235 				 * looked up on that interface. This ire has
9236 				 * RTF_SETSRC flag, so the source address of the
9237 				 * packet must be changed.
9238 				 */
9239 				ipha->ipha_src = fire->ire_src_addr;
9240 			}
9241 		} else {
9242 			ASSERT((connp == NULL) ||
9243 			    (connp->conn_outgoing_ill != NULL) ||
9244 			    (connp->conn_dontroute) ||
9245 			    infop->ip_opt_ill_index != 0);
9246 			/*
9247 			 * The only ways we can come here are:
9248 			 * 1) IP_BOUND_IF socket option is set
9249 			 * 2) SO_DONTROUTE socket option is set
9250 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9251 			 * In all cases, the new ire will not be added
9252 			 * into cache table.
9253 			 */
9254 			ire_marks |= IRE_MARK_NOADD;
9255 		}
9256 
9257 		switch (ipif->ipif_net_type) {
9258 		case IRE_IF_NORESOLVER: {
9259 			/* We have what we need to build an IRE_CACHE. */
9260 
9261 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9262 			    (dst_ill->ill_resolver_mp == NULL)) {
9263 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9264 				    "for IRE_IF_NORESOLVER ire %p has "
9265 				    "no ill_resolver_mp\n",
9266 				    (void *)dst_ill, (void *)ire));
9267 				break;
9268 			}
9269 
9270 			/*
9271 			 * The new ire inherits the IRE_OFFSUBNET flags
9272 			 * and source address, if this was requested.
9273 			 */
9274 			ire = ire_create(
9275 			    (uchar_t *)&dst,		/* dest address */
9276 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9277 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9278 			    NULL,			/* gateway address */
9279 			    &ipif->ipif_mtu,
9280 			    NULL,			/* no src nce */
9281 			    dst_ill->ill_rq,		/* recv-from queue */
9282 			    dst_ill->ill_wq,		/* send-to queue */
9283 			    IRE_CACHE,
9284 			    src_ipif,
9285 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9286 			    (fire != NULL) ?		/* Parent handle */
9287 			    fire->ire_phandle : 0,
9288 			    ihandle,			/* Interface handle */
9289 			    (fire != NULL) ?
9290 			    (fire->ire_flags &
9291 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9292 			    (save_ire == NULL ? &ire_uinfo_null :
9293 			    &save_ire->ire_uinfo),
9294 			    NULL,
9295 			    NULL,
9296 			    ipst);
9297 
9298 			if (ire == NULL) {
9299 				if (save_ire != NULL)
9300 					ire_refrele(save_ire);
9301 				break;
9302 			}
9303 
9304 			ire->ire_marks |= ire_marks;
9305 
9306 			/*
9307 			 * If IRE_MARK_NOADD is set then we need to convert
9308 			 * the max_fragp to a useable value now. This is
9309 			 * normally done in ire_add_v[46]. We also need to
9310 			 * associate the ire with an nce (normally would be
9311 			 * done in ip_wput_nondata()).
9312 			 *
9313 			 * Note that IRE_MARK_NOADD packets created here
9314 			 * do not have a non-null ire_mp pointer. The null
9315 			 * value of ire_bucket indicates that they were
9316 			 * never added.
9317 			 */
9318 			if (ire->ire_marks & IRE_MARK_NOADD) {
9319 				uint_t  max_frag;
9320 
9321 				max_frag = *ire->ire_max_fragp;
9322 				ire->ire_max_fragp = NULL;
9323 				ire->ire_max_frag = max_frag;
9324 
9325 				if ((ire->ire_nce = ndp_lookup_v4(
9326 				    ire_to_ill(ire),
9327 				    (ire->ire_gateway_addr != INADDR_ANY ?
9328 				    &ire->ire_gateway_addr : &ire->ire_addr),
9329 				    B_FALSE)) == NULL) {
9330 					if (save_ire != NULL)
9331 						ire_refrele(save_ire);
9332 					break;
9333 				}
9334 				ASSERT(ire->ire_nce->nce_state ==
9335 				    ND_REACHABLE);
9336 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9337 			}
9338 
9339 			/* Prevent save_ire from getting deleted */
9340 			if (save_ire != NULL) {
9341 				IRB_REFHOLD(save_ire->ire_bucket);
9342 				/* Has it been removed already ? */
9343 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9344 					IRB_REFRELE(save_ire->ire_bucket);
9345 					ire_refrele(save_ire);
9346 					break;
9347 				}
9348 			}
9349 
9350 			ire_add_then_send(q, ire, first_mp);
9351 
9352 			/* Assert that save_ire is not deleted yet. */
9353 			if (save_ire != NULL) {
9354 				ASSERT(save_ire->ire_ptpn != NULL);
9355 				IRB_REFRELE(save_ire->ire_bucket);
9356 				ire_refrele(save_ire);
9357 				save_ire = NULL;
9358 			}
9359 			if (fire != NULL) {
9360 				ire_refrele(fire);
9361 				fire = NULL;
9362 			}
9363 
9364 			/*
9365 			 * the resolution loop is re-entered if this
9366 			 * was requested through flags and if we
9367 			 * actually are in a multirouting case.
9368 			 */
9369 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9370 				boolean_t need_resolve =
9371 				    ire_multirt_need_resolve(ipha_dst,
9372 				    MBLK_GETLABEL(copy_mp), ipst);
9373 				if (!need_resolve) {
9374 					MULTIRT_DEBUG_UNTAG(copy_mp);
9375 					freemsg(copy_mp);
9376 					copy_mp = NULL;
9377 				} else {
9378 					/*
9379 					 * ipif_lookup_group() calls
9380 					 * ire_lookup_multi() that uses
9381 					 * ire_ftable_lookup() to find
9382 					 * an IRE_INTERFACE for the group.
9383 					 * In the multirt case,
9384 					 * ire_lookup_multi() then invokes
9385 					 * ire_multirt_lookup() to find
9386 					 * the next resolvable ire.
9387 					 * As a result, we obtain an new
9388 					 * interface, derived from the
9389 					 * next ire.
9390 					 */
9391 					ipif_refrele(ipif);
9392 					ipif = ipif_lookup_group(ipha_dst,
9393 					    zoneid, ipst);
9394 					ip2dbg(("ip_newroute_ipif: "
9395 					    "multirt dst %08x, ipif %p\n",
9396 					    htonl(dst), (void *)ipif));
9397 					if (ipif != NULL) {
9398 						mp = copy_mp;
9399 						copy_mp = NULL;
9400 						multirt_resolve_next = B_TRUE;
9401 						continue;
9402 					} else {
9403 						freemsg(copy_mp);
9404 					}
9405 				}
9406 			}
9407 			if (ipif != NULL)
9408 				ipif_refrele(ipif);
9409 			ill_refrele(dst_ill);
9410 			ipif_refrele(src_ipif);
9411 			return;
9412 		}
9413 		case IRE_IF_RESOLVER:
9414 			/*
9415 			 * We can't build an IRE_CACHE yet, but at least
9416 			 * we found a resolver that can help.
9417 			 */
9418 			res_mp = dst_ill->ill_resolver_mp;
9419 			if (!OK_RESOLVER_MP(res_mp))
9420 				break;
9421 
9422 			/*
9423 			 * We obtain a partial IRE_CACHE which we will pass
9424 			 * along with the resolver query.  When the response
9425 			 * comes back it will be there ready for us to add.
9426 			 * The new ire inherits the IRE_OFFSUBNET flags
9427 			 * and source address, if this was requested.
9428 			 * The ire_max_frag is atomically set under the
9429 			 * irebucket lock in ire_add_v[46]. Only in the
9430 			 * case of IRE_MARK_NOADD, we set it here itself.
9431 			 */
9432 			ire = ire_create_mp(
9433 			    (uchar_t *)&dst,		/* dest address */
9434 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9435 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9436 			    NULL,			/* gateway address */
9437 			    (ire_marks & IRE_MARK_NOADD) ?
9438 			    ipif->ipif_mtu : 0,		/* max_frag */
9439 			    NULL,			/* no src nce */
9440 			    dst_ill->ill_rq,		/* recv-from queue */
9441 			    dst_ill->ill_wq,		/* send-to queue */
9442 			    IRE_CACHE,
9443 			    src_ipif,
9444 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9445 			    (fire != NULL) ?		/* Parent handle */
9446 			    fire->ire_phandle : 0,
9447 			    ihandle,			/* Interface handle */
9448 			    (fire != NULL) ?		/* flags if any */
9449 			    (fire->ire_flags &
9450 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9451 			    (save_ire == NULL ? &ire_uinfo_null :
9452 			    &save_ire->ire_uinfo),
9453 			    NULL,
9454 			    NULL,
9455 			    ipst);
9456 
9457 			if (save_ire != NULL) {
9458 				ire_refrele(save_ire);
9459 				save_ire = NULL;
9460 			}
9461 			if (ire == NULL)
9462 				break;
9463 
9464 			ire->ire_marks |= ire_marks;
9465 			/*
9466 			 * Construct message chain for the resolver of the
9467 			 * form:
9468 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9469 			 *
9470 			 * NOTE : ire will be added later when the response
9471 			 * comes back from ARP. If the response does not
9472 			 * come back, ARP frees the packet. For this reason,
9473 			 * we can't REFHOLD the bucket of save_ire to prevent
9474 			 * deletions. We may not be able to REFRELE the
9475 			 * bucket if the response never comes back.
9476 			 * Thus, before adding the ire, ire_add_v4 will make
9477 			 * sure that the interface route does not get deleted.
9478 			 * This is the only case unlike ip_newroute_v6,
9479 			 * ip_newroute_ipif_v6 where we can always prevent
9480 			 * deletions because ire_add_then_send is called after
9481 			 * creating the IRE.
9482 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9483 			 * does not add this IRE into the IRE CACHE.
9484 			 */
9485 			ASSERT(ire->ire_mp != NULL);
9486 			ire->ire_mp->b_cont = first_mp;
9487 			/* Have saved_mp handy, for cleanup if canput fails */
9488 			saved_mp = mp;
9489 			mp = copyb(res_mp);
9490 			if (mp == NULL) {
9491 				/* Prepare for cleanup */
9492 				mp = saved_mp; /* pkt */
9493 				ire_delete(ire); /* ire_mp */
9494 				ire = NULL;
9495 				if (copy_mp != NULL) {
9496 					MULTIRT_DEBUG_UNTAG(copy_mp);
9497 					freemsg(copy_mp);
9498 					copy_mp = NULL;
9499 				}
9500 				break;
9501 			}
9502 			linkb(mp, ire->ire_mp);
9503 
9504 			/*
9505 			 * Fill in the source and dest addrs for the resolver.
9506 			 * NOTE: this depends on memory layouts imposed by
9507 			 * ill_init().
9508 			 */
9509 			areq = (areq_t *)mp->b_rptr;
9510 			addrp = (ipaddr_t *)((char *)areq +
9511 			    areq->areq_sender_addr_offset);
9512 			*addrp = ire->ire_src_addr;
9513 			addrp = (ipaddr_t *)((char *)areq +
9514 			    areq->areq_target_addr_offset);
9515 			*addrp = dst;
9516 			/* Up to the resolver. */
9517 			if (canputnext(dst_ill->ill_rq) &&
9518 			    !(dst_ill->ill_arp_closing)) {
9519 				putnext(dst_ill->ill_rq, mp);
9520 				/*
9521 				 * The response will come back in ip_wput
9522 				 * with db_type IRE_DB_TYPE.
9523 				 */
9524 			} else {
9525 				mp->b_cont = NULL;
9526 				freeb(mp); /* areq */
9527 				ire_delete(ire); /* ire_mp */
9528 				saved_mp->b_next = NULL;
9529 				saved_mp->b_prev = NULL;
9530 				freemsg(first_mp); /* pkt */
9531 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9532 			}
9533 
9534 			if (fire != NULL) {
9535 				ire_refrele(fire);
9536 				fire = NULL;
9537 			}
9538 
9539 
9540 			/*
9541 			 * The resolution loop is re-entered if this was
9542 			 * requested through flags and we actually are
9543 			 * in a multirouting case.
9544 			 */
9545 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9546 				boolean_t need_resolve =
9547 				    ire_multirt_need_resolve(ipha_dst,
9548 				    MBLK_GETLABEL(copy_mp), ipst);
9549 				if (!need_resolve) {
9550 					MULTIRT_DEBUG_UNTAG(copy_mp);
9551 					freemsg(copy_mp);
9552 					copy_mp = NULL;
9553 				} else {
9554 					/*
9555 					 * ipif_lookup_group() calls
9556 					 * ire_lookup_multi() that uses
9557 					 * ire_ftable_lookup() to find
9558 					 * an IRE_INTERFACE for the group.
9559 					 * In the multirt case,
9560 					 * ire_lookup_multi() then invokes
9561 					 * ire_multirt_lookup() to find
9562 					 * the next resolvable ire.
9563 					 * As a result, we obtain an new
9564 					 * interface, derived from the
9565 					 * next ire.
9566 					 */
9567 					ipif_refrele(ipif);
9568 					ipif = ipif_lookup_group(ipha_dst,
9569 					    zoneid, ipst);
9570 					if (ipif != NULL) {
9571 						mp = copy_mp;
9572 						copy_mp = NULL;
9573 						multirt_resolve_next = B_TRUE;
9574 						continue;
9575 					} else {
9576 						freemsg(copy_mp);
9577 					}
9578 				}
9579 			}
9580 			if (ipif != NULL)
9581 				ipif_refrele(ipif);
9582 			ill_refrele(dst_ill);
9583 			ipif_refrele(src_ipif);
9584 			return;
9585 		default:
9586 			break;
9587 		}
9588 	} while (multirt_resolve_next);
9589 
9590 err_ret:
9591 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9592 	if (fire != NULL)
9593 		ire_refrele(fire);
9594 	ipif_refrele(ipif);
9595 	/* Did this packet originate externally? */
9596 	if (dst_ill != NULL)
9597 		ill_refrele(dst_ill);
9598 	if (src_ipif != NULL)
9599 		ipif_refrele(src_ipif);
9600 	if (mp->b_prev || mp->b_next) {
9601 		mp->b_next = NULL;
9602 		mp->b_prev = NULL;
9603 	} else {
9604 		/*
9605 		 * Since ip_wput() isn't close to finished, we fill
9606 		 * in enough of the header for credible error reporting.
9607 		 */
9608 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9609 			/* Failed */
9610 			freemsg(first_mp);
9611 			if (ire != NULL)
9612 				ire_refrele(ire);
9613 			return;
9614 		}
9615 	}
9616 	/*
9617 	 * At this point we will have ire only if RTF_BLACKHOLE
9618 	 * or RTF_REJECT flags are set on the IRE. It will not
9619 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9620 	 */
9621 	if (ire != NULL) {
9622 		if (ire->ire_flags & RTF_BLACKHOLE) {
9623 			ire_refrele(ire);
9624 			freemsg(first_mp);
9625 			return;
9626 		}
9627 		ire_refrele(ire);
9628 	}
9629 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9630 }
9631 
9632 /* Name/Value Table Lookup Routine */
9633 char *
9634 ip_nv_lookup(nv_t *nv, int value)
9635 {
9636 	if (!nv)
9637 		return (NULL);
9638 	for (; nv->nv_name; nv++) {
9639 		if (nv->nv_value == value)
9640 			return (nv->nv_name);
9641 	}
9642 	return ("unknown");
9643 }
9644 
9645 /*
9646  * This is a module open, i.e. this is a control stream for access
9647  * to a DLPI device.  We allocate an ill_t as the instance data in
9648  * this case.
9649  */
9650 int
9651 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9652 {
9653 	ill_t	*ill;
9654 	int	err;
9655 	zoneid_t zoneid;
9656 	netstack_t *ns;
9657 	ip_stack_t *ipst;
9658 
9659 	/*
9660 	 * Prevent unprivileged processes from pushing IP so that
9661 	 * they can't send raw IP.
9662 	 */
9663 	if (secpolicy_net_rawaccess(credp) != 0)
9664 		return (EPERM);
9665 
9666 	ns = netstack_find_by_cred(credp);
9667 	ASSERT(ns != NULL);
9668 	ipst = ns->netstack_ip;
9669 	ASSERT(ipst != NULL);
9670 
9671 	/*
9672 	 * For exclusive stacks we set the zoneid to zero
9673 	 * to make IP operate as if in the global zone.
9674 	 */
9675 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9676 		zoneid = GLOBAL_ZONEID;
9677 	else
9678 		zoneid = crgetzoneid(credp);
9679 
9680 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9681 	q->q_ptr = WR(q)->q_ptr = ill;
9682 	ill->ill_ipst = ipst;
9683 	ill->ill_zoneid = zoneid;
9684 
9685 	/*
9686 	 * ill_init initializes the ill fields and then sends down
9687 	 * down a DL_INFO_REQ after calling qprocson.
9688 	 */
9689 	err = ill_init(q, ill);
9690 	if (err != 0) {
9691 		mi_free(ill);
9692 		netstack_rele(ipst->ips_netstack);
9693 		q->q_ptr = NULL;
9694 		WR(q)->q_ptr = NULL;
9695 		return (err);
9696 	}
9697 
9698 	/* ill_init initializes the ipsq marking this thread as writer */
9699 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9700 	/* Wait for the DL_INFO_ACK */
9701 	mutex_enter(&ill->ill_lock);
9702 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9703 		/*
9704 		 * Return value of 0 indicates a pending signal.
9705 		 */
9706 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9707 		if (err == 0) {
9708 			mutex_exit(&ill->ill_lock);
9709 			(void) ip_close(q, 0);
9710 			return (EINTR);
9711 		}
9712 	}
9713 	mutex_exit(&ill->ill_lock);
9714 
9715 	/*
9716 	 * ip_rput_other could have set an error  in ill_error on
9717 	 * receipt of M_ERROR.
9718 	 */
9719 
9720 	err = ill->ill_error;
9721 	if (err != 0) {
9722 		(void) ip_close(q, 0);
9723 		return (err);
9724 	}
9725 
9726 	ill->ill_credp = credp;
9727 	crhold(credp);
9728 
9729 	mutex_enter(&ipst->ips_ip_mi_lock);
9730 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9731 	    credp);
9732 	mutex_exit(&ipst->ips_ip_mi_lock);
9733 	if (err) {
9734 		(void) ip_close(q, 0);
9735 		return (err);
9736 	}
9737 	return (0);
9738 }
9739 
9740 /* For /dev/ip aka AF_INET open */
9741 int
9742 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9743 {
9744 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9745 }
9746 
9747 /* For /dev/ip6 aka AF_INET6 open */
9748 int
9749 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9750 {
9751 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9752 }
9753 
9754 /* IP open routine. */
9755 int
9756 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9757     boolean_t isv6)
9758 {
9759 	conn_t 		*connp;
9760 	major_t		maj;
9761 	zoneid_t	zoneid;
9762 	netstack_t	*ns;
9763 	ip_stack_t	*ipst;
9764 
9765 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9766 
9767 	/* Allow reopen. */
9768 	if (q->q_ptr != NULL)
9769 		return (0);
9770 
9771 	if (sflag & MODOPEN) {
9772 		/* This is a module open */
9773 		return (ip_modopen(q, devp, flag, sflag, credp));
9774 	}
9775 
9776 	ns = netstack_find_by_cred(credp);
9777 	ASSERT(ns != NULL);
9778 	ipst = ns->netstack_ip;
9779 	ASSERT(ipst != NULL);
9780 
9781 	/*
9782 	 * For exclusive stacks we set the zoneid to zero
9783 	 * to make IP operate as if in the global zone.
9784 	 */
9785 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9786 		zoneid = GLOBAL_ZONEID;
9787 	else
9788 		zoneid = crgetzoneid(credp);
9789 
9790 	/*
9791 	 * We are opening as a device. This is an IP client stream, and we
9792 	 * allocate an conn_t as the instance data.
9793 	 */
9794 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9795 
9796 	/*
9797 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9798 	 * done by netstack_find_by_cred()
9799 	 */
9800 	netstack_rele(ipst->ips_netstack);
9801 
9802 	connp->conn_zoneid = zoneid;
9803 
9804 	connp->conn_upq = q;
9805 	q->q_ptr = WR(q)->q_ptr = connp;
9806 
9807 	if (flag & SO_SOCKSTR)
9808 		connp->conn_flags |= IPCL_SOCKET;
9809 
9810 	/* Minor tells us which /dev entry was opened */
9811 	if (isv6) {
9812 		connp->conn_flags |= IPCL_ISV6;
9813 		connp->conn_af_isv6 = B_TRUE;
9814 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9815 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9816 	} else {
9817 		connp->conn_af_isv6 = B_FALSE;
9818 		connp->conn_pkt_isv6 = B_FALSE;
9819 	}
9820 
9821 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9822 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9823 		connp->conn_minor_arena = ip_minor_arena_la;
9824 	} else {
9825 		/*
9826 		 * Either minor numbers in the large arena were exhausted
9827 		 * or a non socket application is doing the open.
9828 		 * Try to allocate from the small arena.
9829 		 */
9830 		if ((connp->conn_dev =
9831 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9832 			/* CONN_DEC_REF takes care of netstack_rele() */
9833 			q->q_ptr = WR(q)->q_ptr = NULL;
9834 			CONN_DEC_REF(connp);
9835 			return (EBUSY);
9836 		}
9837 		connp->conn_minor_arena = ip_minor_arena_sa;
9838 	}
9839 
9840 	maj = getemajor(*devp);
9841 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9842 
9843 	/*
9844 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9845 	 */
9846 	connp->conn_cred = credp;
9847 
9848 	/*
9849 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9850 	 */
9851 	connp->conn_recv = ip_conn_input;
9852 
9853 	crhold(connp->conn_cred);
9854 
9855 	/*
9856 	 * If the caller has the process-wide flag set, then default to MAC
9857 	 * exempt mode.  This allows read-down to unlabeled hosts.
9858 	 */
9859 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9860 		connp->conn_mac_exempt = B_TRUE;
9861 
9862 	connp->conn_rq = q;
9863 	connp->conn_wq = WR(q);
9864 
9865 	/* Non-zero default values */
9866 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9867 
9868 	/*
9869 	 * Make the conn globally visible to walkers
9870 	 */
9871 	ASSERT(connp->conn_ref == 1);
9872 	mutex_enter(&connp->conn_lock);
9873 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9874 	mutex_exit(&connp->conn_lock);
9875 
9876 	qprocson(q);
9877 
9878 	return (0);
9879 }
9880 
9881 /*
9882  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9883  * Note that there is no race since either ip_output function works - it
9884  * is just an optimization to enter the best ip_output routine directly.
9885  */
9886 void
9887 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9888     ip_stack_t *ipst)
9889 {
9890 	if (isv6)  {
9891 		if (bump_mib) {
9892 			BUMP_MIB(&ipst->ips_ip6_mib,
9893 			    ipIfStatsOutSwitchIPVersion);
9894 		}
9895 		connp->conn_send = ip_output_v6;
9896 		connp->conn_pkt_isv6 = B_TRUE;
9897 	} else {
9898 		if (bump_mib) {
9899 			BUMP_MIB(&ipst->ips_ip_mib,
9900 			    ipIfStatsOutSwitchIPVersion);
9901 		}
9902 		connp->conn_send = ip_output;
9903 		connp->conn_pkt_isv6 = B_FALSE;
9904 	}
9905 
9906 }
9907 
9908 /*
9909  * See if IPsec needs loading because of the options in mp.
9910  */
9911 static boolean_t
9912 ipsec_opt_present(mblk_t *mp)
9913 {
9914 	uint8_t *optcp, *next_optcp, *opt_endcp;
9915 	struct opthdr *opt;
9916 	struct T_opthdr *topt;
9917 	int opthdr_len;
9918 	t_uscalar_t optname, optlevel;
9919 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9920 	ipsec_req_t *ipsr;
9921 
9922 	/*
9923 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9924 	 * return TRUE.
9925 	 */
9926 
9927 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9928 	opt_endcp = optcp + tor->OPT_length;
9929 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9930 		opthdr_len = sizeof (struct T_opthdr);
9931 	} else {		/* O_OPTMGMT_REQ */
9932 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9933 		opthdr_len = sizeof (struct opthdr);
9934 	}
9935 	for (; optcp < opt_endcp; optcp = next_optcp) {
9936 		if (optcp + opthdr_len > opt_endcp)
9937 			return (B_FALSE);	/* Not enough option header. */
9938 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9939 			topt = (struct T_opthdr *)optcp;
9940 			optlevel = topt->level;
9941 			optname = topt->name;
9942 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9943 		} else {
9944 			opt = (struct opthdr *)optcp;
9945 			optlevel = opt->level;
9946 			optname = opt->name;
9947 			next_optcp = optcp + opthdr_len +
9948 			    _TPI_ALIGN_OPT(opt->len);
9949 		}
9950 		if ((next_optcp < optcp) || /* wraparound pointer space */
9951 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9952 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9953 			return (B_FALSE); /* bad option buffer */
9954 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9955 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9956 			/*
9957 			 * Check to see if it's an all-bypass or all-zeroes
9958 			 * IPsec request.  Don't bother loading IPsec if
9959 			 * the socket doesn't want to use it.  (A good example
9960 			 * is a bypass request.)
9961 			 *
9962 			 * Basically, if any of the non-NEVER bits are set,
9963 			 * load IPsec.
9964 			 */
9965 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9966 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9967 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9968 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9969 			    != 0)
9970 				return (B_TRUE);
9971 		}
9972 	}
9973 	return (B_FALSE);
9974 }
9975 
9976 /*
9977  * If conn is is waiting for ipsec to finish loading, kick it.
9978  */
9979 /* ARGSUSED */
9980 static void
9981 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9982 {
9983 	t_scalar_t	optreq_prim;
9984 	mblk_t		*mp;
9985 	cred_t		*cr;
9986 	int		err = 0;
9987 
9988 	/*
9989 	 * This function is called, after ipsec loading is complete.
9990 	 * Since IP checks exclusively and atomically (i.e it prevents
9991 	 * ipsec load from completing until ip_optcom_req completes)
9992 	 * whether ipsec load is complete, there cannot be a race with IP
9993 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9994 	 */
9995 	mutex_enter(&connp->conn_lock);
9996 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9997 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9998 		mp = connp->conn_ipsec_opt_mp;
9999 		connp->conn_ipsec_opt_mp = NULL;
10000 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10001 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10002 		mutex_exit(&connp->conn_lock);
10003 
10004 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10005 
10006 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10007 		if (optreq_prim == T_OPTMGMT_REQ) {
10008 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10009 			    &ip_opt_obj, B_FALSE);
10010 		} else {
10011 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10012 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10013 			    &ip_opt_obj, B_FALSE);
10014 		}
10015 		if (err != EINPROGRESS)
10016 			CONN_OPER_PENDING_DONE(connp);
10017 		return;
10018 	}
10019 	mutex_exit(&connp->conn_lock);
10020 }
10021 
10022 /*
10023  * Called from the ipsec_loader thread, outside any perimeter, to tell
10024  * ip qenable any of the queues waiting for the ipsec loader to
10025  * complete.
10026  */
10027 void
10028 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10029 {
10030 	netstack_t *ns = ipss->ipsec_netstack;
10031 
10032 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10033 }
10034 
10035 /*
10036  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10037  * determines the grp on which it has to become exclusive, queues the mp
10038  * and sq draining restarts the optmgmt
10039  */
10040 static boolean_t
10041 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10042 {
10043 	conn_t *connp = Q_TO_CONN(q);
10044 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10045 
10046 	/*
10047 	 * Take IPsec requests and treat them special.
10048 	 */
10049 	if (ipsec_opt_present(mp)) {
10050 		/* First check if IPsec is loaded. */
10051 		mutex_enter(&ipss->ipsec_loader_lock);
10052 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10053 			mutex_exit(&ipss->ipsec_loader_lock);
10054 			return (B_FALSE);
10055 		}
10056 		mutex_enter(&connp->conn_lock);
10057 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10058 
10059 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10060 		connp->conn_ipsec_opt_mp = mp;
10061 		mutex_exit(&connp->conn_lock);
10062 		mutex_exit(&ipss->ipsec_loader_lock);
10063 
10064 		ipsec_loader_loadnow(ipss);
10065 		return (B_TRUE);
10066 	}
10067 	return (B_FALSE);
10068 }
10069 
10070 /*
10071  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10072  * all of them are copied to the conn_t. If the req is "zero", the policy is
10073  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10074  * fields.
10075  * We keep only the latest setting of the policy and thus policy setting
10076  * is not incremental/cumulative.
10077  *
10078  * Requests to set policies with multiple alternative actions will
10079  * go through a different API.
10080  */
10081 int
10082 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10083 {
10084 	uint_t ah_req = 0;
10085 	uint_t esp_req = 0;
10086 	uint_t se_req = 0;
10087 	ipsec_selkey_t sel;
10088 	ipsec_act_t *actp = NULL;
10089 	uint_t nact;
10090 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10091 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10092 	ipsec_policy_root_t *pr;
10093 	ipsec_policy_head_t *ph;
10094 	int fam;
10095 	boolean_t is_pol_reset;
10096 	int error = 0;
10097 	netstack_t	*ns = connp->conn_netstack;
10098 	ip_stack_t	*ipst = ns->netstack_ip;
10099 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10100 
10101 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10102 
10103 	/*
10104 	 * The IP_SEC_OPT option does not allow variable length parameters,
10105 	 * hence a request cannot be NULL.
10106 	 */
10107 	if (req == NULL)
10108 		return (EINVAL);
10109 
10110 	ah_req = req->ipsr_ah_req;
10111 	esp_req = req->ipsr_esp_req;
10112 	se_req = req->ipsr_self_encap_req;
10113 
10114 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10115 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10116 		return (EINVAL);
10117 
10118 	/*
10119 	 * Are we dealing with a request to reset the policy (i.e.
10120 	 * zero requests).
10121 	 */
10122 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10123 	    (esp_req & REQ_MASK) == 0 &&
10124 	    (se_req & REQ_MASK) == 0);
10125 
10126 	if (!is_pol_reset) {
10127 		/*
10128 		 * If we couldn't load IPsec, fail with "protocol
10129 		 * not supported".
10130 		 * IPsec may not have been loaded for a request with zero
10131 		 * policies, so we don't fail in this case.
10132 		 */
10133 		mutex_enter(&ipss->ipsec_loader_lock);
10134 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10135 			mutex_exit(&ipss->ipsec_loader_lock);
10136 			return (EPROTONOSUPPORT);
10137 		}
10138 		mutex_exit(&ipss->ipsec_loader_lock);
10139 
10140 		/*
10141 		 * Test for valid requests. Invalid algorithms
10142 		 * need to be tested by IPsec code because new
10143 		 * algorithms can be added dynamically.
10144 		 */
10145 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10146 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10147 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10148 			return (EINVAL);
10149 		}
10150 
10151 		/*
10152 		 * Only privileged users can issue these
10153 		 * requests.
10154 		 */
10155 		if (((ah_req & IPSEC_PREF_NEVER) ||
10156 		    (esp_req & IPSEC_PREF_NEVER) ||
10157 		    (se_req & IPSEC_PREF_NEVER)) &&
10158 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10159 			return (EPERM);
10160 		}
10161 
10162 		/*
10163 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10164 		 * are mutually exclusive.
10165 		 */
10166 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10167 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10168 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10169 			/* Both of them are set */
10170 			return (EINVAL);
10171 		}
10172 	}
10173 
10174 	mutex_enter(&connp->conn_lock);
10175 
10176 	/*
10177 	 * If we have already cached policies in ip_bind_connected*(), don't
10178 	 * let them change now. We cache policies for connections
10179 	 * whose src,dst [addr, port] is known.
10180 	 */
10181 	if (connp->conn_policy_cached) {
10182 		mutex_exit(&connp->conn_lock);
10183 		return (EINVAL);
10184 	}
10185 
10186 	/*
10187 	 * We have a zero policies, reset the connection policy if already
10188 	 * set. This will cause the connection to inherit the
10189 	 * global policy, if any.
10190 	 */
10191 	if (is_pol_reset) {
10192 		if (connp->conn_policy != NULL) {
10193 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10194 			connp->conn_policy = NULL;
10195 		}
10196 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10197 		connp->conn_in_enforce_policy = B_FALSE;
10198 		connp->conn_out_enforce_policy = B_FALSE;
10199 		mutex_exit(&connp->conn_lock);
10200 		return (0);
10201 	}
10202 
10203 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10204 	    ipst->ips_netstack);
10205 	if (ph == NULL)
10206 		goto enomem;
10207 
10208 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10209 	if (actp == NULL)
10210 		goto enomem;
10211 
10212 	/*
10213 	 * Always allocate IPv4 policy entries, since they can also
10214 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10215 	 */
10216 	bzero(&sel, sizeof (sel));
10217 	sel.ipsl_valid = IPSL_IPV4;
10218 
10219 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10220 	    ipst->ips_netstack);
10221 	if (pin4 == NULL)
10222 		goto enomem;
10223 
10224 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10225 	    ipst->ips_netstack);
10226 	if (pout4 == NULL)
10227 		goto enomem;
10228 
10229 	if (connp->conn_af_isv6) {
10230 		/*
10231 		 * We're looking at a v6 socket, also allocate the
10232 		 * v6-specific entries...
10233 		 */
10234 		sel.ipsl_valid = IPSL_IPV6;
10235 		pin6 = ipsec_policy_create(&sel, actp, nact,
10236 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10237 		if (pin6 == NULL)
10238 			goto enomem;
10239 
10240 		pout6 = ipsec_policy_create(&sel, actp, nact,
10241 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10242 		if (pout6 == NULL)
10243 			goto enomem;
10244 
10245 		/*
10246 		 * .. and file them away in the right place.
10247 		 */
10248 		fam = IPSEC_AF_V6;
10249 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10250 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10251 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10252 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10253 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10254 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10255 	}
10256 
10257 	ipsec_actvec_free(actp, nact);
10258 
10259 	/*
10260 	 * File the v4 policies.
10261 	 */
10262 	fam = IPSEC_AF_V4;
10263 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10264 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10265 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10266 
10267 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10268 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10269 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10270 
10271 	/*
10272 	 * If the requests need security, set enforce_policy.
10273 	 * If the requests are IPSEC_PREF_NEVER, one should
10274 	 * still set conn_out_enforce_policy so that an ipsec_out
10275 	 * gets attached in ip_wput. This is needed so that
10276 	 * for connections that we don't cache policy in ip_bind,
10277 	 * if global policy matches in ip_wput_attach_policy, we
10278 	 * don't wrongly inherit global policy. Similarly, we need
10279 	 * to set conn_in_enforce_policy also so that we don't verify
10280 	 * policy wrongly.
10281 	 */
10282 	if ((ah_req & REQ_MASK) != 0 ||
10283 	    (esp_req & REQ_MASK) != 0 ||
10284 	    (se_req & REQ_MASK) != 0) {
10285 		connp->conn_in_enforce_policy = B_TRUE;
10286 		connp->conn_out_enforce_policy = B_TRUE;
10287 		connp->conn_flags |= IPCL_CHECK_POLICY;
10288 	}
10289 
10290 	mutex_exit(&connp->conn_lock);
10291 	return (error);
10292 #undef REQ_MASK
10293 
10294 	/*
10295 	 * Common memory-allocation-failure exit path.
10296 	 */
10297 enomem:
10298 	mutex_exit(&connp->conn_lock);
10299 	if (actp != NULL)
10300 		ipsec_actvec_free(actp, nact);
10301 	if (pin4 != NULL)
10302 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10303 	if (pout4 != NULL)
10304 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10305 	if (pin6 != NULL)
10306 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10307 	if (pout6 != NULL)
10308 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10309 	return (ENOMEM);
10310 }
10311 
10312 /*
10313  * Only for options that pass in an IP addr. Currently only V4 options
10314  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10315  * So this function assumes level is IPPROTO_IP
10316  */
10317 int
10318 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10319     mblk_t *first_mp)
10320 {
10321 	ipif_t *ipif = NULL;
10322 	int error;
10323 	ill_t *ill;
10324 	int zoneid;
10325 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10326 
10327 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10328 
10329 	if (addr != INADDR_ANY || checkonly) {
10330 		ASSERT(connp != NULL);
10331 		zoneid = IPCL_ZONEID(connp);
10332 		if (option == IP_NEXTHOP) {
10333 			ipif = ipif_lookup_onlink_addr(addr,
10334 			    connp->conn_zoneid, ipst);
10335 		} else {
10336 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10337 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10338 			    &error, ipst);
10339 		}
10340 		if (ipif == NULL) {
10341 			if (error == EINPROGRESS)
10342 				return (error);
10343 			else if ((option == IP_MULTICAST_IF) ||
10344 			    (option == IP_NEXTHOP))
10345 				return (EHOSTUNREACH);
10346 			else
10347 				return (EINVAL);
10348 		} else if (checkonly) {
10349 			if (option == IP_MULTICAST_IF) {
10350 				ill = ipif->ipif_ill;
10351 				/* not supported by the virtual network iface */
10352 				if (IS_VNI(ill)) {
10353 					ipif_refrele(ipif);
10354 					return (EINVAL);
10355 				}
10356 			}
10357 			ipif_refrele(ipif);
10358 			return (0);
10359 		}
10360 		ill = ipif->ipif_ill;
10361 		mutex_enter(&connp->conn_lock);
10362 		mutex_enter(&ill->ill_lock);
10363 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10364 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10365 			mutex_exit(&ill->ill_lock);
10366 			mutex_exit(&connp->conn_lock);
10367 			ipif_refrele(ipif);
10368 			return (option == IP_MULTICAST_IF ?
10369 			    EHOSTUNREACH : EINVAL);
10370 		}
10371 	} else {
10372 		mutex_enter(&connp->conn_lock);
10373 	}
10374 
10375 	/* None of the options below are supported on the VNI */
10376 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10377 		mutex_exit(&ill->ill_lock);
10378 		mutex_exit(&connp->conn_lock);
10379 		ipif_refrele(ipif);
10380 		return (EINVAL);
10381 	}
10382 
10383 	switch (option) {
10384 	case IP_DONTFAILOVER_IF:
10385 		/*
10386 		 * This option is used by in.mpathd to ensure
10387 		 * that IPMP probe packets only go out on the
10388 		 * test interfaces. in.mpathd sets this option
10389 		 * on the non-failover interfaces.
10390 		 * For backward compatibility, this option
10391 		 * implicitly sets IP_MULTICAST_IF, as used
10392 		 * be done in bind(), so that ip_wput gets
10393 		 * this ipif to send mcast packets.
10394 		 */
10395 		if (ipif != NULL) {
10396 			ASSERT(addr != INADDR_ANY);
10397 			connp->conn_nofailover_ill = ipif->ipif_ill;
10398 			connp->conn_multicast_ipif = ipif;
10399 		} else {
10400 			ASSERT(addr == INADDR_ANY);
10401 			connp->conn_nofailover_ill = NULL;
10402 			connp->conn_multicast_ipif = NULL;
10403 		}
10404 		break;
10405 
10406 	case IP_MULTICAST_IF:
10407 		connp->conn_multicast_ipif = ipif;
10408 		break;
10409 	case IP_NEXTHOP:
10410 		connp->conn_nexthop_v4 = addr;
10411 		connp->conn_nexthop_set = B_TRUE;
10412 		break;
10413 	}
10414 
10415 	if (ipif != NULL) {
10416 		mutex_exit(&ill->ill_lock);
10417 		mutex_exit(&connp->conn_lock);
10418 		ipif_refrele(ipif);
10419 		return (0);
10420 	}
10421 	mutex_exit(&connp->conn_lock);
10422 	/* We succeded in cleared the option */
10423 	return (0);
10424 }
10425 
10426 /*
10427  * For options that pass in an ifindex specifying the ill. V6 options always
10428  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10429  */
10430 int
10431 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10432     int level, int option, mblk_t *first_mp)
10433 {
10434 	ill_t *ill = NULL;
10435 	int error = 0;
10436 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10437 
10438 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10439 	if (ifindex != 0) {
10440 		ASSERT(connp != NULL);
10441 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10442 		    first_mp, ip_restart_optmgmt, &error, ipst);
10443 		if (ill != NULL) {
10444 			if (checkonly) {
10445 				/* not supported by the virtual network iface */
10446 				if (IS_VNI(ill)) {
10447 					ill_refrele(ill);
10448 					return (EINVAL);
10449 				}
10450 				ill_refrele(ill);
10451 				return (0);
10452 			}
10453 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10454 			    0, NULL)) {
10455 				ill_refrele(ill);
10456 				ill = NULL;
10457 				mutex_enter(&connp->conn_lock);
10458 				goto setit;
10459 			}
10460 			mutex_enter(&connp->conn_lock);
10461 			mutex_enter(&ill->ill_lock);
10462 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10463 				mutex_exit(&ill->ill_lock);
10464 				mutex_exit(&connp->conn_lock);
10465 				ill_refrele(ill);
10466 				ill = NULL;
10467 				mutex_enter(&connp->conn_lock);
10468 			}
10469 			goto setit;
10470 		} else if (error == EINPROGRESS) {
10471 			return (error);
10472 		} else {
10473 			error = 0;
10474 		}
10475 	}
10476 	mutex_enter(&connp->conn_lock);
10477 setit:
10478 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10479 
10480 	/*
10481 	 * The options below assume that the ILL (if any) transmits and/or
10482 	 * receives traffic. Neither of which is true for the virtual network
10483 	 * interface, so fail setting these on a VNI.
10484 	 */
10485 	if (IS_VNI(ill)) {
10486 		ASSERT(ill != NULL);
10487 		mutex_exit(&ill->ill_lock);
10488 		mutex_exit(&connp->conn_lock);
10489 		ill_refrele(ill);
10490 		return (EINVAL);
10491 	}
10492 
10493 	if (level == IPPROTO_IP) {
10494 		switch (option) {
10495 		case IP_BOUND_IF:
10496 			connp->conn_incoming_ill = ill;
10497 			connp->conn_outgoing_ill = ill;
10498 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10499 			    0 : ifindex;
10500 			break;
10501 
10502 		case IP_MULTICAST_IF:
10503 			/*
10504 			 * This option is an internal special. The socket
10505 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10506 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10507 			 * specifies an ifindex and we try first on V6 ill's.
10508 			 * If we don't find one, we they try using on v4 ill's
10509 			 * intenally and we come here.
10510 			 */
10511 			if (!checkonly && ill != NULL) {
10512 				ipif_t	*ipif;
10513 				ipif = ill->ill_ipif;
10514 
10515 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10516 					mutex_exit(&ill->ill_lock);
10517 					mutex_exit(&connp->conn_lock);
10518 					ill_refrele(ill);
10519 					ill = NULL;
10520 					mutex_enter(&connp->conn_lock);
10521 				} else {
10522 					connp->conn_multicast_ipif = ipif;
10523 				}
10524 			}
10525 			break;
10526 
10527 		case IP_DHCPINIT_IF:
10528 			if (connp->conn_dhcpinit_ill != NULL) {
10529 				/*
10530 				 * We've locked the conn so conn_cleanup_ill()
10531 				 * cannot clear conn_dhcpinit_ill -- so it's
10532 				 * safe to access the ill.
10533 				 */
10534 				ill_t *oill = connp->conn_dhcpinit_ill;
10535 
10536 				ASSERT(oill->ill_dhcpinit != 0);
10537 				atomic_dec_32(&oill->ill_dhcpinit);
10538 				connp->conn_dhcpinit_ill = NULL;
10539 			}
10540 
10541 			if (ill != NULL) {
10542 				connp->conn_dhcpinit_ill = ill;
10543 				atomic_inc_32(&ill->ill_dhcpinit);
10544 			}
10545 			break;
10546 		}
10547 	} else {
10548 		switch (option) {
10549 		case IPV6_BOUND_IF:
10550 			connp->conn_incoming_ill = ill;
10551 			connp->conn_outgoing_ill = ill;
10552 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10553 			    0 : ifindex;
10554 			break;
10555 
10556 		case IPV6_BOUND_PIF:
10557 			/*
10558 			 * Limit all transmit to this ill.
10559 			 * Unlike IPV6_BOUND_IF, using this option
10560 			 * prevents load spreading and failover from
10561 			 * happening when the interface is part of the
10562 			 * group. That's why we don't need to remember
10563 			 * the ifindex in orig_bound_ifindex as in
10564 			 * IPV6_BOUND_IF.
10565 			 */
10566 			connp->conn_outgoing_pill = ill;
10567 			break;
10568 
10569 		case IPV6_DONTFAILOVER_IF:
10570 			/*
10571 			 * This option is used by in.mpathd to ensure
10572 			 * that IPMP probe packets only go out on the
10573 			 * test interfaces. in.mpathd sets this option
10574 			 * on the non-failover interfaces.
10575 			 */
10576 			connp->conn_nofailover_ill = ill;
10577 			/*
10578 			 * For backward compatibility, this option
10579 			 * implicitly sets ip_multicast_ill as used in
10580 			 * IPV6_MULTICAST_IF so that ip_wput gets
10581 			 * this ill to send mcast packets.
10582 			 */
10583 			connp->conn_multicast_ill = ill;
10584 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10585 			    0 : ifindex;
10586 			break;
10587 
10588 		case IPV6_MULTICAST_IF:
10589 			/*
10590 			 * Set conn_multicast_ill to be the IPv6 ill.
10591 			 * Set conn_multicast_ipif to be an IPv4 ipif
10592 			 * for ifindex to make IPv4 mapped addresses
10593 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10594 			 * Even if no IPv6 ill exists for the ifindex
10595 			 * we need to check for an IPv4 ifindex in order
10596 			 * for this to work with mapped addresses. In that
10597 			 * case only set conn_multicast_ipif.
10598 			 */
10599 			if (!checkonly) {
10600 				if (ifindex == 0) {
10601 					connp->conn_multicast_ill = NULL;
10602 					connp->conn_orig_multicast_ifindex = 0;
10603 					connp->conn_multicast_ipif = NULL;
10604 				} else if (ill != NULL) {
10605 					connp->conn_multicast_ill = ill;
10606 					connp->conn_orig_multicast_ifindex =
10607 					    ifindex;
10608 				}
10609 			}
10610 			break;
10611 		}
10612 	}
10613 
10614 	if (ill != NULL) {
10615 		mutex_exit(&ill->ill_lock);
10616 		mutex_exit(&connp->conn_lock);
10617 		ill_refrele(ill);
10618 		return (0);
10619 	}
10620 	mutex_exit(&connp->conn_lock);
10621 	/*
10622 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10623 	 * locate the ill and could not set the option (ifindex != 0)
10624 	 */
10625 	return (ifindex == 0 ? 0 : EINVAL);
10626 }
10627 
10628 /* This routine sets socket options. */
10629 /* ARGSUSED */
10630 int
10631 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10632     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10633     void *dummy, cred_t *cr, mblk_t *first_mp)
10634 {
10635 	int		*i1 = (int *)invalp;
10636 	conn_t		*connp = Q_TO_CONN(q);
10637 	int		error = 0;
10638 	boolean_t	checkonly;
10639 	ire_t		*ire;
10640 	boolean_t	found;
10641 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10642 
10643 	switch (optset_context) {
10644 
10645 	case SETFN_OPTCOM_CHECKONLY:
10646 		checkonly = B_TRUE;
10647 		/*
10648 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10649 		 * inlen != 0 implies value supplied and
10650 		 * 	we have to "pretend" to set it.
10651 		 * inlen == 0 implies that there is no
10652 		 * 	value part in T_CHECK request and just validation
10653 		 * done elsewhere should be enough, we just return here.
10654 		 */
10655 		if (inlen == 0) {
10656 			*outlenp = 0;
10657 			return (0);
10658 		}
10659 		break;
10660 	case SETFN_OPTCOM_NEGOTIATE:
10661 	case SETFN_UD_NEGOTIATE:
10662 	case SETFN_CONN_NEGOTIATE:
10663 		checkonly = B_FALSE;
10664 		break;
10665 	default:
10666 		/*
10667 		 * We should never get here
10668 		 */
10669 		*outlenp = 0;
10670 		return (EINVAL);
10671 	}
10672 
10673 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10674 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10675 
10676 	/*
10677 	 * For fixed length options, no sanity check
10678 	 * of passed in length is done. It is assumed *_optcom_req()
10679 	 * routines do the right thing.
10680 	 */
10681 
10682 	switch (level) {
10683 	case SOL_SOCKET:
10684 		/*
10685 		 * conn_lock protects the bitfields, and is used to
10686 		 * set the fields atomically.
10687 		 */
10688 		switch (name) {
10689 		case SO_BROADCAST:
10690 			if (!checkonly) {
10691 				/* TODO: use value someplace? */
10692 				mutex_enter(&connp->conn_lock);
10693 				connp->conn_broadcast = *i1 ? 1 : 0;
10694 				mutex_exit(&connp->conn_lock);
10695 			}
10696 			break;	/* goto sizeof (int) option return */
10697 		case SO_USELOOPBACK:
10698 			if (!checkonly) {
10699 				/* TODO: use value someplace? */
10700 				mutex_enter(&connp->conn_lock);
10701 				connp->conn_loopback = *i1 ? 1 : 0;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case SO_DONTROUTE:
10706 			if (!checkonly) {
10707 				mutex_enter(&connp->conn_lock);
10708 				connp->conn_dontroute = *i1 ? 1 : 0;
10709 				mutex_exit(&connp->conn_lock);
10710 			}
10711 			break;	/* goto sizeof (int) option return */
10712 		case SO_REUSEADDR:
10713 			if (!checkonly) {
10714 				mutex_enter(&connp->conn_lock);
10715 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10716 				mutex_exit(&connp->conn_lock);
10717 			}
10718 			break;	/* goto sizeof (int) option return */
10719 		case SO_PROTOTYPE:
10720 			if (!checkonly) {
10721 				mutex_enter(&connp->conn_lock);
10722 				connp->conn_proto = *i1;
10723 				mutex_exit(&connp->conn_lock);
10724 			}
10725 			break;	/* goto sizeof (int) option return */
10726 		case SO_ALLZONES:
10727 			if (!checkonly) {
10728 				mutex_enter(&connp->conn_lock);
10729 				if (IPCL_IS_BOUND(connp)) {
10730 					mutex_exit(&connp->conn_lock);
10731 					return (EINVAL);
10732 				}
10733 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10734 				mutex_exit(&connp->conn_lock);
10735 			}
10736 			break;	/* goto sizeof (int) option return */
10737 		case SO_ANON_MLP:
10738 			if (!checkonly) {
10739 				mutex_enter(&connp->conn_lock);
10740 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10741 				mutex_exit(&connp->conn_lock);
10742 			}
10743 			break;	/* goto sizeof (int) option return */
10744 		case SO_MAC_EXEMPT:
10745 			if (secpolicy_net_mac_aware(cr) != 0 ||
10746 			    IPCL_IS_BOUND(connp))
10747 				return (EACCES);
10748 			if (!checkonly) {
10749 				mutex_enter(&connp->conn_lock);
10750 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10751 				mutex_exit(&connp->conn_lock);
10752 			}
10753 			break;	/* goto sizeof (int) option return */
10754 		default:
10755 			/*
10756 			 * "soft" error (negative)
10757 			 * option not handled at this level
10758 			 * Note: Do not modify *outlenp
10759 			 */
10760 			return (-EINVAL);
10761 		}
10762 		break;
10763 	case IPPROTO_IP:
10764 		switch (name) {
10765 		case IP_NEXTHOP:
10766 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10767 				return (EPERM);
10768 			/* FALLTHRU */
10769 		case IP_MULTICAST_IF:
10770 		case IP_DONTFAILOVER_IF: {
10771 			ipaddr_t addr = *i1;
10772 
10773 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10774 			    first_mp);
10775 			if (error != 0)
10776 				return (error);
10777 			break;	/* goto sizeof (int) option return */
10778 		}
10779 
10780 		case IP_MULTICAST_TTL:
10781 			/* Recorded in transport above IP */
10782 			*outvalp = *invalp;
10783 			*outlenp = sizeof (uchar_t);
10784 			return (0);
10785 		case IP_MULTICAST_LOOP:
10786 			if (!checkonly) {
10787 				mutex_enter(&connp->conn_lock);
10788 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10789 				mutex_exit(&connp->conn_lock);
10790 			}
10791 			*outvalp = *invalp;
10792 			*outlenp = sizeof (uchar_t);
10793 			return (0);
10794 		case IP_ADD_MEMBERSHIP:
10795 		case MCAST_JOIN_GROUP:
10796 		case IP_DROP_MEMBERSHIP:
10797 		case MCAST_LEAVE_GROUP: {
10798 			struct ip_mreq *mreqp;
10799 			struct group_req *greqp;
10800 			ire_t *ire;
10801 			boolean_t done = B_FALSE;
10802 			ipaddr_t group, ifaddr;
10803 			struct sockaddr_in *sin;
10804 			uint32_t *ifindexp;
10805 			boolean_t mcast_opt = B_TRUE;
10806 			mcast_record_t fmode;
10807 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10808 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10809 
10810 			switch (name) {
10811 			case IP_ADD_MEMBERSHIP:
10812 				mcast_opt = B_FALSE;
10813 				/* FALLTHRU */
10814 			case MCAST_JOIN_GROUP:
10815 				fmode = MODE_IS_EXCLUDE;
10816 				optfn = ip_opt_add_group;
10817 				break;
10818 
10819 			case IP_DROP_MEMBERSHIP:
10820 				mcast_opt = B_FALSE;
10821 				/* FALLTHRU */
10822 			case MCAST_LEAVE_GROUP:
10823 				fmode = MODE_IS_INCLUDE;
10824 				optfn = ip_opt_delete_group;
10825 				break;
10826 			}
10827 
10828 			if (mcast_opt) {
10829 				greqp = (struct group_req *)i1;
10830 				sin = (struct sockaddr_in *)&greqp->gr_group;
10831 				if (sin->sin_family != AF_INET) {
10832 					*outlenp = 0;
10833 					return (ENOPROTOOPT);
10834 				}
10835 				group = (ipaddr_t)sin->sin_addr.s_addr;
10836 				ifaddr = INADDR_ANY;
10837 				ifindexp = &greqp->gr_interface;
10838 			} else {
10839 				mreqp = (struct ip_mreq *)i1;
10840 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10841 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10842 				ifindexp = NULL;
10843 			}
10844 
10845 			/*
10846 			 * In the multirouting case, we need to replicate
10847 			 * the request on all interfaces that will take part
10848 			 * in replication.  We do so because multirouting is
10849 			 * reflective, thus we will probably receive multi-
10850 			 * casts on those interfaces.
10851 			 * The ip_multirt_apply_membership() succeeds if the
10852 			 * operation succeeds on at least one interface.
10853 			 */
10854 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10855 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10856 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10857 			if (ire != NULL) {
10858 				if (ire->ire_flags & RTF_MULTIRT) {
10859 					error = ip_multirt_apply_membership(
10860 					    optfn, ire, connp, checkonly, group,
10861 					    fmode, INADDR_ANY, first_mp);
10862 					done = B_TRUE;
10863 				}
10864 				ire_refrele(ire);
10865 			}
10866 			if (!done) {
10867 				error = optfn(connp, checkonly, group, ifaddr,
10868 				    ifindexp, fmode, INADDR_ANY, first_mp);
10869 			}
10870 			if (error) {
10871 				/*
10872 				 * EINPROGRESS is a soft error, needs retry
10873 				 * so don't make *outlenp zero.
10874 				 */
10875 				if (error != EINPROGRESS)
10876 					*outlenp = 0;
10877 				return (error);
10878 			}
10879 			/* OK return - copy input buffer into output buffer */
10880 			if (invalp != outvalp) {
10881 				/* don't trust bcopy for identical src/dst */
10882 				bcopy(invalp, outvalp, inlen);
10883 			}
10884 			*outlenp = inlen;
10885 			return (0);
10886 		}
10887 		case IP_BLOCK_SOURCE:
10888 		case IP_UNBLOCK_SOURCE:
10889 		case IP_ADD_SOURCE_MEMBERSHIP:
10890 		case IP_DROP_SOURCE_MEMBERSHIP:
10891 		case MCAST_BLOCK_SOURCE:
10892 		case MCAST_UNBLOCK_SOURCE:
10893 		case MCAST_JOIN_SOURCE_GROUP:
10894 		case MCAST_LEAVE_SOURCE_GROUP: {
10895 			struct ip_mreq_source *imreqp;
10896 			struct group_source_req *gsreqp;
10897 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10898 			uint32_t ifindex = 0;
10899 			mcast_record_t fmode;
10900 			struct sockaddr_in *sin;
10901 			ire_t *ire;
10902 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10903 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10904 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10905 
10906 			switch (name) {
10907 			case IP_BLOCK_SOURCE:
10908 				mcast_opt = B_FALSE;
10909 				/* FALLTHRU */
10910 			case MCAST_BLOCK_SOURCE:
10911 				fmode = MODE_IS_EXCLUDE;
10912 				optfn = ip_opt_add_group;
10913 				break;
10914 
10915 			case IP_UNBLOCK_SOURCE:
10916 				mcast_opt = B_FALSE;
10917 				/* FALLTHRU */
10918 			case MCAST_UNBLOCK_SOURCE:
10919 				fmode = MODE_IS_EXCLUDE;
10920 				optfn = ip_opt_delete_group;
10921 				break;
10922 
10923 			case IP_ADD_SOURCE_MEMBERSHIP:
10924 				mcast_opt = B_FALSE;
10925 				/* FALLTHRU */
10926 			case MCAST_JOIN_SOURCE_GROUP:
10927 				fmode = MODE_IS_INCLUDE;
10928 				optfn = ip_opt_add_group;
10929 				break;
10930 
10931 			case IP_DROP_SOURCE_MEMBERSHIP:
10932 				mcast_opt = B_FALSE;
10933 				/* FALLTHRU */
10934 			case MCAST_LEAVE_SOURCE_GROUP:
10935 				fmode = MODE_IS_INCLUDE;
10936 				optfn = ip_opt_delete_group;
10937 				break;
10938 			}
10939 
10940 			if (mcast_opt) {
10941 				gsreqp = (struct group_source_req *)i1;
10942 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10943 					*outlenp = 0;
10944 					return (ENOPROTOOPT);
10945 				}
10946 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10947 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10948 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10949 				src = (ipaddr_t)sin->sin_addr.s_addr;
10950 				ifindex = gsreqp->gsr_interface;
10951 			} else {
10952 				imreqp = (struct ip_mreq_source *)i1;
10953 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10954 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10955 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10956 			}
10957 
10958 			/*
10959 			 * In the multirouting case, we need to replicate
10960 			 * the request as noted in the mcast cases above.
10961 			 */
10962 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10963 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10964 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10965 			if (ire != NULL) {
10966 				if (ire->ire_flags & RTF_MULTIRT) {
10967 					error = ip_multirt_apply_membership(
10968 					    optfn, ire, connp, checkonly, grp,
10969 					    fmode, src, first_mp);
10970 					done = B_TRUE;
10971 				}
10972 				ire_refrele(ire);
10973 			}
10974 			if (!done) {
10975 				error = optfn(connp, checkonly, grp, ifaddr,
10976 				    &ifindex, fmode, src, first_mp);
10977 			}
10978 			if (error != 0) {
10979 				/*
10980 				 * EINPROGRESS is a soft error, needs retry
10981 				 * so don't make *outlenp zero.
10982 				 */
10983 				if (error != EINPROGRESS)
10984 					*outlenp = 0;
10985 				return (error);
10986 			}
10987 			/* OK return - copy input buffer into output buffer */
10988 			if (invalp != outvalp) {
10989 				bcopy(invalp, outvalp, inlen);
10990 			}
10991 			*outlenp = inlen;
10992 			return (0);
10993 		}
10994 		case IP_SEC_OPT:
10995 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10996 			if (error != 0) {
10997 				*outlenp = 0;
10998 				return (error);
10999 			}
11000 			break;
11001 		case IP_HDRINCL:
11002 		case IP_OPTIONS:
11003 		case T_IP_OPTIONS:
11004 		case IP_TOS:
11005 		case T_IP_TOS:
11006 		case IP_TTL:
11007 		case IP_RECVDSTADDR:
11008 		case IP_RECVOPTS:
11009 			/* OK return - copy input buffer into output buffer */
11010 			if (invalp != outvalp) {
11011 				/* don't trust bcopy for identical src/dst */
11012 				bcopy(invalp, outvalp, inlen);
11013 			}
11014 			*outlenp = inlen;
11015 			return (0);
11016 		case IP_RECVIF:
11017 			/* Retrieve the inbound interface index */
11018 			if (!checkonly) {
11019 				mutex_enter(&connp->conn_lock);
11020 				connp->conn_recvif = *i1 ? 1 : 0;
11021 				mutex_exit(&connp->conn_lock);
11022 			}
11023 			break;	/* goto sizeof (int) option return */
11024 		case IP_RECVPKTINFO:
11025 			if (!checkonly) {
11026 				mutex_enter(&connp->conn_lock);
11027 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11028 				mutex_exit(&connp->conn_lock);
11029 			}
11030 			break;	/* goto sizeof (int) option return */
11031 		case IP_RECVSLLA:
11032 			/* Retrieve the source link layer address */
11033 			if (!checkonly) {
11034 				mutex_enter(&connp->conn_lock);
11035 				connp->conn_recvslla = *i1 ? 1 : 0;
11036 				mutex_exit(&connp->conn_lock);
11037 			}
11038 			break;	/* goto sizeof (int) option return */
11039 		case MRT_INIT:
11040 		case MRT_DONE:
11041 		case MRT_ADD_VIF:
11042 		case MRT_DEL_VIF:
11043 		case MRT_ADD_MFC:
11044 		case MRT_DEL_MFC:
11045 		case MRT_ASSERT:
11046 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11047 				*outlenp = 0;
11048 				return (error);
11049 			}
11050 			error = ip_mrouter_set((int)name, q, checkonly,
11051 			    (uchar_t *)invalp, inlen, first_mp);
11052 			if (error) {
11053 				*outlenp = 0;
11054 				return (error);
11055 			}
11056 			/* OK return - copy input buffer into output buffer */
11057 			if (invalp != outvalp) {
11058 				/* don't trust bcopy for identical src/dst */
11059 				bcopy(invalp, outvalp, inlen);
11060 			}
11061 			*outlenp = inlen;
11062 			return (0);
11063 		case IP_BOUND_IF:
11064 		case IP_DHCPINIT_IF:
11065 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11066 			    level, name, first_mp);
11067 			if (error != 0)
11068 				return (error);
11069 			break; 		/* goto sizeof (int) option return */
11070 
11071 		case IP_UNSPEC_SRC:
11072 			/* Allow sending with a zero source address */
11073 			if (!checkonly) {
11074 				mutex_enter(&connp->conn_lock);
11075 				connp->conn_unspec_src = *i1 ? 1 : 0;
11076 				mutex_exit(&connp->conn_lock);
11077 			}
11078 			break;	/* goto sizeof (int) option return */
11079 		default:
11080 			/*
11081 			 * "soft" error (negative)
11082 			 * option not handled at this level
11083 			 * Note: Do not modify *outlenp
11084 			 */
11085 			return (-EINVAL);
11086 		}
11087 		break;
11088 	case IPPROTO_IPV6:
11089 		switch (name) {
11090 		case IPV6_BOUND_IF:
11091 		case IPV6_BOUND_PIF:
11092 		case IPV6_DONTFAILOVER_IF:
11093 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11094 			    level, name, first_mp);
11095 			if (error != 0)
11096 				return (error);
11097 			break; 		/* goto sizeof (int) option return */
11098 
11099 		case IPV6_MULTICAST_IF:
11100 			/*
11101 			 * The only possible errors are EINPROGRESS and
11102 			 * EINVAL. EINPROGRESS will be restarted and is not
11103 			 * a hard error. We call this option on both V4 and V6
11104 			 * If both return EINVAL, then this call returns
11105 			 * EINVAL. If at least one of them succeeds we
11106 			 * return success.
11107 			 */
11108 			found = B_FALSE;
11109 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11110 			    level, name, first_mp);
11111 			if (error == EINPROGRESS)
11112 				return (error);
11113 			if (error == 0)
11114 				found = B_TRUE;
11115 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11116 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11117 			if (error == 0)
11118 				found = B_TRUE;
11119 			if (!found)
11120 				return (error);
11121 			break; 		/* goto sizeof (int) option return */
11122 
11123 		case IPV6_MULTICAST_HOPS:
11124 			/* Recorded in transport above IP */
11125 			break;	/* goto sizeof (int) option return */
11126 		case IPV6_MULTICAST_LOOP:
11127 			if (!checkonly) {
11128 				mutex_enter(&connp->conn_lock);
11129 				connp->conn_multicast_loop = *i1;
11130 				mutex_exit(&connp->conn_lock);
11131 			}
11132 			break;	/* goto sizeof (int) option return */
11133 		case IPV6_JOIN_GROUP:
11134 		case MCAST_JOIN_GROUP:
11135 		case IPV6_LEAVE_GROUP:
11136 		case MCAST_LEAVE_GROUP: {
11137 			struct ipv6_mreq *ip_mreqp;
11138 			struct group_req *greqp;
11139 			ire_t *ire;
11140 			boolean_t done = B_FALSE;
11141 			in6_addr_t groupv6;
11142 			uint32_t ifindex;
11143 			boolean_t mcast_opt = B_TRUE;
11144 			mcast_record_t fmode;
11145 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11146 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11147 
11148 			switch (name) {
11149 			case IPV6_JOIN_GROUP:
11150 				mcast_opt = B_FALSE;
11151 				/* FALLTHRU */
11152 			case MCAST_JOIN_GROUP:
11153 				fmode = MODE_IS_EXCLUDE;
11154 				optfn = ip_opt_add_group_v6;
11155 				break;
11156 
11157 			case IPV6_LEAVE_GROUP:
11158 				mcast_opt = B_FALSE;
11159 				/* FALLTHRU */
11160 			case MCAST_LEAVE_GROUP:
11161 				fmode = MODE_IS_INCLUDE;
11162 				optfn = ip_opt_delete_group_v6;
11163 				break;
11164 			}
11165 
11166 			if (mcast_opt) {
11167 				struct sockaddr_in *sin;
11168 				struct sockaddr_in6 *sin6;
11169 				greqp = (struct group_req *)i1;
11170 				if (greqp->gr_group.ss_family == AF_INET) {
11171 					sin = (struct sockaddr_in *)
11172 					    &(greqp->gr_group);
11173 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11174 					    &groupv6);
11175 				} else {
11176 					sin6 = (struct sockaddr_in6 *)
11177 					    &(greqp->gr_group);
11178 					groupv6 = sin6->sin6_addr;
11179 				}
11180 				ifindex = greqp->gr_interface;
11181 			} else {
11182 				ip_mreqp = (struct ipv6_mreq *)i1;
11183 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11184 				ifindex = ip_mreqp->ipv6mr_interface;
11185 			}
11186 			/*
11187 			 * In the multirouting case, we need to replicate
11188 			 * the request on all interfaces that will take part
11189 			 * in replication.  We do so because multirouting is
11190 			 * reflective, thus we will probably receive multi-
11191 			 * casts on those interfaces.
11192 			 * The ip_multirt_apply_membership_v6() succeeds if
11193 			 * the operation succeeds on at least one interface.
11194 			 */
11195 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11196 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11197 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11198 			if (ire != NULL) {
11199 				if (ire->ire_flags & RTF_MULTIRT) {
11200 					error = ip_multirt_apply_membership_v6(
11201 					    optfn, ire, connp, checkonly,
11202 					    &groupv6, fmode, &ipv6_all_zeros,
11203 					    first_mp);
11204 					done = B_TRUE;
11205 				}
11206 				ire_refrele(ire);
11207 			}
11208 			if (!done) {
11209 				error = optfn(connp, checkonly, &groupv6,
11210 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11211 			}
11212 			if (error) {
11213 				/*
11214 				 * EINPROGRESS is a soft error, needs retry
11215 				 * so don't make *outlenp zero.
11216 				 */
11217 				if (error != EINPROGRESS)
11218 					*outlenp = 0;
11219 				return (error);
11220 			}
11221 			/* OK return - copy input buffer into output buffer */
11222 			if (invalp != outvalp) {
11223 				/* don't trust bcopy for identical src/dst */
11224 				bcopy(invalp, outvalp, inlen);
11225 			}
11226 			*outlenp = inlen;
11227 			return (0);
11228 		}
11229 		case MCAST_BLOCK_SOURCE:
11230 		case MCAST_UNBLOCK_SOURCE:
11231 		case MCAST_JOIN_SOURCE_GROUP:
11232 		case MCAST_LEAVE_SOURCE_GROUP: {
11233 			struct group_source_req *gsreqp;
11234 			in6_addr_t v6grp, v6src;
11235 			uint32_t ifindex;
11236 			mcast_record_t fmode;
11237 			ire_t *ire;
11238 			boolean_t done = B_FALSE;
11239 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11240 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11241 
11242 			switch (name) {
11243 			case MCAST_BLOCK_SOURCE:
11244 				fmode = MODE_IS_EXCLUDE;
11245 				optfn = ip_opt_add_group_v6;
11246 				break;
11247 			case MCAST_UNBLOCK_SOURCE:
11248 				fmode = MODE_IS_EXCLUDE;
11249 				optfn = ip_opt_delete_group_v6;
11250 				break;
11251 			case MCAST_JOIN_SOURCE_GROUP:
11252 				fmode = MODE_IS_INCLUDE;
11253 				optfn = ip_opt_add_group_v6;
11254 				break;
11255 			case MCAST_LEAVE_SOURCE_GROUP:
11256 				fmode = MODE_IS_INCLUDE;
11257 				optfn = ip_opt_delete_group_v6;
11258 				break;
11259 			}
11260 
11261 			gsreqp = (struct group_source_req *)i1;
11262 			ifindex = gsreqp->gsr_interface;
11263 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11264 				struct sockaddr_in *s;
11265 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11266 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11267 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11268 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11269 			} else {
11270 				struct sockaddr_in6 *s6;
11271 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11272 				v6grp = s6->sin6_addr;
11273 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11274 				v6src = s6->sin6_addr;
11275 			}
11276 
11277 			/*
11278 			 * In the multirouting case, we need to replicate
11279 			 * the request as noted in the mcast cases above.
11280 			 */
11281 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11282 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11283 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11284 			if (ire != NULL) {
11285 				if (ire->ire_flags & RTF_MULTIRT) {
11286 					error = ip_multirt_apply_membership_v6(
11287 					    optfn, ire, connp, checkonly,
11288 					    &v6grp, fmode, &v6src, first_mp);
11289 					done = B_TRUE;
11290 				}
11291 				ire_refrele(ire);
11292 			}
11293 			if (!done) {
11294 				error = optfn(connp, checkonly, &v6grp,
11295 				    ifindex, fmode, &v6src, first_mp);
11296 			}
11297 			if (error != 0) {
11298 				/*
11299 				 * EINPROGRESS is a soft error, needs retry
11300 				 * so don't make *outlenp zero.
11301 				 */
11302 				if (error != EINPROGRESS)
11303 					*outlenp = 0;
11304 				return (error);
11305 			}
11306 			/* OK return - copy input buffer into output buffer */
11307 			if (invalp != outvalp) {
11308 				bcopy(invalp, outvalp, inlen);
11309 			}
11310 			*outlenp = inlen;
11311 			return (0);
11312 		}
11313 		case IPV6_UNICAST_HOPS:
11314 			/* Recorded in transport above IP */
11315 			break;	/* goto sizeof (int) option return */
11316 		case IPV6_UNSPEC_SRC:
11317 			/* Allow sending with a zero source address */
11318 			if (!checkonly) {
11319 				mutex_enter(&connp->conn_lock);
11320 				connp->conn_unspec_src = *i1 ? 1 : 0;
11321 				mutex_exit(&connp->conn_lock);
11322 			}
11323 			break;	/* goto sizeof (int) option return */
11324 		case IPV6_RECVPKTINFO:
11325 			if (!checkonly) {
11326 				mutex_enter(&connp->conn_lock);
11327 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11328 				mutex_exit(&connp->conn_lock);
11329 			}
11330 			break;	/* goto sizeof (int) option return */
11331 		case IPV6_RECVTCLASS:
11332 			if (!checkonly) {
11333 				if (*i1 < 0 || *i1 > 1) {
11334 					return (EINVAL);
11335 				}
11336 				mutex_enter(&connp->conn_lock);
11337 				connp->conn_ipv6_recvtclass = *i1;
11338 				mutex_exit(&connp->conn_lock);
11339 			}
11340 			break;
11341 		case IPV6_RECVPATHMTU:
11342 			if (!checkonly) {
11343 				if (*i1 < 0 || *i1 > 1) {
11344 					return (EINVAL);
11345 				}
11346 				mutex_enter(&connp->conn_lock);
11347 				connp->conn_ipv6_recvpathmtu = *i1;
11348 				mutex_exit(&connp->conn_lock);
11349 			}
11350 			break;
11351 		case IPV6_RECVHOPLIMIT:
11352 			if (!checkonly) {
11353 				mutex_enter(&connp->conn_lock);
11354 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11355 				mutex_exit(&connp->conn_lock);
11356 			}
11357 			break;	/* goto sizeof (int) option return */
11358 		case IPV6_RECVHOPOPTS:
11359 			if (!checkonly) {
11360 				mutex_enter(&connp->conn_lock);
11361 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11362 				mutex_exit(&connp->conn_lock);
11363 			}
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_RECVDSTOPTS:
11366 			if (!checkonly) {
11367 				mutex_enter(&connp->conn_lock);
11368 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11369 				mutex_exit(&connp->conn_lock);
11370 			}
11371 			break;	/* goto sizeof (int) option return */
11372 		case IPV6_RECVRTHDR:
11373 			if (!checkonly) {
11374 				mutex_enter(&connp->conn_lock);
11375 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11376 				mutex_exit(&connp->conn_lock);
11377 			}
11378 			break;	/* goto sizeof (int) option return */
11379 		case IPV6_RECVRTHDRDSTOPTS:
11380 			if (!checkonly) {
11381 				mutex_enter(&connp->conn_lock);
11382 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11383 				mutex_exit(&connp->conn_lock);
11384 			}
11385 			break;	/* goto sizeof (int) option return */
11386 		case IPV6_PKTINFO:
11387 			if (inlen == 0)
11388 				return (-EINVAL);	/* clearing option */
11389 			error = ip6_set_pktinfo(cr, connp,
11390 			    (struct in6_pktinfo *)invalp, first_mp);
11391 			if (error != 0)
11392 				*outlenp = 0;
11393 			else
11394 				*outlenp = inlen;
11395 			return (error);
11396 		case IPV6_NEXTHOP: {
11397 			struct sockaddr_in6 *sin6;
11398 
11399 			/* Verify that the nexthop is reachable */
11400 			if (inlen == 0)
11401 				return (-EINVAL);	/* clearing option */
11402 
11403 			sin6 = (struct sockaddr_in6 *)invalp;
11404 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11405 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11406 			    NULL, MATCH_IRE_DEFAULT, ipst);
11407 
11408 			if (ire == NULL) {
11409 				*outlenp = 0;
11410 				return (EHOSTUNREACH);
11411 			}
11412 			ire_refrele(ire);
11413 			return (-EINVAL);
11414 		}
11415 		case IPV6_SEC_OPT:
11416 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11417 			if (error != 0) {
11418 				*outlenp = 0;
11419 				return (error);
11420 			}
11421 			break;
11422 		case IPV6_SRC_PREFERENCES: {
11423 			/*
11424 			 * This is implemented strictly in the ip module
11425 			 * (here and in tcp_opt_*() to accomodate tcp
11426 			 * sockets).  Modules above ip pass this option
11427 			 * down here since ip is the only one that needs to
11428 			 * be aware of source address preferences.
11429 			 *
11430 			 * This socket option only affects connected
11431 			 * sockets that haven't already bound to a specific
11432 			 * IPv6 address.  In other words, sockets that
11433 			 * don't call bind() with an address other than the
11434 			 * unspecified address and that call connect().
11435 			 * ip_bind_connected_v6() passes these preferences
11436 			 * to the ipif_select_source_v6() function.
11437 			 */
11438 			if (inlen != sizeof (uint32_t))
11439 				return (EINVAL);
11440 			error = ip6_set_src_preferences(connp,
11441 			    *(uint32_t *)invalp);
11442 			if (error != 0) {
11443 				*outlenp = 0;
11444 				return (error);
11445 			} else {
11446 				*outlenp = sizeof (uint32_t);
11447 			}
11448 			break;
11449 		}
11450 		case IPV6_V6ONLY:
11451 			if (*i1 < 0 || *i1 > 1) {
11452 				return (EINVAL);
11453 			}
11454 			mutex_enter(&connp->conn_lock);
11455 			connp->conn_ipv6_v6only = *i1;
11456 			mutex_exit(&connp->conn_lock);
11457 			break;
11458 		default:
11459 			return (-EINVAL);
11460 		}
11461 		break;
11462 	default:
11463 		/*
11464 		 * "soft" error (negative)
11465 		 * option not handled at this level
11466 		 * Note: Do not modify *outlenp
11467 		 */
11468 		return (-EINVAL);
11469 	}
11470 	/*
11471 	 * Common case of return from an option that is sizeof (int)
11472 	 */
11473 	*(int *)outvalp = *i1;
11474 	*outlenp = sizeof (int);
11475 	return (0);
11476 }
11477 
11478 /*
11479  * This routine gets default values of certain options whose default
11480  * values are maintained by protocol specific code
11481  */
11482 /* ARGSUSED */
11483 int
11484 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11485 {
11486 	int *i1 = (int *)ptr;
11487 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11488 
11489 	switch (level) {
11490 	case IPPROTO_IP:
11491 		switch (name) {
11492 		case IP_MULTICAST_TTL:
11493 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11494 			return (sizeof (uchar_t));
11495 		case IP_MULTICAST_LOOP:
11496 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11497 			return (sizeof (uchar_t));
11498 		default:
11499 			return (-1);
11500 		}
11501 	case IPPROTO_IPV6:
11502 		switch (name) {
11503 		case IPV6_UNICAST_HOPS:
11504 			*i1 = ipst->ips_ipv6_def_hops;
11505 			return (sizeof (int));
11506 		case IPV6_MULTICAST_HOPS:
11507 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11508 			return (sizeof (int));
11509 		case IPV6_MULTICAST_LOOP:
11510 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11511 			return (sizeof (int));
11512 		case IPV6_V6ONLY:
11513 			*i1 = 1;
11514 			return (sizeof (int));
11515 		default:
11516 			return (-1);
11517 		}
11518 	default:
11519 		return (-1);
11520 	}
11521 	/* NOTREACHED */
11522 }
11523 
11524 /*
11525  * Given a destination address and a pointer to where to put the information
11526  * this routine fills in the mtuinfo.
11527  */
11528 int
11529 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11530     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11531 {
11532 	ire_t *ire;
11533 	ip_stack_t	*ipst = ns->netstack_ip;
11534 
11535 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11536 		return (-1);
11537 
11538 	bzero(mtuinfo, sizeof (*mtuinfo));
11539 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11540 	mtuinfo->ip6m_addr.sin6_port = port;
11541 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11542 
11543 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11544 	if (ire != NULL) {
11545 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11546 		ire_refrele(ire);
11547 	} else {
11548 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11549 	}
11550 	return (sizeof (struct ip6_mtuinfo));
11551 }
11552 
11553 /*
11554  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11555  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11556  * isn't.  This doesn't matter as the error checking is done properly for the
11557  * other MRT options coming in through ip_opt_set.
11558  */
11559 int
11560 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11561 {
11562 	conn_t		*connp = Q_TO_CONN(q);
11563 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11564 
11565 	switch (level) {
11566 	case IPPROTO_IP:
11567 		switch (name) {
11568 		case MRT_VERSION:
11569 		case MRT_ASSERT:
11570 			(void) ip_mrouter_get(name, q, ptr);
11571 			return (sizeof (int));
11572 		case IP_SEC_OPT:
11573 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11574 		case IP_NEXTHOP:
11575 			if (connp->conn_nexthop_set) {
11576 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11577 				return (sizeof (ipaddr_t));
11578 			} else
11579 				return (0);
11580 		case IP_RECVPKTINFO:
11581 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11582 			return (sizeof (int));
11583 		default:
11584 			break;
11585 		}
11586 		break;
11587 	case IPPROTO_IPV6:
11588 		switch (name) {
11589 		case IPV6_SEC_OPT:
11590 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11591 		case IPV6_SRC_PREFERENCES: {
11592 			return (ip6_get_src_preferences(connp,
11593 			    (uint32_t *)ptr));
11594 		}
11595 		case IPV6_V6ONLY:
11596 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11597 			return (sizeof (int));
11598 		case IPV6_PATHMTU:
11599 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11600 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11601 		default:
11602 			break;
11603 		}
11604 		break;
11605 	default:
11606 		break;
11607 	}
11608 	return (-1);
11609 }
11610 
11611 /* Named Dispatch routine to get a current value out of our parameter table. */
11612 /* ARGSUSED */
11613 static int
11614 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11615 {
11616 	ipparam_t *ippa = (ipparam_t *)cp;
11617 
11618 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11619 	return (0);
11620 }
11621 
11622 /* ARGSUSED */
11623 static int
11624 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11625 {
11626 
11627 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11628 	return (0);
11629 }
11630 
11631 /*
11632  * Set ip{,6}_forwarding values.  This means walking through all of the
11633  * ill's and toggling their forwarding values.
11634  */
11635 /* ARGSUSED */
11636 static int
11637 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11638 {
11639 	long new_value;
11640 	int *forwarding_value = (int *)cp;
11641 	ill_t *ill;
11642 	boolean_t isv6;
11643 	ill_walk_context_t ctx;
11644 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11645 
11646 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11647 
11648 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11649 	    new_value < 0 || new_value > 1) {
11650 		return (EINVAL);
11651 	}
11652 
11653 	*forwarding_value = new_value;
11654 
11655 	/*
11656 	 * Regardless of the current value of ip_forwarding, set all per-ill
11657 	 * values of ip_forwarding to the value being set.
11658 	 *
11659 	 * Bring all the ill's up to date with the new global value.
11660 	 */
11661 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11662 
11663 	if (isv6)
11664 		ill = ILL_START_WALK_V6(&ctx, ipst);
11665 	else
11666 		ill = ILL_START_WALK_V4(&ctx, ipst);
11667 
11668 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11669 		(void) ill_forward_set(ill, new_value != 0);
11670 
11671 	rw_exit(&ipst->ips_ill_g_lock);
11672 	return (0);
11673 }
11674 
11675 /*
11676  * Walk through the param array specified registering each element with the
11677  * Named Dispatch handler. This is called only during init. So it is ok
11678  * not to acquire any locks
11679  */
11680 static boolean_t
11681 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11682     ipndp_t *ipnd, size_t ipnd_cnt)
11683 {
11684 	for (; ippa_cnt-- > 0; ippa++) {
11685 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11686 			if (!nd_load(ndp, ippa->ip_param_name,
11687 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11688 				nd_free(ndp);
11689 				return (B_FALSE);
11690 			}
11691 		}
11692 	}
11693 
11694 	for (; ipnd_cnt-- > 0; ipnd++) {
11695 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11696 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11697 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11698 			    ipnd->ip_ndp_data)) {
11699 				nd_free(ndp);
11700 				return (B_FALSE);
11701 			}
11702 		}
11703 	}
11704 
11705 	return (B_TRUE);
11706 }
11707 
11708 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11709 /* ARGSUSED */
11710 static int
11711 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11712 {
11713 	long		new_value;
11714 	ipparam_t	*ippa = (ipparam_t *)cp;
11715 
11716 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11717 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11718 		return (EINVAL);
11719 	}
11720 	ippa->ip_param_value = new_value;
11721 	return (0);
11722 }
11723 
11724 /*
11725  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11726  * When an ipf is passed here for the first time, if
11727  * we already have in-order fragments on the queue, we convert from the fast-
11728  * path reassembly scheme to the hard-case scheme.  From then on, additional
11729  * fragments are reassembled here.  We keep track of the start and end offsets
11730  * of each piece, and the number of holes in the chain.  When the hole count
11731  * goes to zero, we are done!
11732  *
11733  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11734  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11735  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11736  * after the call to ip_reassemble().
11737  */
11738 int
11739 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11740     size_t msg_len)
11741 {
11742 	uint_t	end;
11743 	mblk_t	*next_mp;
11744 	mblk_t	*mp1;
11745 	uint_t	offset;
11746 	boolean_t incr_dups = B_TRUE;
11747 	boolean_t offset_zero_seen = B_FALSE;
11748 	boolean_t pkt_boundary_checked = B_FALSE;
11749 
11750 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11751 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11752 
11753 	/* Add in byte count */
11754 	ipf->ipf_count += msg_len;
11755 	if (ipf->ipf_end) {
11756 		/*
11757 		 * We were part way through in-order reassembly, but now there
11758 		 * is a hole.  We walk through messages already queued, and
11759 		 * mark them for hard case reassembly.  We know that up till
11760 		 * now they were in order starting from offset zero.
11761 		 */
11762 		offset = 0;
11763 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11764 			IP_REASS_SET_START(mp1, offset);
11765 			if (offset == 0) {
11766 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11767 				offset = -ipf->ipf_nf_hdr_len;
11768 			}
11769 			offset += mp1->b_wptr - mp1->b_rptr;
11770 			IP_REASS_SET_END(mp1, offset);
11771 		}
11772 		/* One hole at the end. */
11773 		ipf->ipf_hole_cnt = 1;
11774 		/* Brand it as a hard case, forever. */
11775 		ipf->ipf_end = 0;
11776 	}
11777 	/* Walk through all the new pieces. */
11778 	do {
11779 		end = start + (mp->b_wptr - mp->b_rptr);
11780 		/*
11781 		 * If start is 0, decrease 'end' only for the first mblk of
11782 		 * the fragment. Otherwise 'end' can get wrong value in the
11783 		 * second pass of the loop if first mblk is exactly the
11784 		 * size of ipf_nf_hdr_len.
11785 		 */
11786 		if (start == 0 && !offset_zero_seen) {
11787 			/* First segment */
11788 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11789 			end -= ipf->ipf_nf_hdr_len;
11790 			offset_zero_seen = B_TRUE;
11791 		}
11792 		next_mp = mp->b_cont;
11793 		/*
11794 		 * We are checking to see if there is any interesing data
11795 		 * to process.  If there isn't and the mblk isn't the
11796 		 * one which carries the unfragmentable header then we
11797 		 * drop it.  It's possible to have just the unfragmentable
11798 		 * header come through without any data.  That needs to be
11799 		 * saved.
11800 		 *
11801 		 * If the assert at the top of this function holds then the
11802 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11803 		 * is infrequently traveled enough that the test is left in
11804 		 * to protect against future code changes which break that
11805 		 * invariant.
11806 		 */
11807 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11808 			/* Empty.  Blast it. */
11809 			IP_REASS_SET_START(mp, 0);
11810 			IP_REASS_SET_END(mp, 0);
11811 			/*
11812 			 * If the ipf points to the mblk we are about to free,
11813 			 * update ipf to point to the next mblk (or NULL
11814 			 * if none).
11815 			 */
11816 			if (ipf->ipf_mp->b_cont == mp)
11817 				ipf->ipf_mp->b_cont = next_mp;
11818 			freeb(mp);
11819 			continue;
11820 		}
11821 		mp->b_cont = NULL;
11822 		IP_REASS_SET_START(mp, start);
11823 		IP_REASS_SET_END(mp, end);
11824 		if (!ipf->ipf_tail_mp) {
11825 			ipf->ipf_tail_mp = mp;
11826 			ipf->ipf_mp->b_cont = mp;
11827 			if (start == 0 || !more) {
11828 				ipf->ipf_hole_cnt = 1;
11829 				/*
11830 				 * if the first fragment comes in more than one
11831 				 * mblk, this loop will be executed for each
11832 				 * mblk. Need to adjust hole count so exiting
11833 				 * this routine will leave hole count at 1.
11834 				 */
11835 				if (next_mp)
11836 					ipf->ipf_hole_cnt++;
11837 			} else
11838 				ipf->ipf_hole_cnt = 2;
11839 			continue;
11840 		} else if (ipf->ipf_last_frag_seen && !more &&
11841 		    !pkt_boundary_checked) {
11842 			/*
11843 			 * We check datagram boundary only if this fragment
11844 			 * claims to be the last fragment and we have seen a
11845 			 * last fragment in the past too. We do this only
11846 			 * once for a given fragment.
11847 			 *
11848 			 * start cannot be 0 here as fragments with start=0
11849 			 * and MF=0 gets handled as a complete packet. These
11850 			 * fragments should not reach here.
11851 			 */
11852 
11853 			if (start + msgdsize(mp) !=
11854 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11855 				/*
11856 				 * We have two fragments both of which claim
11857 				 * to be the last fragment but gives conflicting
11858 				 * information about the whole datagram size.
11859 				 * Something fishy is going on. Drop the
11860 				 * fragment and free up the reassembly list.
11861 				 */
11862 				return (IP_REASS_FAILED);
11863 			}
11864 
11865 			/*
11866 			 * We shouldn't come to this code block again for this
11867 			 * particular fragment.
11868 			 */
11869 			pkt_boundary_checked = B_TRUE;
11870 		}
11871 
11872 		/* New stuff at or beyond tail? */
11873 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11874 		if (start >= offset) {
11875 			if (ipf->ipf_last_frag_seen) {
11876 				/* current fragment is beyond last fragment */
11877 				return (IP_REASS_FAILED);
11878 			}
11879 			/* Link it on end. */
11880 			ipf->ipf_tail_mp->b_cont = mp;
11881 			ipf->ipf_tail_mp = mp;
11882 			if (more) {
11883 				if (start != offset)
11884 					ipf->ipf_hole_cnt++;
11885 			} else if (start == offset && next_mp == NULL)
11886 					ipf->ipf_hole_cnt--;
11887 			continue;
11888 		}
11889 		mp1 = ipf->ipf_mp->b_cont;
11890 		offset = IP_REASS_START(mp1);
11891 		/* New stuff at the front? */
11892 		if (start < offset) {
11893 			if (start == 0) {
11894 				if (end >= offset) {
11895 					/* Nailed the hole at the begining. */
11896 					ipf->ipf_hole_cnt--;
11897 				}
11898 			} else if (end < offset) {
11899 				/*
11900 				 * A hole, stuff, and a hole where there used
11901 				 * to be just a hole.
11902 				 */
11903 				ipf->ipf_hole_cnt++;
11904 			}
11905 			mp->b_cont = mp1;
11906 			/* Check for overlap. */
11907 			while (end > offset) {
11908 				if (end < IP_REASS_END(mp1)) {
11909 					mp->b_wptr -= end - offset;
11910 					IP_REASS_SET_END(mp, offset);
11911 					BUMP_MIB(ill->ill_ip_mib,
11912 					    ipIfStatsReasmPartDups);
11913 					break;
11914 				}
11915 				/* Did we cover another hole? */
11916 				if ((mp1->b_cont &&
11917 				    IP_REASS_END(mp1) !=
11918 				    IP_REASS_START(mp1->b_cont) &&
11919 				    end >= IP_REASS_START(mp1->b_cont)) ||
11920 				    (!ipf->ipf_last_frag_seen && !more)) {
11921 					ipf->ipf_hole_cnt--;
11922 				}
11923 				/* Clip out mp1. */
11924 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11925 					/*
11926 					 * After clipping out mp1, this guy
11927 					 * is now hanging off the end.
11928 					 */
11929 					ipf->ipf_tail_mp = mp;
11930 				}
11931 				IP_REASS_SET_START(mp1, 0);
11932 				IP_REASS_SET_END(mp1, 0);
11933 				/* Subtract byte count */
11934 				ipf->ipf_count -= mp1->b_datap->db_lim -
11935 				    mp1->b_datap->db_base;
11936 				freeb(mp1);
11937 				BUMP_MIB(ill->ill_ip_mib,
11938 				    ipIfStatsReasmPartDups);
11939 				mp1 = mp->b_cont;
11940 				if (!mp1)
11941 					break;
11942 				offset = IP_REASS_START(mp1);
11943 			}
11944 			ipf->ipf_mp->b_cont = mp;
11945 			continue;
11946 		}
11947 		/*
11948 		 * The new piece starts somewhere between the start of the head
11949 		 * and before the end of the tail.
11950 		 */
11951 		for (; mp1; mp1 = mp1->b_cont) {
11952 			offset = IP_REASS_END(mp1);
11953 			if (start < offset) {
11954 				if (end <= offset) {
11955 					/* Nothing new. */
11956 					IP_REASS_SET_START(mp, 0);
11957 					IP_REASS_SET_END(mp, 0);
11958 					/* Subtract byte count */
11959 					ipf->ipf_count -= mp->b_datap->db_lim -
11960 					    mp->b_datap->db_base;
11961 					if (incr_dups) {
11962 						ipf->ipf_num_dups++;
11963 						incr_dups = B_FALSE;
11964 					}
11965 					freeb(mp);
11966 					BUMP_MIB(ill->ill_ip_mib,
11967 					    ipIfStatsReasmDuplicates);
11968 					break;
11969 				}
11970 				/*
11971 				 * Trim redundant stuff off beginning of new
11972 				 * piece.
11973 				 */
11974 				IP_REASS_SET_START(mp, offset);
11975 				mp->b_rptr += offset - start;
11976 				BUMP_MIB(ill->ill_ip_mib,
11977 				    ipIfStatsReasmPartDups);
11978 				start = offset;
11979 				if (!mp1->b_cont) {
11980 					/*
11981 					 * After trimming, this guy is now
11982 					 * hanging off the end.
11983 					 */
11984 					mp1->b_cont = mp;
11985 					ipf->ipf_tail_mp = mp;
11986 					if (!more) {
11987 						ipf->ipf_hole_cnt--;
11988 					}
11989 					break;
11990 				}
11991 			}
11992 			if (start >= IP_REASS_START(mp1->b_cont))
11993 				continue;
11994 			/* Fill a hole */
11995 			if (start > offset)
11996 				ipf->ipf_hole_cnt++;
11997 			mp->b_cont = mp1->b_cont;
11998 			mp1->b_cont = mp;
11999 			mp1 = mp->b_cont;
12000 			offset = IP_REASS_START(mp1);
12001 			if (end >= offset) {
12002 				ipf->ipf_hole_cnt--;
12003 				/* Check for overlap. */
12004 				while (end > offset) {
12005 					if (end < IP_REASS_END(mp1)) {
12006 						mp->b_wptr -= end - offset;
12007 						IP_REASS_SET_END(mp, offset);
12008 						/*
12009 						 * TODO we might bump
12010 						 * this up twice if there is
12011 						 * overlap at both ends.
12012 						 */
12013 						BUMP_MIB(ill->ill_ip_mib,
12014 						    ipIfStatsReasmPartDups);
12015 						break;
12016 					}
12017 					/* Did we cover another hole? */
12018 					if ((mp1->b_cont &&
12019 					    IP_REASS_END(mp1)
12020 					    != IP_REASS_START(mp1->b_cont) &&
12021 					    end >=
12022 					    IP_REASS_START(mp1->b_cont)) ||
12023 					    (!ipf->ipf_last_frag_seen &&
12024 					    !more)) {
12025 						ipf->ipf_hole_cnt--;
12026 					}
12027 					/* Clip out mp1. */
12028 					if ((mp->b_cont = mp1->b_cont) ==
12029 					    NULL) {
12030 						/*
12031 						 * After clipping out mp1,
12032 						 * this guy is now hanging
12033 						 * off the end.
12034 						 */
12035 						ipf->ipf_tail_mp = mp;
12036 					}
12037 					IP_REASS_SET_START(mp1, 0);
12038 					IP_REASS_SET_END(mp1, 0);
12039 					/* Subtract byte count */
12040 					ipf->ipf_count -=
12041 					    mp1->b_datap->db_lim -
12042 					    mp1->b_datap->db_base;
12043 					freeb(mp1);
12044 					BUMP_MIB(ill->ill_ip_mib,
12045 					    ipIfStatsReasmPartDups);
12046 					mp1 = mp->b_cont;
12047 					if (!mp1)
12048 						break;
12049 					offset = IP_REASS_START(mp1);
12050 				}
12051 			}
12052 			break;
12053 		}
12054 	} while (start = end, mp = next_mp);
12055 
12056 	/* Fragment just processed could be the last one. Remember this fact */
12057 	if (!more)
12058 		ipf->ipf_last_frag_seen = B_TRUE;
12059 
12060 	/* Still got holes? */
12061 	if (ipf->ipf_hole_cnt)
12062 		return (IP_REASS_PARTIAL);
12063 	/* Clean up overloaded fields to avoid upstream disasters. */
12064 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12065 		IP_REASS_SET_START(mp1, 0);
12066 		IP_REASS_SET_END(mp1, 0);
12067 	}
12068 	return (IP_REASS_COMPLETE);
12069 }
12070 
12071 /*
12072  * ipsec processing for the fast path, used for input UDP Packets
12073  * Returns true if ready for passup to UDP.
12074  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12075  * was an ESP-in-UDP packet, etc.).
12076  */
12077 static boolean_t
12078 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12079     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12080 {
12081 	uint32_t	ill_index;
12082 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12083 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12084 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12085 	udp_t		*udp = connp->conn_udp;
12086 
12087 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12088 	/* The ill_index of the incoming ILL */
12089 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12090 
12091 	/* pass packet up to the transport */
12092 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12093 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12094 		    NULL, mctl_present);
12095 		if (*first_mpp == NULL) {
12096 			return (B_FALSE);
12097 		}
12098 	}
12099 
12100 	/* Initiate IPPF processing for fastpath UDP */
12101 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12102 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12103 		if (*mpp == NULL) {
12104 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12105 			    "deferred/dropped during IPPF processing\n"));
12106 			return (B_FALSE);
12107 		}
12108 	}
12109 	/*
12110 	 * Remove 0-spi if it's 0, or move everything behind
12111 	 * the UDP header over it and forward to ESP via
12112 	 * ip_proto_input().
12113 	 */
12114 	if (udp->udp_nat_t_endpoint) {
12115 		if (mctl_present) {
12116 			/* mctl_present *shouldn't* happen. */
12117 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12118 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12119 			    &ipss->ipsec_dropper);
12120 			*first_mpp = NULL;
12121 			return (B_FALSE);
12122 		}
12123 
12124 		/* "ill" is "recv_ill" in actuality. */
12125 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12126 			return (B_FALSE);
12127 
12128 		/* Else continue like a normal UDP packet. */
12129 	}
12130 
12131 	/*
12132 	 * We make the checks as below since we are in the fast path
12133 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12134 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12135 	 */
12136 	if (connp->conn_recvif || connp->conn_recvslla ||
12137 	    connp->conn_ip_recvpktinfo) {
12138 		if (connp->conn_recvif) {
12139 			in_flags = IPF_RECVIF;
12140 		}
12141 		/*
12142 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12143 		 * so the flag passed to ip_add_info is based on IP version
12144 		 * of connp.
12145 		 */
12146 		if (connp->conn_ip_recvpktinfo) {
12147 			if (connp->conn_af_isv6) {
12148 				/*
12149 				 * V6 only needs index
12150 				 */
12151 				in_flags |= IPF_RECVIF;
12152 			} else {
12153 				/*
12154 				 * V4 needs index + matching address.
12155 				 */
12156 				in_flags |= IPF_RECVADDR;
12157 			}
12158 		}
12159 		if (connp->conn_recvslla) {
12160 			in_flags |= IPF_RECVSLLA;
12161 		}
12162 		/*
12163 		 * since in_flags are being set ill will be
12164 		 * referenced in ip_add_info, so it better not
12165 		 * be NULL.
12166 		 */
12167 		/*
12168 		 * the actual data will be contained in b_cont
12169 		 * upon successful return of the following call.
12170 		 * If the call fails then the original mblk is
12171 		 * returned.
12172 		 */
12173 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12174 		    ipst);
12175 	}
12176 
12177 	return (B_TRUE);
12178 }
12179 
12180 /*
12181  * Fragmentation reassembly.  Each ILL has a hash table for
12182  * queuing packets undergoing reassembly for all IPIFs
12183  * associated with the ILL.  The hash is based on the packet
12184  * IP ident field.  The ILL frag hash table was allocated
12185  * as a timer block at the time the ILL was created.  Whenever
12186  * there is anything on the reassembly queue, the timer will
12187  * be running.  Returns B_TRUE if successful else B_FALSE;
12188  * frees mp on failure.
12189  */
12190 static boolean_t
12191 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12192     uint32_t *cksum_val, uint16_t *cksum_flags)
12193 {
12194 	uint32_t	frag_offset_flags;
12195 	ill_t		*ill = (ill_t *)q->q_ptr;
12196 	mblk_t		*mp = *mpp;
12197 	mblk_t		*t_mp;
12198 	ipaddr_t	dst;
12199 	uint8_t		proto = ipha->ipha_protocol;
12200 	uint32_t	sum_val;
12201 	uint16_t	sum_flags;
12202 	ipf_t		*ipf;
12203 	ipf_t		**ipfp;
12204 	ipfb_t		*ipfb;
12205 	uint16_t	ident;
12206 	uint32_t	offset;
12207 	ipaddr_t	src;
12208 	uint_t		hdr_length;
12209 	uint32_t	end;
12210 	mblk_t		*mp1;
12211 	mblk_t		*tail_mp;
12212 	size_t		count;
12213 	size_t		msg_len;
12214 	uint8_t		ecn_info = 0;
12215 	uint32_t	packet_size;
12216 	boolean_t	pruned = B_FALSE;
12217 	ip_stack_t *ipst = ill->ill_ipst;
12218 
12219 	if (cksum_val != NULL)
12220 		*cksum_val = 0;
12221 	if (cksum_flags != NULL)
12222 		*cksum_flags = 0;
12223 
12224 	/*
12225 	 * Drop the fragmented as early as possible, if
12226 	 * we don't have resource(s) to re-assemble.
12227 	 */
12228 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12229 		freemsg(mp);
12230 		return (B_FALSE);
12231 	}
12232 
12233 	/* Check for fragmentation offset; return if there's none */
12234 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12235 	    (IPH_MF | IPH_OFFSET)) == 0)
12236 		return (B_TRUE);
12237 
12238 	/*
12239 	 * We utilize hardware computed checksum info only for UDP since
12240 	 * IP fragmentation is a normal occurence for the protocol.  In
12241 	 * addition, checksum offload support for IP fragments carrying
12242 	 * UDP payload is commonly implemented across network adapters.
12243 	 */
12244 	ASSERT(ill != NULL);
12245 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12246 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12247 		mblk_t *mp1 = mp->b_cont;
12248 		int32_t len;
12249 
12250 		/* Record checksum information from the packet */
12251 		sum_val = (uint32_t)DB_CKSUM16(mp);
12252 		sum_flags = DB_CKSUMFLAGS(mp);
12253 
12254 		/* IP payload offset from beginning of mblk */
12255 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12256 
12257 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12258 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12259 		    offset >= DB_CKSUMSTART(mp) &&
12260 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12261 			uint32_t adj;
12262 			/*
12263 			 * Partial checksum has been calculated by hardware
12264 			 * and attached to the packet; in addition, any
12265 			 * prepended extraneous data is even byte aligned.
12266 			 * If any such data exists, we adjust the checksum;
12267 			 * this would also handle any postpended data.
12268 			 */
12269 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12270 			    mp, mp1, len, adj);
12271 
12272 			/* One's complement subtract extraneous checksum */
12273 			if (adj >= sum_val)
12274 				sum_val = ~(adj - sum_val) & 0xFFFF;
12275 			else
12276 				sum_val -= adj;
12277 		}
12278 	} else {
12279 		sum_val = 0;
12280 		sum_flags = 0;
12281 	}
12282 
12283 	/* Clear hardware checksumming flag */
12284 	DB_CKSUMFLAGS(mp) = 0;
12285 
12286 	ident = ipha->ipha_ident;
12287 	offset = (frag_offset_flags << 3) & 0xFFFF;
12288 	src = ipha->ipha_src;
12289 	dst = ipha->ipha_dst;
12290 	hdr_length = IPH_HDR_LENGTH(ipha);
12291 	end = ntohs(ipha->ipha_length) - hdr_length;
12292 
12293 	/* If end == 0 then we have a packet with no data, so just free it */
12294 	if (end == 0) {
12295 		freemsg(mp);
12296 		return (B_FALSE);
12297 	}
12298 
12299 	/* Record the ECN field info. */
12300 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12301 	if (offset != 0) {
12302 		/*
12303 		 * If this isn't the first piece, strip the header, and
12304 		 * add the offset to the end value.
12305 		 */
12306 		mp->b_rptr += hdr_length;
12307 		end += offset;
12308 	}
12309 
12310 	msg_len = MBLKSIZE(mp);
12311 	tail_mp = mp;
12312 	while (tail_mp->b_cont != NULL) {
12313 		tail_mp = tail_mp->b_cont;
12314 		msg_len += MBLKSIZE(tail_mp);
12315 	}
12316 
12317 	/* If the reassembly list for this ILL will get too big, prune it */
12318 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12319 	    ipst->ips_ip_reass_queue_bytes) {
12320 		ill_frag_prune(ill,
12321 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12322 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12323 		pruned = B_TRUE;
12324 	}
12325 
12326 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12327 	mutex_enter(&ipfb->ipfb_lock);
12328 
12329 	ipfp = &ipfb->ipfb_ipf;
12330 	/* Try to find an existing fragment queue for this packet. */
12331 	for (;;) {
12332 		ipf = ipfp[0];
12333 		if (ipf != NULL) {
12334 			/*
12335 			 * It has to match on ident and src/dst address.
12336 			 */
12337 			if (ipf->ipf_ident == ident &&
12338 			    ipf->ipf_src == src &&
12339 			    ipf->ipf_dst == dst &&
12340 			    ipf->ipf_protocol == proto) {
12341 				/*
12342 				 * If we have received too many
12343 				 * duplicate fragments for this packet
12344 				 * free it.
12345 				 */
12346 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12347 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12348 					freemsg(mp);
12349 					mutex_exit(&ipfb->ipfb_lock);
12350 					return (B_FALSE);
12351 				}
12352 				/* Found it. */
12353 				break;
12354 			}
12355 			ipfp = &ipf->ipf_hash_next;
12356 			continue;
12357 		}
12358 
12359 		/*
12360 		 * If we pruned the list, do we want to store this new
12361 		 * fragment?. We apply an optimization here based on the
12362 		 * fact that most fragments will be received in order.
12363 		 * So if the offset of this incoming fragment is zero,
12364 		 * it is the first fragment of a new packet. We will
12365 		 * keep it.  Otherwise drop the fragment, as we have
12366 		 * probably pruned the packet already (since the
12367 		 * packet cannot be found).
12368 		 */
12369 		if (pruned && offset != 0) {
12370 			mutex_exit(&ipfb->ipfb_lock);
12371 			freemsg(mp);
12372 			return (B_FALSE);
12373 		}
12374 
12375 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12376 			/*
12377 			 * Too many fragmented packets in this hash
12378 			 * bucket. Free the oldest.
12379 			 */
12380 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12381 		}
12382 
12383 		/* New guy.  Allocate a frag message. */
12384 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12385 		if (mp1 == NULL) {
12386 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12387 			freemsg(mp);
12388 reass_done:
12389 			mutex_exit(&ipfb->ipfb_lock);
12390 			return (B_FALSE);
12391 		}
12392 
12393 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12394 		mp1->b_cont = mp;
12395 
12396 		/* Initialize the fragment header. */
12397 		ipf = (ipf_t *)mp1->b_rptr;
12398 		ipf->ipf_mp = mp1;
12399 		ipf->ipf_ptphn = ipfp;
12400 		ipfp[0] = ipf;
12401 		ipf->ipf_hash_next = NULL;
12402 		ipf->ipf_ident = ident;
12403 		ipf->ipf_protocol = proto;
12404 		ipf->ipf_src = src;
12405 		ipf->ipf_dst = dst;
12406 		ipf->ipf_nf_hdr_len = 0;
12407 		/* Record reassembly start time. */
12408 		ipf->ipf_timestamp = gethrestime_sec();
12409 		/* Record ipf generation and account for frag header */
12410 		ipf->ipf_gen = ill->ill_ipf_gen++;
12411 		ipf->ipf_count = MBLKSIZE(mp1);
12412 		ipf->ipf_last_frag_seen = B_FALSE;
12413 		ipf->ipf_ecn = ecn_info;
12414 		ipf->ipf_num_dups = 0;
12415 		ipfb->ipfb_frag_pkts++;
12416 		ipf->ipf_checksum = 0;
12417 		ipf->ipf_checksum_flags = 0;
12418 
12419 		/* Store checksum value in fragment header */
12420 		if (sum_flags != 0) {
12421 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12422 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12423 			ipf->ipf_checksum = sum_val;
12424 			ipf->ipf_checksum_flags = sum_flags;
12425 		}
12426 
12427 		/*
12428 		 * We handle reassembly two ways.  In the easy case,
12429 		 * where all the fragments show up in order, we do
12430 		 * minimal bookkeeping, and just clip new pieces on
12431 		 * the end.  If we ever see a hole, then we go off
12432 		 * to ip_reassemble which has to mark the pieces and
12433 		 * keep track of the number of holes, etc.  Obviously,
12434 		 * the point of having both mechanisms is so we can
12435 		 * handle the easy case as efficiently as possible.
12436 		 */
12437 		if (offset == 0) {
12438 			/* Easy case, in-order reassembly so far. */
12439 			ipf->ipf_count += msg_len;
12440 			ipf->ipf_tail_mp = tail_mp;
12441 			/*
12442 			 * Keep track of next expected offset in
12443 			 * ipf_end.
12444 			 */
12445 			ipf->ipf_end = end;
12446 			ipf->ipf_nf_hdr_len = hdr_length;
12447 		} else {
12448 			/* Hard case, hole at the beginning. */
12449 			ipf->ipf_tail_mp = NULL;
12450 			/*
12451 			 * ipf_end == 0 means that we have given up
12452 			 * on easy reassembly.
12453 			 */
12454 			ipf->ipf_end = 0;
12455 
12456 			/* Forget checksum offload from now on */
12457 			ipf->ipf_checksum_flags = 0;
12458 
12459 			/*
12460 			 * ipf_hole_cnt is set by ip_reassemble.
12461 			 * ipf_count is updated by ip_reassemble.
12462 			 * No need to check for return value here
12463 			 * as we don't expect reassembly to complete
12464 			 * or fail for the first fragment itself.
12465 			 */
12466 			(void) ip_reassemble(mp, ipf,
12467 			    (frag_offset_flags & IPH_OFFSET) << 3,
12468 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12469 		}
12470 		/* Update per ipfb and ill byte counts */
12471 		ipfb->ipfb_count += ipf->ipf_count;
12472 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12473 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12474 		/* If the frag timer wasn't already going, start it. */
12475 		mutex_enter(&ill->ill_lock);
12476 		ill_frag_timer_start(ill);
12477 		mutex_exit(&ill->ill_lock);
12478 		goto reass_done;
12479 	}
12480 
12481 	/*
12482 	 * If the packet's flag has changed (it could be coming up
12483 	 * from an interface different than the previous, therefore
12484 	 * possibly different checksum capability), then forget about
12485 	 * any stored checksum states.  Otherwise add the value to
12486 	 * the existing one stored in the fragment header.
12487 	 */
12488 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12489 		sum_val += ipf->ipf_checksum;
12490 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12491 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12492 		ipf->ipf_checksum = sum_val;
12493 	} else if (ipf->ipf_checksum_flags != 0) {
12494 		/* Forget checksum offload from now on */
12495 		ipf->ipf_checksum_flags = 0;
12496 	}
12497 
12498 	/*
12499 	 * We have a new piece of a datagram which is already being
12500 	 * reassembled.  Update the ECN info if all IP fragments
12501 	 * are ECN capable.  If there is one which is not, clear
12502 	 * all the info.  If there is at least one which has CE
12503 	 * code point, IP needs to report that up to transport.
12504 	 */
12505 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12506 		if (ecn_info == IPH_ECN_CE)
12507 			ipf->ipf_ecn = IPH_ECN_CE;
12508 	} else {
12509 		ipf->ipf_ecn = IPH_ECN_NECT;
12510 	}
12511 	if (offset && ipf->ipf_end == offset) {
12512 		/* The new fragment fits at the end */
12513 		ipf->ipf_tail_mp->b_cont = mp;
12514 		/* Update the byte count */
12515 		ipf->ipf_count += msg_len;
12516 		/* Update per ipfb and ill byte counts */
12517 		ipfb->ipfb_count += msg_len;
12518 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12519 		atomic_add_32(&ill->ill_frag_count, msg_len);
12520 		if (frag_offset_flags & IPH_MF) {
12521 			/* More to come. */
12522 			ipf->ipf_end = end;
12523 			ipf->ipf_tail_mp = tail_mp;
12524 			goto reass_done;
12525 		}
12526 	} else {
12527 		/* Go do the hard cases. */
12528 		int ret;
12529 
12530 		if (offset == 0)
12531 			ipf->ipf_nf_hdr_len = hdr_length;
12532 
12533 		/* Save current byte count */
12534 		count = ipf->ipf_count;
12535 		ret = ip_reassemble(mp, ipf,
12536 		    (frag_offset_flags & IPH_OFFSET) << 3,
12537 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12538 		/* Count of bytes added and subtracted (freeb()ed) */
12539 		count = ipf->ipf_count - count;
12540 		if (count) {
12541 			/* Update per ipfb and ill byte counts */
12542 			ipfb->ipfb_count += count;
12543 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12544 			atomic_add_32(&ill->ill_frag_count, count);
12545 		}
12546 		if (ret == IP_REASS_PARTIAL) {
12547 			goto reass_done;
12548 		} else if (ret == IP_REASS_FAILED) {
12549 			/* Reassembly failed. Free up all resources */
12550 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12551 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12552 				IP_REASS_SET_START(t_mp, 0);
12553 				IP_REASS_SET_END(t_mp, 0);
12554 			}
12555 			freemsg(mp);
12556 			goto reass_done;
12557 		}
12558 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12559 	}
12560 	/*
12561 	 * We have completed reassembly.  Unhook the frag header from
12562 	 * the reassembly list.
12563 	 *
12564 	 * Before we free the frag header, record the ECN info
12565 	 * to report back to the transport.
12566 	 */
12567 	ecn_info = ipf->ipf_ecn;
12568 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12569 	ipfp = ipf->ipf_ptphn;
12570 
12571 	/* We need to supply these to caller */
12572 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12573 		sum_val = ipf->ipf_checksum;
12574 	else
12575 		sum_val = 0;
12576 
12577 	mp1 = ipf->ipf_mp;
12578 	count = ipf->ipf_count;
12579 	ipf = ipf->ipf_hash_next;
12580 	if (ipf != NULL)
12581 		ipf->ipf_ptphn = ipfp;
12582 	ipfp[0] = ipf;
12583 	atomic_add_32(&ill->ill_frag_count, -count);
12584 	ASSERT(ipfb->ipfb_count >= count);
12585 	ipfb->ipfb_count -= count;
12586 	ipfb->ipfb_frag_pkts--;
12587 	mutex_exit(&ipfb->ipfb_lock);
12588 	/* Ditch the frag header. */
12589 	mp = mp1->b_cont;
12590 
12591 	freeb(mp1);
12592 
12593 	/* Restore original IP length in header. */
12594 	packet_size = (uint32_t)msgdsize(mp);
12595 	if (packet_size > IP_MAXPACKET) {
12596 		freemsg(mp);
12597 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12598 		return (B_FALSE);
12599 	}
12600 
12601 	if (DB_REF(mp) > 1) {
12602 		mblk_t *mp2 = copymsg(mp);
12603 
12604 		freemsg(mp);
12605 		if (mp2 == NULL) {
12606 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12607 			return (B_FALSE);
12608 		}
12609 		mp = mp2;
12610 	}
12611 	ipha = (ipha_t *)mp->b_rptr;
12612 
12613 	ipha->ipha_length = htons((uint16_t)packet_size);
12614 	/* We're now complete, zip the frag state */
12615 	ipha->ipha_fragment_offset_and_flags = 0;
12616 	/* Record the ECN info. */
12617 	ipha->ipha_type_of_service &= 0xFC;
12618 	ipha->ipha_type_of_service |= ecn_info;
12619 	*mpp = mp;
12620 
12621 	/* Reassembly is successful; return checksum information if needed */
12622 	if (cksum_val != NULL)
12623 		*cksum_val = sum_val;
12624 	if (cksum_flags != NULL)
12625 		*cksum_flags = sum_flags;
12626 
12627 	return (B_TRUE);
12628 }
12629 
12630 /*
12631  * Perform ip header check sum update local options.
12632  * return B_TRUE if all is well, else return B_FALSE and release
12633  * the mp. caller is responsible for decrementing ire ref cnt.
12634  */
12635 static boolean_t
12636 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12637     ip_stack_t *ipst)
12638 {
12639 	mblk_t		*first_mp;
12640 	boolean_t	mctl_present;
12641 	uint16_t	sum;
12642 
12643 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12644 	/*
12645 	 * Don't do the checksum if it has gone through AH/ESP
12646 	 * processing.
12647 	 */
12648 	if (!mctl_present) {
12649 		sum = ip_csum_hdr(ipha);
12650 		if (sum != 0) {
12651 			if (ill != NULL) {
12652 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12653 			} else {
12654 				BUMP_MIB(&ipst->ips_ip_mib,
12655 				    ipIfStatsInCksumErrs);
12656 			}
12657 			freemsg(first_mp);
12658 			return (B_FALSE);
12659 		}
12660 	}
12661 
12662 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12663 		if (mctl_present)
12664 			freeb(first_mp);
12665 		return (B_FALSE);
12666 	}
12667 
12668 	return (B_TRUE);
12669 }
12670 
12671 /*
12672  * All udp packet are delivered to the local host via this routine.
12673  */
12674 void
12675 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12676     ill_t *recv_ill)
12677 {
12678 	uint32_t	sum;
12679 	uint32_t	u1;
12680 	boolean_t	mctl_present;
12681 	conn_t		*connp;
12682 	mblk_t		*first_mp;
12683 	uint16_t	*up;
12684 	ill_t		*ill = (ill_t *)q->q_ptr;
12685 	uint16_t	reass_hck_flags = 0;
12686 	ip_stack_t	*ipst;
12687 
12688 	ASSERT(recv_ill != NULL);
12689 	ipst = recv_ill->ill_ipst;
12690 
12691 #define	rptr    ((uchar_t *)ipha)
12692 
12693 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12694 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12695 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12696 	ASSERT(ill != NULL);
12697 
12698 	/*
12699 	 * FAST PATH for udp packets
12700 	 */
12701 
12702 	/* u1 is # words of IP options */
12703 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12704 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12705 
12706 	/* IP options present */
12707 	if (u1 != 0)
12708 		goto ipoptions;
12709 
12710 	/* Check the IP header checksum.  */
12711 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12712 		/* Clear the IP header h/w cksum flag */
12713 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12714 	} else if (!mctl_present) {
12715 		/*
12716 		 * Don't verify header checksum if this packet is coming
12717 		 * back from AH/ESP as we already did it.
12718 		 */
12719 #define	uph	((uint16_t *)ipha)
12720 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12721 		    uph[6] + uph[7] + uph[8] + uph[9];
12722 #undef	uph
12723 		/* finish doing IP checksum */
12724 		sum = (sum & 0xFFFF) + (sum >> 16);
12725 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12726 		if (sum != 0 && sum != 0xFFFF) {
12727 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12728 			freemsg(first_mp);
12729 			return;
12730 		}
12731 	}
12732 
12733 	/*
12734 	 * Count for SNMP of inbound packets for ire.
12735 	 * if mctl is present this might be a secure packet and
12736 	 * has already been counted for in ip_proto_input().
12737 	 */
12738 	if (!mctl_present) {
12739 		UPDATE_IB_PKT_COUNT(ire);
12740 		ire->ire_last_used_time = lbolt;
12741 	}
12742 
12743 	/* packet part of fragmented IP packet? */
12744 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12745 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12746 		goto fragmented;
12747 	}
12748 
12749 	/* u1 = IP header length (20 bytes) */
12750 	u1 = IP_SIMPLE_HDR_LENGTH;
12751 
12752 	/* packet does not contain complete IP & UDP headers */
12753 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12754 		goto udppullup;
12755 
12756 	/* up points to UDP header */
12757 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12758 #define	iphs    ((uint16_t *)ipha)
12759 
12760 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12761 	if (up[3] != 0) {
12762 		mblk_t *mp1 = mp->b_cont;
12763 		boolean_t cksum_err;
12764 		uint16_t hck_flags = 0;
12765 
12766 		/* Pseudo-header checksum */
12767 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12768 		    iphs[9] + up[2];
12769 
12770 		/*
12771 		 * Revert to software checksum calculation if the interface
12772 		 * isn't capable of checksum offload or if IPsec is present.
12773 		 */
12774 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12775 			hck_flags = DB_CKSUMFLAGS(mp);
12776 
12777 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12778 			IP_STAT(ipst, ip_in_sw_cksum);
12779 
12780 		IP_CKSUM_RECV(hck_flags, u1,
12781 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12782 		    (int32_t)((uchar_t *)up - rptr),
12783 		    mp, mp1, cksum_err);
12784 
12785 		if (cksum_err) {
12786 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12787 			if (hck_flags & HCK_FULLCKSUM)
12788 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12789 			else if (hck_flags & HCK_PARTIALCKSUM)
12790 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12791 			else
12792 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12793 
12794 			freemsg(first_mp);
12795 			return;
12796 		}
12797 	}
12798 
12799 	/* Non-fragmented broadcast or multicast packet? */
12800 	if (ire->ire_type == IRE_BROADCAST)
12801 		goto udpslowpath;
12802 
12803 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12804 	    ire->ire_zoneid, ipst)) != NULL) {
12805 		ASSERT(connp->conn_upq != NULL);
12806 		IP_STAT(ipst, ip_udp_fast_path);
12807 
12808 		if (CONN_UDP_FLOWCTLD(connp)) {
12809 			freemsg(mp);
12810 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12811 		} else {
12812 			if (!mctl_present) {
12813 				BUMP_MIB(ill->ill_ip_mib,
12814 				    ipIfStatsHCInDelivers);
12815 			}
12816 			/*
12817 			 * mp and first_mp can change.
12818 			 */
12819 			if (ip_udp_check(q, connp, recv_ill,
12820 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12821 				/* Send it upstream */
12822 				(connp->conn_recv)(connp, mp, NULL);
12823 			}
12824 		}
12825 		/*
12826 		 * freeb() cannot deal with null mblk being passed
12827 		 * in and first_mp can be set to null in the call
12828 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12829 		 */
12830 		if (mctl_present && first_mp != NULL) {
12831 			freeb(first_mp);
12832 		}
12833 		CONN_DEC_REF(connp);
12834 		return;
12835 	}
12836 
12837 	/*
12838 	 * if we got here we know the packet is not fragmented and
12839 	 * has no options. The classifier could not find a conn_t and
12840 	 * most likely its an icmp packet so send it through slow path.
12841 	 */
12842 
12843 	goto udpslowpath;
12844 
12845 ipoptions:
12846 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12847 		goto slow_done;
12848 	}
12849 
12850 	UPDATE_IB_PKT_COUNT(ire);
12851 	ire->ire_last_used_time = lbolt;
12852 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12853 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12854 fragmented:
12855 		/*
12856 		 * "sum" and "reass_hck_flags" are non-zero if the
12857 		 * reassembled packet has a valid hardware computed
12858 		 * checksum information associated with it.
12859 		 */
12860 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12861 			goto slow_done;
12862 		/*
12863 		 * Make sure that first_mp points back to mp as
12864 		 * the mp we came in with could have changed in
12865 		 * ip_rput_fragment().
12866 		 */
12867 		ASSERT(!mctl_present);
12868 		ipha = (ipha_t *)mp->b_rptr;
12869 		first_mp = mp;
12870 	}
12871 
12872 	/* Now we have a complete datagram, destined for this machine. */
12873 	u1 = IPH_HDR_LENGTH(ipha);
12874 	/* Pull up the UDP header, if necessary. */
12875 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12876 udppullup:
12877 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12878 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12879 			freemsg(first_mp);
12880 			goto slow_done;
12881 		}
12882 		ipha = (ipha_t *)mp->b_rptr;
12883 	}
12884 
12885 	/*
12886 	 * Validate the checksum for the reassembled packet; for the
12887 	 * pullup case we calculate the payload checksum in software.
12888 	 */
12889 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12890 	if (up[3] != 0) {
12891 		boolean_t cksum_err;
12892 
12893 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12894 			IP_STAT(ipst, ip_in_sw_cksum);
12895 
12896 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12897 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12898 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12899 		    iphs[9] + up[2], sum, cksum_err);
12900 
12901 		if (cksum_err) {
12902 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12903 
12904 			if (reass_hck_flags & HCK_FULLCKSUM)
12905 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12906 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12907 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12908 			else
12909 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12910 
12911 			freemsg(first_mp);
12912 			goto slow_done;
12913 		}
12914 	}
12915 udpslowpath:
12916 
12917 	/* Clear hardware checksum flag to be safe */
12918 	DB_CKSUMFLAGS(mp) = 0;
12919 
12920 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12921 	    (ire->ire_type == IRE_BROADCAST),
12922 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12923 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12924 
12925 slow_done:
12926 	IP_STAT(ipst, ip_udp_slow_path);
12927 	return;
12928 
12929 #undef  iphs
12930 #undef  rptr
12931 }
12932 
12933 /* ARGSUSED */
12934 static mblk_t *
12935 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12936     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12937     ill_rx_ring_t *ill_ring)
12938 {
12939 	conn_t		*connp;
12940 	uint32_t	sum;
12941 	uint32_t	u1;
12942 	uint16_t	*up;
12943 	int		offset;
12944 	ssize_t		len;
12945 	mblk_t		*mp1;
12946 	boolean_t	syn_present = B_FALSE;
12947 	tcph_t		*tcph;
12948 	uint_t		ip_hdr_len;
12949 	ill_t		*ill = (ill_t *)q->q_ptr;
12950 	zoneid_t	zoneid = ire->ire_zoneid;
12951 	boolean_t	cksum_err;
12952 	uint16_t	hck_flags = 0;
12953 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12954 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12955 
12956 #define	rptr	((uchar_t *)ipha)
12957 
12958 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12959 	ASSERT(ill != NULL);
12960 
12961 	/*
12962 	 * FAST PATH for tcp packets
12963 	 */
12964 
12965 	/* u1 is # words of IP options */
12966 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12967 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12968 
12969 	/* IP options present */
12970 	if (u1) {
12971 		goto ipoptions;
12972 	} else if (!mctl_present) {
12973 		/* Check the IP header checksum.  */
12974 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12975 			/* Clear the IP header h/w cksum flag */
12976 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12977 		} else if (!mctl_present) {
12978 			/*
12979 			 * Don't verify header checksum if this packet
12980 			 * is coming back from AH/ESP as we already did it.
12981 			 */
12982 #define	uph	((uint16_t *)ipha)
12983 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12984 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12985 #undef	uph
12986 			/* finish doing IP checksum */
12987 			sum = (sum & 0xFFFF) + (sum >> 16);
12988 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12989 			if (sum != 0 && sum != 0xFFFF) {
12990 				BUMP_MIB(ill->ill_ip_mib,
12991 				    ipIfStatsInCksumErrs);
12992 				goto error;
12993 			}
12994 		}
12995 	}
12996 
12997 	if (!mctl_present) {
12998 		UPDATE_IB_PKT_COUNT(ire);
12999 		ire->ire_last_used_time = lbolt;
13000 	}
13001 
13002 	/* packet part of fragmented IP packet? */
13003 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13004 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13005 		goto fragmented;
13006 	}
13007 
13008 	/* u1 = IP header length (20 bytes) */
13009 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13010 
13011 	/* does packet contain IP+TCP headers? */
13012 	len = mp->b_wptr - rptr;
13013 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13014 		IP_STAT(ipst, ip_tcppullup);
13015 		goto tcppullup;
13016 	}
13017 
13018 	/* TCP options present? */
13019 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13020 
13021 	/*
13022 	 * If options need to be pulled up, then goto tcpoptions.
13023 	 * otherwise we are still in the fast path
13024 	 */
13025 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13026 		IP_STAT(ipst, ip_tcpoptions);
13027 		goto tcpoptions;
13028 	}
13029 
13030 	/* multiple mblks of tcp data? */
13031 	if ((mp1 = mp->b_cont) != NULL) {
13032 		/* more then two? */
13033 		if (mp1->b_cont != NULL) {
13034 			IP_STAT(ipst, ip_multipkttcp);
13035 			goto multipkttcp;
13036 		}
13037 		len += mp1->b_wptr - mp1->b_rptr;
13038 	}
13039 
13040 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13041 
13042 	/* part of pseudo checksum */
13043 
13044 	/* TCP datagram length */
13045 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13046 
13047 #define	iphs    ((uint16_t *)ipha)
13048 
13049 #ifdef	_BIG_ENDIAN
13050 	u1 += IPPROTO_TCP;
13051 #else
13052 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13053 #endif
13054 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13055 
13056 	/*
13057 	 * Revert to software checksum calculation if the interface
13058 	 * isn't capable of checksum offload or if IPsec is present.
13059 	 */
13060 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13061 		hck_flags = DB_CKSUMFLAGS(mp);
13062 
13063 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13064 		IP_STAT(ipst, ip_in_sw_cksum);
13065 
13066 	IP_CKSUM_RECV(hck_flags, u1,
13067 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13068 	    (int32_t)((uchar_t *)up - rptr),
13069 	    mp, mp1, cksum_err);
13070 
13071 	if (cksum_err) {
13072 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13073 
13074 		if (hck_flags & HCK_FULLCKSUM)
13075 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13076 		else if (hck_flags & HCK_PARTIALCKSUM)
13077 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13078 		else
13079 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13080 
13081 		goto error;
13082 	}
13083 
13084 try_again:
13085 
13086 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13087 	    zoneid, ipst)) == NULL) {
13088 		/* Send the TH_RST */
13089 		goto no_conn;
13090 	}
13091 
13092 	/*
13093 	 * TCP FAST PATH for AF_INET socket.
13094 	 *
13095 	 * TCP fast path to avoid extra work. An AF_INET socket type
13096 	 * does not have facility to receive extra information via
13097 	 * ip_process or ip_add_info. Also, when the connection was
13098 	 * established, we made a check if this connection is impacted
13099 	 * by any global IPsec policy or per connection policy (a
13100 	 * policy that comes in effect later will not apply to this
13101 	 * connection). Since all this can be determined at the
13102 	 * connection establishment time, a quick check of flags
13103 	 * can avoid extra work.
13104 	 */
13105 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13106 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13107 		ASSERT(first_mp == mp);
13108 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13109 		SET_SQUEUE(mp, tcp_rput_data, connp);
13110 		return (mp);
13111 	}
13112 
13113 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13114 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13115 		if (IPCL_IS_TCP(connp)) {
13116 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13117 			DB_CKSUMSTART(mp) =
13118 			    (intptr_t)ip_squeue_get(ill_ring);
13119 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13120 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13121 				BUMP_MIB(ill->ill_ip_mib,
13122 				    ipIfStatsHCInDelivers);
13123 				SET_SQUEUE(mp, connp->conn_recv, connp);
13124 				return (mp);
13125 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13126 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13127 				BUMP_MIB(ill->ill_ip_mib,
13128 				    ipIfStatsHCInDelivers);
13129 				ip_squeue_enter_unbound++;
13130 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13131 				    connp);
13132 				return (mp);
13133 			}
13134 			syn_present = B_TRUE;
13135 		}
13136 
13137 	}
13138 
13139 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13140 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13141 
13142 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13143 		/* No need to send this packet to TCP */
13144 		if ((flags & TH_RST) || (flags & TH_URG)) {
13145 			CONN_DEC_REF(connp);
13146 			freemsg(first_mp);
13147 			return (NULL);
13148 		}
13149 		if (flags & TH_ACK) {
13150 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13151 			    ipst->ips_netstack->netstack_tcp, connp);
13152 			CONN_DEC_REF(connp);
13153 			return (NULL);
13154 		}
13155 
13156 		CONN_DEC_REF(connp);
13157 		freemsg(first_mp);
13158 		return (NULL);
13159 	}
13160 
13161 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13162 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13163 		    ipha, NULL, mctl_present);
13164 		if (first_mp == NULL) {
13165 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13166 			CONN_DEC_REF(connp);
13167 			return (NULL);
13168 		}
13169 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13170 			ASSERT(syn_present);
13171 			if (mctl_present) {
13172 				ASSERT(first_mp != mp);
13173 				first_mp->b_datap->db_struioflag |=
13174 				    STRUIO_POLICY;
13175 			} else {
13176 				ASSERT(first_mp == mp);
13177 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13178 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13179 			}
13180 		} else {
13181 			/*
13182 			 * Discard first_mp early since we're dealing with a
13183 			 * fully-connected conn_t and tcp doesn't do policy in
13184 			 * this case.
13185 			 */
13186 			if (mctl_present) {
13187 				freeb(first_mp);
13188 				mctl_present = B_FALSE;
13189 			}
13190 			first_mp = mp;
13191 		}
13192 	}
13193 
13194 	/* Initiate IPPF processing for fastpath */
13195 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13196 		uint32_t	ill_index;
13197 
13198 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13199 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13200 		if (mp == NULL) {
13201 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13202 			    "deferred/dropped during IPPF processing\n"));
13203 			CONN_DEC_REF(connp);
13204 			if (mctl_present)
13205 				freeb(first_mp);
13206 			return (NULL);
13207 		} else if (mctl_present) {
13208 			/*
13209 			 * ip_process might return a new mp.
13210 			 */
13211 			ASSERT(first_mp != mp);
13212 			first_mp->b_cont = mp;
13213 		} else {
13214 			first_mp = mp;
13215 		}
13216 
13217 	}
13218 
13219 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13220 		/*
13221 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13222 		 * make sure IPF_RECVIF is passed to ip_add_info.
13223 		 */
13224 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13225 		    IPCL_ZONEID(connp), ipst);
13226 		if (mp == NULL) {
13227 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13228 			CONN_DEC_REF(connp);
13229 			if (mctl_present)
13230 				freeb(first_mp);
13231 			return (NULL);
13232 		} else if (mctl_present) {
13233 			/*
13234 			 * ip_add_info might return a new mp.
13235 			 */
13236 			ASSERT(first_mp != mp);
13237 			first_mp->b_cont = mp;
13238 		} else {
13239 			first_mp = mp;
13240 		}
13241 	}
13242 
13243 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13244 	if (IPCL_IS_TCP(connp)) {
13245 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13246 		return (first_mp);
13247 	} else {
13248 		/* SOCK_RAW, IPPROTO_TCP case */
13249 		(connp->conn_recv)(connp, first_mp, NULL);
13250 		CONN_DEC_REF(connp);
13251 		return (NULL);
13252 	}
13253 
13254 no_conn:
13255 	/* Initiate IPPf processing, if needed. */
13256 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13257 		uint32_t ill_index;
13258 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13259 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13260 		if (first_mp == NULL) {
13261 			return (NULL);
13262 		}
13263 	}
13264 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13265 
13266 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13267 	    ipst->ips_netstack->netstack_tcp, NULL);
13268 	return (NULL);
13269 ipoptions:
13270 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13271 		goto slow_done;
13272 	}
13273 
13274 	UPDATE_IB_PKT_COUNT(ire);
13275 	ire->ire_last_used_time = lbolt;
13276 
13277 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13278 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13279 fragmented:
13280 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13281 			if (mctl_present)
13282 				freeb(first_mp);
13283 			goto slow_done;
13284 		}
13285 		/*
13286 		 * Make sure that first_mp points back to mp as
13287 		 * the mp we came in with could have changed in
13288 		 * ip_rput_fragment().
13289 		 */
13290 		ASSERT(!mctl_present);
13291 		ipha = (ipha_t *)mp->b_rptr;
13292 		first_mp = mp;
13293 	}
13294 
13295 	/* Now we have a complete datagram, destined for this machine. */
13296 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13297 
13298 	len = mp->b_wptr - mp->b_rptr;
13299 	/* Pull up a minimal TCP header, if necessary. */
13300 	if (len < (u1 + 20)) {
13301 tcppullup:
13302 		if (!pullupmsg(mp, u1 + 20)) {
13303 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13304 			goto error;
13305 		}
13306 		ipha = (ipha_t *)mp->b_rptr;
13307 		len = mp->b_wptr - mp->b_rptr;
13308 	}
13309 
13310 	/*
13311 	 * Extract the offset field from the TCP header.  As usual, we
13312 	 * try to help the compiler more than the reader.
13313 	 */
13314 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13315 	if (offset != 5) {
13316 tcpoptions:
13317 		if (offset < 5) {
13318 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13319 			goto error;
13320 		}
13321 		/*
13322 		 * There must be TCP options.
13323 		 * Make sure we can grab them.
13324 		 */
13325 		offset <<= 2;
13326 		offset += u1;
13327 		if (len < offset) {
13328 			if (!pullupmsg(mp, offset)) {
13329 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13330 				goto error;
13331 			}
13332 			ipha = (ipha_t *)mp->b_rptr;
13333 			len = mp->b_wptr - rptr;
13334 		}
13335 	}
13336 
13337 	/* Get the total packet length in len, including headers. */
13338 	if (mp->b_cont) {
13339 multipkttcp:
13340 		len = msgdsize(mp);
13341 	}
13342 
13343 	/*
13344 	 * Check the TCP checksum by pulling together the pseudo-
13345 	 * header checksum, and passing it to ip_csum to be added in
13346 	 * with the TCP datagram.
13347 	 *
13348 	 * Since we are not using the hwcksum if available we must
13349 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13350 	 * If either of these fails along the way the mblk is freed.
13351 	 * If this logic ever changes and mblk is reused to say send
13352 	 * ICMP's back, then this flag may need to be cleared in
13353 	 * other places as well.
13354 	 */
13355 	DB_CKSUMFLAGS(mp) = 0;
13356 
13357 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13358 
13359 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13360 #ifdef	_BIG_ENDIAN
13361 	u1 += IPPROTO_TCP;
13362 #else
13363 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13364 #endif
13365 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13366 	/*
13367 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13368 	 */
13369 	IP_STAT(ipst, ip_in_sw_cksum);
13370 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13371 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13372 		goto error;
13373 	}
13374 
13375 	IP_STAT(ipst, ip_tcp_slow_path);
13376 	goto try_again;
13377 #undef  iphs
13378 #undef  rptr
13379 
13380 error:
13381 	freemsg(first_mp);
13382 slow_done:
13383 	return (NULL);
13384 }
13385 
13386 /* ARGSUSED */
13387 static void
13388 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13389     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13390 {
13391 	conn_t		*connp;
13392 	uint32_t	sum;
13393 	uint32_t	u1;
13394 	ssize_t		len;
13395 	sctp_hdr_t	*sctph;
13396 	zoneid_t	zoneid = ire->ire_zoneid;
13397 	uint32_t	pktsum;
13398 	uint32_t	calcsum;
13399 	uint32_t	ports;
13400 	in6_addr_t	map_src, map_dst;
13401 	ill_t		*ill = (ill_t *)q->q_ptr;
13402 	ip_stack_t	*ipst;
13403 	sctp_stack_t	*sctps;
13404 	boolean_t	sctp_csum_err = B_FALSE;
13405 
13406 	ASSERT(recv_ill != NULL);
13407 	ipst = recv_ill->ill_ipst;
13408 	sctps = ipst->ips_netstack->netstack_sctp;
13409 
13410 #define	rptr	((uchar_t *)ipha)
13411 
13412 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13413 	ASSERT(ill != NULL);
13414 
13415 	/* u1 is # words of IP options */
13416 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13417 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13418 
13419 	/* IP options present */
13420 	if (u1 > 0) {
13421 		goto ipoptions;
13422 	} else {
13423 		/* Check the IP header checksum.  */
13424 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13425 		    !mctl_present) {
13426 #define	uph	((uint16_t *)ipha)
13427 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13428 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13429 #undef	uph
13430 			/* finish doing IP checksum */
13431 			sum = (sum & 0xFFFF) + (sum >> 16);
13432 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13433 			/*
13434 			 * Don't verify header checksum if this packet
13435 			 * is coming back from AH/ESP as we already did it.
13436 			 */
13437 			if (sum != 0 && sum != 0xFFFF) {
13438 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13439 				goto error;
13440 			}
13441 		}
13442 		/*
13443 		 * Since there is no SCTP h/w cksum support yet, just
13444 		 * clear the flag.
13445 		 */
13446 		DB_CKSUMFLAGS(mp) = 0;
13447 	}
13448 
13449 	/*
13450 	 * Don't verify header checksum if this packet is coming
13451 	 * back from AH/ESP as we already did it.
13452 	 */
13453 	if (!mctl_present) {
13454 		UPDATE_IB_PKT_COUNT(ire);
13455 		ire->ire_last_used_time = lbolt;
13456 	}
13457 
13458 	/* packet part of fragmented IP packet? */
13459 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13460 	if (u1 & (IPH_MF | IPH_OFFSET))
13461 		goto fragmented;
13462 
13463 	/* u1 = IP header length (20 bytes) */
13464 	u1 = IP_SIMPLE_HDR_LENGTH;
13465 
13466 find_sctp_client:
13467 	/* Pullup if we don't have the sctp common header. */
13468 	len = MBLKL(mp);
13469 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13470 		if (mp->b_cont == NULL ||
13471 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13472 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13473 			goto error;
13474 		}
13475 		ipha = (ipha_t *)mp->b_rptr;
13476 		len = MBLKL(mp);
13477 	}
13478 
13479 	sctph = (sctp_hdr_t *)(rptr + u1);
13480 #ifdef	DEBUG
13481 	if (!skip_sctp_cksum) {
13482 #endif
13483 		pktsum = sctph->sh_chksum;
13484 		sctph->sh_chksum = 0;
13485 		calcsum = sctp_cksum(mp, u1);
13486 		sctph->sh_chksum = pktsum;
13487 		if (calcsum != pktsum)
13488 			sctp_csum_err = B_TRUE;
13489 #ifdef	DEBUG	/* skip_sctp_cksum */
13490 	}
13491 #endif
13492 	/* get the ports */
13493 	ports = *(uint32_t *)&sctph->sh_sport;
13494 
13495 	IRE_REFRELE(ire);
13496 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13497 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13498 	if (sctp_csum_err) {
13499 		/*
13500 		 * No potential sctp checksum errors go to the Sun
13501 		 * sctp stack however they might be Adler-32 summed
13502 		 * packets a userland stack bound to a raw IP socket
13503 		 * could reasonably use. Note though that Adler-32 is
13504 		 * a long deprecated algorithm and customer sctp
13505 		 * networks should eventually migrate to CRC-32 at
13506 		 * which time this facility should be removed.
13507 		 */
13508 		flags |= IP_FF_SCTP_CSUM_ERR;
13509 		goto no_conn;
13510 	}
13511 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13512 	    sctps)) == NULL) {
13513 		/* Check for raw socket or OOTB handling */
13514 		goto no_conn;
13515 	}
13516 
13517 	/* Found a client; up it goes */
13518 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13519 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13520 	return;
13521 
13522 no_conn:
13523 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13524 	    ports, mctl_present, flags, B_TRUE, zoneid);
13525 	return;
13526 
13527 ipoptions:
13528 	DB_CKSUMFLAGS(mp) = 0;
13529 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13530 		goto slow_done;
13531 
13532 	UPDATE_IB_PKT_COUNT(ire);
13533 	ire->ire_last_used_time = lbolt;
13534 
13535 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13536 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13537 fragmented:
13538 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13539 			goto slow_done;
13540 		/*
13541 		 * Make sure that first_mp points back to mp as
13542 		 * the mp we came in with could have changed in
13543 		 * ip_rput_fragment().
13544 		 */
13545 		ASSERT(!mctl_present);
13546 		ipha = (ipha_t *)mp->b_rptr;
13547 		first_mp = mp;
13548 	}
13549 
13550 	/* Now we have a complete datagram, destined for this machine. */
13551 	u1 = IPH_HDR_LENGTH(ipha);
13552 	goto find_sctp_client;
13553 #undef  iphs
13554 #undef  rptr
13555 
13556 error:
13557 	freemsg(first_mp);
13558 slow_done:
13559 	IRE_REFRELE(ire);
13560 }
13561 
13562 #define	VER_BITS	0xF0
13563 #define	VERSION_6	0x60
13564 
13565 static boolean_t
13566 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13567     ipaddr_t *dstp, ip_stack_t *ipst)
13568 {
13569 	uint_t	opt_len;
13570 	ipha_t *ipha;
13571 	ssize_t len;
13572 	uint_t	pkt_len;
13573 
13574 	ASSERT(ill != NULL);
13575 	IP_STAT(ipst, ip_ipoptions);
13576 	ipha = *iphapp;
13577 
13578 #define	rptr    ((uchar_t *)ipha)
13579 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13580 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13581 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13582 		freemsg(mp);
13583 		return (B_FALSE);
13584 	}
13585 
13586 	/* multiple mblk or too short */
13587 	pkt_len = ntohs(ipha->ipha_length);
13588 
13589 	/* Get the number of words of IP options in the IP header. */
13590 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13591 	if (opt_len) {
13592 		/* IP Options present!  Validate and process. */
13593 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13594 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13595 			goto done;
13596 		}
13597 		/*
13598 		 * Recompute complete header length and make sure we
13599 		 * have access to all of it.
13600 		 */
13601 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13602 		if (len > (mp->b_wptr - rptr)) {
13603 			if (len > pkt_len) {
13604 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13605 				goto done;
13606 			}
13607 			if (!pullupmsg(mp, len)) {
13608 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13609 				goto done;
13610 			}
13611 			ipha = (ipha_t *)mp->b_rptr;
13612 		}
13613 		/*
13614 		 * Go off to ip_rput_options which returns the next hop
13615 		 * destination address, which may have been affected
13616 		 * by source routing.
13617 		 */
13618 		IP_STAT(ipst, ip_opt);
13619 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13620 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13621 			return (B_FALSE);
13622 		}
13623 	}
13624 	*iphapp = ipha;
13625 	return (B_TRUE);
13626 done:
13627 	/* clear b_prev - used by ip_mroute_decap */
13628 	mp->b_prev = NULL;
13629 	freemsg(mp);
13630 	return (B_FALSE);
13631 #undef  rptr
13632 }
13633 
13634 /*
13635  * Deal with the fact that there is no ire for the destination.
13636  */
13637 static ire_t *
13638 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13639 {
13640 	ipha_t	*ipha;
13641 	ill_t	*ill;
13642 	ire_t	*ire;
13643 	ip_stack_t *ipst;
13644 	enum	ire_forward_action ret_action;
13645 
13646 	ipha = (ipha_t *)mp->b_rptr;
13647 	ill = (ill_t *)q->q_ptr;
13648 
13649 	ASSERT(ill != NULL);
13650 	ipst = ill->ill_ipst;
13651 
13652 	/*
13653 	 * No IRE for this destination, so it can't be for us.
13654 	 * Unless we are forwarding, drop the packet.
13655 	 * We have to let source routed packets through
13656 	 * since we don't yet know if they are 'ping -l'
13657 	 * packets i.e. if they will go out over the
13658 	 * same interface as they came in on.
13659 	 */
13660 	if (ll_multicast) {
13661 		freemsg(mp);
13662 		return (NULL);
13663 	}
13664 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13665 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13666 		freemsg(mp);
13667 		return (NULL);
13668 	}
13669 
13670 	/*
13671 	 * Mark this packet as having originated externally.
13672 	 *
13673 	 * For non-forwarding code path, ire_send later double
13674 	 * checks this interface to see if it is still exists
13675 	 * post-ARP resolution.
13676 	 *
13677 	 * Also, IPQOS uses this to differentiate between
13678 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13679 	 * QOS packet processing in ip_wput_attach_llhdr().
13680 	 * The QoS module can mark the b_band for a fastpath message
13681 	 * or the dl_priority field in a unitdata_req header for
13682 	 * CoS marking. This info can only be found in
13683 	 * ip_wput_attach_llhdr().
13684 	 */
13685 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13686 	/*
13687 	 * Clear the indication that this may have a hardware checksum
13688 	 * as we are not using it
13689 	 */
13690 	DB_CKSUMFLAGS(mp) = 0;
13691 
13692 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13693 	    MBLK_GETLABEL(mp), ipst);
13694 
13695 	if (ire == NULL && ret_action == Forward_check_multirt) {
13696 		/* Let ip_newroute handle CGTP  */
13697 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13698 		return (NULL);
13699 	}
13700 
13701 	if (ire != NULL)
13702 		return (ire);
13703 
13704 	mp->b_prev = mp->b_next = 0;
13705 
13706 	if (ret_action == Forward_blackhole) {
13707 		freemsg(mp);
13708 		return (NULL);
13709 	}
13710 	/* send icmp unreachable */
13711 	q = WR(q);
13712 	/* Sent by forwarding path, and router is global zone */
13713 	if (ip_source_routed(ipha, ipst)) {
13714 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13715 		    GLOBAL_ZONEID, ipst);
13716 	} else {
13717 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13718 		    ipst);
13719 	}
13720 
13721 	return (NULL);
13722 
13723 }
13724 
13725 /*
13726  * check ip header length and align it.
13727  */
13728 static boolean_t
13729 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13730 {
13731 	ssize_t len;
13732 	ill_t *ill;
13733 	ipha_t	*ipha;
13734 
13735 	len = MBLKL(mp);
13736 
13737 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13738 		ill = (ill_t *)q->q_ptr;
13739 
13740 		if (!OK_32PTR(mp->b_rptr))
13741 			IP_STAT(ipst, ip_notaligned1);
13742 		else
13743 			IP_STAT(ipst, ip_notaligned2);
13744 		/* Guard against bogus device drivers */
13745 		if (len < 0) {
13746 			/* clear b_prev - used by ip_mroute_decap */
13747 			mp->b_prev = NULL;
13748 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13749 			freemsg(mp);
13750 			return (B_FALSE);
13751 		}
13752 
13753 		if (ip_rput_pullups++ == 0) {
13754 			ipha = (ipha_t *)mp->b_rptr;
13755 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13756 			    "ip_check_and_align_header: %s forced us to "
13757 			    " pullup pkt, hdr len %ld, hdr addr %p",
13758 			    ill->ill_name, len, ipha);
13759 		}
13760 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13761 			/* clear b_prev - used by ip_mroute_decap */
13762 			mp->b_prev = NULL;
13763 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13764 			freemsg(mp);
13765 			return (B_FALSE);
13766 		}
13767 	}
13768 	return (B_TRUE);
13769 }
13770 
13771 ire_t *
13772 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13773 {
13774 	ire_t		*new_ire;
13775 	ill_t		*ire_ill;
13776 	uint_t		ifindex;
13777 	ip_stack_t	*ipst = ill->ill_ipst;
13778 	boolean_t	strict_check = B_FALSE;
13779 
13780 	/*
13781 	 * This packet came in on an interface other than the one associated
13782 	 * with the first ire we found for the destination address. We do
13783 	 * another ire lookup here, using the ingress ill, to see if the
13784 	 * interface is in an interface group.
13785 	 * As long as the ills belong to the same group, we don't consider
13786 	 * them to be arriving on the wrong interface. Thus, if the switch
13787 	 * is doing inbound load spreading, we won't drop packets when the
13788 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13789 	 * for 'usesrc groups' where the destination address may belong to
13790 	 * another interface to allow multipathing to happen.
13791 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13792 	 * where the local address may not be unique. In this case we were
13793 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13794 	 * actually returned. The new lookup, which is more specific, should
13795 	 * only find the IRE_LOCAL associated with the ingress ill if one
13796 	 * exists.
13797 	 */
13798 
13799 	if (ire->ire_ipversion == IPV4_VERSION) {
13800 		if (ipst->ips_ip_strict_dst_multihoming)
13801 			strict_check = B_TRUE;
13802 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13803 		    ill->ill_ipif, ALL_ZONES, NULL,
13804 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13805 	} else {
13806 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13807 		if (ipst->ips_ipv6_strict_dst_multihoming)
13808 			strict_check = B_TRUE;
13809 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13810 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13811 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13812 	}
13813 	/*
13814 	 * If the same ire that was returned in ip_input() is found then this
13815 	 * is an indication that interface groups are in use. The packet
13816 	 * arrived on a different ill in the group than the one associated with
13817 	 * the destination address.  If a different ire was found then the same
13818 	 * IP address must be hosted on multiple ills. This is possible with
13819 	 * unnumbered point2point interfaces. We switch to use this new ire in
13820 	 * order to have accurate interface statistics.
13821 	 */
13822 	if (new_ire != NULL) {
13823 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13824 			ire_refrele(ire);
13825 			ire = new_ire;
13826 		} else {
13827 			ire_refrele(new_ire);
13828 		}
13829 		return (ire);
13830 	} else if ((ire->ire_rfq == NULL) &&
13831 	    (ire->ire_ipversion == IPV4_VERSION)) {
13832 		/*
13833 		 * The best match could have been the original ire which
13834 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13835 		 * the strict multihoming checks are irrelevant as we consider
13836 		 * local addresses hosted on lo0 to be interface agnostic. We
13837 		 * only expect a null ire_rfq on IREs which are associated with
13838 		 * lo0 hence we can return now.
13839 		 */
13840 		return (ire);
13841 	}
13842 
13843 	/*
13844 	 * Chase pointers once and store locally.
13845 	 */
13846 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13847 	    (ill_t *)(ire->ire_rfq->q_ptr);
13848 	ifindex = ill->ill_usesrc_ifindex;
13849 
13850 	/*
13851 	 * Check if it's a legal address on the 'usesrc' interface.
13852 	 */
13853 	if ((ifindex != 0) && (ire_ill != NULL) &&
13854 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13855 		return (ire);
13856 	}
13857 
13858 	/*
13859 	 * If the ip*_strict_dst_multihoming switch is on then we can
13860 	 * only accept this packet if the interface is marked as routing.
13861 	 */
13862 	if (!(strict_check))
13863 		return (ire);
13864 
13865 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13866 	    ILLF_ROUTER) != 0) {
13867 		return (ire);
13868 	}
13869 
13870 	ire_refrele(ire);
13871 	return (NULL);
13872 }
13873 
13874 ire_t *
13875 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13876 {
13877 	ipha_t	*ipha;
13878 	ire_t	*src_ire;
13879 	ill_t	*stq_ill;
13880 	uint_t	hlen;
13881 	uint_t	pkt_len;
13882 	uint32_t sum;
13883 	queue_t	*dev_q;
13884 	ip_stack_t *ipst = ill->ill_ipst;
13885 	mblk_t *fpmp;
13886 	enum	ire_forward_action ret_action;
13887 
13888 	ipha = (ipha_t *)mp->b_rptr;
13889 
13890 	if (ire != NULL &&
13891 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13892 	    ire->ire_zoneid != ALL_ZONES) {
13893 		/*
13894 		 * Should only use IREs that are visible to the global
13895 		 * zone for forwarding.
13896 		 */
13897 		ire_refrele(ire);
13898 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13899 	}
13900 
13901 	/*
13902 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13903 	 * The loopback address check for both src and dst has already
13904 	 * been checked in ip_input
13905 	 */
13906 
13907 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13908 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13909 		goto drop;
13910 	}
13911 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13912 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13913 
13914 	if (src_ire != NULL) {
13915 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13916 		ire_refrele(src_ire);
13917 		goto drop;
13918 	}
13919 
13920 	/* No ire cache of nexthop. So first create one  */
13921 	if (ire == NULL) {
13922 
13923 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13924 		    NULL, ipst);
13925 		/*
13926 		 * We only come to ip_fast_forward if ip_cgtp_filter
13927 		 * is not set. So ire_forward() should not return with
13928 		 * Forward_check_multirt as the next action.
13929 		 */
13930 		ASSERT(ret_action != Forward_check_multirt);
13931 		if (ire == NULL) {
13932 			/* An attempt was made to forward the packet */
13933 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13934 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13935 			mp->b_prev = mp->b_next = 0;
13936 			/* send icmp unreachable */
13937 			/* Sent by forwarding path, and router is global zone */
13938 			if (ret_action == Forward_ret_icmp_err) {
13939 				if (ip_source_routed(ipha, ipst)) {
13940 					icmp_unreachable(ill->ill_wq, mp,
13941 					    ICMP_SOURCE_ROUTE_FAILED,
13942 					    GLOBAL_ZONEID, ipst);
13943 				} else {
13944 					icmp_unreachable(ill->ill_wq, mp,
13945 					    ICMP_HOST_UNREACHABLE,
13946 					    GLOBAL_ZONEID, ipst);
13947 				}
13948 			} else {
13949 				freemsg(mp);
13950 			}
13951 			return (NULL);
13952 		}
13953 	}
13954 
13955 	/*
13956 	 * Forwarding fastpath exception case:
13957 	 * If either of the follwoing case is true, we take
13958 	 * the slowpath
13959 	 *	o forwarding is not enabled
13960 	 *	o incoming and outgoing interface are the same, or the same
13961 	 *	  IPMP group
13962 	 *	o corresponding ire is in incomplete state
13963 	 *	o packet needs fragmentation
13964 	 *	o ARP cache is not resolved
13965 	 *
13966 	 * The codeflow from here on is thus:
13967 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13968 	 */
13969 	pkt_len = ntohs(ipha->ipha_length);
13970 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13971 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13972 	    !(ill->ill_flags & ILLF_ROUTER) ||
13973 	    (ill == stq_ill) ||
13974 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13975 	    (ire->ire_nce == NULL) ||
13976 	    (pkt_len > ire->ire_max_frag) ||
13977 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13978 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13979 	    ipha->ipha_ttl <= 1) {
13980 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13981 		    ipha, ill, B_FALSE);
13982 		return (ire);
13983 	}
13984 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13985 
13986 	DTRACE_PROBE4(ip4__forwarding__start,
13987 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13988 
13989 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13990 	    ipst->ips_ipv4firewall_forwarding,
13991 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13992 
13993 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13994 
13995 	if (mp == NULL)
13996 		goto drop;
13997 
13998 	mp->b_datap->db_struioun.cksum.flags = 0;
13999 	/* Adjust the checksum to reflect the ttl decrement. */
14000 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14001 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14002 	ipha->ipha_ttl--;
14003 
14004 	/*
14005 	 * Write the link layer header.  We can do this safely here,
14006 	 * because we have already tested to make sure that the IP
14007 	 * policy is not set, and that we have a fast path destination
14008 	 * header.
14009 	 */
14010 	mp->b_rptr -= hlen;
14011 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14012 
14013 	UPDATE_IB_PKT_COUNT(ire);
14014 	ire->ire_last_used_time = lbolt;
14015 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14016 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14017 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14018 
14019 	dev_q = ire->ire_stq->q_next;
14020 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14021 	    !canputnext(ire->ire_stq)) {
14022 		goto indiscard;
14023 	}
14024 	if (ILL_DLS_CAPABLE(stq_ill)) {
14025 		/*
14026 		 * Send the packet directly to DLD, where it
14027 		 * may be queued depending on the availability
14028 		 * of transmit resources at the media layer.
14029 		 */
14030 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14031 	} else {
14032 		DTRACE_PROBE4(ip4__physical__out__start,
14033 		    ill_t *, NULL, ill_t *, stq_ill,
14034 		    ipha_t *, ipha, mblk_t *, mp);
14035 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14036 		    ipst->ips_ipv4firewall_physical_out,
14037 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14038 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14039 		if (mp == NULL)
14040 			goto drop;
14041 		putnext(ire->ire_stq, mp);
14042 	}
14043 	return (ire);
14044 
14045 indiscard:
14046 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14047 drop:
14048 	if (mp != NULL)
14049 		freemsg(mp);
14050 	return (ire);
14051 
14052 }
14053 
14054 /*
14055  * This function is called in the forwarding slowpath, when
14056  * either the ire lacks the link-layer address, or the packet needs
14057  * further processing(eg. fragmentation), before transmission.
14058  */
14059 
14060 static void
14061 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14062     ill_t *ill, boolean_t ll_multicast)
14063 {
14064 	ill_group_t	*ill_group;
14065 	ill_group_t	*ire_group;
14066 	queue_t		*dev_q;
14067 	ire_t		*src_ire;
14068 	ip_stack_t	*ipst = ill->ill_ipst;
14069 
14070 	ASSERT(ire->ire_stq != NULL);
14071 
14072 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14073 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14074 
14075 	if (ll_multicast != 0) {
14076 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14077 		goto drop_pkt;
14078 	}
14079 
14080 	/*
14081 	 * check if ipha_src is a broadcast address. Note that this
14082 	 * check is redundant when we get here from ip_fast_forward()
14083 	 * which has already done this check. However, since we can
14084 	 * also get here from ip_rput_process_broadcast() or, for
14085 	 * for the slow path through ip_fast_forward(), we perform
14086 	 * the check again for code-reusability
14087 	 */
14088 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14089 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14090 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14091 		if (src_ire != NULL)
14092 			ire_refrele(src_ire);
14093 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14094 		ip2dbg(("ip_rput_process_forward: Received packet with"
14095 		    " bad src/dst address on %s\n", ill->ill_name));
14096 		goto drop_pkt;
14097 	}
14098 
14099 	ill_group = ill->ill_group;
14100 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14101 	/*
14102 	 * Check if we want to forward this one at this time.
14103 	 * We allow source routed packets on a host provided that
14104 	 * they go out the same interface or same interface group
14105 	 * as they came in on.
14106 	 *
14107 	 * XXX To be quicker, we may wish to not chase pointers to
14108 	 * get the ILLF_ROUTER flag and instead store the
14109 	 * forwarding policy in the ire.  An unfortunate
14110 	 * side-effect of that would be requiring an ire flush
14111 	 * whenever the ILLF_ROUTER flag changes.
14112 	 */
14113 	if (((ill->ill_flags &
14114 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14115 	    ILLF_ROUTER) == 0) &&
14116 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14117 	    (ill_group != NULL && ill_group == ire_group)))) {
14118 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14119 		if (ip_source_routed(ipha, ipst)) {
14120 			q = WR(q);
14121 			/*
14122 			 * Clear the indication that this may have
14123 			 * hardware checksum as we are not using it.
14124 			 */
14125 			DB_CKSUMFLAGS(mp) = 0;
14126 			/* Sent by forwarding path, and router is global zone */
14127 			icmp_unreachable(q, mp,
14128 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14129 			return;
14130 		}
14131 		goto drop_pkt;
14132 	}
14133 
14134 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14135 
14136 	/* Packet is being forwarded. Turning off hwcksum flag. */
14137 	DB_CKSUMFLAGS(mp) = 0;
14138 	if (ipst->ips_ip_g_send_redirects) {
14139 		/*
14140 		 * Check whether the incoming interface and outgoing
14141 		 * interface is part of the same group. If so,
14142 		 * send redirects.
14143 		 *
14144 		 * Check the source address to see if it originated
14145 		 * on the same logical subnet it is going back out on.
14146 		 * If so, we should be able to send it a redirect.
14147 		 * Avoid sending a redirect if the destination
14148 		 * is directly connected (i.e., ipha_dst is the same
14149 		 * as ire_gateway_addr or the ire_addr of the
14150 		 * nexthop IRE_CACHE ), or if the packet was source
14151 		 * routed out this interface.
14152 		 */
14153 		ipaddr_t src, nhop;
14154 		mblk_t	*mp1;
14155 		ire_t	*nhop_ire = NULL;
14156 
14157 		/*
14158 		 * Check whether ire_rfq and q are from the same ill
14159 		 * or if they are not same, they at least belong
14160 		 * to the same group. If so, send redirects.
14161 		 */
14162 		if ((ire->ire_rfq == q ||
14163 		    (ill_group != NULL && ill_group == ire_group)) &&
14164 		    !ip_source_routed(ipha, ipst)) {
14165 
14166 			nhop = (ire->ire_gateway_addr != 0 ?
14167 			    ire->ire_gateway_addr : ire->ire_addr);
14168 
14169 			if (ipha->ipha_dst == nhop) {
14170 				/*
14171 				 * We avoid sending a redirect if the
14172 				 * destination is directly connected
14173 				 * because it is possible that multiple
14174 				 * IP subnets may have been configured on
14175 				 * the link, and the source may not
14176 				 * be on the same subnet as ip destination,
14177 				 * even though they are on the same
14178 				 * physical link.
14179 				 */
14180 				goto sendit;
14181 			}
14182 
14183 			src = ipha->ipha_src;
14184 
14185 			/*
14186 			 * We look up the interface ire for the nexthop,
14187 			 * to see if ipha_src is in the same subnet
14188 			 * as the nexthop.
14189 			 *
14190 			 * Note that, if, in the future, IRE_CACHE entries
14191 			 * are obsoleted,  this lookup will not be needed,
14192 			 * as the ire passed to this function will be the
14193 			 * same as the nhop_ire computed below.
14194 			 */
14195 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14196 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14197 			    0, NULL, MATCH_IRE_TYPE, ipst);
14198 
14199 			if (nhop_ire != NULL) {
14200 				if ((src & nhop_ire->ire_mask) ==
14201 				    (nhop & nhop_ire->ire_mask)) {
14202 					/*
14203 					 * The source is directly connected.
14204 					 * Just copy the ip header (which is
14205 					 * in the first mblk)
14206 					 */
14207 					mp1 = copyb(mp);
14208 					if (mp1 != NULL) {
14209 						icmp_send_redirect(WR(q), mp1,
14210 						    nhop, ipst);
14211 					}
14212 				}
14213 				ire_refrele(nhop_ire);
14214 			}
14215 		}
14216 	}
14217 sendit:
14218 	dev_q = ire->ire_stq->q_next;
14219 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14220 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14221 		freemsg(mp);
14222 		return;
14223 	}
14224 
14225 	ip_rput_forward(ire, ipha, mp, ill);
14226 	return;
14227 
14228 drop_pkt:
14229 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14230 	freemsg(mp);
14231 }
14232 
14233 ire_t *
14234 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14235     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14236 {
14237 	queue_t		*q;
14238 	uint16_t	hcksumflags;
14239 	ip_stack_t	*ipst = ill->ill_ipst;
14240 
14241 	q = *qp;
14242 
14243 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14244 
14245 	/*
14246 	 * Clear the indication that this may have hardware
14247 	 * checksum as we are not using it for forwarding.
14248 	 */
14249 	hcksumflags = DB_CKSUMFLAGS(mp);
14250 	DB_CKSUMFLAGS(mp) = 0;
14251 
14252 	/*
14253 	 * Directed broadcast forwarding: if the packet came in over a
14254 	 * different interface then it is routed out over we can forward it.
14255 	 */
14256 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14257 		ire_refrele(ire);
14258 		freemsg(mp);
14259 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14260 		return (NULL);
14261 	}
14262 	/*
14263 	 * For multicast we have set dst to be INADDR_BROADCAST
14264 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14265 	 * only for broadcast packets.
14266 	 */
14267 	if (!CLASSD(ipha->ipha_dst)) {
14268 		ire_t *new_ire;
14269 		ipif_t *ipif;
14270 		/*
14271 		 * For ill groups, as the switch duplicates broadcasts
14272 		 * across all the ports, we need to filter out and
14273 		 * send up only one copy. There is one copy for every
14274 		 * broadcast address on each ill. Thus, we look for a
14275 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14276 		 * later to see whether this ill is eligible to receive
14277 		 * them or not. ill_nominate_bcast_rcv() nominates only
14278 		 * one set of IREs for receiving.
14279 		 */
14280 
14281 		ipif = ipif_get_next_ipif(NULL, ill);
14282 		if (ipif == NULL) {
14283 			ire_refrele(ire);
14284 			freemsg(mp);
14285 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14286 			return (NULL);
14287 		}
14288 		new_ire = ire_ctable_lookup(dst, 0, 0,
14289 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14290 		ipif_refrele(ipif);
14291 
14292 		if (new_ire != NULL) {
14293 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14294 				ire_refrele(ire);
14295 				ire_refrele(new_ire);
14296 				freemsg(mp);
14297 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14298 				return (NULL);
14299 			}
14300 			/*
14301 			 * In the special case of multirouted broadcast
14302 			 * packets, we unconditionally need to "gateway"
14303 			 * them to the appropriate interface here.
14304 			 * In the normal case, this cannot happen, because
14305 			 * there is no broadcast IRE tagged with the
14306 			 * RTF_MULTIRT flag.
14307 			 */
14308 			if (new_ire->ire_flags & RTF_MULTIRT) {
14309 				ire_refrele(new_ire);
14310 				if (ire->ire_rfq != NULL) {
14311 					q = ire->ire_rfq;
14312 					*qp = q;
14313 				}
14314 			} else {
14315 				ire_refrele(ire);
14316 				ire = new_ire;
14317 			}
14318 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14319 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14320 				/*
14321 				 * Free the message if
14322 				 * ip_g_forward_directed_bcast is turned
14323 				 * off for non-local broadcast.
14324 				 */
14325 				ire_refrele(ire);
14326 				freemsg(mp);
14327 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14328 				return (NULL);
14329 			}
14330 		} else {
14331 			/*
14332 			 * This CGTP packet successfully passed the
14333 			 * CGTP filter, but the related CGTP
14334 			 * broadcast IRE has not been found,
14335 			 * meaning that the redundant ipif is
14336 			 * probably down. However, if we discarded
14337 			 * this packet, its duplicate would be
14338 			 * filtered out by the CGTP filter so none
14339 			 * of them would get through. So we keep
14340 			 * going with this one.
14341 			 */
14342 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14343 			if (ire->ire_rfq != NULL) {
14344 				q = ire->ire_rfq;
14345 				*qp = q;
14346 			}
14347 		}
14348 	}
14349 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14350 		/*
14351 		 * Verify that there are not more then one
14352 		 * IRE_BROADCAST with this broadcast address which
14353 		 * has ire_stq set.
14354 		 * TODO: simplify, loop over all IRE's
14355 		 */
14356 		ire_t	*ire1;
14357 		int	num_stq = 0;
14358 		mblk_t	*mp1;
14359 
14360 		/* Find the first one with ire_stq set */
14361 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14362 		for (ire1 = ire; ire1 &&
14363 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14364 		    ire1 = ire1->ire_next)
14365 			;
14366 		if (ire1) {
14367 			ire_refrele(ire);
14368 			ire = ire1;
14369 			IRE_REFHOLD(ire);
14370 		}
14371 
14372 		/* Check if there are additional ones with stq set */
14373 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14374 			if (ire->ire_addr != ire1->ire_addr)
14375 				break;
14376 			if (ire1->ire_stq) {
14377 				num_stq++;
14378 				break;
14379 			}
14380 		}
14381 		rw_exit(&ire->ire_bucket->irb_lock);
14382 		if (num_stq == 1 && ire->ire_stq != NULL) {
14383 			ip1dbg(("ip_rput_process_broadcast: directed "
14384 			    "broadcast to 0x%x\n",
14385 			    ntohl(ire->ire_addr)));
14386 			mp1 = copymsg(mp);
14387 			if (mp1) {
14388 				switch (ipha->ipha_protocol) {
14389 				case IPPROTO_UDP:
14390 					ip_udp_input(q, mp1, ipha, ire, ill);
14391 					break;
14392 				default:
14393 					ip_proto_input(q, mp1, ipha, ire, ill,
14394 					    B_FALSE);
14395 					break;
14396 				}
14397 			}
14398 			/*
14399 			 * Adjust ttl to 2 (1+1 - the forward engine
14400 			 * will decrement it by one.
14401 			 */
14402 			if (ip_csum_hdr(ipha)) {
14403 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14404 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14405 				freemsg(mp);
14406 				ire_refrele(ire);
14407 				return (NULL);
14408 			}
14409 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14410 			ipha->ipha_hdr_checksum = 0;
14411 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14412 			ip_rput_process_forward(q, mp, ire, ipha,
14413 			    ill, ll_multicast);
14414 			ire_refrele(ire);
14415 			return (NULL);
14416 		}
14417 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14418 		    ntohl(ire->ire_addr)));
14419 	}
14420 
14421 
14422 	/* Restore any hardware checksum flags */
14423 	DB_CKSUMFLAGS(mp) = hcksumflags;
14424 	return (ire);
14425 }
14426 
14427 /* ARGSUSED */
14428 static boolean_t
14429 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14430     int *ll_multicast, ipaddr_t *dstp)
14431 {
14432 	ip_stack_t	*ipst = ill->ill_ipst;
14433 
14434 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14435 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14436 	    ntohs(ipha->ipha_length));
14437 
14438 	/*
14439 	 * Forward packets only if we have joined the allmulti
14440 	 * group on this interface.
14441 	 */
14442 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14443 		int retval;
14444 
14445 		/*
14446 		 * Clear the indication that this may have hardware
14447 		 * checksum as we are not using it.
14448 		 */
14449 		DB_CKSUMFLAGS(mp) = 0;
14450 		retval = ip_mforward(ill, ipha, mp);
14451 		/* ip_mforward updates mib variables if needed */
14452 		/* clear b_prev - used by ip_mroute_decap */
14453 		mp->b_prev = NULL;
14454 
14455 		switch (retval) {
14456 		case 0:
14457 			/*
14458 			 * pkt is okay and arrived on phyint.
14459 			 *
14460 			 * If we are running as a multicast router
14461 			 * we need to see all IGMP and/or PIM packets.
14462 			 */
14463 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14464 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14465 				goto done;
14466 			}
14467 			break;
14468 		case -1:
14469 			/* pkt is mal-formed, toss it */
14470 			goto drop_pkt;
14471 		case 1:
14472 			/* pkt is okay and arrived on a tunnel */
14473 			/*
14474 			 * If we are running a multicast router
14475 			 *  we need to see all igmp packets.
14476 			 */
14477 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14478 				*dstp = INADDR_BROADCAST;
14479 				*ll_multicast = 1;
14480 				return (B_FALSE);
14481 			}
14482 
14483 			goto drop_pkt;
14484 		}
14485 	}
14486 
14487 	ILM_WALKER_HOLD(ill);
14488 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14489 		/*
14490 		 * This might just be caused by the fact that
14491 		 * multiple IP Multicast addresses map to the same
14492 		 * link layer multicast - no need to increment counter!
14493 		 */
14494 		ILM_WALKER_RELE(ill);
14495 		freemsg(mp);
14496 		return (B_TRUE);
14497 	}
14498 	ILM_WALKER_RELE(ill);
14499 done:
14500 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14501 	/*
14502 	 * This assumes the we deliver to all streams for multicast
14503 	 * and broadcast packets.
14504 	 */
14505 	*dstp = INADDR_BROADCAST;
14506 	*ll_multicast = 1;
14507 	return (B_FALSE);
14508 drop_pkt:
14509 	ip2dbg(("ip_rput: drop pkt\n"));
14510 	freemsg(mp);
14511 	return (B_TRUE);
14512 }
14513 
14514 /*
14515  * This function is used to both return an indication of whether or not
14516  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14517  * and in doing so, determine whether or not it is broadcast vs multicast.
14518  * For it to be a broadcast packet, we must have the appropriate mblk_t
14519  * hanging off the ill_t.  If this is either not present or doesn't match
14520  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14521  * to be multicast.  Thus NICs that have no broadcast address (or no
14522  * capability for one, such as point to point links) cannot return as
14523  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14524  * the return values simplifies the current use of the return value of this
14525  * function, which is to pass through the multicast/broadcast characteristic
14526  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14527  * changing the return value to some other symbol demands the appropriate
14528  * "translation" when hpe_flags is set prior to calling hook_run() for
14529  * packet events.
14530  */
14531 int
14532 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14533 {
14534 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14535 	mblk_t *bmp;
14536 
14537 	if (ind->dl_group_address) {
14538 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14539 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14540 		    MBLKL(mb) &&
14541 		    (bmp = ill->ill_bcast_mp) != NULL) {
14542 			dl_unitdata_req_t *dlur;
14543 			uint8_t *bphys_addr;
14544 
14545 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14546 			if (ill->ill_sap_length < 0)
14547 				bphys_addr = (uchar_t *)dlur +
14548 				    dlur->dl_dest_addr_offset;
14549 			else
14550 				bphys_addr = (uchar_t *)dlur +
14551 				    dlur->dl_dest_addr_offset +
14552 				    ill->ill_sap_length;
14553 
14554 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14555 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14556 				return (HPE_BROADCAST);
14557 			}
14558 			return (HPE_MULTICAST);
14559 		}
14560 		return (HPE_MULTICAST);
14561 	}
14562 	return (0);
14563 }
14564 
14565 static boolean_t
14566 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14567     int *ll_multicast, mblk_t **mpp)
14568 {
14569 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14570 	boolean_t must_copy = B_FALSE;
14571 	struct iocblk   *iocp;
14572 	ipha_t		*ipha;
14573 	ip_stack_t	*ipst = ill->ill_ipst;
14574 
14575 #define	rptr    ((uchar_t *)ipha)
14576 
14577 	first_mp = *first_mpp;
14578 	mp = *mpp;
14579 
14580 	ASSERT(first_mp == mp);
14581 
14582 	/*
14583 	 * if db_ref > 1 then copymsg and free original. Packet may be
14584 	 * changed and do not want other entity who has a reference to this
14585 	 * message to trip over the changes. This is a blind change because
14586 	 * trying to catch all places that might change packet is too
14587 	 * difficult (since it may be a module above this one)
14588 	 *
14589 	 * This corresponds to the non-fast path case. We walk down the full
14590 	 * chain in this case, and check the db_ref count of all the dblks,
14591 	 * and do a copymsg if required. It is possible that the db_ref counts
14592 	 * of the data blocks in the mblk chain can be different.
14593 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14594 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14595 	 * 'snoop' is running.
14596 	 */
14597 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14598 		if (mp1->b_datap->db_ref > 1) {
14599 			must_copy = B_TRUE;
14600 			break;
14601 		}
14602 	}
14603 
14604 	if (must_copy) {
14605 		mp1 = copymsg(mp);
14606 		if (mp1 == NULL) {
14607 			for (mp1 = mp; mp1 != NULL;
14608 			    mp1 = mp1->b_cont) {
14609 				mp1->b_next = NULL;
14610 				mp1->b_prev = NULL;
14611 			}
14612 			freemsg(mp);
14613 			if (ill != NULL) {
14614 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14615 			} else {
14616 				BUMP_MIB(&ipst->ips_ip_mib,
14617 				    ipIfStatsInDiscards);
14618 			}
14619 			return (B_TRUE);
14620 		}
14621 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14622 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14623 			/* Copy b_prev - used by ip_mroute_decap */
14624 			to_mp->b_prev = from_mp->b_prev;
14625 			from_mp->b_prev = NULL;
14626 		}
14627 		*first_mpp = first_mp = mp1;
14628 		freemsg(mp);
14629 		mp = mp1;
14630 		*mpp = mp1;
14631 	}
14632 
14633 	ipha = (ipha_t *)mp->b_rptr;
14634 
14635 	/*
14636 	 * previous code has a case for M_DATA.
14637 	 * We want to check how that happens.
14638 	 */
14639 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14640 	switch (first_mp->b_datap->db_type) {
14641 	case M_PROTO:
14642 	case M_PCPROTO:
14643 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14644 		    DL_UNITDATA_IND) {
14645 			/* Go handle anything other than data elsewhere. */
14646 			ip_rput_dlpi(q, mp);
14647 			return (B_TRUE);
14648 		}
14649 
14650 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14651 		/* Ditch the DLPI header. */
14652 		mp1 = mp->b_cont;
14653 		ASSERT(first_mp == mp);
14654 		*first_mpp = mp1;
14655 		freeb(mp);
14656 		*mpp = mp1;
14657 		return (B_FALSE);
14658 	case M_IOCACK:
14659 		ip1dbg(("got iocack "));
14660 		iocp = (struct iocblk *)mp->b_rptr;
14661 		switch (iocp->ioc_cmd) {
14662 		case DL_IOC_HDR_INFO:
14663 			ill = (ill_t *)q->q_ptr;
14664 			ill_fastpath_ack(ill, mp);
14665 			return (B_TRUE);
14666 		case SIOCSTUNPARAM:
14667 		case OSIOCSTUNPARAM:
14668 			/* Go through qwriter_ip */
14669 			break;
14670 		case SIOCGTUNPARAM:
14671 		case OSIOCGTUNPARAM:
14672 			ip_rput_other(NULL, q, mp, NULL);
14673 			return (B_TRUE);
14674 		default:
14675 			putnext(q, mp);
14676 			return (B_TRUE);
14677 		}
14678 		/* FALLTHRU */
14679 	case M_ERROR:
14680 	case M_HANGUP:
14681 		/*
14682 		 * Since this is on the ill stream we unconditionally
14683 		 * bump up the refcount
14684 		 */
14685 		ill_refhold(ill);
14686 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14687 		return (B_TRUE);
14688 	case M_CTL:
14689 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14690 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14691 		    IPHADA_M_CTL)) {
14692 			/*
14693 			 * It's an IPsec accelerated packet.
14694 			 * Make sure that the ill from which we received the
14695 			 * packet has enabled IPsec hardware acceleration.
14696 			 */
14697 			if (!(ill->ill_capabilities &
14698 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14699 				/* IPsec kstats: bean counter */
14700 				freemsg(mp);
14701 				return (B_TRUE);
14702 			}
14703 
14704 			/*
14705 			 * Make mp point to the mblk following the M_CTL,
14706 			 * then process according to type of mp.
14707 			 * After this processing, first_mp will point to
14708 			 * the data-attributes and mp to the pkt following
14709 			 * the M_CTL.
14710 			 */
14711 			mp = first_mp->b_cont;
14712 			if (mp == NULL) {
14713 				freemsg(first_mp);
14714 				return (B_TRUE);
14715 			}
14716 			/*
14717 			 * A Hardware Accelerated packet can only be M_DATA
14718 			 * ESP or AH packet.
14719 			 */
14720 			if (mp->b_datap->db_type != M_DATA) {
14721 				/* non-M_DATA IPsec accelerated packet */
14722 				IPSECHW_DEBUG(IPSECHW_PKT,
14723 				    ("non-M_DATA IPsec accelerated pkt\n"));
14724 				freemsg(first_mp);
14725 				return (B_TRUE);
14726 			}
14727 			ipha = (ipha_t *)mp->b_rptr;
14728 			if (ipha->ipha_protocol != IPPROTO_AH &&
14729 			    ipha->ipha_protocol != IPPROTO_ESP) {
14730 				IPSECHW_DEBUG(IPSECHW_PKT,
14731 				    ("non-M_DATA IPsec accelerated pkt\n"));
14732 				freemsg(first_mp);
14733 				return (B_TRUE);
14734 			}
14735 			*mpp = mp;
14736 			return (B_FALSE);
14737 		}
14738 		putnext(q, mp);
14739 		return (B_TRUE);
14740 	case M_IOCNAK:
14741 		ip1dbg(("got iocnak "));
14742 		iocp = (struct iocblk *)mp->b_rptr;
14743 		switch (iocp->ioc_cmd) {
14744 		case SIOCSTUNPARAM:
14745 		case OSIOCSTUNPARAM:
14746 			/*
14747 			 * Since this is on the ill stream we unconditionally
14748 			 * bump up the refcount
14749 			 */
14750 			ill_refhold(ill);
14751 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14752 			return (B_TRUE);
14753 		case DL_IOC_HDR_INFO:
14754 		case SIOCGTUNPARAM:
14755 		case OSIOCGTUNPARAM:
14756 			ip_rput_other(NULL, q, mp, NULL);
14757 			return (B_TRUE);
14758 		default:
14759 			break;
14760 		}
14761 		/* FALLTHRU */
14762 	default:
14763 		putnext(q, mp);
14764 		return (B_TRUE);
14765 	}
14766 }
14767 
14768 /* Read side put procedure.  Packets coming from the wire arrive here. */
14769 void
14770 ip_rput(queue_t *q, mblk_t *mp)
14771 {
14772 	ill_t	*ill;
14773 	union DL_primitives *dl;
14774 
14775 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14776 
14777 	ill = (ill_t *)q->q_ptr;
14778 
14779 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14780 		/*
14781 		 * If things are opening or closing, only accept high-priority
14782 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14783 		 * created; on close, things hanging off the ill may have been
14784 		 * freed already.)
14785 		 */
14786 		dl = (union DL_primitives *)mp->b_rptr;
14787 		if (DB_TYPE(mp) != M_PCPROTO ||
14788 		    dl->dl_primitive == DL_UNITDATA_IND) {
14789 			/*
14790 			 * SIOC[GS]TUNPARAM ioctls can come here.
14791 			 */
14792 			inet_freemsg(mp);
14793 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14794 			    "ip_rput_end: q %p (%S)", q, "uninit");
14795 			return;
14796 		}
14797 	}
14798 
14799 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14800 	    "ip_rput_end: q %p (%S)", q, "end");
14801 
14802 	ip_input(ill, NULL, mp, NULL);
14803 }
14804 
14805 static mblk_t *
14806 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14807 {
14808 	mblk_t *mp1;
14809 	boolean_t adjusted = B_FALSE;
14810 	ip_stack_t *ipst = ill->ill_ipst;
14811 
14812 	IP_STAT(ipst, ip_db_ref);
14813 	/*
14814 	 * The IP_RECVSLLA option depends on having the
14815 	 * link layer header. First check that:
14816 	 * a> the underlying device is of type ether,
14817 	 * since this option is currently supported only
14818 	 * over ethernet.
14819 	 * b> there is enough room to copy over the link
14820 	 * layer header.
14821 	 *
14822 	 * Once the checks are done, adjust rptr so that
14823 	 * the link layer header will be copied via
14824 	 * copymsg. Note that, IFT_ETHER may be returned
14825 	 * by some non-ethernet drivers but in this case
14826 	 * the second check will fail.
14827 	 */
14828 	if (ill->ill_type == IFT_ETHER &&
14829 	    (mp->b_rptr - mp->b_datap->db_base) >=
14830 	    sizeof (struct ether_header)) {
14831 		mp->b_rptr -= sizeof (struct ether_header);
14832 		adjusted = B_TRUE;
14833 	}
14834 	mp1 = copymsg(mp);
14835 
14836 	if (mp1 == NULL) {
14837 		mp->b_next = NULL;
14838 		/* clear b_prev - used by ip_mroute_decap */
14839 		mp->b_prev = NULL;
14840 		freemsg(mp);
14841 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14842 		return (NULL);
14843 	}
14844 
14845 	if (adjusted) {
14846 		/*
14847 		 * Copy is done. Restore the pointer in
14848 		 * the _new_ mblk
14849 		 */
14850 		mp1->b_rptr += sizeof (struct ether_header);
14851 	}
14852 
14853 	/* Copy b_prev - used by ip_mroute_decap */
14854 	mp1->b_prev = mp->b_prev;
14855 	mp->b_prev = NULL;
14856 
14857 	/* preserve the hardware checksum flags and data, if present */
14858 	if (DB_CKSUMFLAGS(mp) != 0) {
14859 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14860 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14861 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14862 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14863 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14864 	}
14865 
14866 	freemsg(mp);
14867 	return (mp1);
14868 }
14869 
14870 /*
14871  * Direct read side procedure capable of dealing with chains. GLDv3 based
14872  * drivers call this function directly with mblk chains while STREAMS
14873  * read side procedure ip_rput() calls this for single packet with ip_ring
14874  * set to NULL to process one packet at a time.
14875  *
14876  * The ill will always be valid if this function is called directly from
14877  * the driver.
14878  *
14879  * If ip_input() is called from GLDv3:
14880  *
14881  *   - This must be a non-VLAN IP stream.
14882  *   - 'mp' is either an untagged or a special priority-tagged packet.
14883  *   - Any VLAN tag that was in the MAC header has been stripped.
14884  *
14885  * If the IP header in packet is not 32-bit aligned, every message in the
14886  * chain will be aligned before further operations. This is required on SPARC
14887  * platform.
14888  */
14889 /* ARGSUSED */
14890 void
14891 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14892     struct mac_header_info_s *mhip)
14893 {
14894 	ipaddr_t		dst = NULL;
14895 	ipaddr_t		prev_dst;
14896 	ire_t			*ire = NULL;
14897 	ipha_t			*ipha;
14898 	uint_t			pkt_len;
14899 	ssize_t			len;
14900 	uint_t			opt_len;
14901 	int			ll_multicast;
14902 	int			cgtp_flt_pkt;
14903 	queue_t			*q = ill->ill_rq;
14904 	squeue_t		*curr_sqp = NULL;
14905 	mblk_t 			*head = NULL;
14906 	mblk_t			*tail = NULL;
14907 	mblk_t			*first_mp;
14908 	mblk_t 			*mp;
14909 	mblk_t			*dmp;
14910 	int			cnt = 0;
14911 	ip_stack_t		*ipst = ill->ill_ipst;
14912 
14913 	ASSERT(mp_chain != NULL);
14914 	ASSERT(ill != NULL);
14915 
14916 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14917 
14918 #define	rptr	((uchar_t *)ipha)
14919 
14920 	while (mp_chain != NULL) {
14921 		first_mp = mp = mp_chain;
14922 		mp_chain = mp_chain->b_next;
14923 		mp->b_next = NULL;
14924 		ll_multicast = 0;
14925 
14926 		/*
14927 		 * We do ire caching from one iteration to
14928 		 * another. In the event the packet chain contains
14929 		 * all packets from the same dst, this caching saves
14930 		 * an ire_cache_lookup for each of the succeeding
14931 		 * packets in a packet chain.
14932 		 */
14933 		prev_dst = dst;
14934 
14935 		/*
14936 		 * if db_ref > 1 then copymsg and free original. Packet
14937 		 * may be changed and we do not want the other entity
14938 		 * who has a reference to this message to trip over the
14939 		 * changes. This is a blind change because trying to
14940 		 * catch all places that might change the packet is too
14941 		 * difficult.
14942 		 *
14943 		 * This corresponds to the fast path case, where we have
14944 		 * a chain of M_DATA mblks.  We check the db_ref count
14945 		 * of only the 1st data block in the mblk chain. There
14946 		 * doesn't seem to be a reason why a device driver would
14947 		 * send up data with varying db_ref counts in the mblk
14948 		 * chain. In any case the Fast path is a private
14949 		 * interface, and our drivers don't do such a thing.
14950 		 * Given the above assumption, there is no need to walk
14951 		 * down the entire mblk chain (which could have a
14952 		 * potential performance problem)
14953 		 */
14954 
14955 		if (DB_REF(mp) > 1) {
14956 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14957 				continue;
14958 		}
14959 
14960 		/*
14961 		 * Check and align the IP header.
14962 		 */
14963 		first_mp = mp;
14964 		if (DB_TYPE(mp) == M_DATA) {
14965 			dmp = mp;
14966 		} else if (DB_TYPE(mp) == M_PROTO &&
14967 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14968 			dmp = mp->b_cont;
14969 		} else {
14970 			dmp = NULL;
14971 		}
14972 		if (dmp != NULL) {
14973 			/*
14974 			 * IP header ptr not aligned?
14975 			 * OR IP header not complete in first mblk
14976 			 */
14977 			if (!OK_32PTR(dmp->b_rptr) ||
14978 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14979 				if (!ip_check_and_align_header(q, dmp, ipst))
14980 					continue;
14981 			}
14982 		}
14983 
14984 		/*
14985 		 * ip_input fast path
14986 		 */
14987 
14988 		/* mblk type is not M_DATA */
14989 		if (DB_TYPE(mp) != M_DATA) {
14990 			if (ip_rput_process_notdata(q, &first_mp, ill,
14991 			    &ll_multicast, &mp))
14992 				continue;
14993 
14994 			/*
14995 			 * The only way we can get here is if we had a
14996 			 * packet that was either a DL_UNITDATA_IND or
14997 			 * an M_CTL for an IPsec accelerated packet.
14998 			 *
14999 			 * In either case, the first_mp will point to
15000 			 * the leading M_PROTO or M_CTL.
15001 			 */
15002 			ASSERT(first_mp != NULL);
15003 		} else if (mhip != NULL) {
15004 			/*
15005 			 * ll_multicast is set here so that it is ready
15006 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15007 			 * manipulates ll_multicast in the same fashion when
15008 			 * called from ip_rput_process_notdata.
15009 			 */
15010 			switch (mhip->mhi_dsttype) {
15011 			case MAC_ADDRTYPE_MULTICAST :
15012 				ll_multicast = HPE_MULTICAST;
15013 				break;
15014 			case MAC_ADDRTYPE_BROADCAST :
15015 				ll_multicast = HPE_BROADCAST;
15016 				break;
15017 			default :
15018 				break;
15019 			}
15020 		}
15021 
15022 		/* Make sure its an M_DATA and that its aligned */
15023 		ASSERT(DB_TYPE(mp) == M_DATA);
15024 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15025 
15026 		ipha = (ipha_t *)mp->b_rptr;
15027 		len = mp->b_wptr - rptr;
15028 		pkt_len = ntohs(ipha->ipha_length);
15029 
15030 		/*
15031 		 * We must count all incoming packets, even if they end
15032 		 * up being dropped later on.
15033 		 */
15034 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15035 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15036 
15037 		/* multiple mblk or too short */
15038 		len -= pkt_len;
15039 		if (len != 0) {
15040 			/*
15041 			 * Make sure we have data length consistent
15042 			 * with the IP header.
15043 			 */
15044 			if (mp->b_cont == NULL) {
15045 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15046 					BUMP_MIB(ill->ill_ip_mib,
15047 					    ipIfStatsInHdrErrors);
15048 					ip2dbg(("ip_input: drop pkt\n"));
15049 					freemsg(mp);
15050 					continue;
15051 				}
15052 				mp->b_wptr = rptr + pkt_len;
15053 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15054 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15055 					BUMP_MIB(ill->ill_ip_mib,
15056 					    ipIfStatsInHdrErrors);
15057 					ip2dbg(("ip_input: drop pkt\n"));
15058 					freemsg(mp);
15059 					continue;
15060 				}
15061 				(void) adjmsg(mp, -len);
15062 				IP_STAT(ipst, ip_multimblk3);
15063 			}
15064 		}
15065 
15066 		/* Obtain the dst of the current packet */
15067 		dst = ipha->ipha_dst;
15068 
15069 		/*
15070 		 * The following test for loopback is faster than
15071 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15072 		 * operations.
15073 		 * Note that these addresses are always in network byte order
15074 		 */
15075 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15076 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15077 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15078 			freemsg(mp);
15079 			continue;
15080 		}
15081 
15082 		/*
15083 		 * The event for packets being received from a 'physical'
15084 		 * interface is placed after validation of the source and/or
15085 		 * destination address as being local so that packets can be
15086 		 * redirected to loopback addresses using ipnat.
15087 		 */
15088 		DTRACE_PROBE4(ip4__physical__in__start,
15089 		    ill_t *, ill, ill_t *, NULL,
15090 		    ipha_t *, ipha, mblk_t *, first_mp);
15091 
15092 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15093 		    ipst->ips_ipv4firewall_physical_in,
15094 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15095 
15096 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15097 
15098 		if (first_mp == NULL) {
15099 			continue;
15100 		}
15101 		dst = ipha->ipha_dst;
15102 
15103 		/*
15104 		 * Attach any necessary label information to
15105 		 * this packet
15106 		 */
15107 		if (is_system_labeled() &&
15108 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15109 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15110 			freemsg(mp);
15111 			continue;
15112 		}
15113 
15114 		/*
15115 		 * Reuse the cached ire only if the ipha_dst of the previous
15116 		 * packet is the same as the current packet AND it is not
15117 		 * INADDR_ANY.
15118 		 */
15119 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15120 		    (ire != NULL)) {
15121 			ire_refrele(ire);
15122 			ire = NULL;
15123 		}
15124 		opt_len = ipha->ipha_version_and_hdr_length -
15125 		    IP_SIMPLE_HDR_VERSION;
15126 
15127 		/*
15128 		 * Check to see if we can take the fastpath.
15129 		 * That is possible if the following conditions are met
15130 		 *	o Tsol disabled
15131 		 *	o CGTP disabled
15132 		 *	o ipp_action_count is 0
15133 		 *	o no options in the packet
15134 		 *	o not a RSVP packet
15135 		 * 	o not a multicast packet
15136 		 *	o ill not in IP_DHCPINIT_IF mode
15137 		 */
15138 		if (!is_system_labeled() &&
15139 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15140 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15141 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15142 			if (ire == NULL)
15143 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15144 				    ipst);
15145 
15146 			/* incoming packet is for forwarding */
15147 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15148 				ire = ip_fast_forward(ire, dst, ill, mp);
15149 				continue;
15150 			}
15151 			/* incoming packet is for local consumption */
15152 			if (ire->ire_type & IRE_LOCAL)
15153 				goto local;
15154 		}
15155 
15156 		/*
15157 		 * Disable ire caching for anything more complex
15158 		 * than the simple fast path case we checked for above.
15159 		 */
15160 		if (ire != NULL) {
15161 			ire_refrele(ire);
15162 			ire = NULL;
15163 		}
15164 
15165 		/*
15166 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15167 		 * server to unicast DHCP packets to a DHCP client using the
15168 		 * IP address it is offering to the client.  This can be
15169 		 * disabled through the "broadcast bit", but not all DHCP
15170 		 * servers honor that bit.  Therefore, to interoperate with as
15171 		 * many DHCP servers as possible, the DHCP client allows the
15172 		 * server to unicast, but we treat those packets as broadcast
15173 		 * here.  Note that we don't rewrite the packet itself since
15174 		 * (a) that would mess up the checksums and (b) the DHCP
15175 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15176 		 * hand it the packet regardless.
15177 		 */
15178 		if (ill->ill_dhcpinit != 0 &&
15179 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15180 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15181 			udpha_t *udpha;
15182 
15183 			/*
15184 			 * Reload ipha since pullupmsg() can change b_rptr.
15185 			 */
15186 			ipha = (ipha_t *)mp->b_rptr;
15187 			udpha = (udpha_t *)&ipha[1];
15188 
15189 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15190 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15191 				    mblk_t *, mp);
15192 				dst = INADDR_BROADCAST;
15193 			}
15194 		}
15195 
15196 		/* Full-blown slow path */
15197 		if (opt_len != 0) {
15198 			if (len != 0)
15199 				IP_STAT(ipst, ip_multimblk4);
15200 			else
15201 				IP_STAT(ipst, ip_ipoptions);
15202 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15203 			    &dst, ipst))
15204 				continue;
15205 		}
15206 
15207 		/*
15208 		 * Invoke the CGTP (multirouting) filtering module to process
15209 		 * the incoming packet. Packets identified as duplicates
15210 		 * must be discarded. Filtering is active only if the
15211 		 * the ip_cgtp_filter ndd variable is non-zero.
15212 		 */
15213 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15214 		if (ipst->ips_ip_cgtp_filter &&
15215 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15216 			netstackid_t stackid;
15217 
15218 			stackid = ipst->ips_netstack->netstack_stackid;
15219 			cgtp_flt_pkt =
15220 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15221 			    ill->ill_phyint->phyint_ifindex, mp);
15222 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15223 				freemsg(first_mp);
15224 				continue;
15225 			}
15226 		}
15227 
15228 		/*
15229 		 * If rsvpd is running, let RSVP daemon handle its processing
15230 		 * and forwarding of RSVP multicast/unicast packets.
15231 		 * If rsvpd is not running but mrouted is running, RSVP
15232 		 * multicast packets are forwarded as multicast traffic
15233 		 * and RSVP unicast packets are forwarded by unicast router.
15234 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15235 		 * packets are not forwarded, but the unicast packets are
15236 		 * forwarded like unicast traffic.
15237 		 */
15238 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15239 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15240 		    NULL) {
15241 			/* RSVP packet and rsvpd running. Treat as ours */
15242 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15243 			/*
15244 			 * This assumes that we deliver to all streams for
15245 			 * multicast and broadcast packets.
15246 			 * We have to force ll_multicast to 1 to handle the
15247 			 * M_DATA messages passed in from ip_mroute_decap.
15248 			 */
15249 			dst = INADDR_BROADCAST;
15250 			ll_multicast = 1;
15251 		} else if (CLASSD(dst)) {
15252 			/* packet is multicast */
15253 			mp->b_next = NULL;
15254 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15255 			    &ll_multicast, &dst))
15256 				continue;
15257 		}
15258 
15259 		if (ire == NULL) {
15260 			ire = ire_cache_lookup(dst, ALL_ZONES,
15261 			    MBLK_GETLABEL(mp), ipst);
15262 		}
15263 
15264 		if (ire != NULL && ire->ire_stq != NULL &&
15265 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15266 		    ire->ire_zoneid != ALL_ZONES) {
15267 			/*
15268 			 * Should only use IREs that are visible from the
15269 			 * global zone for forwarding.
15270 			 */
15271 			ire_refrele(ire);
15272 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15273 			    MBLK_GETLABEL(mp), ipst);
15274 		}
15275 
15276 		if (ire == NULL) {
15277 			/*
15278 			 * No IRE for this destination, so it can't be for us.
15279 			 * Unless we are forwarding, drop the packet.
15280 			 * We have to let source routed packets through
15281 			 * since we don't yet know if they are 'ping -l'
15282 			 * packets i.e. if they will go out over the
15283 			 * same interface as they came in on.
15284 			 */
15285 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15286 			if (ire == NULL)
15287 				continue;
15288 		}
15289 
15290 		/*
15291 		 * Broadcast IRE may indicate either broadcast or
15292 		 * multicast packet
15293 		 */
15294 		if (ire->ire_type == IRE_BROADCAST) {
15295 			/*
15296 			 * Skip broadcast checks if packet is UDP multicast;
15297 			 * we'd rather not enter ip_rput_process_broadcast()
15298 			 * unless the packet is broadcast for real, since
15299 			 * that routine is a no-op for multicast.
15300 			 */
15301 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15302 			    !CLASSD(ipha->ipha_dst)) {
15303 				ire = ip_rput_process_broadcast(&q, mp,
15304 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15305 				    ll_multicast);
15306 				if (ire == NULL)
15307 					continue;
15308 			}
15309 		} else if (ire->ire_stq != NULL) {
15310 			/* fowarding? */
15311 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15312 			    ll_multicast);
15313 			/* ip_rput_process_forward consumed the packet */
15314 			continue;
15315 		}
15316 
15317 local:
15318 		/*
15319 		 * If the queue in the ire is different to the ingress queue
15320 		 * then we need to check to see if we can accept the packet.
15321 		 * Note that for multicast packets and broadcast packets sent
15322 		 * to a broadcast address which is shared between multiple
15323 		 * interfaces we should not do this since we just got a random
15324 		 * broadcast ire.
15325 		 */
15326 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15327 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15328 			    ill)) == NULL) {
15329 				/* Drop packet */
15330 				BUMP_MIB(ill->ill_ip_mib,
15331 				    ipIfStatsForwProhibits);
15332 				freemsg(mp);
15333 				continue;
15334 			}
15335 			if (ire->ire_rfq != NULL)
15336 				q = ire->ire_rfq;
15337 		}
15338 
15339 		switch (ipha->ipha_protocol) {
15340 		case IPPROTO_TCP:
15341 			ASSERT(first_mp == mp);
15342 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15343 			    mp, 0, q, ip_ring)) != NULL) {
15344 				if (curr_sqp == NULL) {
15345 					curr_sqp = GET_SQUEUE(mp);
15346 					ASSERT(cnt == 0);
15347 					cnt++;
15348 					head = tail = mp;
15349 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15350 					ASSERT(tail != NULL);
15351 					cnt++;
15352 					tail->b_next = mp;
15353 					tail = mp;
15354 				} else {
15355 					/*
15356 					 * A different squeue. Send the
15357 					 * chain for the previous squeue on
15358 					 * its way. This shouldn't happen
15359 					 * often unless interrupt binding
15360 					 * changes.
15361 					 */
15362 					IP_STAT(ipst, ip_input_multi_squeue);
15363 					squeue_enter_chain(curr_sqp, head,
15364 					    tail, cnt, SQTAG_IP_INPUT);
15365 					curr_sqp = GET_SQUEUE(mp);
15366 					head = mp;
15367 					tail = mp;
15368 					cnt = 1;
15369 				}
15370 			}
15371 			continue;
15372 		case IPPROTO_UDP:
15373 			ASSERT(first_mp == mp);
15374 			ip_udp_input(q, mp, ipha, ire, ill);
15375 			continue;
15376 		case IPPROTO_SCTP:
15377 			ASSERT(first_mp == mp);
15378 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15379 			    q, dst);
15380 			/* ire has been released by ip_sctp_input */
15381 			ire = NULL;
15382 			continue;
15383 		default:
15384 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15385 			continue;
15386 		}
15387 	}
15388 
15389 	if (ire != NULL)
15390 		ire_refrele(ire);
15391 
15392 	if (head != NULL)
15393 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15394 
15395 	/*
15396 	 * This code is there just to make netperf/ttcp look good.
15397 	 *
15398 	 * Its possible that after being in polling mode (and having cleared
15399 	 * the backlog), squeues have turned the interrupt frequency higher
15400 	 * to improve latency at the expense of more CPU utilization (less
15401 	 * packets per interrupts or more number of interrupts). Workloads
15402 	 * like ttcp/netperf do manage to tickle polling once in a while
15403 	 * but for the remaining time, stay in higher interrupt mode since
15404 	 * their packet arrival rate is pretty uniform and this shows up
15405 	 * as higher CPU utilization. Since people care about CPU utilization
15406 	 * while running netperf/ttcp, turn the interrupt frequency back to
15407 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15408 	 */
15409 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15410 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15411 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15412 			ip_ring->rr_blank(ip_ring->rr_handle,
15413 			    ip_ring->rr_normal_blank_time,
15414 			    ip_ring->rr_normal_pkt_cnt);
15415 		}
15416 		}
15417 
15418 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15419 	    "ip_input_end: q %p (%S)", q, "end");
15420 #undef  rptr
15421 }
15422 
15423 static void
15424 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15425     t_uscalar_t err)
15426 {
15427 	if (dl_err == DL_SYSERR) {
15428 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15429 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15430 		    ill->ill_name, dl_primstr(prim), err);
15431 		return;
15432 	}
15433 
15434 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15435 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15436 	    dl_errstr(dl_err));
15437 }
15438 
15439 /*
15440  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15441  * than DL_UNITDATA_IND messages. If we need to process this message
15442  * exclusively, we call qwriter_ip, in which case we also need to call
15443  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15444  */
15445 void
15446 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15447 {
15448 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15449 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15450 	ill_t		*ill = (ill_t *)q->q_ptr;
15451 	boolean_t	pending;
15452 
15453 	ip1dbg(("ip_rput_dlpi"));
15454 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15455 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15456 		    "%s (0x%x), unix %u\n", ill->ill_name,
15457 		    dl_primstr(dlea->dl_error_primitive),
15458 		    dlea->dl_error_primitive,
15459 		    dl_errstr(dlea->dl_errno),
15460 		    dlea->dl_errno,
15461 		    dlea->dl_unix_errno));
15462 	}
15463 
15464 	/*
15465 	 * If we received an ACK but didn't send a request for it, then it
15466 	 * can't be part of any pending operation; discard up-front.
15467 	 */
15468 	switch (dloa->dl_primitive) {
15469 	case DL_NOTIFY_IND:
15470 		pending = B_TRUE;
15471 		break;
15472 	case DL_ERROR_ACK:
15473 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15474 		break;
15475 	case DL_OK_ACK:
15476 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15477 		break;
15478 	case DL_INFO_ACK:
15479 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15480 		break;
15481 	case DL_BIND_ACK:
15482 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15483 		break;
15484 	case DL_PHYS_ADDR_ACK:
15485 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15486 		break;
15487 	case DL_NOTIFY_ACK:
15488 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15489 		break;
15490 	case DL_CONTROL_ACK:
15491 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15492 		break;
15493 	case DL_CAPABILITY_ACK:
15494 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15495 		break;
15496 	default:
15497 		/* Not a DLPI message we support or were expecting */
15498 		freemsg(mp);
15499 		return;
15500 	}
15501 
15502 	if (!pending) {
15503 		freemsg(mp);
15504 		return;
15505 	}
15506 
15507 	switch (dloa->dl_primitive) {
15508 	case DL_ERROR_ACK:
15509 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15510 			mutex_enter(&ill->ill_lock);
15511 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15512 			cv_signal(&ill->ill_cv);
15513 			mutex_exit(&ill->ill_lock);
15514 		}
15515 		break;
15516 
15517 	case DL_OK_ACK:
15518 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15519 		    dl_primstr((int)dloa->dl_correct_primitive)));
15520 		switch (dloa->dl_correct_primitive) {
15521 		case DL_UNBIND_REQ:
15522 			mutex_enter(&ill->ill_lock);
15523 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15524 			cv_signal(&ill->ill_cv);
15525 			mutex_exit(&ill->ill_lock);
15526 			break;
15527 
15528 		case DL_ENABMULTI_REQ:
15529 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15530 				ill->ill_dlpi_multicast_state = IDS_OK;
15531 			break;
15532 		}
15533 		break;
15534 	default:
15535 		break;
15536 	}
15537 
15538 	/*
15539 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15540 	 * need to become writer to continue to process it.  Because an
15541 	 * exclusive operation doesn't complete until replies to all queued
15542 	 * DLPI messages have been received, we know we're in the middle of an
15543 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15544 	 *
15545 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15546 	 * Since this is on the ill stream we unconditionally bump up the
15547 	 * refcount without doing ILL_CAN_LOOKUP().
15548 	 */
15549 	ill_refhold(ill);
15550 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15551 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15552 	else
15553 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15554 }
15555 
15556 /*
15557  * Handling of DLPI messages that require exclusive access to the ipsq.
15558  *
15559  * Need to do ill_pending_mp_release on ioctl completion, which could
15560  * happen here. (along with mi_copy_done)
15561  */
15562 /* ARGSUSED */
15563 static void
15564 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15565 {
15566 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15567 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15568 	int		err = 0;
15569 	ill_t		*ill;
15570 	ipif_t		*ipif = NULL;
15571 	mblk_t		*mp1 = NULL;
15572 	conn_t		*connp = NULL;
15573 	t_uscalar_t	paddrreq;
15574 	mblk_t		*mp_hw;
15575 	boolean_t	success;
15576 	boolean_t	ioctl_aborted = B_FALSE;
15577 	boolean_t	log = B_TRUE;
15578 	ip_stack_t		*ipst;
15579 
15580 	ip1dbg(("ip_rput_dlpi_writer .."));
15581 	ill = (ill_t *)q->q_ptr;
15582 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15583 
15584 	ASSERT(IAM_WRITER_ILL(ill));
15585 
15586 	ipst = ill->ill_ipst;
15587 
15588 	/*
15589 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15590 	 * both are null or non-null. However we can assert that only
15591 	 * after grabbing the ipsq_lock. So we don't make any assertion
15592 	 * here and in other places in the code.
15593 	 */
15594 	ipif = ipsq->ipsq_pending_ipif;
15595 	/*
15596 	 * The current ioctl could have been aborted by the user and a new
15597 	 * ioctl to bring up another ill could have started. We could still
15598 	 * get a response from the driver later.
15599 	 */
15600 	if (ipif != NULL && ipif->ipif_ill != ill)
15601 		ioctl_aborted = B_TRUE;
15602 
15603 	switch (dloa->dl_primitive) {
15604 	case DL_ERROR_ACK:
15605 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15606 		    dl_primstr(dlea->dl_error_primitive)));
15607 
15608 		switch (dlea->dl_error_primitive) {
15609 		case DL_PROMISCON_REQ:
15610 		case DL_PROMISCOFF_REQ:
15611 		case DL_DISABMULTI_REQ:
15612 		case DL_UNBIND_REQ:
15613 		case DL_ATTACH_REQ:
15614 		case DL_INFO_REQ:
15615 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15616 			break;
15617 		case DL_NOTIFY_REQ:
15618 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15619 			log = B_FALSE;
15620 			break;
15621 		case DL_PHYS_ADDR_REQ:
15622 			/*
15623 			 * For IPv6 only, there are two additional
15624 			 * phys_addr_req's sent to the driver to get the
15625 			 * IPv6 token and lla. This allows IP to acquire
15626 			 * the hardware address format for a given interface
15627 			 * without having built in knowledge of the hardware
15628 			 * address. ill_phys_addr_pend keeps track of the last
15629 			 * DL_PAR sent so we know which response we are
15630 			 * dealing with. ill_dlpi_done will update
15631 			 * ill_phys_addr_pend when it sends the next req.
15632 			 * We don't complete the IOCTL until all three DL_PARs
15633 			 * have been attempted, so set *_len to 0 and break.
15634 			 */
15635 			paddrreq = ill->ill_phys_addr_pend;
15636 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15637 			if (paddrreq == DL_IPV6_TOKEN) {
15638 				ill->ill_token_length = 0;
15639 				log = B_FALSE;
15640 				break;
15641 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15642 				ill->ill_nd_lla_len = 0;
15643 				log = B_FALSE;
15644 				break;
15645 			}
15646 			/*
15647 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15648 			 * We presumably have an IOCTL hanging out waiting
15649 			 * for completion. Find it and complete the IOCTL
15650 			 * with the error noted.
15651 			 * However, ill_dl_phys was called on an ill queue
15652 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15653 			 * set. But the ioctl is known to be pending on ill_wq.
15654 			 */
15655 			if (!ill->ill_ifname_pending)
15656 				break;
15657 			ill->ill_ifname_pending = 0;
15658 			if (!ioctl_aborted)
15659 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15660 			if (mp1 != NULL) {
15661 				/*
15662 				 * This operation (SIOCSLIFNAME) must have
15663 				 * happened on the ill. Assert there is no conn
15664 				 */
15665 				ASSERT(connp == NULL);
15666 				q = ill->ill_wq;
15667 			}
15668 			break;
15669 		case DL_BIND_REQ:
15670 			ill_dlpi_done(ill, DL_BIND_REQ);
15671 			if (ill->ill_ifname_pending)
15672 				break;
15673 			/*
15674 			 * Something went wrong with the bind.  We presumably
15675 			 * have an IOCTL hanging out waiting for completion.
15676 			 * Find it, take down the interface that was coming
15677 			 * up, and complete the IOCTL with the error noted.
15678 			 */
15679 			if (!ioctl_aborted)
15680 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15681 			if (mp1 != NULL) {
15682 				/*
15683 				 * This operation (SIOCSLIFFLAGS) must have
15684 				 * happened from a conn.
15685 				 */
15686 				ASSERT(connp != NULL);
15687 				q = CONNP_TO_WQ(connp);
15688 				if (ill->ill_move_in_progress) {
15689 					ILL_CLEAR_MOVE(ill);
15690 				}
15691 				(void) ipif_down(ipif, NULL, NULL);
15692 				/* error is set below the switch */
15693 			}
15694 			break;
15695 		case DL_ENABMULTI_REQ:
15696 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15697 
15698 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15699 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15700 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15701 				ipif_t *ipif;
15702 
15703 				printf("ip: joining multicasts failed (%d)"
15704 				    " on %s - will use link layer "
15705 				    "broadcasts for multicast\n",
15706 				    dlea->dl_errno, ill->ill_name);
15707 
15708 				/*
15709 				 * Set up the multicast mapping alone.
15710 				 * writer, so ok to access ill->ill_ipif
15711 				 * without any lock.
15712 				 */
15713 				ipif = ill->ill_ipif;
15714 				mutex_enter(&ill->ill_phyint->phyint_lock);
15715 				ill->ill_phyint->phyint_flags |=
15716 				    PHYI_MULTI_BCAST;
15717 				mutex_exit(&ill->ill_phyint->phyint_lock);
15718 
15719 				if (!ill->ill_isv6) {
15720 					(void) ipif_arp_setup_multicast(ipif,
15721 					    NULL);
15722 				} else {
15723 					(void) ipif_ndp_setup_multicast(ipif,
15724 					    NULL);
15725 				}
15726 			}
15727 			freemsg(mp);	/* Don't want to pass this up */
15728 			return;
15729 
15730 		case DL_CAPABILITY_REQ:
15731 		case DL_CONTROL_REQ:
15732 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15733 			ill->ill_dlpi_capab_state = IDS_FAILED;
15734 			freemsg(mp);
15735 			return;
15736 		}
15737 		/*
15738 		 * Note the error for IOCTL completion (mp1 is set when
15739 		 * ready to complete ioctl). If ill_ifname_pending_err is
15740 		 * set, an error occured during plumbing (ill_ifname_pending),
15741 		 * so we want to report that error.
15742 		 *
15743 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15744 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15745 		 * expected to get errack'd if the driver doesn't support
15746 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15747 		 * if these error conditions are encountered.
15748 		 */
15749 		if (mp1 != NULL) {
15750 			if (ill->ill_ifname_pending_err != 0)  {
15751 				err = ill->ill_ifname_pending_err;
15752 				ill->ill_ifname_pending_err = 0;
15753 			} else {
15754 				err = dlea->dl_unix_errno ?
15755 				    dlea->dl_unix_errno : ENXIO;
15756 			}
15757 		/*
15758 		 * If we're plumbing an interface and an error hasn't already
15759 		 * been saved, set ill_ifname_pending_err to the error passed
15760 		 * up. Ignore the error if log is B_FALSE (see comment above).
15761 		 */
15762 		} else if (log && ill->ill_ifname_pending &&
15763 		    ill->ill_ifname_pending_err == 0) {
15764 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15765 			    dlea->dl_unix_errno : ENXIO;
15766 		}
15767 
15768 		if (log)
15769 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15770 			    dlea->dl_errno, dlea->dl_unix_errno);
15771 		break;
15772 	case DL_CAPABILITY_ACK:
15773 		/* Call a routine to handle this one. */
15774 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15775 		ill_capability_ack(ill, mp);
15776 
15777 		/*
15778 		 * If the ack is due to renegotiation, we will need to send
15779 		 * a new CAPABILITY_REQ to start the renegotiation.
15780 		 */
15781 		if (ill->ill_capab_reneg) {
15782 			ill->ill_capab_reneg = B_FALSE;
15783 			ill_capability_probe(ill);
15784 		}
15785 		break;
15786 	case DL_CONTROL_ACK:
15787 		/* We treat all of these as "fire and forget" */
15788 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15789 		break;
15790 	case DL_INFO_ACK:
15791 		/* Call a routine to handle this one. */
15792 		ill_dlpi_done(ill, DL_INFO_REQ);
15793 		ip_ll_subnet_defaults(ill, mp);
15794 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15795 		return;
15796 	case DL_BIND_ACK:
15797 		/*
15798 		 * We should have an IOCTL waiting on this unless
15799 		 * sent by ill_dl_phys, in which case just return
15800 		 */
15801 		ill_dlpi_done(ill, DL_BIND_REQ);
15802 		if (ill->ill_ifname_pending)
15803 			break;
15804 
15805 		if (!ioctl_aborted)
15806 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15807 		if (mp1 == NULL)
15808 			break;
15809 		/*
15810 		 * Because mp1 was added by ill_dl_up(), and it always
15811 		 * passes a valid connp, connp must be valid here.
15812 		 */
15813 		ASSERT(connp != NULL);
15814 		q = CONNP_TO_WQ(connp);
15815 
15816 		/*
15817 		 * We are exclusive. So nothing can change even after
15818 		 * we get the pending mp. If need be we can put it back
15819 		 * and restart, as in calling ipif_arp_up()  below.
15820 		 */
15821 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15822 
15823 		mutex_enter(&ill->ill_lock);
15824 		ill->ill_dl_up = 1;
15825 		(void) ill_hook_event_create(ill, 0, NE_UP, NULL, 0);
15826 		mutex_exit(&ill->ill_lock);
15827 
15828 		/*
15829 		 * Now bring up the resolver; when that is complete, we'll
15830 		 * create IREs.  Note that we intentionally mirror what
15831 		 * ipif_up() would have done, because we got here by way of
15832 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15833 		 */
15834 		if (ill->ill_isv6) {
15835 			/*
15836 			 * v6 interfaces.
15837 			 * Unlike ARP which has to do another bind
15838 			 * and attach, once we get here we are
15839 			 * done with NDP. Except in the case of
15840 			 * ILLF_XRESOLV, in which case we send an
15841 			 * AR_INTERFACE_UP to the external resolver.
15842 			 * If all goes well, the ioctl will complete
15843 			 * in ip_rput(). If there's an error, we
15844 			 * complete it here.
15845 			 */
15846 			if ((err = ipif_ndp_up(ipif)) == 0) {
15847 				if (ill->ill_flags & ILLF_XRESOLV) {
15848 					mutex_enter(&connp->conn_lock);
15849 					mutex_enter(&ill->ill_lock);
15850 					success = ipsq_pending_mp_add(
15851 					    connp, ipif, q, mp1, 0);
15852 					mutex_exit(&ill->ill_lock);
15853 					mutex_exit(&connp->conn_lock);
15854 					if (success) {
15855 						err = ipif_resolver_up(ipif,
15856 						    Res_act_initial);
15857 						if (err == EINPROGRESS) {
15858 							freemsg(mp);
15859 							return;
15860 						}
15861 						ASSERT(err != 0);
15862 						mp1 = ipsq_pending_mp_get(ipsq,
15863 						    &connp);
15864 						ASSERT(mp1 != NULL);
15865 					} else {
15866 						/* conn has started closing */
15867 						err = EINTR;
15868 					}
15869 				} else { /* Non XRESOLV interface */
15870 					(void) ipif_resolver_up(ipif,
15871 					    Res_act_initial);
15872 					err = ipif_up_done_v6(ipif);
15873 				}
15874 			}
15875 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15876 			/*
15877 			 * ARP and other v4 external resolvers.
15878 			 * Leave the pending mblk intact so that
15879 			 * the ioctl completes in ip_rput().
15880 			 */
15881 			mutex_enter(&connp->conn_lock);
15882 			mutex_enter(&ill->ill_lock);
15883 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15884 			mutex_exit(&ill->ill_lock);
15885 			mutex_exit(&connp->conn_lock);
15886 			if (success) {
15887 				err = ipif_resolver_up(ipif, Res_act_initial);
15888 				if (err == EINPROGRESS) {
15889 					freemsg(mp);
15890 					return;
15891 				}
15892 				ASSERT(err != 0);
15893 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15894 			} else {
15895 				/* The conn has started closing */
15896 				err = EINTR;
15897 			}
15898 		} else {
15899 			/*
15900 			 * This one is complete. Reply to pending ioctl.
15901 			 */
15902 			(void) ipif_resolver_up(ipif, Res_act_initial);
15903 			err = ipif_up_done(ipif);
15904 		}
15905 
15906 		if ((err == 0) && (ill->ill_up_ipifs)) {
15907 			err = ill_up_ipifs(ill, q, mp1);
15908 			if (err == EINPROGRESS) {
15909 				freemsg(mp);
15910 				return;
15911 			}
15912 		}
15913 
15914 		if (ill->ill_up_ipifs) {
15915 			ill_group_cleanup(ill);
15916 		}
15917 
15918 		break;
15919 	case DL_NOTIFY_IND: {
15920 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15921 		ire_t *ire;
15922 		boolean_t need_ire_walk_v4 = B_FALSE;
15923 		boolean_t need_ire_walk_v6 = B_FALSE;
15924 
15925 		switch (notify->dl_notification) {
15926 		case DL_NOTE_PHYS_ADDR:
15927 			err = ill_set_phys_addr(ill, mp);
15928 			break;
15929 
15930 		case DL_NOTE_FASTPATH_FLUSH:
15931 			ill_fastpath_flush(ill);
15932 			break;
15933 
15934 		case DL_NOTE_SDU_SIZE:
15935 			/*
15936 			 * Change the MTU size of the interface, of all
15937 			 * attached ipif's, and of all relevant ire's.  The
15938 			 * new value's a uint32_t at notify->dl_data.
15939 			 * Mtu change Vs. new ire creation - protocol below.
15940 			 *
15941 			 * a Mark the ipif as IPIF_CHANGING.
15942 			 * b Set the new mtu in the ipif.
15943 			 * c Change the ire_max_frag on all affected ires
15944 			 * d Unmark the IPIF_CHANGING
15945 			 *
15946 			 * To see how the protocol works, assume an interface
15947 			 * route is also being added simultaneously by
15948 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15949 			 * the ire. If the ire is created before step a,
15950 			 * it will be cleaned up by step c. If the ire is
15951 			 * created after step d, it will see the new value of
15952 			 * ipif_mtu. Any attempt to create the ire between
15953 			 * steps a to d will fail because of the IPIF_CHANGING
15954 			 * flag. Note that ire_create() is passed a pointer to
15955 			 * the ipif_mtu, and not the value. During ire_add
15956 			 * under the bucket lock, the ire_max_frag of the
15957 			 * new ire being created is set from the ipif/ire from
15958 			 * which it is being derived.
15959 			 */
15960 			mutex_enter(&ill->ill_lock);
15961 			ill->ill_max_frag = (uint_t)notify->dl_data;
15962 
15963 			/*
15964 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15965 			 * leave it alone
15966 			 */
15967 			if (ill->ill_mtu_userspecified) {
15968 				mutex_exit(&ill->ill_lock);
15969 				break;
15970 			}
15971 			ill->ill_max_mtu = ill->ill_max_frag;
15972 			if (ill->ill_isv6) {
15973 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15974 					ill->ill_max_mtu = IPV6_MIN_MTU;
15975 			} else {
15976 				if (ill->ill_max_mtu < IP_MIN_MTU)
15977 					ill->ill_max_mtu = IP_MIN_MTU;
15978 			}
15979 			for (ipif = ill->ill_ipif; ipif != NULL;
15980 			    ipif = ipif->ipif_next) {
15981 				/*
15982 				 * Don't override the mtu if the user
15983 				 * has explicitly set it.
15984 				 */
15985 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15986 					continue;
15987 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15988 				if (ipif->ipif_isv6)
15989 					ire = ipif_to_ire_v6(ipif);
15990 				else
15991 					ire = ipif_to_ire(ipif);
15992 				if (ire != NULL) {
15993 					ire->ire_max_frag = ipif->ipif_mtu;
15994 					ire_refrele(ire);
15995 				}
15996 				if (ipif->ipif_flags & IPIF_UP) {
15997 					if (ill->ill_isv6)
15998 						need_ire_walk_v6 = B_TRUE;
15999 					else
16000 						need_ire_walk_v4 = B_TRUE;
16001 				}
16002 			}
16003 			mutex_exit(&ill->ill_lock);
16004 			if (need_ire_walk_v4)
16005 				ire_walk_v4(ill_mtu_change, (char *)ill,
16006 				    ALL_ZONES, ipst);
16007 			if (need_ire_walk_v6)
16008 				ire_walk_v6(ill_mtu_change, (char *)ill,
16009 				    ALL_ZONES, ipst);
16010 			break;
16011 		case DL_NOTE_LINK_UP:
16012 		case DL_NOTE_LINK_DOWN: {
16013 			/*
16014 			 * We are writer. ill / phyint / ipsq assocs stable.
16015 			 * The RUNNING flag reflects the state of the link.
16016 			 */
16017 			phyint_t *phyint = ill->ill_phyint;
16018 			uint64_t new_phyint_flags;
16019 			boolean_t changed = B_FALSE;
16020 			boolean_t went_up;
16021 
16022 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16023 			mutex_enter(&phyint->phyint_lock);
16024 			new_phyint_flags = went_up ?
16025 			    phyint->phyint_flags | PHYI_RUNNING :
16026 			    phyint->phyint_flags & ~PHYI_RUNNING;
16027 			if (new_phyint_flags != phyint->phyint_flags) {
16028 				phyint->phyint_flags = new_phyint_flags;
16029 				changed = B_TRUE;
16030 			}
16031 			mutex_exit(&phyint->phyint_lock);
16032 			/*
16033 			 * ill_restart_dad handles the DAD restart and routing
16034 			 * socket notification logic.
16035 			 */
16036 			if (changed) {
16037 				ill_restart_dad(phyint->phyint_illv4, went_up);
16038 				ill_restart_dad(phyint->phyint_illv6, went_up);
16039 			}
16040 			break;
16041 		}
16042 		case DL_NOTE_PROMISC_ON_PHYS:
16043 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16044 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16045 			mutex_enter(&ill->ill_lock);
16046 			ill->ill_promisc_on_phys = B_TRUE;
16047 			mutex_exit(&ill->ill_lock);
16048 			break;
16049 		case DL_NOTE_PROMISC_OFF_PHYS:
16050 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16051 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16052 			mutex_enter(&ill->ill_lock);
16053 			ill->ill_promisc_on_phys = B_FALSE;
16054 			mutex_exit(&ill->ill_lock);
16055 			break;
16056 		case DL_NOTE_CAPAB_RENEG:
16057 			/*
16058 			 * Something changed on the driver side.
16059 			 * It wants us to renegotiate the capabilities
16060 			 * on this ill. One possible cause is the aggregation
16061 			 * interface under us where a port got added or
16062 			 * went away.
16063 			 *
16064 			 * If the capability negotiation is already done
16065 			 * or is in progress, reset the capabilities and
16066 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16067 			 * so that when the ack comes back, we can start
16068 			 * the renegotiation process.
16069 			 *
16070 			 * Note that if ill_capab_reneg is already B_TRUE
16071 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16072 			 * the capability resetting request has been sent
16073 			 * and the renegotiation has not been started yet;
16074 			 * nothing needs to be done in this case.
16075 			 */
16076 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16077 				ill_capability_reset(ill);
16078 				ill->ill_capab_reneg = B_TRUE;
16079 			}
16080 			break;
16081 		default:
16082 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16083 			    "type 0x%x for DL_NOTIFY_IND\n",
16084 			    notify->dl_notification));
16085 			break;
16086 		}
16087 
16088 		/*
16089 		 * As this is an asynchronous operation, we
16090 		 * should not call ill_dlpi_done
16091 		 */
16092 		break;
16093 	}
16094 	case DL_NOTIFY_ACK: {
16095 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16096 
16097 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16098 			ill->ill_note_link = 1;
16099 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16100 		break;
16101 	}
16102 	case DL_PHYS_ADDR_ACK: {
16103 		/*
16104 		 * As part of plumbing the interface via SIOCSLIFNAME,
16105 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16106 		 * whose answers we receive here.  As each answer is received,
16107 		 * we call ill_dlpi_done() to dispatch the next request as
16108 		 * we're processing the current one.  Once all answers have
16109 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16110 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16111 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16112 		 * available, but we know the ioctl is pending on ill_wq.)
16113 		 */
16114 		uint_t paddrlen, paddroff;
16115 
16116 		paddrreq = ill->ill_phys_addr_pend;
16117 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16118 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16119 
16120 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16121 		if (paddrreq == DL_IPV6_TOKEN) {
16122 			/*
16123 			 * bcopy to low-order bits of ill_token
16124 			 *
16125 			 * XXX Temporary hack - currently, all known tokens
16126 			 * are 64 bits, so I'll cheat for the moment.
16127 			 */
16128 			bcopy(mp->b_rptr + paddroff,
16129 			    &ill->ill_token.s6_addr32[2], paddrlen);
16130 			ill->ill_token_length = paddrlen;
16131 			break;
16132 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16133 			ASSERT(ill->ill_nd_lla_mp == NULL);
16134 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16135 			mp = NULL;
16136 			break;
16137 		}
16138 
16139 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16140 		ASSERT(ill->ill_phys_addr_mp == NULL);
16141 		if (!ill->ill_ifname_pending)
16142 			break;
16143 		ill->ill_ifname_pending = 0;
16144 		if (!ioctl_aborted)
16145 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16146 		if (mp1 != NULL) {
16147 			ASSERT(connp == NULL);
16148 			q = ill->ill_wq;
16149 		}
16150 		/*
16151 		 * If any error acks received during the plumbing sequence,
16152 		 * ill_ifname_pending_err will be set. Break out and send up
16153 		 * the error to the pending ioctl.
16154 		 */
16155 		if (ill->ill_ifname_pending_err != 0) {
16156 			err = ill->ill_ifname_pending_err;
16157 			ill->ill_ifname_pending_err = 0;
16158 			break;
16159 		}
16160 
16161 		ill->ill_phys_addr_mp = mp;
16162 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16163 		mp = NULL;
16164 
16165 		/*
16166 		 * If paddrlen is zero, the DLPI provider doesn't support
16167 		 * physical addresses.  The other two tests were historical
16168 		 * workarounds for bugs in our former PPP implementation, but
16169 		 * now other things have grown dependencies on them -- e.g.,
16170 		 * the tun module specifies a dl_addr_length of zero in its
16171 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16172 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16173 		 * but only after careful testing ensures that all dependent
16174 		 * broken DLPI providers have been fixed.
16175 		 */
16176 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16177 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16178 			ill->ill_phys_addr = NULL;
16179 		} else if (paddrlen != ill->ill_phys_addr_length) {
16180 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16181 			    paddrlen, ill->ill_phys_addr_length));
16182 			err = EINVAL;
16183 			break;
16184 		}
16185 
16186 		if (ill->ill_nd_lla_mp == NULL) {
16187 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16188 				err = ENOMEM;
16189 				break;
16190 			}
16191 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16192 		}
16193 
16194 		/*
16195 		 * Set the interface token.  If the zeroth interface address
16196 		 * is unspecified, then set it to the link local address.
16197 		 */
16198 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16199 			(void) ill_setdefaulttoken(ill);
16200 
16201 		ASSERT(ill->ill_ipif->ipif_id == 0);
16202 		if (ipif != NULL &&
16203 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16204 			(void) ipif_setlinklocal(ipif);
16205 		}
16206 		break;
16207 	}
16208 	case DL_OK_ACK:
16209 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16210 		    dl_primstr((int)dloa->dl_correct_primitive),
16211 		    dloa->dl_correct_primitive));
16212 		switch (dloa->dl_correct_primitive) {
16213 		case DL_PROMISCON_REQ:
16214 		case DL_PROMISCOFF_REQ:
16215 		case DL_ENABMULTI_REQ:
16216 		case DL_DISABMULTI_REQ:
16217 		case DL_UNBIND_REQ:
16218 		case DL_ATTACH_REQ:
16219 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16220 			break;
16221 		}
16222 		break;
16223 	default:
16224 		break;
16225 	}
16226 
16227 	freemsg(mp);
16228 	if (mp1 != NULL) {
16229 		/*
16230 		 * The operation must complete without EINPROGRESS
16231 		 * since ipsq_pending_mp_get() has removed the mblk
16232 		 * from ipsq_pending_mp.  Otherwise, the operation
16233 		 * will be stuck forever in the ipsq.
16234 		 */
16235 		ASSERT(err != EINPROGRESS);
16236 
16237 		switch (ipsq->ipsq_current_ioctl) {
16238 		case 0:
16239 			ipsq_current_finish(ipsq);
16240 			break;
16241 
16242 		case SIOCLIFADDIF:
16243 		case SIOCSLIFNAME:
16244 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16245 			break;
16246 
16247 		default:
16248 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16249 			break;
16250 		}
16251 	}
16252 }
16253 
16254 /*
16255  * ip_rput_other is called by ip_rput to handle messages modifying the global
16256  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16257  */
16258 /* ARGSUSED */
16259 void
16260 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16261 {
16262 	ill_t		*ill;
16263 	struct iocblk	*iocp;
16264 	mblk_t		*mp1;
16265 	conn_t		*connp = NULL;
16266 
16267 	ip1dbg(("ip_rput_other "));
16268 	ill = (ill_t *)q->q_ptr;
16269 	/*
16270 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16271 	 * in which case ipsq is NULL.
16272 	 */
16273 	if (ipsq != NULL) {
16274 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16275 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16276 	}
16277 
16278 	switch (mp->b_datap->db_type) {
16279 	case M_ERROR:
16280 	case M_HANGUP:
16281 		/*
16282 		 * The device has a problem.  We force the ILL down.  It can
16283 		 * be brought up again manually using SIOCSIFFLAGS (via
16284 		 * ifconfig or equivalent).
16285 		 */
16286 		ASSERT(ipsq != NULL);
16287 		if (mp->b_rptr < mp->b_wptr)
16288 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16289 		if (ill->ill_error == 0)
16290 			ill->ill_error = ENXIO;
16291 		if (!ill_down_start(q, mp))
16292 			return;
16293 		ipif_all_down_tail(ipsq, q, mp, NULL);
16294 		break;
16295 	case M_IOCACK:
16296 		iocp = (struct iocblk *)mp->b_rptr;
16297 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16298 		switch (iocp->ioc_cmd) {
16299 		case SIOCSTUNPARAM:
16300 		case OSIOCSTUNPARAM:
16301 			ASSERT(ipsq != NULL);
16302 			/*
16303 			 * Finish socket ioctl passed through to tun.
16304 			 * We should have an IOCTL waiting on this.
16305 			 */
16306 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16307 			if (ill->ill_isv6) {
16308 				struct iftun_req *ta;
16309 
16310 				/*
16311 				 * if a source or destination is
16312 				 * being set, try and set the link
16313 				 * local address for the tunnel
16314 				 */
16315 				ta = (struct iftun_req *)mp->b_cont->
16316 				    b_cont->b_rptr;
16317 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16318 					ipif_set_tun_llink(ill, ta);
16319 				}
16320 
16321 			}
16322 			if (mp1 != NULL) {
16323 				/*
16324 				 * Now copy back the b_next/b_prev used by
16325 				 * mi code for the mi_copy* functions.
16326 				 * See ip_sioctl_tunparam() for the reason.
16327 				 * Also protect against missing b_cont.
16328 				 */
16329 				if (mp->b_cont != NULL) {
16330 					mp->b_cont->b_next =
16331 					    mp1->b_cont->b_next;
16332 					mp->b_cont->b_prev =
16333 					    mp1->b_cont->b_prev;
16334 				}
16335 				inet_freemsg(mp1);
16336 				ASSERT(connp != NULL);
16337 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16338 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16339 			} else {
16340 				ASSERT(connp == NULL);
16341 				putnext(q, mp);
16342 			}
16343 			break;
16344 		case SIOCGTUNPARAM:
16345 		case OSIOCGTUNPARAM:
16346 			/*
16347 			 * This is really M_IOCDATA from the tunnel driver.
16348 			 * convert back and complete the ioctl.
16349 			 * We should have an IOCTL waiting on this.
16350 			 */
16351 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16352 			if (mp1) {
16353 				/*
16354 				 * Now copy back the b_next/b_prev used by
16355 				 * mi code for the mi_copy* functions.
16356 				 * See ip_sioctl_tunparam() for the reason.
16357 				 * Also protect against missing b_cont.
16358 				 */
16359 				if (mp->b_cont != NULL) {
16360 					mp->b_cont->b_next =
16361 					    mp1->b_cont->b_next;
16362 					mp->b_cont->b_prev =
16363 					    mp1->b_cont->b_prev;
16364 				}
16365 				inet_freemsg(mp1);
16366 				if (iocp->ioc_error == 0)
16367 					mp->b_datap->db_type = M_IOCDATA;
16368 				ASSERT(connp != NULL);
16369 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16370 				    iocp->ioc_error, COPYOUT, NULL);
16371 			} else {
16372 				ASSERT(connp == NULL);
16373 				putnext(q, mp);
16374 			}
16375 			break;
16376 		default:
16377 			break;
16378 		}
16379 		break;
16380 	case M_IOCNAK:
16381 		iocp = (struct iocblk *)mp->b_rptr;
16382 
16383 		switch (iocp->ioc_cmd) {
16384 		int mode;
16385 
16386 		case DL_IOC_HDR_INFO:
16387 			/*
16388 			 * If this was the first attempt turn of the
16389 			 * fastpath probing.
16390 			 */
16391 			mutex_enter(&ill->ill_lock);
16392 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16393 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16394 				mutex_exit(&ill->ill_lock);
16395 				ill_fastpath_nack(ill);
16396 				ip1dbg(("ip_rput: DLPI fastpath off on "
16397 				    "interface %s\n",
16398 				    ill->ill_name));
16399 			} else {
16400 				mutex_exit(&ill->ill_lock);
16401 			}
16402 			freemsg(mp);
16403 			break;
16404 		case SIOCSTUNPARAM:
16405 		case OSIOCSTUNPARAM:
16406 			ASSERT(ipsq != NULL);
16407 			/*
16408 			 * Finish socket ioctl passed through to tun
16409 			 * We should have an IOCTL waiting on this.
16410 			 */
16411 			/* FALLTHRU */
16412 		case SIOCGTUNPARAM:
16413 		case OSIOCGTUNPARAM:
16414 			/*
16415 			 * This is really M_IOCDATA from the tunnel driver.
16416 			 * convert back and complete the ioctl.
16417 			 * We should have an IOCTL waiting on this.
16418 			 */
16419 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16420 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16421 				mp1 = ill_pending_mp_get(ill, &connp,
16422 				    iocp->ioc_id);
16423 				mode = COPYOUT;
16424 				ipsq = NULL;
16425 			} else {
16426 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16427 				mode = NO_COPYOUT;
16428 			}
16429 			if (mp1 != NULL) {
16430 				/*
16431 				 * Now copy back the b_next/b_prev used by
16432 				 * mi code for the mi_copy* functions.
16433 				 * See ip_sioctl_tunparam() for the reason.
16434 				 * Also protect against missing b_cont.
16435 				 */
16436 				if (mp->b_cont != NULL) {
16437 					mp->b_cont->b_next =
16438 					    mp1->b_cont->b_next;
16439 					mp->b_cont->b_prev =
16440 					    mp1->b_cont->b_prev;
16441 				}
16442 				inet_freemsg(mp1);
16443 				if (iocp->ioc_error == 0)
16444 					iocp->ioc_error = EINVAL;
16445 				ASSERT(connp != NULL);
16446 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16447 				    iocp->ioc_error, mode, ipsq);
16448 			} else {
16449 				ASSERT(connp == NULL);
16450 				putnext(q, mp);
16451 			}
16452 			break;
16453 		default:
16454 			break;
16455 		}
16456 	default:
16457 		break;
16458 	}
16459 }
16460 
16461 /*
16462  * NOTE : This function does not ire_refrele the ire argument passed in.
16463  *
16464  * IPQoS notes
16465  * IP policy is invoked twice for a forwarded packet, once on the read side
16466  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16467  * enabled. An additional parameter, in_ill, has been added for this purpose.
16468  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16469  * because ip_mroute drops this information.
16470  *
16471  */
16472 void
16473 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16474 {
16475 	uint32_t	old_pkt_len;
16476 	uint32_t	pkt_len;
16477 	queue_t	*q;
16478 	uint32_t	sum;
16479 #define	rptr	((uchar_t *)ipha)
16480 	uint32_t	max_frag;
16481 	uint32_t	ill_index;
16482 	ill_t		*out_ill;
16483 	mib2_ipIfStatsEntry_t *mibptr;
16484 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16485 
16486 	/* Get the ill_index of the incoming ILL */
16487 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16488 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16489 
16490 	/* Initiate Read side IPPF processing */
16491 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16492 		ip_process(IPP_FWD_IN, &mp, ill_index);
16493 		if (mp == NULL) {
16494 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16495 			    "during IPPF processing\n"));
16496 			return;
16497 		}
16498 	}
16499 
16500 	/* Adjust the checksum to reflect the ttl decrement. */
16501 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16502 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16503 
16504 	if (ipha->ipha_ttl-- <= 1) {
16505 		if (ip_csum_hdr(ipha)) {
16506 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16507 			goto drop_pkt;
16508 		}
16509 		/*
16510 		 * Note: ire_stq this will be NULL for multicast
16511 		 * datagrams using the long path through arp (the IRE
16512 		 * is not an IRE_CACHE). This should not cause
16513 		 * problems since we don't generate ICMP errors for
16514 		 * multicast packets.
16515 		 */
16516 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16517 		q = ire->ire_stq;
16518 		if (q != NULL) {
16519 			/* Sent by forwarding path, and router is global zone */
16520 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16521 			    GLOBAL_ZONEID, ipst);
16522 		} else
16523 			freemsg(mp);
16524 		return;
16525 	}
16526 
16527 	/*
16528 	 * Don't forward if the interface is down
16529 	 */
16530 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16531 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16532 		ip2dbg(("ip_rput_forward:interface is down\n"));
16533 		goto drop_pkt;
16534 	}
16535 
16536 	/* Get the ill_index of the outgoing ILL */
16537 	out_ill = ire_to_ill(ire);
16538 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16539 
16540 	DTRACE_PROBE4(ip4__forwarding__start,
16541 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16542 
16543 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16544 	    ipst->ips_ipv4firewall_forwarding,
16545 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16546 
16547 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16548 
16549 	if (mp == NULL)
16550 		return;
16551 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16552 
16553 	if (is_system_labeled()) {
16554 		mblk_t *mp1;
16555 
16556 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16557 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16558 			goto drop_pkt;
16559 		}
16560 		/* Size may have changed */
16561 		mp = mp1;
16562 		ipha = (ipha_t *)mp->b_rptr;
16563 		pkt_len = ntohs(ipha->ipha_length);
16564 	}
16565 
16566 	/* Check if there are options to update */
16567 	if (!IS_SIMPLE_IPH(ipha)) {
16568 		if (ip_csum_hdr(ipha)) {
16569 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16570 			goto drop_pkt;
16571 		}
16572 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16573 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16574 			return;
16575 		}
16576 
16577 		ipha->ipha_hdr_checksum = 0;
16578 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16579 	}
16580 	max_frag = ire->ire_max_frag;
16581 	if (pkt_len > max_frag) {
16582 		/*
16583 		 * It needs fragging on its way out.  We haven't
16584 		 * verified the header checksum yet.  Since we
16585 		 * are going to put a surely good checksum in the
16586 		 * outgoing header, we have to make sure that it
16587 		 * was good coming in.
16588 		 */
16589 		if (ip_csum_hdr(ipha)) {
16590 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16591 			goto drop_pkt;
16592 		}
16593 		/* Initiate Write side IPPF processing */
16594 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16595 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16596 			if (mp == NULL) {
16597 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16598 				    " during IPPF processing\n"));
16599 				return;
16600 			}
16601 		}
16602 		/*
16603 		 * Handle labeled packet resizing.
16604 		 *
16605 		 * If we have added a label, inform ip_wput_frag() of its
16606 		 * effect on the MTU for ICMP messages.
16607 		 */
16608 		if (pkt_len > old_pkt_len) {
16609 			uint32_t secopt_size;
16610 
16611 			secopt_size = pkt_len - old_pkt_len;
16612 			if (secopt_size < max_frag)
16613 				max_frag -= secopt_size;
16614 		}
16615 
16616 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16617 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16618 		return;
16619 	}
16620 
16621 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16622 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16623 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16624 	    ipst->ips_ipv4firewall_physical_out,
16625 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16626 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16627 	if (mp == NULL)
16628 		return;
16629 
16630 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16631 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16632 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16633 	/* ip_xmit_v4 always consumes the packet */
16634 	return;
16635 
16636 drop_pkt:;
16637 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16638 	freemsg(mp);
16639 #undef	rptr
16640 }
16641 
16642 void
16643 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16644 {
16645 	ire_t	*ire;
16646 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16647 
16648 	ASSERT(!ipif->ipif_isv6);
16649 	/*
16650 	 * Find an IRE which matches the destination and the outgoing
16651 	 * queue in the cache table. All we need is an IRE_CACHE which
16652 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16653 	 * then it is enough to have some IRE_CACHE in the group.
16654 	 */
16655 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16656 		dst = ipif->ipif_pp_dst_addr;
16657 
16658 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16659 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16660 	if (ire == NULL) {
16661 		/*
16662 		 * Mark this packet to make it be delivered to
16663 		 * ip_rput_forward after the new ire has been
16664 		 * created.
16665 		 */
16666 		mp->b_prev = NULL;
16667 		mp->b_next = mp;
16668 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16669 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16670 	} else {
16671 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16672 		IRE_REFRELE(ire);
16673 	}
16674 }
16675 
16676 /* Update any source route, record route or timestamp options */
16677 static int
16678 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16679 {
16680 	ipoptp_t	opts;
16681 	uchar_t		*opt;
16682 	uint8_t		optval;
16683 	uint8_t		optlen;
16684 	ipaddr_t	dst;
16685 	uint32_t	ts;
16686 	ire_t		*dst_ire = NULL;
16687 	ire_t		*tmp_ire = NULL;
16688 	timestruc_t	now;
16689 
16690 	ip2dbg(("ip_rput_forward_options\n"));
16691 	dst = ipha->ipha_dst;
16692 	for (optval = ipoptp_first(&opts, ipha);
16693 	    optval != IPOPT_EOL;
16694 	    optval = ipoptp_next(&opts)) {
16695 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16696 		opt = opts.ipoptp_cur;
16697 		optlen = opts.ipoptp_len;
16698 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16699 		    optval, opts.ipoptp_len));
16700 		switch (optval) {
16701 			uint32_t off;
16702 		case IPOPT_SSRR:
16703 		case IPOPT_LSRR:
16704 			/* Check if adminstratively disabled */
16705 			if (!ipst->ips_ip_forward_src_routed) {
16706 				if (ire->ire_stq != NULL) {
16707 					/*
16708 					 * Sent by forwarding path, and router
16709 					 * is global zone
16710 					 */
16711 					icmp_unreachable(ire->ire_stq, mp,
16712 					    ICMP_SOURCE_ROUTE_FAILED,
16713 					    GLOBAL_ZONEID, ipst);
16714 				} else {
16715 					ip0dbg(("ip_rput_forward_options: "
16716 					    "unable to send unreach\n"));
16717 					freemsg(mp);
16718 				}
16719 				return (-1);
16720 			}
16721 
16722 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16723 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16724 			if (dst_ire == NULL) {
16725 				/*
16726 				 * Must be partial since ip_rput_options
16727 				 * checked for strict.
16728 				 */
16729 				break;
16730 			}
16731 			off = opt[IPOPT_OFFSET];
16732 			off--;
16733 		redo_srr:
16734 			if (optlen < IP_ADDR_LEN ||
16735 			    off > optlen - IP_ADDR_LEN) {
16736 				/* End of source route */
16737 				ip1dbg((
16738 				    "ip_rput_forward_options: end of SR\n"));
16739 				ire_refrele(dst_ire);
16740 				break;
16741 			}
16742 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16743 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16744 			    IP_ADDR_LEN);
16745 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16746 			    ntohl(dst)));
16747 
16748 			/*
16749 			 * Check if our address is present more than
16750 			 * once as consecutive hops in source route.
16751 			 */
16752 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16753 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16754 			if (tmp_ire != NULL) {
16755 				ire_refrele(tmp_ire);
16756 				off += IP_ADDR_LEN;
16757 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16758 				goto redo_srr;
16759 			}
16760 			ipha->ipha_dst = dst;
16761 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16762 			ire_refrele(dst_ire);
16763 			break;
16764 		case IPOPT_RR:
16765 			off = opt[IPOPT_OFFSET];
16766 			off--;
16767 			if (optlen < IP_ADDR_LEN ||
16768 			    off > optlen - IP_ADDR_LEN) {
16769 				/* No more room - ignore */
16770 				ip1dbg((
16771 				    "ip_rput_forward_options: end of RR\n"));
16772 				break;
16773 			}
16774 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16775 			    IP_ADDR_LEN);
16776 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16777 			break;
16778 		case IPOPT_TS:
16779 			/* Insert timestamp if there is room */
16780 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16781 			case IPOPT_TS_TSONLY:
16782 				off = IPOPT_TS_TIMELEN;
16783 				break;
16784 			case IPOPT_TS_PRESPEC:
16785 			case IPOPT_TS_PRESPEC_RFC791:
16786 				/* Verify that the address matched */
16787 				off = opt[IPOPT_OFFSET] - 1;
16788 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16789 				dst_ire = ire_ctable_lookup(dst, 0,
16790 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16791 				    MATCH_IRE_TYPE, ipst);
16792 				if (dst_ire == NULL) {
16793 					/* Not for us */
16794 					break;
16795 				}
16796 				ire_refrele(dst_ire);
16797 				/* FALLTHRU */
16798 			case IPOPT_TS_TSANDADDR:
16799 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16800 				break;
16801 			default:
16802 				/*
16803 				 * ip_*put_options should have already
16804 				 * dropped this packet.
16805 				 */
16806 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16807 				    "unknown IT - bug in ip_rput_options?\n");
16808 				return (0);	/* Keep "lint" happy */
16809 			}
16810 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16811 				/* Increase overflow counter */
16812 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16813 				opt[IPOPT_POS_OV_FLG] =
16814 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16815 				    (off << 4));
16816 				break;
16817 			}
16818 			off = opt[IPOPT_OFFSET] - 1;
16819 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16820 			case IPOPT_TS_PRESPEC:
16821 			case IPOPT_TS_PRESPEC_RFC791:
16822 			case IPOPT_TS_TSANDADDR:
16823 				bcopy(&ire->ire_src_addr,
16824 				    (char *)opt + off, IP_ADDR_LEN);
16825 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16826 				/* FALLTHRU */
16827 			case IPOPT_TS_TSONLY:
16828 				off = opt[IPOPT_OFFSET] - 1;
16829 				/* Compute # of milliseconds since midnight */
16830 				gethrestime(&now);
16831 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16832 				    now.tv_nsec / (NANOSEC / MILLISEC);
16833 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16834 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16835 				break;
16836 			}
16837 			break;
16838 		}
16839 	}
16840 	return (0);
16841 }
16842 
16843 /*
16844  * This is called after processing at least one of AH/ESP headers.
16845  *
16846  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16847  * the actual, physical interface on which the packet was received,
16848  * but, when ip_strict_dst_multihoming is set to 1, could be the
16849  * interface which had the ipha_dst configured when the packet went
16850  * through ip_rput. The ill_index corresponding to the recv_ill
16851  * is saved in ipsec_in_rill_index
16852  *
16853  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16854  * cannot assume "ire" points to valid data for any IPv6 cases.
16855  */
16856 void
16857 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16858 {
16859 	mblk_t *mp;
16860 	ipaddr_t dst;
16861 	in6_addr_t *v6dstp;
16862 	ipha_t *ipha;
16863 	ip6_t *ip6h;
16864 	ipsec_in_t *ii;
16865 	boolean_t ill_need_rele = B_FALSE;
16866 	boolean_t rill_need_rele = B_FALSE;
16867 	boolean_t ire_need_rele = B_FALSE;
16868 	netstack_t	*ns;
16869 	ip_stack_t	*ipst;
16870 
16871 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16872 	ASSERT(ii->ipsec_in_ill_index != 0);
16873 	ns = ii->ipsec_in_ns;
16874 	ASSERT(ii->ipsec_in_ns != NULL);
16875 	ipst = ns->netstack_ip;
16876 
16877 	mp = ipsec_mp->b_cont;
16878 	ASSERT(mp != NULL);
16879 
16880 
16881 	if (ill == NULL) {
16882 		ASSERT(recv_ill == NULL);
16883 		/*
16884 		 * We need to get the original queue on which ip_rput_local
16885 		 * or ip_rput_data_v6 was called.
16886 		 */
16887 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16888 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16889 		ill_need_rele = B_TRUE;
16890 
16891 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16892 			recv_ill = ill_lookup_on_ifindex(
16893 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16894 			    NULL, NULL, NULL, NULL, ipst);
16895 			rill_need_rele = B_TRUE;
16896 		} else {
16897 			recv_ill = ill;
16898 		}
16899 
16900 		if ((ill == NULL) || (recv_ill == NULL)) {
16901 			ip0dbg(("ip_fanout_proto_again: interface "
16902 			    "disappeared\n"));
16903 			if (ill != NULL)
16904 				ill_refrele(ill);
16905 			if (recv_ill != NULL)
16906 				ill_refrele(recv_ill);
16907 			freemsg(ipsec_mp);
16908 			return;
16909 		}
16910 	}
16911 
16912 	ASSERT(ill != NULL && recv_ill != NULL);
16913 
16914 	if (mp->b_datap->db_type == M_CTL) {
16915 		/*
16916 		 * AH/ESP is returning the ICMP message after
16917 		 * removing their headers. Fanout again till
16918 		 * it gets to the right protocol.
16919 		 */
16920 		if (ii->ipsec_in_v4) {
16921 			icmph_t *icmph;
16922 			int iph_hdr_length;
16923 			int hdr_length;
16924 
16925 			ipha = (ipha_t *)mp->b_rptr;
16926 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16927 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16928 			ipha = (ipha_t *)&icmph[1];
16929 			hdr_length = IPH_HDR_LENGTH(ipha);
16930 			/*
16931 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16932 			 * Reset the type to M_DATA.
16933 			 */
16934 			mp->b_datap->db_type = M_DATA;
16935 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16936 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16937 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16938 		} else {
16939 			icmp6_t *icmp6;
16940 			int hdr_length;
16941 
16942 			ip6h = (ip6_t *)mp->b_rptr;
16943 			/* Don't call hdr_length_v6() unless you have to. */
16944 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16945 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16946 			else
16947 				hdr_length = IPV6_HDR_LEN;
16948 
16949 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16950 			/*
16951 			 * icmp_inbound_error_fanout_v6 may need to do
16952 			 * pullupmsg.  Reset the type to M_DATA.
16953 			 */
16954 			mp->b_datap->db_type = M_DATA;
16955 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16956 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16957 		}
16958 		if (ill_need_rele)
16959 			ill_refrele(ill);
16960 		if (rill_need_rele)
16961 			ill_refrele(recv_ill);
16962 		return;
16963 	}
16964 
16965 	if (ii->ipsec_in_v4) {
16966 		ipha = (ipha_t *)mp->b_rptr;
16967 		dst = ipha->ipha_dst;
16968 		if (CLASSD(dst)) {
16969 			/*
16970 			 * Multicast has to be delivered to all streams.
16971 			 */
16972 			dst = INADDR_BROADCAST;
16973 		}
16974 
16975 		if (ire == NULL) {
16976 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16977 			    MBLK_GETLABEL(mp), ipst);
16978 			if (ire == NULL) {
16979 				if (ill_need_rele)
16980 					ill_refrele(ill);
16981 				if (rill_need_rele)
16982 					ill_refrele(recv_ill);
16983 				ip1dbg(("ip_fanout_proto_again: "
16984 				    "IRE not found"));
16985 				freemsg(ipsec_mp);
16986 				return;
16987 			}
16988 			ire_need_rele = B_TRUE;
16989 		}
16990 
16991 		switch (ipha->ipha_protocol) {
16992 			case IPPROTO_UDP:
16993 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16994 				    recv_ill);
16995 				if (ire_need_rele)
16996 					ire_refrele(ire);
16997 				break;
16998 			case IPPROTO_TCP:
16999 				if (!ire_need_rele)
17000 					IRE_REFHOLD(ire);
17001 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17002 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17003 				IRE_REFRELE(ire);
17004 				if (mp != NULL)
17005 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17006 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17007 				break;
17008 			case IPPROTO_SCTP:
17009 				if (!ire_need_rele)
17010 					IRE_REFHOLD(ire);
17011 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17012 				    ipsec_mp, 0, ill->ill_rq, dst);
17013 				break;
17014 			default:
17015 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17016 				    recv_ill, B_FALSE);
17017 				if (ire_need_rele)
17018 					ire_refrele(ire);
17019 				break;
17020 		}
17021 	} else {
17022 		uint32_t rput_flags = 0;
17023 
17024 		ip6h = (ip6_t *)mp->b_rptr;
17025 		v6dstp = &ip6h->ip6_dst;
17026 		/*
17027 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17028 		 * address.
17029 		 *
17030 		 * Currently, we don't store that state in the IPSEC_IN
17031 		 * message, and we may need to.
17032 		 */
17033 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17034 		    IP6_IN_LLMCAST : 0);
17035 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17036 		    NULL, NULL);
17037 	}
17038 	if (ill_need_rele)
17039 		ill_refrele(ill);
17040 	if (rill_need_rele)
17041 		ill_refrele(recv_ill);
17042 }
17043 
17044 /*
17045  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17046  * returns 'true' if there are still fragments left on the queue, in
17047  * which case we restart the timer.
17048  */
17049 void
17050 ill_frag_timer(void *arg)
17051 {
17052 	ill_t	*ill = (ill_t *)arg;
17053 	boolean_t frag_pending;
17054 	ip_stack_t	*ipst = ill->ill_ipst;
17055 
17056 	mutex_enter(&ill->ill_lock);
17057 	ASSERT(!ill->ill_fragtimer_executing);
17058 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17059 		ill->ill_frag_timer_id = 0;
17060 		mutex_exit(&ill->ill_lock);
17061 		return;
17062 	}
17063 	ill->ill_fragtimer_executing = 1;
17064 	mutex_exit(&ill->ill_lock);
17065 
17066 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17067 
17068 	/*
17069 	 * Restart the timer, if we have fragments pending or if someone
17070 	 * wanted us to be scheduled again.
17071 	 */
17072 	mutex_enter(&ill->ill_lock);
17073 	ill->ill_fragtimer_executing = 0;
17074 	ill->ill_frag_timer_id = 0;
17075 	if (frag_pending || ill->ill_fragtimer_needrestart)
17076 		ill_frag_timer_start(ill);
17077 	mutex_exit(&ill->ill_lock);
17078 }
17079 
17080 void
17081 ill_frag_timer_start(ill_t *ill)
17082 {
17083 	ip_stack_t	*ipst = ill->ill_ipst;
17084 
17085 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17086 
17087 	/* If the ill is closing or opening don't proceed */
17088 	if (ill->ill_state_flags & ILL_CONDEMNED)
17089 		return;
17090 
17091 	if (ill->ill_fragtimer_executing) {
17092 		/*
17093 		 * ill_frag_timer is currently executing. Just record the
17094 		 * the fact that we want the timer to be restarted.
17095 		 * ill_frag_timer will post a timeout before it returns,
17096 		 * ensuring it will be called again.
17097 		 */
17098 		ill->ill_fragtimer_needrestart = 1;
17099 		return;
17100 	}
17101 
17102 	if (ill->ill_frag_timer_id == 0) {
17103 		/*
17104 		 * The timer is neither running nor is the timeout handler
17105 		 * executing. Post a timeout so that ill_frag_timer will be
17106 		 * called
17107 		 */
17108 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17109 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17110 		ill->ill_fragtimer_needrestart = 0;
17111 	}
17112 }
17113 
17114 /*
17115  * This routine is needed for loopback when forwarding multicasts.
17116  *
17117  * IPQoS Notes:
17118  * IPPF processing is done in fanout routines.
17119  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17120  * processing for IPsec packets is done when it comes back in clear.
17121  * NOTE : The callers of this function need to do the ire_refrele for the
17122  *	  ire that is being passed in.
17123  */
17124 void
17125 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17126     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17127 {
17128 	ill_t	*ill = (ill_t *)q->q_ptr;
17129 	uint32_t	sum;
17130 	uint32_t	u1;
17131 	uint32_t	u2;
17132 	int		hdr_length;
17133 	boolean_t	mctl_present;
17134 	mblk_t		*first_mp = mp;
17135 	mblk_t		*hada_mp = NULL;
17136 	ipha_t		*inner_ipha;
17137 	ip_stack_t	*ipst;
17138 
17139 	ASSERT(recv_ill != NULL);
17140 	ipst = recv_ill->ill_ipst;
17141 
17142 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17143 	    "ip_rput_locl_start: q %p", q);
17144 
17145 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17146 	ASSERT(ill != NULL);
17147 
17148 
17149 #define	rptr	((uchar_t *)ipha)
17150 #define	iphs	((uint16_t *)ipha)
17151 
17152 	/*
17153 	 * no UDP or TCP packet should come here anymore.
17154 	 */
17155 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17156 	    ipha->ipha_protocol != IPPROTO_UDP);
17157 
17158 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17159 	if (mctl_present &&
17160 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17161 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17162 
17163 		/*
17164 		 * It's an IPsec accelerated packet.
17165 		 * Keep a pointer to the data attributes around until
17166 		 * we allocate the ipsec_info_t.
17167 		 */
17168 		IPSECHW_DEBUG(IPSECHW_PKT,
17169 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17170 		hada_mp = first_mp;
17171 		hada_mp->b_cont = NULL;
17172 		/*
17173 		 * Since it is accelerated, it comes directly from
17174 		 * the ill and the data attributes is followed by
17175 		 * the packet data.
17176 		 */
17177 		ASSERT(mp->b_datap->db_type != M_CTL);
17178 		first_mp = mp;
17179 		mctl_present = B_FALSE;
17180 	}
17181 
17182 	/*
17183 	 * IF M_CTL is not present, then ipsec_in_is_secure
17184 	 * should return B_TRUE. There is a case where loopback
17185 	 * packets has an M_CTL in the front with all the
17186 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17187 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17188 	 * packets never comes here, it is safe to ASSERT the
17189 	 * following.
17190 	 */
17191 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17192 
17193 	/*
17194 	 * Also, we should never have an mctl_present if this is an
17195 	 * ESP-in-UDP packet.
17196 	 */
17197 	ASSERT(!mctl_present || !esp_in_udp_packet);
17198 
17199 
17200 	/* u1 is # words of IP options */
17201 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17202 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17203 
17204 	/*
17205 	 * Don't verify header checksum if we just removed UDP header or
17206 	 * packet is coming back from AH/ESP.
17207 	 */
17208 	if (!esp_in_udp_packet && !mctl_present) {
17209 		if (u1) {
17210 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17211 				if (hada_mp != NULL)
17212 					freemsg(hada_mp);
17213 				return;
17214 			}
17215 		} else {
17216 			/* Check the IP header checksum.  */
17217 #define	uph	((uint16_t *)ipha)
17218 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17219 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17220 #undef  uph
17221 			/* finish doing IP checksum */
17222 			sum = (sum & 0xFFFF) + (sum >> 16);
17223 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17224 			if (sum && sum != 0xFFFF) {
17225 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17226 				goto drop_pkt;
17227 			}
17228 		}
17229 	}
17230 
17231 	/*
17232 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17233 	 * might be called more than once for secure packets, count only
17234 	 * the first time.
17235 	 */
17236 	if (!mctl_present) {
17237 		UPDATE_IB_PKT_COUNT(ire);
17238 		ire->ire_last_used_time = lbolt;
17239 	}
17240 
17241 	/* Check for fragmentation offset. */
17242 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17243 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17244 	if (u1) {
17245 		/*
17246 		 * We re-assemble fragments before we do the AH/ESP
17247 		 * processing. Thus, M_CTL should not be present
17248 		 * while we are re-assembling.
17249 		 */
17250 		ASSERT(!mctl_present);
17251 		ASSERT(first_mp == mp);
17252 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17253 			return;
17254 		}
17255 		/*
17256 		 * Make sure that first_mp points back to mp as
17257 		 * the mp we came in with could have changed in
17258 		 * ip_rput_fragment().
17259 		 */
17260 		ipha = (ipha_t *)mp->b_rptr;
17261 		first_mp = mp;
17262 	}
17263 
17264 	/*
17265 	 * Clear hardware checksumming flag as it is currently only
17266 	 * used by TCP and UDP.
17267 	 */
17268 	DB_CKSUMFLAGS(mp) = 0;
17269 
17270 	/* Now we have a complete datagram, destined for this machine. */
17271 	u1 = IPH_HDR_LENGTH(ipha);
17272 	switch (ipha->ipha_protocol) {
17273 	case IPPROTO_ICMP: {
17274 		ire_t		*ire_zone;
17275 		ilm_t		*ilm;
17276 		mblk_t		*mp1;
17277 		zoneid_t	last_zoneid;
17278 
17279 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17280 			ASSERT(ire->ire_type == IRE_BROADCAST);
17281 			/*
17282 			 * In the multicast case, applications may have joined
17283 			 * the group from different zones, so we need to deliver
17284 			 * the packet to each of them. Loop through the
17285 			 * multicast memberships structures (ilm) on the receive
17286 			 * ill and send a copy of the packet up each matching
17287 			 * one. However, we don't do this for multicasts sent on
17288 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17289 			 * they must stay in the sender's zone.
17290 			 *
17291 			 * ilm_add_v6() ensures that ilms in the same zone are
17292 			 * contiguous in the ill_ilm list. We use this property
17293 			 * to avoid sending duplicates needed when two
17294 			 * applications in the same zone join the same group on
17295 			 * different logical interfaces: we ignore the ilm if
17296 			 * its zoneid is the same as the last matching one.
17297 			 * In addition, the sending of the packet for
17298 			 * ire_zoneid is delayed until all of the other ilms
17299 			 * have been exhausted.
17300 			 */
17301 			last_zoneid = -1;
17302 			ILM_WALKER_HOLD(recv_ill);
17303 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17304 			    ilm = ilm->ilm_next) {
17305 				if ((ilm->ilm_flags & ILM_DELETED) ||
17306 				    ipha->ipha_dst != ilm->ilm_addr ||
17307 				    ilm->ilm_zoneid == last_zoneid ||
17308 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17309 				    ilm->ilm_zoneid == ALL_ZONES ||
17310 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17311 					continue;
17312 				mp1 = ip_copymsg(first_mp);
17313 				if (mp1 == NULL)
17314 					continue;
17315 				icmp_inbound(q, mp1, B_TRUE, ill,
17316 				    0, sum, mctl_present, B_TRUE,
17317 				    recv_ill, ilm->ilm_zoneid);
17318 				last_zoneid = ilm->ilm_zoneid;
17319 			}
17320 			ILM_WALKER_RELE(recv_ill);
17321 		} else if (ire->ire_type == IRE_BROADCAST) {
17322 			/*
17323 			 * In the broadcast case, there may be many zones
17324 			 * which need a copy of the packet delivered to them.
17325 			 * There is one IRE_BROADCAST per broadcast address
17326 			 * and per zone; we walk those using a helper function.
17327 			 * In addition, the sending of the packet for ire is
17328 			 * delayed until all of the other ires have been
17329 			 * processed.
17330 			 */
17331 			IRB_REFHOLD(ire->ire_bucket);
17332 			ire_zone = NULL;
17333 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17334 			    ire)) != NULL) {
17335 				mp1 = ip_copymsg(first_mp);
17336 				if (mp1 == NULL)
17337 					continue;
17338 
17339 				UPDATE_IB_PKT_COUNT(ire_zone);
17340 				ire_zone->ire_last_used_time = lbolt;
17341 				icmp_inbound(q, mp1, B_TRUE, ill,
17342 				    0, sum, mctl_present, B_TRUE,
17343 				    recv_ill, ire_zone->ire_zoneid);
17344 			}
17345 			IRB_REFRELE(ire->ire_bucket);
17346 		}
17347 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17348 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17349 		    ire->ire_zoneid);
17350 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17351 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17352 		return;
17353 	}
17354 	case IPPROTO_IGMP:
17355 		/*
17356 		 * If we are not willing to accept IGMP packets in clear,
17357 		 * then check with global policy.
17358 		 */
17359 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17360 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17361 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17362 			if (first_mp == NULL)
17363 				return;
17364 		}
17365 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17366 			freemsg(first_mp);
17367 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17368 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17369 			return;
17370 		}
17371 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17372 			/* Bad packet - discarded by igmp_input */
17373 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17374 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17375 			if (mctl_present)
17376 				freeb(first_mp);
17377 			return;
17378 		}
17379 		/*
17380 		 * igmp_input() may have returned the pulled up message.
17381 		 * So first_mp and ipha need to be reinitialized.
17382 		 */
17383 		ipha = (ipha_t *)mp->b_rptr;
17384 		if (mctl_present)
17385 			first_mp->b_cont = mp;
17386 		else
17387 			first_mp = mp;
17388 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17389 		    connf_head != NULL) {
17390 			/* No user-level listener for IGMP packets */
17391 			goto drop_pkt;
17392 		}
17393 		/* deliver to local raw users */
17394 		break;
17395 	case IPPROTO_PIM:
17396 		/*
17397 		 * If we are not willing to accept PIM packets in clear,
17398 		 * then check with global policy.
17399 		 */
17400 		if (ipst->ips_pim_accept_clear_messages == 0) {
17401 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17402 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17403 			if (first_mp == NULL)
17404 				return;
17405 		}
17406 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17407 			freemsg(first_mp);
17408 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17409 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17410 			return;
17411 		}
17412 		if (pim_input(q, mp, ill) != 0) {
17413 			/* Bad packet - discarded by pim_input */
17414 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17415 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17416 			if (mctl_present)
17417 				freeb(first_mp);
17418 			return;
17419 		}
17420 
17421 		/*
17422 		 * pim_input() may have pulled up the message so ipha needs to
17423 		 * be reinitialized.
17424 		 */
17425 		ipha = (ipha_t *)mp->b_rptr;
17426 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17427 		    connf_head != NULL) {
17428 			/* No user-level listener for PIM packets */
17429 			goto drop_pkt;
17430 		}
17431 		/* deliver to local raw users */
17432 		break;
17433 	case IPPROTO_ENCAP:
17434 		/*
17435 		 * Handle self-encapsulated packets (IP-in-IP where
17436 		 * the inner addresses == the outer addresses).
17437 		 */
17438 		hdr_length = IPH_HDR_LENGTH(ipha);
17439 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17440 		    mp->b_wptr) {
17441 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17442 			    sizeof (ipha_t) - mp->b_rptr)) {
17443 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17444 				freemsg(first_mp);
17445 				return;
17446 			}
17447 			ipha = (ipha_t *)mp->b_rptr;
17448 		}
17449 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17450 		/*
17451 		 * Check the sanity of the inner IP header.
17452 		 */
17453 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17454 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17455 			freemsg(first_mp);
17456 			return;
17457 		}
17458 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17459 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17460 			freemsg(first_mp);
17461 			return;
17462 		}
17463 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17464 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17465 			ipsec_in_t *ii;
17466 
17467 			/*
17468 			 * Self-encapsulated tunnel packet. Remove
17469 			 * the outer IP header and fanout again.
17470 			 * We also need to make sure that the inner
17471 			 * header is pulled up until options.
17472 			 */
17473 			mp->b_rptr = (uchar_t *)inner_ipha;
17474 			ipha = inner_ipha;
17475 			hdr_length = IPH_HDR_LENGTH(ipha);
17476 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17477 				if (!pullupmsg(mp, (uchar_t *)ipha +
17478 				    + hdr_length - mp->b_rptr)) {
17479 					freemsg(first_mp);
17480 					return;
17481 				}
17482 				ipha = (ipha_t *)mp->b_rptr;
17483 			}
17484 			if (hdr_length > sizeof (ipha_t)) {
17485 				/* We got options on the inner packet. */
17486 				ipaddr_t dst = ipha->ipha_dst;
17487 
17488 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17489 				    -1) {
17490 					/* Bad options! */
17491 					return;
17492 				}
17493 				if (dst != ipha->ipha_dst) {
17494 					/*
17495 					 * Someone put a source-route in
17496 					 * the inside header of a self-
17497 					 * encapsulated packet.  Drop it
17498 					 * with extreme prejudice and let
17499 					 * the sender know.
17500 					 */
17501 					icmp_unreachable(q, first_mp,
17502 					    ICMP_SOURCE_ROUTE_FAILED,
17503 					    recv_ill->ill_zoneid, ipst);
17504 					return;
17505 				}
17506 			}
17507 			if (!mctl_present) {
17508 				ASSERT(first_mp == mp);
17509 				/*
17510 				 * This means that somebody is sending
17511 				 * Self-encapsualted packets without AH/ESP.
17512 				 * If AH/ESP was present, we would have already
17513 				 * allocated the first_mp.
17514 				 *
17515 				 * Send this packet to find a tunnel endpoint.
17516 				 * if I can't find one, an ICMP
17517 				 * PROTOCOL_UNREACHABLE will get sent.
17518 				 */
17519 				goto fanout;
17520 			}
17521 			/*
17522 			 * We generally store the ill_index if we need to
17523 			 * do IPsec processing as we lose the ill queue when
17524 			 * we come back. But in this case, we never should
17525 			 * have to store the ill_index here as it should have
17526 			 * been stored previously when we processed the
17527 			 * AH/ESP header in this routine or for non-ipsec
17528 			 * cases, we still have the queue. But for some bad
17529 			 * packets from the wire, we can get to IPsec after
17530 			 * this and we better store the index for that case.
17531 			 */
17532 			ill = (ill_t *)q->q_ptr;
17533 			ii = (ipsec_in_t *)first_mp->b_rptr;
17534 			ii->ipsec_in_ill_index =
17535 			    ill->ill_phyint->phyint_ifindex;
17536 			ii->ipsec_in_rill_index =
17537 			    recv_ill->ill_phyint->phyint_ifindex;
17538 			if (ii->ipsec_in_decaps) {
17539 				/*
17540 				 * This packet is self-encapsulated multiple
17541 				 * times. We don't want to recurse infinitely.
17542 				 * To keep it simple, drop the packet.
17543 				 */
17544 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17545 				freemsg(first_mp);
17546 				return;
17547 			}
17548 			ii->ipsec_in_decaps = B_TRUE;
17549 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17550 			    ire);
17551 			return;
17552 		}
17553 		break;
17554 	case IPPROTO_AH:
17555 	case IPPROTO_ESP: {
17556 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17557 
17558 		/*
17559 		 * Fast path for AH/ESP. If this is the first time
17560 		 * we are sending a datagram to AH/ESP, allocate
17561 		 * a IPSEC_IN message and prepend it. Otherwise,
17562 		 * just fanout.
17563 		 */
17564 
17565 		int ipsec_rc;
17566 		ipsec_in_t *ii;
17567 		netstack_t *ns = ipst->ips_netstack;
17568 
17569 		IP_STAT(ipst, ipsec_proto_ahesp);
17570 		if (!mctl_present) {
17571 			ASSERT(first_mp == mp);
17572 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17573 			if (first_mp == NULL) {
17574 				ip1dbg(("ip_proto_input: IPSEC_IN "
17575 				    "allocation failure.\n"));
17576 				freemsg(hada_mp); /* okay ifnull */
17577 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17578 				freemsg(mp);
17579 				return;
17580 			}
17581 			/*
17582 			 * Store the ill_index so that when we come back
17583 			 * from IPsec we ride on the same queue.
17584 			 */
17585 			ill = (ill_t *)q->q_ptr;
17586 			ii = (ipsec_in_t *)first_mp->b_rptr;
17587 			ii->ipsec_in_ill_index =
17588 			    ill->ill_phyint->phyint_ifindex;
17589 			ii->ipsec_in_rill_index =
17590 			    recv_ill->ill_phyint->phyint_ifindex;
17591 			first_mp->b_cont = mp;
17592 			/*
17593 			 * Cache hardware acceleration info.
17594 			 */
17595 			if (hada_mp != NULL) {
17596 				IPSECHW_DEBUG(IPSECHW_PKT,
17597 				    ("ip_rput_local: caching data attr.\n"));
17598 				ii->ipsec_in_accelerated = B_TRUE;
17599 				ii->ipsec_in_da = hada_mp;
17600 				hada_mp = NULL;
17601 			}
17602 		} else {
17603 			ii = (ipsec_in_t *)first_mp->b_rptr;
17604 		}
17605 
17606 		if (!ipsec_loaded(ipss)) {
17607 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17608 			    ire->ire_zoneid, ipst);
17609 			return;
17610 		}
17611 
17612 		ns = ipst->ips_netstack;
17613 		/* select inbound SA and have IPsec process the pkt */
17614 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17615 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17616 			boolean_t esp_in_udp_sa;
17617 			if (esph == NULL)
17618 				return;
17619 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17620 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17621 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17622 			    IPSA_F_NATT) != 0);
17623 			/*
17624 			 * The following is a fancy, but quick, way of saying:
17625 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17626 			 *    OR
17627 			 * ESP SA and ESP-in-UDP packet --> drop
17628 			 */
17629 			if (esp_in_udp_sa != esp_in_udp_packet) {
17630 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17631 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17632 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17633 				    &ns->netstack_ipsec->ipsec_dropper);
17634 				return;
17635 			}
17636 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17637 			    first_mp, esph);
17638 		} else {
17639 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17640 			if (ah == NULL)
17641 				return;
17642 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17643 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17644 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17645 			    first_mp, ah);
17646 		}
17647 
17648 		switch (ipsec_rc) {
17649 		case IPSEC_STATUS_SUCCESS:
17650 			break;
17651 		case IPSEC_STATUS_FAILED:
17652 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17653 			/* FALLTHRU */
17654 		case IPSEC_STATUS_PENDING:
17655 			return;
17656 		}
17657 		/* we're done with IPsec processing, send it up */
17658 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17659 		return;
17660 	}
17661 	default:
17662 		break;
17663 	}
17664 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17665 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17666 		    ire->ire_zoneid));
17667 		goto drop_pkt;
17668 	}
17669 	/*
17670 	 * Handle protocols with which IP is less intimate.  There
17671 	 * can be more than one stream bound to a particular
17672 	 * protocol.  When this is the case, each one gets a copy
17673 	 * of any incoming packets.
17674 	 */
17675 fanout:
17676 	ip_fanout_proto(q, first_mp, ill, ipha,
17677 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17678 	    B_TRUE, recv_ill, ire->ire_zoneid);
17679 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17680 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17681 	return;
17682 
17683 drop_pkt:
17684 	freemsg(first_mp);
17685 	if (hada_mp != NULL)
17686 		freeb(hada_mp);
17687 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17688 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17689 #undef	rptr
17690 #undef  iphs
17691 
17692 }
17693 
17694 /*
17695  * Update any source route, record route or timestamp options.
17696  * Check that we are at end of strict source route.
17697  * The options have already been checked for sanity in ip_rput_options().
17698  */
17699 static boolean_t
17700 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17701     ip_stack_t *ipst)
17702 {
17703 	ipoptp_t	opts;
17704 	uchar_t		*opt;
17705 	uint8_t		optval;
17706 	uint8_t		optlen;
17707 	ipaddr_t	dst;
17708 	uint32_t	ts;
17709 	ire_t		*dst_ire;
17710 	timestruc_t	now;
17711 	zoneid_t	zoneid;
17712 	ill_t		*ill;
17713 
17714 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17715 
17716 	ip2dbg(("ip_rput_local_options\n"));
17717 
17718 	for (optval = ipoptp_first(&opts, ipha);
17719 	    optval != IPOPT_EOL;
17720 	    optval = ipoptp_next(&opts)) {
17721 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17722 		opt = opts.ipoptp_cur;
17723 		optlen = opts.ipoptp_len;
17724 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17725 		    optval, optlen));
17726 		switch (optval) {
17727 			uint32_t off;
17728 		case IPOPT_SSRR:
17729 		case IPOPT_LSRR:
17730 			off = opt[IPOPT_OFFSET];
17731 			off--;
17732 			if (optlen < IP_ADDR_LEN ||
17733 			    off > optlen - IP_ADDR_LEN) {
17734 				/* End of source route */
17735 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17736 				break;
17737 			}
17738 			/*
17739 			 * This will only happen if two consecutive entries
17740 			 * in the source route contains our address or if
17741 			 * it is a packet with a loose source route which
17742 			 * reaches us before consuming the whole source route
17743 			 */
17744 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17745 			if (optval == IPOPT_SSRR) {
17746 				goto bad_src_route;
17747 			}
17748 			/*
17749 			 * Hack: instead of dropping the packet truncate the
17750 			 * source route to what has been used by filling the
17751 			 * rest with IPOPT_NOP.
17752 			 */
17753 			opt[IPOPT_OLEN] = (uint8_t)off;
17754 			while (off < optlen) {
17755 				opt[off++] = IPOPT_NOP;
17756 			}
17757 			break;
17758 		case IPOPT_RR:
17759 			off = opt[IPOPT_OFFSET];
17760 			off--;
17761 			if (optlen < IP_ADDR_LEN ||
17762 			    off > optlen - IP_ADDR_LEN) {
17763 				/* No more room - ignore */
17764 				ip1dbg((
17765 				    "ip_rput_local_options: end of RR\n"));
17766 				break;
17767 			}
17768 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17769 			    IP_ADDR_LEN);
17770 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17771 			break;
17772 		case IPOPT_TS:
17773 			/* Insert timestamp if there is romm */
17774 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17775 			case IPOPT_TS_TSONLY:
17776 				off = IPOPT_TS_TIMELEN;
17777 				break;
17778 			case IPOPT_TS_PRESPEC:
17779 			case IPOPT_TS_PRESPEC_RFC791:
17780 				/* Verify that the address matched */
17781 				off = opt[IPOPT_OFFSET] - 1;
17782 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17783 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17784 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17785 				    ipst);
17786 				if (dst_ire == NULL) {
17787 					/* Not for us */
17788 					break;
17789 				}
17790 				ire_refrele(dst_ire);
17791 				/* FALLTHRU */
17792 			case IPOPT_TS_TSANDADDR:
17793 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17794 				break;
17795 			default:
17796 				/*
17797 				 * ip_*put_options should have already
17798 				 * dropped this packet.
17799 				 */
17800 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17801 				    "unknown IT - bug in ip_rput_options?\n");
17802 				return (B_TRUE);	/* Keep "lint" happy */
17803 			}
17804 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17805 				/* Increase overflow counter */
17806 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17807 				opt[IPOPT_POS_OV_FLG] =
17808 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17809 				    (off << 4));
17810 				break;
17811 			}
17812 			off = opt[IPOPT_OFFSET] - 1;
17813 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17814 			case IPOPT_TS_PRESPEC:
17815 			case IPOPT_TS_PRESPEC_RFC791:
17816 			case IPOPT_TS_TSANDADDR:
17817 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17818 				    IP_ADDR_LEN);
17819 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17820 				/* FALLTHRU */
17821 			case IPOPT_TS_TSONLY:
17822 				off = opt[IPOPT_OFFSET] - 1;
17823 				/* Compute # of milliseconds since midnight */
17824 				gethrestime(&now);
17825 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17826 				    now.tv_nsec / (NANOSEC / MILLISEC);
17827 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17828 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17829 				break;
17830 			}
17831 			break;
17832 		}
17833 	}
17834 	return (B_TRUE);
17835 
17836 bad_src_route:
17837 	q = WR(q);
17838 	if (q->q_next != NULL)
17839 		ill = q->q_ptr;
17840 	else
17841 		ill = NULL;
17842 
17843 	/* make sure we clear any indication of a hardware checksum */
17844 	DB_CKSUMFLAGS(mp) = 0;
17845 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17846 	if (zoneid == ALL_ZONES)
17847 		freemsg(mp);
17848 	else
17849 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17850 	return (B_FALSE);
17851 
17852 }
17853 
17854 /*
17855  * Process IP options in an inbound packet.  If an option affects the
17856  * effective destination address, return the next hop address via dstp.
17857  * Returns -1 if something fails in which case an ICMP error has been sent
17858  * and mp freed.
17859  */
17860 static int
17861 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17862     ip_stack_t *ipst)
17863 {
17864 	ipoptp_t	opts;
17865 	uchar_t		*opt;
17866 	uint8_t		optval;
17867 	uint8_t		optlen;
17868 	ipaddr_t	dst;
17869 	intptr_t	code = 0;
17870 	ire_t		*ire = NULL;
17871 	zoneid_t	zoneid;
17872 	ill_t		*ill;
17873 
17874 	ip2dbg(("ip_rput_options\n"));
17875 	dst = ipha->ipha_dst;
17876 	for (optval = ipoptp_first(&opts, ipha);
17877 	    optval != IPOPT_EOL;
17878 	    optval = ipoptp_next(&opts)) {
17879 		opt = opts.ipoptp_cur;
17880 		optlen = opts.ipoptp_len;
17881 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17882 		    optval, optlen));
17883 		/*
17884 		 * Note: we need to verify the checksum before we
17885 		 * modify anything thus this routine only extracts the next
17886 		 * hop dst from any source route.
17887 		 */
17888 		switch (optval) {
17889 			uint32_t off;
17890 		case IPOPT_SSRR:
17891 		case IPOPT_LSRR:
17892 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17893 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17894 			if (ire == NULL) {
17895 				if (optval == IPOPT_SSRR) {
17896 					ip1dbg(("ip_rput_options: not next"
17897 					    " strict source route 0x%x\n",
17898 					    ntohl(dst)));
17899 					code = (char *)&ipha->ipha_dst -
17900 					    (char *)ipha;
17901 					goto param_prob; /* RouterReq's */
17902 				}
17903 				ip2dbg(("ip_rput_options: "
17904 				    "not next source route 0x%x\n",
17905 				    ntohl(dst)));
17906 				break;
17907 			}
17908 			ire_refrele(ire);
17909 
17910 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17911 				ip1dbg((
17912 				    "ip_rput_options: bad option offset\n"));
17913 				code = (char *)&opt[IPOPT_OLEN] -
17914 				    (char *)ipha;
17915 				goto param_prob;
17916 			}
17917 			off = opt[IPOPT_OFFSET];
17918 			off--;
17919 		redo_srr:
17920 			if (optlen < IP_ADDR_LEN ||
17921 			    off > optlen - IP_ADDR_LEN) {
17922 				/* End of source route */
17923 				ip1dbg(("ip_rput_options: end of SR\n"));
17924 				break;
17925 			}
17926 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17927 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17928 			    ntohl(dst)));
17929 
17930 			/*
17931 			 * Check if our address is present more than
17932 			 * once as consecutive hops in source route.
17933 			 * XXX verify per-interface ip_forwarding
17934 			 * for source route?
17935 			 */
17936 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17937 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17938 
17939 			if (ire != NULL) {
17940 				ire_refrele(ire);
17941 				off += IP_ADDR_LEN;
17942 				goto redo_srr;
17943 			}
17944 
17945 			if (dst == htonl(INADDR_LOOPBACK)) {
17946 				ip1dbg(("ip_rput_options: loopback addr in "
17947 				    "source route!\n"));
17948 				goto bad_src_route;
17949 			}
17950 			/*
17951 			 * For strict: verify that dst is directly
17952 			 * reachable.
17953 			 */
17954 			if (optval == IPOPT_SSRR) {
17955 				ire = ire_ftable_lookup(dst, 0, 0,
17956 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17957 				    MBLK_GETLABEL(mp),
17958 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17959 				if (ire == NULL) {
17960 					ip1dbg(("ip_rput_options: SSRR not "
17961 					    "directly reachable: 0x%x\n",
17962 					    ntohl(dst)));
17963 					goto bad_src_route;
17964 				}
17965 				ire_refrele(ire);
17966 			}
17967 			/*
17968 			 * Defer update of the offset and the record route
17969 			 * until the packet is forwarded.
17970 			 */
17971 			break;
17972 		case IPOPT_RR:
17973 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17974 				ip1dbg((
17975 				    "ip_rput_options: bad option offset\n"));
17976 				code = (char *)&opt[IPOPT_OLEN] -
17977 				    (char *)ipha;
17978 				goto param_prob;
17979 			}
17980 			break;
17981 		case IPOPT_TS:
17982 			/*
17983 			 * Verify that length >= 5 and that there is either
17984 			 * room for another timestamp or that the overflow
17985 			 * counter is not maxed out.
17986 			 */
17987 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17988 			if (optlen < IPOPT_MINLEN_IT) {
17989 				goto param_prob;
17990 			}
17991 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17992 				ip1dbg((
17993 				    "ip_rput_options: bad option offset\n"));
17994 				code = (char *)&opt[IPOPT_OFFSET] -
17995 				    (char *)ipha;
17996 				goto param_prob;
17997 			}
17998 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17999 			case IPOPT_TS_TSONLY:
18000 				off = IPOPT_TS_TIMELEN;
18001 				break;
18002 			case IPOPT_TS_TSANDADDR:
18003 			case IPOPT_TS_PRESPEC:
18004 			case IPOPT_TS_PRESPEC_RFC791:
18005 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18006 				break;
18007 			default:
18008 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18009 				    (char *)ipha;
18010 				goto param_prob;
18011 			}
18012 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18013 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18014 				/*
18015 				 * No room and the overflow counter is 15
18016 				 * already.
18017 				 */
18018 				goto param_prob;
18019 			}
18020 			break;
18021 		}
18022 	}
18023 
18024 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18025 		*dstp = dst;
18026 		return (0);
18027 	}
18028 
18029 	ip1dbg(("ip_rput_options: error processing IP options."));
18030 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18031 
18032 param_prob:
18033 	q = WR(q);
18034 	if (q->q_next != NULL)
18035 		ill = q->q_ptr;
18036 	else
18037 		ill = NULL;
18038 
18039 	/* make sure we clear any indication of a hardware checksum */
18040 	DB_CKSUMFLAGS(mp) = 0;
18041 	/* Don't know whether this is for non-global or global/forwarding */
18042 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18043 	if (zoneid == ALL_ZONES)
18044 		freemsg(mp);
18045 	else
18046 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18047 	return (-1);
18048 
18049 bad_src_route:
18050 	q = WR(q);
18051 	if (q->q_next != NULL)
18052 		ill = q->q_ptr;
18053 	else
18054 		ill = NULL;
18055 
18056 	/* make sure we clear any indication of a hardware checksum */
18057 	DB_CKSUMFLAGS(mp) = 0;
18058 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18059 	if (zoneid == ALL_ZONES)
18060 		freemsg(mp);
18061 	else
18062 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18063 	return (-1);
18064 }
18065 
18066 /*
18067  * IP & ICMP info in >=14 msg's ...
18068  *  - ip fixed part (mib2_ip_t)
18069  *  - icmp fixed part (mib2_icmp_t)
18070  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18071  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18072  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18073  *  - ipRouteAttributeTable (ip 102)	labeled routes
18074  *  - ip multicast membership (ip_member_t)
18075  *  - ip multicast source filtering (ip_grpsrc_t)
18076  *  - igmp fixed part (struct igmpstat)
18077  *  - multicast routing stats (struct mrtstat)
18078  *  - multicast routing vifs (array of struct vifctl)
18079  *  - multicast routing routes (array of struct mfcctl)
18080  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18081  *					One per ill plus one generic
18082  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18083  *					One per ill plus one generic
18084  *  - ipv6RouteEntry			all IPv6 IREs
18085  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18086  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18087  *  - ipv6AddrEntry			all IPv6 ipifs
18088  *  - ipv6 multicast membership (ipv6_member_t)
18089  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18090  *
18091  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18092  *
18093  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18094  * already filled in by the caller.
18095  * Return value of 0 indicates that no messages were sent and caller
18096  * should free mpctl.
18097  */
18098 int
18099 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18100 {
18101 	ip_stack_t *ipst;
18102 	sctp_stack_t *sctps;
18103 
18104 	if (q->q_next != NULL) {
18105 		ipst = ILLQ_TO_IPST(q);
18106 	} else {
18107 		ipst = CONNQ_TO_IPST(q);
18108 	}
18109 	ASSERT(ipst != NULL);
18110 	sctps = ipst->ips_netstack->netstack_sctp;
18111 
18112 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18113 		return (0);
18114 	}
18115 
18116 	/*
18117 	 * For the purposes of the (broken) packet shell use
18118 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18119 	 * to make TCP and UDP appear first in the list of mib items.
18120 	 * TBD: We could expand this and use it in netstat so that
18121 	 * the kernel doesn't have to produce large tables (connections,
18122 	 * routes, etc) when netstat only wants the statistics or a particular
18123 	 * table.
18124 	 */
18125 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18126 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18127 			return (1);
18128 		}
18129 	}
18130 
18131 	if (level != MIB2_TCP) {
18132 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18133 			return (1);
18134 		}
18135 	}
18136 
18137 	if (level != MIB2_UDP) {
18138 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18139 			return (1);
18140 		}
18141 	}
18142 
18143 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18144 	    ipst)) == NULL) {
18145 		return (1);
18146 	}
18147 
18148 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18149 		return (1);
18150 	}
18151 
18152 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18153 		return (1);
18154 	}
18155 
18156 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18157 		return (1);
18158 	}
18159 
18160 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18161 		return (1);
18162 	}
18163 
18164 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18165 		return (1);
18166 	}
18167 
18168 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18169 		return (1);
18170 	}
18171 
18172 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18173 		return (1);
18174 	}
18175 
18176 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18177 		return (1);
18178 	}
18179 
18180 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18181 		return (1);
18182 	}
18183 
18184 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18185 		return (1);
18186 	}
18187 
18188 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18189 		return (1);
18190 	}
18191 
18192 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18193 		return (1);
18194 	}
18195 
18196 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18197 		return (1);
18198 	}
18199 
18200 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18201 		return (1);
18202 	}
18203 
18204 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18205 	if (mpctl == NULL) {
18206 		return (1);
18207 	}
18208 
18209 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18210 		return (1);
18211 	}
18212 	freemsg(mpctl);
18213 	return (1);
18214 }
18215 
18216 
18217 /* Get global (legacy) IPv4 statistics */
18218 static mblk_t *
18219 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18220     ip_stack_t *ipst)
18221 {
18222 	mib2_ip_t		old_ip_mib;
18223 	struct opthdr		*optp;
18224 	mblk_t			*mp2ctl;
18225 
18226 	/*
18227 	 * make a copy of the original message
18228 	 */
18229 	mp2ctl = copymsg(mpctl);
18230 
18231 	/* fixed length IP structure... */
18232 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18233 	optp->level = MIB2_IP;
18234 	optp->name = 0;
18235 	SET_MIB(old_ip_mib.ipForwarding,
18236 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18237 	SET_MIB(old_ip_mib.ipDefaultTTL,
18238 	    (uint32_t)ipst->ips_ip_def_ttl);
18239 	SET_MIB(old_ip_mib.ipReasmTimeout,
18240 	    ipst->ips_ip_g_frag_timeout);
18241 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18242 	    sizeof (mib2_ipAddrEntry_t));
18243 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18244 	    sizeof (mib2_ipRouteEntry_t));
18245 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18246 	    sizeof (mib2_ipNetToMediaEntry_t));
18247 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18248 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18249 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18250 	    sizeof (mib2_ipAttributeEntry_t));
18251 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18252 
18253 	/*
18254 	 * Grab the statistics from the new IP MIB
18255 	 */
18256 	SET_MIB(old_ip_mib.ipInReceives,
18257 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18258 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18259 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18260 	SET_MIB(old_ip_mib.ipForwDatagrams,
18261 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18262 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18263 	    ipmib->ipIfStatsInUnknownProtos);
18264 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18265 	SET_MIB(old_ip_mib.ipInDelivers,
18266 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18267 	SET_MIB(old_ip_mib.ipOutRequests,
18268 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18269 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18270 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18271 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18272 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18273 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18274 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18275 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18276 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18277 
18278 	/* ipRoutingDiscards is not being used */
18279 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18280 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18281 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18282 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18283 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18284 	    ipmib->ipIfStatsReasmDuplicates);
18285 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18286 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18287 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18288 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18289 	SET_MIB(old_ip_mib.rawipInOverflows,
18290 	    ipmib->rawipIfStatsInOverflows);
18291 
18292 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18293 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18294 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18295 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18296 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18297 	    ipmib->ipIfStatsOutSwitchIPVersion);
18298 
18299 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18300 	    (int)sizeof (old_ip_mib))) {
18301 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18302 		    (uint_t)sizeof (old_ip_mib)));
18303 	}
18304 
18305 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18306 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18307 	    (int)optp->level, (int)optp->name, (int)optp->len));
18308 	qreply(q, mpctl);
18309 	return (mp2ctl);
18310 }
18311 
18312 /* Per interface IPv4 statistics */
18313 static mblk_t *
18314 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18315 {
18316 	struct opthdr		*optp;
18317 	mblk_t			*mp2ctl;
18318 	ill_t			*ill;
18319 	ill_walk_context_t	ctx;
18320 	mblk_t			*mp_tail = NULL;
18321 	mib2_ipIfStatsEntry_t	global_ip_mib;
18322 
18323 	/*
18324 	 * Make a copy of the original message
18325 	 */
18326 	mp2ctl = copymsg(mpctl);
18327 
18328 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18329 	optp->level = MIB2_IP;
18330 	optp->name = MIB2_IP_TRAFFIC_STATS;
18331 	/* Include "unknown interface" ip_mib */
18332 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18333 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18334 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18335 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18336 	    (ipst->ips_ip_g_forward ? 1 : 2));
18337 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18338 	    (uint32_t)ipst->ips_ip_def_ttl);
18339 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18340 	    sizeof (mib2_ipIfStatsEntry_t));
18341 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18342 	    sizeof (mib2_ipAddrEntry_t));
18343 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18344 	    sizeof (mib2_ipRouteEntry_t));
18345 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18346 	    sizeof (mib2_ipNetToMediaEntry_t));
18347 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18348 	    sizeof (ip_member_t));
18349 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18350 	    sizeof (ip_grpsrc_t));
18351 
18352 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18353 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18354 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18355 		    "failed to allocate %u bytes\n",
18356 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18357 	}
18358 
18359 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18360 
18361 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18362 	ill = ILL_START_WALK_V4(&ctx, ipst);
18363 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18364 		ill->ill_ip_mib->ipIfStatsIfIndex =
18365 		    ill->ill_phyint->phyint_ifindex;
18366 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18367 		    (ipst->ips_ip_g_forward ? 1 : 2));
18368 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18369 		    (uint32_t)ipst->ips_ip_def_ttl);
18370 
18371 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18372 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18373 		    (char *)ill->ill_ip_mib,
18374 		    (int)sizeof (*ill->ill_ip_mib))) {
18375 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18376 			    "failed to allocate %u bytes\n",
18377 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18378 		}
18379 	}
18380 	rw_exit(&ipst->ips_ill_g_lock);
18381 
18382 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18383 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18384 	    "level %d, name %d, len %d\n",
18385 	    (int)optp->level, (int)optp->name, (int)optp->len));
18386 	qreply(q, mpctl);
18387 
18388 	if (mp2ctl == NULL)
18389 		return (NULL);
18390 
18391 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18392 }
18393 
18394 /* Global IPv4 ICMP statistics */
18395 static mblk_t *
18396 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18397 {
18398 	struct opthdr		*optp;
18399 	mblk_t			*mp2ctl;
18400 
18401 	/*
18402 	 * Make a copy of the original message
18403 	 */
18404 	mp2ctl = copymsg(mpctl);
18405 
18406 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18407 	optp->level = MIB2_ICMP;
18408 	optp->name = 0;
18409 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18410 	    (int)sizeof (ipst->ips_icmp_mib))) {
18411 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18412 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18413 	}
18414 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18415 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18416 	    (int)optp->level, (int)optp->name, (int)optp->len));
18417 	qreply(q, mpctl);
18418 	return (mp2ctl);
18419 }
18420 
18421 /* Global IPv4 IGMP statistics */
18422 static mblk_t *
18423 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18424 {
18425 	struct opthdr		*optp;
18426 	mblk_t			*mp2ctl;
18427 
18428 	/*
18429 	 * make a copy of the original message
18430 	 */
18431 	mp2ctl = copymsg(mpctl);
18432 
18433 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18434 	optp->level = EXPER_IGMP;
18435 	optp->name = 0;
18436 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18437 	    (int)sizeof (ipst->ips_igmpstat))) {
18438 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18439 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18440 	}
18441 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18442 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18443 	    (int)optp->level, (int)optp->name, (int)optp->len));
18444 	qreply(q, mpctl);
18445 	return (mp2ctl);
18446 }
18447 
18448 /* Global IPv4 Multicast Routing statistics */
18449 static mblk_t *
18450 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18451 {
18452 	struct opthdr		*optp;
18453 	mblk_t			*mp2ctl;
18454 
18455 	/*
18456 	 * make a copy of the original message
18457 	 */
18458 	mp2ctl = copymsg(mpctl);
18459 
18460 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18461 	optp->level = EXPER_DVMRP;
18462 	optp->name = 0;
18463 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18464 		ip0dbg(("ip_mroute_stats: failed\n"));
18465 	}
18466 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18467 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18468 	    (int)optp->level, (int)optp->name, (int)optp->len));
18469 	qreply(q, mpctl);
18470 	return (mp2ctl);
18471 }
18472 
18473 /* IPv4 address information */
18474 static mblk_t *
18475 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18476 {
18477 	struct opthdr		*optp;
18478 	mblk_t			*mp2ctl;
18479 	mblk_t			*mp_tail = NULL;
18480 	ill_t			*ill;
18481 	ipif_t			*ipif;
18482 	uint_t			bitval;
18483 	mib2_ipAddrEntry_t	mae;
18484 	zoneid_t		zoneid;
18485 	ill_walk_context_t ctx;
18486 
18487 	/*
18488 	 * make a copy of the original message
18489 	 */
18490 	mp2ctl = copymsg(mpctl);
18491 
18492 	/* ipAddrEntryTable */
18493 
18494 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18495 	optp->level = MIB2_IP;
18496 	optp->name = MIB2_IP_ADDR;
18497 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18498 
18499 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18500 	ill = ILL_START_WALK_V4(&ctx, ipst);
18501 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18502 		for (ipif = ill->ill_ipif; ipif != NULL;
18503 		    ipif = ipif->ipif_next) {
18504 			if (ipif->ipif_zoneid != zoneid &&
18505 			    ipif->ipif_zoneid != ALL_ZONES)
18506 				continue;
18507 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18508 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18509 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18510 
18511 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18512 			    OCTET_LENGTH);
18513 			mae.ipAdEntIfIndex.o_length =
18514 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18515 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18516 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18517 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18518 			mae.ipAdEntInfo.ae_subnet_len =
18519 			    ip_mask_to_plen(ipif->ipif_net_mask);
18520 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18521 			for (bitval = 1;
18522 			    bitval &&
18523 			    !(bitval & ipif->ipif_brd_addr);
18524 			    bitval <<= 1)
18525 				noop;
18526 			mae.ipAdEntBcastAddr = bitval;
18527 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18528 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18529 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18530 			mae.ipAdEntInfo.ae_broadcast_addr =
18531 			    ipif->ipif_brd_addr;
18532 			mae.ipAdEntInfo.ae_pp_dst_addr =
18533 			    ipif->ipif_pp_dst_addr;
18534 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18535 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18536 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18537 
18538 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18539 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18540 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18541 				    "allocate %u bytes\n",
18542 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18543 			}
18544 		}
18545 	}
18546 	rw_exit(&ipst->ips_ill_g_lock);
18547 
18548 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18549 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18550 	    (int)optp->level, (int)optp->name, (int)optp->len));
18551 	qreply(q, mpctl);
18552 	return (mp2ctl);
18553 }
18554 
18555 /* IPv6 address information */
18556 static mblk_t *
18557 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18558 {
18559 	struct opthdr		*optp;
18560 	mblk_t			*mp2ctl;
18561 	mblk_t			*mp_tail = NULL;
18562 	ill_t			*ill;
18563 	ipif_t			*ipif;
18564 	mib2_ipv6AddrEntry_t	mae6;
18565 	zoneid_t		zoneid;
18566 	ill_walk_context_t	ctx;
18567 
18568 	/*
18569 	 * make a copy of the original message
18570 	 */
18571 	mp2ctl = copymsg(mpctl);
18572 
18573 	/* ipv6AddrEntryTable */
18574 
18575 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18576 	optp->level = MIB2_IP6;
18577 	optp->name = MIB2_IP6_ADDR;
18578 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18579 
18580 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18581 	ill = ILL_START_WALK_V6(&ctx, ipst);
18582 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18583 		for (ipif = ill->ill_ipif; ipif != NULL;
18584 		    ipif = ipif->ipif_next) {
18585 			if (ipif->ipif_zoneid != zoneid &&
18586 			    ipif->ipif_zoneid != ALL_ZONES)
18587 				continue;
18588 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18589 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18590 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18591 
18592 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18593 			    OCTET_LENGTH);
18594 			mae6.ipv6AddrIfIndex.o_length =
18595 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18596 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18597 			mae6.ipv6AddrPfxLength =
18598 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18599 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18600 			mae6.ipv6AddrInfo.ae_subnet_len =
18601 			    mae6.ipv6AddrPfxLength;
18602 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18603 
18604 			/* Type: stateless(1), stateful(2), unknown(3) */
18605 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18606 				mae6.ipv6AddrType = 1;
18607 			else
18608 				mae6.ipv6AddrType = 2;
18609 			/* Anycast: true(1), false(2) */
18610 			if (ipif->ipif_flags & IPIF_ANYCAST)
18611 				mae6.ipv6AddrAnycastFlag = 1;
18612 			else
18613 				mae6.ipv6AddrAnycastFlag = 2;
18614 
18615 			/*
18616 			 * Address status: preferred(1), deprecated(2),
18617 			 * invalid(3), inaccessible(4), unknown(5)
18618 			 */
18619 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18620 				mae6.ipv6AddrStatus = 3;
18621 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18622 				mae6.ipv6AddrStatus = 2;
18623 			else
18624 				mae6.ipv6AddrStatus = 1;
18625 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18626 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18627 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18628 			    ipif->ipif_v6pp_dst_addr;
18629 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18630 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18631 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18632 			mae6.ipv6AddrIdentifier = ill->ill_token;
18633 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18634 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18635 			mae6.ipv6AddrRetransmitTime =
18636 			    ill->ill_reachable_retrans_time;
18637 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18638 			    (char *)&mae6,
18639 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18640 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18641 				    "allocate %u bytes\n",
18642 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18643 			}
18644 		}
18645 	}
18646 	rw_exit(&ipst->ips_ill_g_lock);
18647 
18648 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18649 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18650 	    (int)optp->level, (int)optp->name, (int)optp->len));
18651 	qreply(q, mpctl);
18652 	return (mp2ctl);
18653 }
18654 
18655 /* IPv4 multicast group membership. */
18656 static mblk_t *
18657 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18658 {
18659 	struct opthdr		*optp;
18660 	mblk_t			*mp2ctl;
18661 	ill_t			*ill;
18662 	ipif_t			*ipif;
18663 	ilm_t			*ilm;
18664 	ip_member_t		ipm;
18665 	mblk_t			*mp_tail = NULL;
18666 	ill_walk_context_t	ctx;
18667 	zoneid_t		zoneid;
18668 
18669 	/*
18670 	 * make a copy of the original message
18671 	 */
18672 	mp2ctl = copymsg(mpctl);
18673 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18674 
18675 	/* ipGroupMember table */
18676 	optp = (struct opthdr *)&mpctl->b_rptr[
18677 	    sizeof (struct T_optmgmt_ack)];
18678 	optp->level = MIB2_IP;
18679 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18680 
18681 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18682 	ill = ILL_START_WALK_V4(&ctx, ipst);
18683 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18684 		ILM_WALKER_HOLD(ill);
18685 		for (ipif = ill->ill_ipif; ipif != NULL;
18686 		    ipif = ipif->ipif_next) {
18687 			if (ipif->ipif_zoneid != zoneid &&
18688 			    ipif->ipif_zoneid != ALL_ZONES)
18689 				continue;	/* not this zone */
18690 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18691 			    OCTET_LENGTH);
18692 			ipm.ipGroupMemberIfIndex.o_length =
18693 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18694 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18695 				ASSERT(ilm->ilm_ipif != NULL);
18696 				ASSERT(ilm->ilm_ill == NULL);
18697 				if (ilm->ilm_ipif != ipif)
18698 					continue;
18699 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18700 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18701 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18702 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18703 				    (char *)&ipm, (int)sizeof (ipm))) {
18704 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18705 					    "failed to allocate %u bytes\n",
18706 					    (uint_t)sizeof (ipm)));
18707 				}
18708 			}
18709 		}
18710 		ILM_WALKER_RELE(ill);
18711 	}
18712 	rw_exit(&ipst->ips_ill_g_lock);
18713 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18714 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18715 	    (int)optp->level, (int)optp->name, (int)optp->len));
18716 	qreply(q, mpctl);
18717 	return (mp2ctl);
18718 }
18719 
18720 /* IPv6 multicast group membership. */
18721 static mblk_t *
18722 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18723 {
18724 	struct opthdr		*optp;
18725 	mblk_t			*mp2ctl;
18726 	ill_t			*ill;
18727 	ilm_t			*ilm;
18728 	ipv6_member_t		ipm6;
18729 	mblk_t			*mp_tail = NULL;
18730 	ill_walk_context_t	ctx;
18731 	zoneid_t		zoneid;
18732 
18733 	/*
18734 	 * make a copy of the original message
18735 	 */
18736 	mp2ctl = copymsg(mpctl);
18737 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18738 
18739 	/* ip6GroupMember table */
18740 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18741 	optp->level = MIB2_IP6;
18742 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18743 
18744 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18745 	ill = ILL_START_WALK_V6(&ctx, ipst);
18746 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18747 		ILM_WALKER_HOLD(ill);
18748 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18749 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18750 			ASSERT(ilm->ilm_ipif == NULL);
18751 			ASSERT(ilm->ilm_ill != NULL);
18752 			if (ilm->ilm_zoneid != zoneid)
18753 				continue;	/* not this zone */
18754 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18755 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18756 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18757 			if (!snmp_append_data2(mpctl->b_cont,
18758 			    &mp_tail,
18759 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18760 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18761 				    "failed to allocate %u bytes\n",
18762 				    (uint_t)sizeof (ipm6)));
18763 			}
18764 		}
18765 		ILM_WALKER_RELE(ill);
18766 	}
18767 	rw_exit(&ipst->ips_ill_g_lock);
18768 
18769 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18770 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18771 	    (int)optp->level, (int)optp->name, (int)optp->len));
18772 	qreply(q, mpctl);
18773 	return (mp2ctl);
18774 }
18775 
18776 /* IP multicast filtered sources */
18777 static mblk_t *
18778 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18779 {
18780 	struct opthdr		*optp;
18781 	mblk_t			*mp2ctl;
18782 	ill_t			*ill;
18783 	ipif_t			*ipif;
18784 	ilm_t			*ilm;
18785 	ip_grpsrc_t		ips;
18786 	mblk_t			*mp_tail = NULL;
18787 	ill_walk_context_t	ctx;
18788 	zoneid_t		zoneid;
18789 	int			i;
18790 	slist_t			*sl;
18791 
18792 	/*
18793 	 * make a copy of the original message
18794 	 */
18795 	mp2ctl = copymsg(mpctl);
18796 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18797 
18798 	/* ipGroupSource table */
18799 	optp = (struct opthdr *)&mpctl->b_rptr[
18800 	    sizeof (struct T_optmgmt_ack)];
18801 	optp->level = MIB2_IP;
18802 	optp->name = EXPER_IP_GROUP_SOURCES;
18803 
18804 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18805 	ill = ILL_START_WALK_V4(&ctx, ipst);
18806 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18807 		ILM_WALKER_HOLD(ill);
18808 		for (ipif = ill->ill_ipif; ipif != NULL;
18809 		    ipif = ipif->ipif_next) {
18810 			if (ipif->ipif_zoneid != zoneid)
18811 				continue;	/* not this zone */
18812 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18813 			    OCTET_LENGTH);
18814 			ips.ipGroupSourceIfIndex.o_length =
18815 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18816 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18817 				ASSERT(ilm->ilm_ipif != NULL);
18818 				ASSERT(ilm->ilm_ill == NULL);
18819 				sl = ilm->ilm_filter;
18820 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18821 					continue;
18822 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18823 				for (i = 0; i < sl->sl_numsrc; i++) {
18824 					if (!IN6_IS_ADDR_V4MAPPED(
18825 					    &sl->sl_addr[i]))
18826 						continue;
18827 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18828 					    ips.ipGroupSourceAddress);
18829 					if (snmp_append_data2(mpctl->b_cont,
18830 					    &mp_tail, (char *)&ips,
18831 					    (int)sizeof (ips)) == 0) {
18832 						ip1dbg(("ip_snmp_get_mib2_"
18833 						    "ip_group_src: failed to "
18834 						    "allocate %u bytes\n",
18835 						    (uint_t)sizeof (ips)));
18836 					}
18837 				}
18838 			}
18839 		}
18840 		ILM_WALKER_RELE(ill);
18841 	}
18842 	rw_exit(&ipst->ips_ill_g_lock);
18843 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18844 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18845 	    (int)optp->level, (int)optp->name, (int)optp->len));
18846 	qreply(q, mpctl);
18847 	return (mp2ctl);
18848 }
18849 
18850 /* IPv6 multicast filtered sources. */
18851 static mblk_t *
18852 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18853 {
18854 	struct opthdr		*optp;
18855 	mblk_t			*mp2ctl;
18856 	ill_t			*ill;
18857 	ilm_t			*ilm;
18858 	ipv6_grpsrc_t		ips6;
18859 	mblk_t			*mp_tail = NULL;
18860 	ill_walk_context_t	ctx;
18861 	zoneid_t		zoneid;
18862 	int			i;
18863 	slist_t			*sl;
18864 
18865 	/*
18866 	 * make a copy of the original message
18867 	 */
18868 	mp2ctl = copymsg(mpctl);
18869 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18870 
18871 	/* ip6GroupMember table */
18872 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18873 	optp->level = MIB2_IP6;
18874 	optp->name = EXPER_IP6_GROUP_SOURCES;
18875 
18876 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18877 	ill = ILL_START_WALK_V6(&ctx, ipst);
18878 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18879 		ILM_WALKER_HOLD(ill);
18880 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18881 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18882 			ASSERT(ilm->ilm_ipif == NULL);
18883 			ASSERT(ilm->ilm_ill != NULL);
18884 			sl = ilm->ilm_filter;
18885 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18886 				continue;
18887 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18888 			for (i = 0; i < sl->sl_numsrc; i++) {
18889 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18890 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18891 				    (char *)&ips6, (int)sizeof (ips6))) {
18892 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18893 					    "group_src: failed to allocate "
18894 					    "%u bytes\n",
18895 					    (uint_t)sizeof (ips6)));
18896 				}
18897 			}
18898 		}
18899 		ILM_WALKER_RELE(ill);
18900 	}
18901 	rw_exit(&ipst->ips_ill_g_lock);
18902 
18903 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18904 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18905 	    (int)optp->level, (int)optp->name, (int)optp->len));
18906 	qreply(q, mpctl);
18907 	return (mp2ctl);
18908 }
18909 
18910 /* Multicast routing virtual interface table. */
18911 static mblk_t *
18912 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18913 {
18914 	struct opthdr		*optp;
18915 	mblk_t			*mp2ctl;
18916 
18917 	/*
18918 	 * make a copy of the original message
18919 	 */
18920 	mp2ctl = copymsg(mpctl);
18921 
18922 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18923 	optp->level = EXPER_DVMRP;
18924 	optp->name = EXPER_DVMRP_VIF;
18925 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18926 		ip0dbg(("ip_mroute_vif: failed\n"));
18927 	}
18928 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18929 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18930 	    (int)optp->level, (int)optp->name, (int)optp->len));
18931 	qreply(q, mpctl);
18932 	return (mp2ctl);
18933 }
18934 
18935 /* Multicast routing table. */
18936 static mblk_t *
18937 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18938 {
18939 	struct opthdr		*optp;
18940 	mblk_t			*mp2ctl;
18941 
18942 	/*
18943 	 * make a copy of the original message
18944 	 */
18945 	mp2ctl = copymsg(mpctl);
18946 
18947 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18948 	optp->level = EXPER_DVMRP;
18949 	optp->name = EXPER_DVMRP_MRT;
18950 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18951 		ip0dbg(("ip_mroute_mrt: failed\n"));
18952 	}
18953 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18954 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18955 	    (int)optp->level, (int)optp->name, (int)optp->len));
18956 	qreply(q, mpctl);
18957 	return (mp2ctl);
18958 }
18959 
18960 /*
18961  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18962  * in one IRE walk.
18963  */
18964 static mblk_t *
18965 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18966 {
18967 	struct opthdr	*optp;
18968 	mblk_t		*mp2ctl;	/* Returned */
18969 	mblk_t		*mp3ctl;	/* nettomedia */
18970 	mblk_t		*mp4ctl;	/* routeattrs */
18971 	iproutedata_t	ird;
18972 	zoneid_t	zoneid;
18973 
18974 	/*
18975 	 * make copies of the original message
18976 	 *	- mp2ctl is returned unchanged to the caller for his use
18977 	 *	- mpctl is sent upstream as ipRouteEntryTable
18978 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18979 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18980 	 */
18981 	mp2ctl = copymsg(mpctl);
18982 	mp3ctl = copymsg(mpctl);
18983 	mp4ctl = copymsg(mpctl);
18984 	if (mp3ctl == NULL || mp4ctl == NULL) {
18985 		freemsg(mp4ctl);
18986 		freemsg(mp3ctl);
18987 		freemsg(mp2ctl);
18988 		freemsg(mpctl);
18989 		return (NULL);
18990 	}
18991 
18992 	bzero(&ird, sizeof (ird));
18993 
18994 	ird.ird_route.lp_head = mpctl->b_cont;
18995 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18996 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18997 
18998 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18999 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19000 
19001 	/* ipRouteEntryTable in mpctl */
19002 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19003 	optp->level = MIB2_IP;
19004 	optp->name = MIB2_IP_ROUTE;
19005 	optp->len = msgdsize(ird.ird_route.lp_head);
19006 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19007 	    (int)optp->level, (int)optp->name, (int)optp->len));
19008 	qreply(q, mpctl);
19009 
19010 	/* ipNetToMediaEntryTable in mp3ctl */
19011 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19012 	optp->level = MIB2_IP;
19013 	optp->name = MIB2_IP_MEDIA;
19014 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19015 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19016 	    (int)optp->level, (int)optp->name, (int)optp->len));
19017 	qreply(q, mp3ctl);
19018 
19019 	/* ipRouteAttributeTable in mp4ctl */
19020 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19021 	optp->level = MIB2_IP;
19022 	optp->name = EXPER_IP_RTATTR;
19023 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19024 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19025 	    (int)optp->level, (int)optp->name, (int)optp->len));
19026 	if (optp->len == 0)
19027 		freemsg(mp4ctl);
19028 	else
19029 		qreply(q, mp4ctl);
19030 
19031 	return (mp2ctl);
19032 }
19033 
19034 /*
19035  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19036  * ipv6NetToMediaEntryTable in an NDP walk.
19037  */
19038 static mblk_t *
19039 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19040 {
19041 	struct opthdr	*optp;
19042 	mblk_t		*mp2ctl;	/* Returned */
19043 	mblk_t		*mp3ctl;	/* nettomedia */
19044 	mblk_t		*mp4ctl;	/* routeattrs */
19045 	iproutedata_t	ird;
19046 	zoneid_t	zoneid;
19047 
19048 	/*
19049 	 * make copies of the original message
19050 	 *	- mp2ctl is returned unchanged to the caller for his use
19051 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19052 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19053 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19054 	 */
19055 	mp2ctl = copymsg(mpctl);
19056 	mp3ctl = copymsg(mpctl);
19057 	mp4ctl = copymsg(mpctl);
19058 	if (mp3ctl == NULL || mp4ctl == NULL) {
19059 		freemsg(mp4ctl);
19060 		freemsg(mp3ctl);
19061 		freemsg(mp2ctl);
19062 		freemsg(mpctl);
19063 		return (NULL);
19064 	}
19065 
19066 	bzero(&ird, sizeof (ird));
19067 
19068 	ird.ird_route.lp_head = mpctl->b_cont;
19069 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19070 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19071 
19072 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19073 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19074 
19075 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19076 	optp->level = MIB2_IP6;
19077 	optp->name = MIB2_IP6_ROUTE;
19078 	optp->len = msgdsize(ird.ird_route.lp_head);
19079 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19080 	    (int)optp->level, (int)optp->name, (int)optp->len));
19081 	qreply(q, mpctl);
19082 
19083 	/* ipv6NetToMediaEntryTable in mp3ctl */
19084 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19085 
19086 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19087 	optp->level = MIB2_IP6;
19088 	optp->name = MIB2_IP6_MEDIA;
19089 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19090 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19091 	    (int)optp->level, (int)optp->name, (int)optp->len));
19092 	qreply(q, mp3ctl);
19093 
19094 	/* ipv6RouteAttributeTable in mp4ctl */
19095 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19096 	optp->level = MIB2_IP6;
19097 	optp->name = EXPER_IP_RTATTR;
19098 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19099 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19100 	    (int)optp->level, (int)optp->name, (int)optp->len));
19101 	if (optp->len == 0)
19102 		freemsg(mp4ctl);
19103 	else
19104 		qreply(q, mp4ctl);
19105 
19106 	return (mp2ctl);
19107 }
19108 
19109 /*
19110  * IPv6 mib: One per ill
19111  */
19112 static mblk_t *
19113 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19114 {
19115 	struct opthdr		*optp;
19116 	mblk_t			*mp2ctl;
19117 	ill_t			*ill;
19118 	ill_walk_context_t	ctx;
19119 	mblk_t			*mp_tail = NULL;
19120 
19121 	/*
19122 	 * Make a copy of the original message
19123 	 */
19124 	mp2ctl = copymsg(mpctl);
19125 
19126 	/* fixed length IPv6 structure ... */
19127 
19128 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19129 	optp->level = MIB2_IP6;
19130 	optp->name = 0;
19131 	/* Include "unknown interface" ip6_mib */
19132 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19133 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19134 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19135 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19136 	    ipst->ips_ipv6_forward ? 1 : 2);
19137 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19138 	    ipst->ips_ipv6_def_hops);
19139 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19140 	    sizeof (mib2_ipIfStatsEntry_t));
19141 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19142 	    sizeof (mib2_ipv6AddrEntry_t));
19143 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19144 	    sizeof (mib2_ipv6RouteEntry_t));
19145 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19146 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19147 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19148 	    sizeof (ipv6_member_t));
19149 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19150 	    sizeof (ipv6_grpsrc_t));
19151 
19152 	/*
19153 	 * Synchronize 64- and 32-bit counters
19154 	 */
19155 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19156 	    ipIfStatsHCInReceives);
19157 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19158 	    ipIfStatsHCInDelivers);
19159 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19160 	    ipIfStatsHCOutRequests);
19161 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19162 	    ipIfStatsHCOutForwDatagrams);
19163 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19164 	    ipIfStatsHCOutMcastPkts);
19165 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19166 	    ipIfStatsHCInMcastPkts);
19167 
19168 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19169 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19170 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19171 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19172 	}
19173 
19174 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19175 	ill = ILL_START_WALK_V6(&ctx, ipst);
19176 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19177 		ill->ill_ip_mib->ipIfStatsIfIndex =
19178 		    ill->ill_phyint->phyint_ifindex;
19179 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19180 		    ipst->ips_ipv6_forward ? 1 : 2);
19181 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19182 		    ill->ill_max_hops);
19183 
19184 		/*
19185 		 * Synchronize 64- and 32-bit counters
19186 		 */
19187 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19188 		    ipIfStatsHCInReceives);
19189 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19190 		    ipIfStatsHCInDelivers);
19191 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19192 		    ipIfStatsHCOutRequests);
19193 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19194 		    ipIfStatsHCOutForwDatagrams);
19195 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19196 		    ipIfStatsHCOutMcastPkts);
19197 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19198 		    ipIfStatsHCInMcastPkts);
19199 
19200 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19201 		    (char *)ill->ill_ip_mib,
19202 		    (int)sizeof (*ill->ill_ip_mib))) {
19203 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19204 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19205 		}
19206 	}
19207 	rw_exit(&ipst->ips_ill_g_lock);
19208 
19209 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19210 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19211 	    (int)optp->level, (int)optp->name, (int)optp->len));
19212 	qreply(q, mpctl);
19213 	return (mp2ctl);
19214 }
19215 
19216 /*
19217  * ICMPv6 mib: One per ill
19218  */
19219 static mblk_t *
19220 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19221 {
19222 	struct opthdr		*optp;
19223 	mblk_t			*mp2ctl;
19224 	ill_t			*ill;
19225 	ill_walk_context_t	ctx;
19226 	mblk_t			*mp_tail = NULL;
19227 	/*
19228 	 * Make a copy of the original message
19229 	 */
19230 	mp2ctl = copymsg(mpctl);
19231 
19232 	/* fixed length ICMPv6 structure ... */
19233 
19234 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19235 	optp->level = MIB2_ICMP6;
19236 	optp->name = 0;
19237 	/* Include "unknown interface" icmp6_mib */
19238 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19239 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19240 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19241 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19242 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19243 	    (char *)&ipst->ips_icmp6_mib,
19244 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19245 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19246 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19247 	}
19248 
19249 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19250 	ill = ILL_START_WALK_V6(&ctx, ipst);
19251 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19252 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19253 		    ill->ill_phyint->phyint_ifindex;
19254 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19255 		    (char *)ill->ill_icmp6_mib,
19256 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19257 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19258 			    "%u bytes\n",
19259 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19260 		}
19261 	}
19262 	rw_exit(&ipst->ips_ill_g_lock);
19263 
19264 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19265 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19266 	    (int)optp->level, (int)optp->name, (int)optp->len));
19267 	qreply(q, mpctl);
19268 	return (mp2ctl);
19269 }
19270 
19271 /*
19272  * ire_walk routine to create both ipRouteEntryTable and
19273  * ipRouteAttributeTable in one IRE walk
19274  */
19275 static void
19276 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19277 {
19278 	ill_t				*ill;
19279 	ipif_t				*ipif;
19280 	mib2_ipRouteEntry_t		*re;
19281 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19282 	ipaddr_t			gw_addr;
19283 	tsol_ire_gw_secattr_t		*attrp;
19284 	tsol_gc_t			*gc = NULL;
19285 	tsol_gcgrp_t			*gcgrp = NULL;
19286 	uint_t				sacnt = 0;
19287 	int				i;
19288 
19289 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19290 
19291 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19292 		return;
19293 
19294 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19295 		mutex_enter(&attrp->igsa_lock);
19296 		if ((gc = attrp->igsa_gc) != NULL) {
19297 			gcgrp = gc->gc_grp;
19298 			ASSERT(gcgrp != NULL);
19299 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19300 			sacnt = 1;
19301 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19302 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19303 			gc = gcgrp->gcgrp_head;
19304 			sacnt = gcgrp->gcgrp_count;
19305 		}
19306 		mutex_exit(&attrp->igsa_lock);
19307 
19308 		/* do nothing if there's no gc to report */
19309 		if (gc == NULL) {
19310 			ASSERT(sacnt == 0);
19311 			if (gcgrp != NULL) {
19312 				/* we might as well drop the lock now */
19313 				rw_exit(&gcgrp->gcgrp_rwlock);
19314 				gcgrp = NULL;
19315 			}
19316 			attrp = NULL;
19317 		}
19318 
19319 		ASSERT(gc == NULL || (gcgrp != NULL &&
19320 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19321 	}
19322 	ASSERT(sacnt == 0 || gc != NULL);
19323 
19324 	if (sacnt != 0 &&
19325 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19326 		kmem_free(re, sizeof (*re));
19327 		rw_exit(&gcgrp->gcgrp_rwlock);
19328 		return;
19329 	}
19330 
19331 	/*
19332 	 * Return all IRE types for route table... let caller pick and choose
19333 	 */
19334 	re->ipRouteDest = ire->ire_addr;
19335 	ipif = ire->ire_ipif;
19336 	re->ipRouteIfIndex.o_length = 0;
19337 	if (ire->ire_type == IRE_CACHE) {
19338 		ill = (ill_t *)ire->ire_stq->q_ptr;
19339 		re->ipRouteIfIndex.o_length =
19340 		    ill->ill_name_length == 0 ? 0 :
19341 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19342 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19343 		    re->ipRouteIfIndex.o_length);
19344 	} else if (ipif != NULL) {
19345 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19346 		re->ipRouteIfIndex.o_length =
19347 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19348 	}
19349 	re->ipRouteMetric1 = -1;
19350 	re->ipRouteMetric2 = -1;
19351 	re->ipRouteMetric3 = -1;
19352 	re->ipRouteMetric4 = -1;
19353 
19354 	gw_addr = ire->ire_gateway_addr;
19355 
19356 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19357 		re->ipRouteNextHop = ire->ire_src_addr;
19358 	else
19359 		re->ipRouteNextHop = gw_addr;
19360 	/* indirect(4), direct(3), or invalid(2) */
19361 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19362 		re->ipRouteType = 2;
19363 	else
19364 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19365 	re->ipRouteProto = -1;
19366 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19367 	re->ipRouteMask = ire->ire_mask;
19368 	re->ipRouteMetric5 = -1;
19369 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19370 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19371 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19372 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19373 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19374 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19375 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19376 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19377 
19378 	if (ire->ire_flags & RTF_DYNAMIC) {
19379 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19380 	} else {
19381 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19382 	}
19383 
19384 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19385 	    (char *)re, (int)sizeof (*re))) {
19386 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19387 		    (uint_t)sizeof (*re)));
19388 	}
19389 
19390 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19391 		iaeptr->iae_routeidx = ird->ird_idx;
19392 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19393 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19394 	}
19395 
19396 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19397 	    (char *)iae, sacnt * sizeof (*iae))) {
19398 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19399 		    (unsigned)(sacnt * sizeof (*iae))));
19400 	}
19401 
19402 	/* bump route index for next pass */
19403 	ird->ird_idx++;
19404 
19405 	kmem_free(re, sizeof (*re));
19406 	if (sacnt != 0)
19407 		kmem_free(iae, sacnt * sizeof (*iae));
19408 
19409 	if (gcgrp != NULL)
19410 		rw_exit(&gcgrp->gcgrp_rwlock);
19411 }
19412 
19413 /*
19414  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19415  */
19416 static void
19417 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19418 {
19419 	ill_t				*ill;
19420 	ipif_t				*ipif;
19421 	mib2_ipv6RouteEntry_t		*re;
19422 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19423 	in6_addr_t			gw_addr_v6;
19424 	tsol_ire_gw_secattr_t		*attrp;
19425 	tsol_gc_t			*gc = NULL;
19426 	tsol_gcgrp_t			*gcgrp = NULL;
19427 	uint_t				sacnt = 0;
19428 	int				i;
19429 
19430 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19431 
19432 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19433 		return;
19434 
19435 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19436 		mutex_enter(&attrp->igsa_lock);
19437 		if ((gc = attrp->igsa_gc) != NULL) {
19438 			gcgrp = gc->gc_grp;
19439 			ASSERT(gcgrp != NULL);
19440 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19441 			sacnt = 1;
19442 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19443 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19444 			gc = gcgrp->gcgrp_head;
19445 			sacnt = gcgrp->gcgrp_count;
19446 		}
19447 		mutex_exit(&attrp->igsa_lock);
19448 
19449 		/* do nothing if there's no gc to report */
19450 		if (gc == NULL) {
19451 			ASSERT(sacnt == 0);
19452 			if (gcgrp != NULL) {
19453 				/* we might as well drop the lock now */
19454 				rw_exit(&gcgrp->gcgrp_rwlock);
19455 				gcgrp = NULL;
19456 			}
19457 			attrp = NULL;
19458 		}
19459 
19460 		ASSERT(gc == NULL || (gcgrp != NULL &&
19461 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19462 	}
19463 	ASSERT(sacnt == 0 || gc != NULL);
19464 
19465 	if (sacnt != 0 &&
19466 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19467 		kmem_free(re, sizeof (*re));
19468 		rw_exit(&gcgrp->gcgrp_rwlock);
19469 		return;
19470 	}
19471 
19472 	/*
19473 	 * Return all IRE types for route table... let caller pick and choose
19474 	 */
19475 	re->ipv6RouteDest = ire->ire_addr_v6;
19476 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19477 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19478 	re->ipv6RouteIfIndex.o_length = 0;
19479 	ipif = ire->ire_ipif;
19480 	if (ire->ire_type == IRE_CACHE) {
19481 		ill = (ill_t *)ire->ire_stq->q_ptr;
19482 		re->ipv6RouteIfIndex.o_length =
19483 		    ill->ill_name_length == 0 ? 0 :
19484 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19485 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19486 		    re->ipv6RouteIfIndex.o_length);
19487 	} else if (ipif != NULL) {
19488 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19489 		re->ipv6RouteIfIndex.o_length =
19490 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19491 	}
19492 
19493 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19494 
19495 	mutex_enter(&ire->ire_lock);
19496 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19497 	mutex_exit(&ire->ire_lock);
19498 
19499 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19500 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19501 	else
19502 		re->ipv6RouteNextHop = gw_addr_v6;
19503 
19504 	/* remote(4), local(3), or discard(2) */
19505 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19506 		re->ipv6RouteType = 2;
19507 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19508 		re->ipv6RouteType = 3;
19509 	else
19510 		re->ipv6RouteType = 4;
19511 
19512 	re->ipv6RouteProtocol	= -1;
19513 	re->ipv6RoutePolicy	= 0;
19514 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19515 	re->ipv6RouteNextHopRDI	= 0;
19516 	re->ipv6RouteWeight	= 0;
19517 	re->ipv6RouteMetric	= 0;
19518 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19519 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19520 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19521 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19522 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19523 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19524 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19525 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19526 
19527 	if (ire->ire_flags & RTF_DYNAMIC) {
19528 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19529 	} else {
19530 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19531 	}
19532 
19533 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19534 	    (char *)re, (int)sizeof (*re))) {
19535 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19536 		    (uint_t)sizeof (*re)));
19537 	}
19538 
19539 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19540 		iaeptr->iae_routeidx = ird->ird_idx;
19541 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19542 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19543 	}
19544 
19545 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19546 	    (char *)iae, sacnt * sizeof (*iae))) {
19547 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19548 		    (unsigned)(sacnt * sizeof (*iae))));
19549 	}
19550 
19551 	/* bump route index for next pass */
19552 	ird->ird_idx++;
19553 
19554 	kmem_free(re, sizeof (*re));
19555 	if (sacnt != 0)
19556 		kmem_free(iae, sacnt * sizeof (*iae));
19557 
19558 	if (gcgrp != NULL)
19559 		rw_exit(&gcgrp->gcgrp_rwlock);
19560 }
19561 
19562 /*
19563  * ndp_walk routine to create ipv6NetToMediaEntryTable
19564  */
19565 static int
19566 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19567 {
19568 	ill_t				*ill;
19569 	mib2_ipv6NetToMediaEntry_t	ntme;
19570 	dl_unitdata_req_t		*dl;
19571 
19572 	ill = nce->nce_ill;
19573 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19574 		return (0);
19575 
19576 	/*
19577 	 * Neighbor cache entry attached to IRE with on-link
19578 	 * destination.
19579 	 */
19580 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19581 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19582 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19583 	    (nce->nce_res_mp != NULL)) {
19584 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19585 		ntme.ipv6NetToMediaPhysAddress.o_length =
19586 		    dl->dl_dest_addr_length;
19587 	} else {
19588 		ntme.ipv6NetToMediaPhysAddress.o_length =
19589 		    ill->ill_phys_addr_length;
19590 	}
19591 	if (nce->nce_res_mp != NULL) {
19592 		bcopy((char *)nce->nce_res_mp->b_rptr +
19593 		    NCE_LL_ADDR_OFFSET(ill),
19594 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19595 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19596 	} else {
19597 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19598 		    ill->ill_phys_addr_length);
19599 	}
19600 	/*
19601 	 * Note: Returns ND_* states. Should be:
19602 	 * reachable(1), stale(2), delay(3), probe(4),
19603 	 * invalid(5), unknown(6)
19604 	 */
19605 	ntme.ipv6NetToMediaState = nce->nce_state;
19606 	ntme.ipv6NetToMediaLastUpdated = 0;
19607 
19608 	/* other(1), dynamic(2), static(3), local(4) */
19609 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19610 		ntme.ipv6NetToMediaType = 4;
19611 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19612 		ntme.ipv6NetToMediaType = 1;
19613 	} else {
19614 		ntme.ipv6NetToMediaType = 2;
19615 	}
19616 
19617 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19618 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19619 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19620 		    (uint_t)sizeof (ntme)));
19621 	}
19622 	return (0);
19623 }
19624 
19625 /*
19626  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19627  */
19628 /* ARGSUSED */
19629 int
19630 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19631 {
19632 	switch (level) {
19633 	case MIB2_IP:
19634 	case MIB2_ICMP:
19635 		switch (name) {
19636 		default:
19637 			break;
19638 		}
19639 		return (1);
19640 	default:
19641 		return (1);
19642 	}
19643 }
19644 
19645 /*
19646  * When there exists both a 64- and 32-bit counter of a particular type
19647  * (i.e., InReceives), only the 64-bit counters are added.
19648  */
19649 void
19650 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19651 {
19652 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19653 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19654 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19655 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19656 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19657 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19658 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19659 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19660 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19661 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19662 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19663 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19664 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19665 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19666 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19667 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19668 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19669 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19670 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19671 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19672 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19673 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19674 	    o2->ipIfStatsInWrongIPVersion);
19675 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19676 	    o2->ipIfStatsInWrongIPVersion);
19677 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19678 	    o2->ipIfStatsOutSwitchIPVersion);
19679 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19680 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19681 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19682 	    o2->ipIfStatsHCInForwDatagrams);
19683 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19684 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19685 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19686 	    o2->ipIfStatsHCOutForwDatagrams);
19687 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19688 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19689 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19690 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19691 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19692 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19693 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19694 	    o2->ipIfStatsHCOutMcastOctets);
19695 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19696 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19697 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19698 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19699 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19700 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19701 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19702 }
19703 
19704 void
19705 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19706 {
19707 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19708 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19709 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19710 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19711 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19712 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19713 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19714 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19715 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19716 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19717 	    o2->ipv6IfIcmpInRouterSolicits);
19718 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19719 	    o2->ipv6IfIcmpInRouterAdvertisements);
19720 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19721 	    o2->ipv6IfIcmpInNeighborSolicits);
19722 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19723 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19724 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19725 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19726 	    o2->ipv6IfIcmpInGroupMembQueries);
19727 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19728 	    o2->ipv6IfIcmpInGroupMembResponses);
19729 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19730 	    o2->ipv6IfIcmpInGroupMembReductions);
19731 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19732 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19733 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19734 	    o2->ipv6IfIcmpOutDestUnreachs);
19735 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19736 	    o2->ipv6IfIcmpOutAdminProhibs);
19737 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19738 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19739 	    o2->ipv6IfIcmpOutParmProblems);
19740 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19741 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19742 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19743 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19744 	    o2->ipv6IfIcmpOutRouterSolicits);
19745 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19746 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19747 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19748 	    o2->ipv6IfIcmpOutNeighborSolicits);
19749 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19750 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19751 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19752 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19753 	    o2->ipv6IfIcmpOutGroupMembQueries);
19754 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19755 	    o2->ipv6IfIcmpOutGroupMembResponses);
19756 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19757 	    o2->ipv6IfIcmpOutGroupMembReductions);
19758 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19759 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19760 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19761 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19762 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19763 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19764 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19765 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19766 	    o2->ipv6IfIcmpInGroupMembTotal);
19767 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19768 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19769 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19770 	    o2->ipv6IfIcmpInGroupMembBadReports);
19771 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19772 	    o2->ipv6IfIcmpInGroupMembOurReports);
19773 }
19774 
19775 /*
19776  * Called before the options are updated to check if this packet will
19777  * be source routed from here.
19778  * This routine assumes that the options are well formed i.e. that they
19779  * have already been checked.
19780  */
19781 static boolean_t
19782 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19783 {
19784 	ipoptp_t	opts;
19785 	uchar_t		*opt;
19786 	uint8_t		optval;
19787 	uint8_t		optlen;
19788 	ipaddr_t	dst;
19789 	ire_t		*ire;
19790 
19791 	if (IS_SIMPLE_IPH(ipha)) {
19792 		ip2dbg(("not source routed\n"));
19793 		return (B_FALSE);
19794 	}
19795 	dst = ipha->ipha_dst;
19796 	for (optval = ipoptp_first(&opts, ipha);
19797 	    optval != IPOPT_EOL;
19798 	    optval = ipoptp_next(&opts)) {
19799 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19800 		opt = opts.ipoptp_cur;
19801 		optlen = opts.ipoptp_len;
19802 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19803 		    optval, optlen));
19804 		switch (optval) {
19805 			uint32_t off;
19806 		case IPOPT_SSRR:
19807 		case IPOPT_LSRR:
19808 			/*
19809 			 * If dst is one of our addresses and there are some
19810 			 * entries left in the source route return (true).
19811 			 */
19812 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19813 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19814 			if (ire == NULL) {
19815 				ip2dbg(("ip_source_routed: not next"
19816 				    " source route 0x%x\n",
19817 				    ntohl(dst)));
19818 				return (B_FALSE);
19819 			}
19820 			ire_refrele(ire);
19821 			off = opt[IPOPT_OFFSET];
19822 			off--;
19823 			if (optlen < IP_ADDR_LEN ||
19824 			    off > optlen - IP_ADDR_LEN) {
19825 				/* End of source route */
19826 				ip1dbg(("ip_source_routed: end of SR\n"));
19827 				return (B_FALSE);
19828 			}
19829 			return (B_TRUE);
19830 		}
19831 	}
19832 	ip2dbg(("not source routed\n"));
19833 	return (B_FALSE);
19834 }
19835 
19836 /*
19837  * Check if the packet contains any source route.
19838  */
19839 static boolean_t
19840 ip_source_route_included(ipha_t *ipha)
19841 {
19842 	ipoptp_t	opts;
19843 	uint8_t		optval;
19844 
19845 	if (IS_SIMPLE_IPH(ipha))
19846 		return (B_FALSE);
19847 	for (optval = ipoptp_first(&opts, ipha);
19848 	    optval != IPOPT_EOL;
19849 	    optval = ipoptp_next(&opts)) {
19850 		switch (optval) {
19851 		case IPOPT_SSRR:
19852 		case IPOPT_LSRR:
19853 			return (B_TRUE);
19854 		}
19855 	}
19856 	return (B_FALSE);
19857 }
19858 
19859 /*
19860  * Called when the IRE expiration timer fires.
19861  */
19862 void
19863 ip_trash_timer_expire(void *args)
19864 {
19865 	int			flush_flag = 0;
19866 	ire_expire_arg_t	iea;
19867 	ip_stack_t		*ipst = (ip_stack_t *)args;
19868 
19869 	iea.iea_ipst = ipst;	/* No netstack_hold */
19870 
19871 	/*
19872 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19873 	 * This lock makes sure that a new invocation of this function
19874 	 * that occurs due to an almost immediate timer firing will not
19875 	 * progress beyond this point until the current invocation is done
19876 	 */
19877 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19878 	ipst->ips_ip_ire_expire_id = 0;
19879 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19880 
19881 	/* Periodic timer */
19882 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19883 	    ipst->ips_ip_ire_arp_interval) {
19884 		/*
19885 		 * Remove all IRE_CACHE entries since they might
19886 		 * contain arp information.
19887 		 */
19888 		flush_flag |= FLUSH_ARP_TIME;
19889 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19890 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19891 	}
19892 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19893 	    ipst->ips_ip_ire_redir_interval) {
19894 		/* Remove all redirects */
19895 		flush_flag |= FLUSH_REDIRECT_TIME;
19896 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19897 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19898 	}
19899 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19900 	    ipst->ips_ip_ire_pathmtu_interval) {
19901 		/* Increase path mtu */
19902 		flush_flag |= FLUSH_MTU_TIME;
19903 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19904 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19905 	}
19906 
19907 	/*
19908 	 * Optimize for the case when there are no redirects in the
19909 	 * ftable, that is, no need to walk the ftable in that case.
19910 	 */
19911 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19912 		iea.iea_flush_flag = flush_flag;
19913 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19914 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19915 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19916 		    NULL, ALL_ZONES, ipst);
19917 	}
19918 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19919 	    ipst->ips_ip_redirect_cnt > 0) {
19920 		iea.iea_flush_flag = flush_flag;
19921 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19922 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19923 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19924 	}
19925 	if (flush_flag & FLUSH_MTU_TIME) {
19926 		/*
19927 		 * Walk all IPv6 IRE's and update them
19928 		 * Note that ARP and redirect timers are not
19929 		 * needed since NUD handles stale entries.
19930 		 */
19931 		flush_flag = FLUSH_MTU_TIME;
19932 		iea.iea_flush_flag = flush_flag;
19933 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19934 		    ALL_ZONES, ipst);
19935 	}
19936 
19937 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19938 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19939 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19940 
19941 	/*
19942 	 * Hold the lock to serialize timeout calls and prevent
19943 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19944 	 * for the timer to fire and a new invocation of this function
19945 	 * to start before the return value of timeout has been stored
19946 	 * in ip_ire_expire_id by the current invocation.
19947 	 */
19948 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19949 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19950 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19951 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19952 }
19953 
19954 /*
19955  * Called by the memory allocator subsystem directly, when the system
19956  * is running low on memory.
19957  */
19958 /* ARGSUSED */
19959 void
19960 ip_trash_ire_reclaim(void *args)
19961 {
19962 	netstack_handle_t nh;
19963 	netstack_t *ns;
19964 
19965 	netstack_next_init(&nh);
19966 	while ((ns = netstack_next(&nh)) != NULL) {
19967 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19968 		netstack_rele(ns);
19969 	}
19970 	netstack_next_fini(&nh);
19971 }
19972 
19973 static void
19974 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19975 {
19976 	ire_cache_count_t icc;
19977 	ire_cache_reclaim_t icr;
19978 	ncc_cache_count_t ncc;
19979 	nce_cache_reclaim_t ncr;
19980 	uint_t delete_cnt;
19981 	/*
19982 	 * Memory reclaim call back.
19983 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19984 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19985 	 * entries, determine what fraction to free for
19986 	 * each category of IRE_CACHE entries giving absolute priority
19987 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19988 	 * entry will be freed unless all offlink entries are freed).
19989 	 */
19990 	icc.icc_total = 0;
19991 	icc.icc_unused = 0;
19992 	icc.icc_offlink = 0;
19993 	icc.icc_pmtu = 0;
19994 	icc.icc_onlink = 0;
19995 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19996 
19997 	/*
19998 	 * Free NCEs for IPv6 like the onlink ires.
19999 	 */
20000 	ncc.ncc_total = 0;
20001 	ncc.ncc_host = 0;
20002 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20003 
20004 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20005 	    icc.icc_pmtu + icc.icc_onlink);
20006 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20007 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20008 	if (delete_cnt == 0)
20009 		return;
20010 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20011 	/* Always delete all unused offlink entries */
20012 	icr.icr_ipst = ipst;
20013 	icr.icr_unused = 1;
20014 	if (delete_cnt <= icc.icc_unused) {
20015 		/*
20016 		 * Only need to free unused entries.  In other words,
20017 		 * there are enough unused entries to free to meet our
20018 		 * target number of freed ire cache entries.
20019 		 */
20020 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20021 		ncr.ncr_host = 0;
20022 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20023 		/*
20024 		 * Only need to free unused entries, plus a fraction of offlink
20025 		 * entries.  It follows from the first if statement that
20026 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20027 		 */
20028 		delete_cnt -= icc.icc_unused;
20029 		/* Round up # deleted by truncating fraction */
20030 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20031 		icr.icr_pmtu = icr.icr_onlink = 0;
20032 		ncr.ncr_host = 0;
20033 	} else if (delete_cnt <=
20034 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20035 		/*
20036 		 * Free all unused and offlink entries, plus a fraction of
20037 		 * pmtu entries.  It follows from the previous if statement
20038 		 * that icc_pmtu is non-zero, and that
20039 		 * delete_cnt != icc_unused + icc_offlink.
20040 		 */
20041 		icr.icr_offlink = 1;
20042 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20043 		/* Round up # deleted by truncating fraction */
20044 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20045 		icr.icr_onlink = 0;
20046 		ncr.ncr_host = 0;
20047 	} else {
20048 		/*
20049 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20050 		 * of onlink entries.  If we're here, then we know that
20051 		 * icc_onlink is non-zero, and that
20052 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20053 		 */
20054 		icr.icr_offlink = icr.icr_pmtu = 1;
20055 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20056 		    icc.icc_pmtu;
20057 		/* Round up # deleted by truncating fraction */
20058 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20059 		/* Using the same delete fraction as for onlink IREs */
20060 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20061 	}
20062 #ifdef DEBUG
20063 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20064 	    "fractions %d/%d/%d/%d\n",
20065 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20066 	    icc.icc_unused, icc.icc_offlink,
20067 	    icc.icc_pmtu, icc.icc_onlink,
20068 	    icr.icr_unused, icr.icr_offlink,
20069 	    icr.icr_pmtu, icr.icr_onlink));
20070 #endif
20071 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20072 	if (ncr.ncr_host != 0)
20073 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20074 		    (uchar_t *)&ncr, ipst);
20075 #ifdef DEBUG
20076 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20077 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20078 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20079 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20080 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20081 	    icc.icc_pmtu, icc.icc_onlink));
20082 #endif
20083 }
20084 
20085 /*
20086  * ip_unbind is called when a copy of an unbind request is received from the
20087  * upper level protocol.  We remove this conn from any fanout hash list it is
20088  * on, and zero out the bind information.  No reply is expected up above.
20089  */
20090 mblk_t *
20091 ip_unbind(queue_t *q, mblk_t *mp)
20092 {
20093 	conn_t	*connp = Q_TO_CONN(q);
20094 
20095 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20096 
20097 	if (is_system_labeled() && connp->conn_anon_port) {
20098 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20099 		    connp->conn_mlp_type, connp->conn_ulp,
20100 		    ntohs(connp->conn_lport), B_FALSE);
20101 		connp->conn_anon_port = 0;
20102 	}
20103 	connp->conn_mlp_type = mlptSingle;
20104 
20105 	ipcl_hash_remove(connp);
20106 
20107 	ASSERT(mp->b_cont == NULL);
20108 	/*
20109 	 * Convert mp into a T_OK_ACK
20110 	 */
20111 	mp = mi_tpi_ok_ack_alloc(mp);
20112 
20113 	/*
20114 	 * should not happen in practice... T_OK_ACK is smaller than the
20115 	 * original message.
20116 	 */
20117 	if (mp == NULL)
20118 		return (NULL);
20119 
20120 	return (mp);
20121 }
20122 
20123 /*
20124  * Write side put procedure.  Outbound data, IOCTLs, responses from
20125  * resolvers, etc, come down through here.
20126  *
20127  * arg2 is always a queue_t *.
20128  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20129  * the zoneid.
20130  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20131  */
20132 void
20133 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20134 {
20135 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20136 }
20137 
20138 void
20139 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20140     ip_opt_info_t *infop)
20141 {
20142 	conn_t		*connp = NULL;
20143 	queue_t		*q = (queue_t *)arg2;
20144 	ipha_t		*ipha;
20145 #define	rptr	((uchar_t *)ipha)
20146 	ire_t		*ire = NULL;
20147 	ire_t		*sctp_ire = NULL;
20148 	uint32_t	v_hlen_tos_len;
20149 	ipaddr_t	dst;
20150 	mblk_t		*first_mp = NULL;
20151 	boolean_t	mctl_present;
20152 	ipsec_out_t	*io;
20153 	int		match_flags;
20154 	ill_t		*attach_ill = NULL;
20155 					/* Bind to IPIF_NOFAILOVER ill etc. */
20156 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20157 	ipif_t		*dst_ipif;
20158 	boolean_t	multirt_need_resolve = B_FALSE;
20159 	mblk_t		*copy_mp = NULL;
20160 	int		err;
20161 	zoneid_t	zoneid;
20162 	boolean_t	need_decref = B_FALSE;
20163 	boolean_t	ignore_dontroute = B_FALSE;
20164 	boolean_t	ignore_nexthop = B_FALSE;
20165 	boolean_t	ip_nexthop = B_FALSE;
20166 	ipaddr_t	nexthop_addr;
20167 	ip_stack_t	*ipst;
20168 
20169 #ifdef	_BIG_ENDIAN
20170 #define	V_HLEN	(v_hlen_tos_len >> 24)
20171 #else
20172 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20173 #endif
20174 
20175 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20176 	    "ip_wput_start: q %p", q);
20177 
20178 	/*
20179 	 * ip_wput fast path
20180 	 */
20181 
20182 	/* is packet from ARP ? */
20183 	if (q->q_next != NULL) {
20184 		zoneid = (zoneid_t)(uintptr_t)arg;
20185 		goto qnext;
20186 	}
20187 
20188 	connp = (conn_t *)arg;
20189 	ASSERT(connp != NULL);
20190 	zoneid = connp->conn_zoneid;
20191 	ipst = connp->conn_netstack->netstack_ip;
20192 
20193 	/* is queue flow controlled? */
20194 	if ((q->q_first != NULL || connp->conn_draining) &&
20195 	    (caller == IP_WPUT)) {
20196 		ASSERT(!need_decref);
20197 		(void) putq(q, mp);
20198 		return;
20199 	}
20200 
20201 	/* Multidata transmit? */
20202 	if (DB_TYPE(mp) == M_MULTIDATA) {
20203 		/*
20204 		 * We should never get here, since all Multidata messages
20205 		 * originating from tcp should have been directed over to
20206 		 * tcp_multisend() in the first place.
20207 		 */
20208 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20209 		freemsg(mp);
20210 		return;
20211 	} else if (DB_TYPE(mp) != M_DATA)
20212 		goto notdata;
20213 
20214 	if (mp->b_flag & MSGHASREF) {
20215 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20216 		mp->b_flag &= ~MSGHASREF;
20217 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20218 		need_decref = B_TRUE;
20219 	}
20220 	ipha = (ipha_t *)mp->b_rptr;
20221 
20222 	/* is IP header non-aligned or mblk smaller than basic IP header */
20223 #ifndef SAFETY_BEFORE_SPEED
20224 	if (!OK_32PTR(rptr) ||
20225 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20226 		goto hdrtoosmall;
20227 #endif
20228 
20229 	ASSERT(OK_32PTR(ipha));
20230 
20231 	/*
20232 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20233 	 * wrong version, we'll catch it again in ip_output_v6.
20234 	 *
20235 	 * Note that this is *only* locally-generated output here, and never
20236 	 * forwarded data, and that we need to deal only with transports that
20237 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20238 	 * label.)
20239 	 */
20240 	if (is_system_labeled() &&
20241 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20242 	    !connp->conn_ulp_labeled) {
20243 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20244 		    connp->conn_mac_exempt, ipst);
20245 		ipha = (ipha_t *)mp->b_rptr;
20246 		if (err != 0) {
20247 			first_mp = mp;
20248 			if (err == EINVAL)
20249 				goto icmp_parameter_problem;
20250 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20251 			goto discard_pkt;
20252 		}
20253 	}
20254 
20255 	ASSERT(infop != NULL);
20256 
20257 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20258 		/*
20259 		 * IP_PKTINFO ancillary option is present.
20260 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20261 		 * allows using address of any zone as the source address.
20262 		 */
20263 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20264 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20265 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20266 		if (ire == NULL)
20267 			goto drop_pkt;
20268 		ire_refrele(ire);
20269 		ire = NULL;
20270 	}
20271 
20272 	/*
20273 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20274 	 * passed in IP_PKTINFO.
20275 	 */
20276 	if (infop->ip_opt_ill_index != 0 &&
20277 	    connp->conn_outgoing_ill == NULL &&
20278 	    connp->conn_nofailover_ill == NULL) {
20279 
20280 		xmit_ill = ill_lookup_on_ifindex(
20281 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20282 		    ipst);
20283 
20284 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20285 			goto drop_pkt;
20286 		/*
20287 		 * check that there is an ipif belonging
20288 		 * to our zone. IPCL_ZONEID is not used because
20289 		 * IP_ALLZONES option is valid only when the ill is
20290 		 * accessible from all zones i.e has a valid ipif in
20291 		 * all zones.
20292 		 */
20293 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20294 			goto drop_pkt;
20295 		}
20296 	}
20297 
20298 	/*
20299 	 * If there is a policy, try to attach an ipsec_out in
20300 	 * the front. At the end, first_mp either points to a
20301 	 * M_DATA message or IPSEC_OUT message linked to a
20302 	 * M_DATA message. We have to do it now as we might
20303 	 * lose the "conn" if we go through ip_newroute.
20304 	 */
20305 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20306 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20307 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20308 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20309 			if (need_decref)
20310 				CONN_DEC_REF(connp);
20311 			return;
20312 		} else {
20313 			ASSERT(mp->b_datap->db_type == M_CTL);
20314 			first_mp = mp;
20315 			mp = mp->b_cont;
20316 			mctl_present = B_TRUE;
20317 		}
20318 	} else {
20319 		first_mp = mp;
20320 		mctl_present = B_FALSE;
20321 	}
20322 
20323 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20324 
20325 	/* is wrong version or IP options present */
20326 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20327 		goto version_hdrlen_check;
20328 	dst = ipha->ipha_dst;
20329 
20330 	if (connp->conn_nofailover_ill != NULL) {
20331 		attach_ill = conn_get_held_ill(connp,
20332 		    &connp->conn_nofailover_ill, &err);
20333 		if (err == ILL_LOOKUP_FAILED) {
20334 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20335 			if (need_decref)
20336 				CONN_DEC_REF(connp);
20337 			freemsg(first_mp);
20338 			return;
20339 		}
20340 	}
20341 
20342 	/* If IP_BOUND_IF has been set, use that ill. */
20343 	if (connp->conn_outgoing_ill != NULL) {
20344 		xmit_ill = conn_get_held_ill(connp,
20345 		    &connp->conn_outgoing_ill, &err);
20346 		if (err == ILL_LOOKUP_FAILED)
20347 			goto drop_pkt;
20348 
20349 		goto send_from_ill;
20350 	}
20351 
20352 	/* is packet multicast? */
20353 	if (CLASSD(dst))
20354 		goto multicast;
20355 
20356 	/*
20357 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20358 	 * takes precedence over conn_dontroute and conn_nexthop_set
20359 	 */
20360 	if (xmit_ill != NULL)
20361 		goto send_from_ill;
20362 
20363 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20364 		/*
20365 		 * If the destination is a broadcast, local, or loopback
20366 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20367 		 * standard path.
20368 		 */
20369 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20370 		if ((ire == NULL) || (ire->ire_type &
20371 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20372 			if (ire != NULL) {
20373 				ire_refrele(ire);
20374 				/* No more access to ire */
20375 				ire = NULL;
20376 			}
20377 			/*
20378 			 * bypass routing checks and go directly to interface.
20379 			 */
20380 			if (connp->conn_dontroute)
20381 				goto dontroute;
20382 
20383 			ASSERT(connp->conn_nexthop_set);
20384 			ip_nexthop = B_TRUE;
20385 			nexthop_addr = connp->conn_nexthop_v4;
20386 			goto send_from_ill;
20387 		}
20388 
20389 		/* Must be a broadcast, a loopback or a local ire */
20390 		ire_refrele(ire);
20391 		/* No more access to ire */
20392 		ire = NULL;
20393 	}
20394 
20395 	if (attach_ill != NULL)
20396 		goto send_from_ill;
20397 
20398 	/*
20399 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20400 	 * this for the tcp global queue and listen end point
20401 	 * as it does not really have a real destination to
20402 	 * talk to.  This is also true for SCTP.
20403 	 */
20404 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20405 	    !connp->conn_fully_bound) {
20406 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20407 		if (ire == NULL)
20408 			goto noirefound;
20409 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20410 		    "ip_wput_end: q %p (%S)", q, "end");
20411 
20412 		/*
20413 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20414 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20415 		 */
20416 		if (ire->ire_flags & RTF_MULTIRT) {
20417 
20418 			/*
20419 			 * Force the TTL of multirouted packets if required.
20420 			 * The TTL of such packets is bounded by the
20421 			 * ip_multirt_ttl ndd variable.
20422 			 */
20423 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20424 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20425 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20426 				    "(was %d), dst 0x%08x\n",
20427 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20428 				    ntohl(ire->ire_addr)));
20429 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20430 			}
20431 			/*
20432 			 * We look at this point if there are pending
20433 			 * unresolved routes. ire_multirt_resolvable()
20434 			 * checks in O(n) that all IRE_OFFSUBNET ire
20435 			 * entries for the packet's destination and
20436 			 * flagged RTF_MULTIRT are currently resolved.
20437 			 * If some remain unresolved, we make a copy
20438 			 * of the current message. It will be used
20439 			 * to initiate additional route resolutions.
20440 			 */
20441 			multirt_need_resolve =
20442 			    ire_multirt_need_resolve(ire->ire_addr,
20443 			    MBLK_GETLABEL(first_mp), ipst);
20444 			ip2dbg(("ip_wput[TCP]: ire %p, "
20445 			    "multirt_need_resolve %d, first_mp %p\n",
20446 			    (void *)ire, multirt_need_resolve,
20447 			    (void *)first_mp));
20448 			if (multirt_need_resolve) {
20449 				copy_mp = copymsg(first_mp);
20450 				if (copy_mp != NULL) {
20451 					MULTIRT_DEBUG_TAG(copy_mp);
20452 				}
20453 			}
20454 		}
20455 
20456 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20457 
20458 		/*
20459 		 * Try to resolve another multiroute if
20460 		 * ire_multirt_need_resolve() deemed it necessary.
20461 		 */
20462 		if (copy_mp != NULL)
20463 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20464 		if (need_decref)
20465 			CONN_DEC_REF(connp);
20466 		return;
20467 	}
20468 
20469 	/*
20470 	 * Access to conn_ire_cache. (protected by conn_lock)
20471 	 *
20472 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20473 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20474 	 * send a packet or two with the IRE_CACHE that is going away.
20475 	 * Access to the ire requires an ire refhold on the ire prior to
20476 	 * its use since an interface unplumb thread may delete the cached
20477 	 * ire and release the refhold at any time.
20478 	 *
20479 	 * Caching an ire in the conn_ire_cache
20480 	 *
20481 	 * o Caching an ire pointer in the conn requires a strict check for
20482 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20483 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20484 	 * in the conn is done after making sure under the bucket lock that the
20485 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20486 	 * caching an ire after the unplumb thread has cleaned up the conn.
20487 	 * If the conn does not send a packet subsequently the unplumb thread
20488 	 * will be hanging waiting for the ire count to drop to zero.
20489 	 *
20490 	 * o We also need to atomically test for a null conn_ire_cache and
20491 	 * set the conn_ire_cache under the the protection of the conn_lock
20492 	 * to avoid races among concurrent threads trying to simultaneously
20493 	 * cache an ire in the conn_ire_cache.
20494 	 */
20495 	mutex_enter(&connp->conn_lock);
20496 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20497 
20498 	if (ire != NULL && ire->ire_addr == dst &&
20499 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20500 
20501 		IRE_REFHOLD(ire);
20502 		mutex_exit(&connp->conn_lock);
20503 
20504 	} else {
20505 		boolean_t cached = B_FALSE;
20506 		connp->conn_ire_cache = NULL;
20507 		mutex_exit(&connp->conn_lock);
20508 		/* Release the old ire */
20509 		if (ire != NULL && sctp_ire == NULL)
20510 			IRE_REFRELE_NOTR(ire);
20511 
20512 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20513 		if (ire == NULL)
20514 			goto noirefound;
20515 		IRE_REFHOLD_NOTR(ire);
20516 
20517 		mutex_enter(&connp->conn_lock);
20518 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20519 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20520 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20521 				if (connp->conn_ulp == IPPROTO_TCP)
20522 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20523 				connp->conn_ire_cache = ire;
20524 				cached = B_TRUE;
20525 			}
20526 			rw_exit(&ire->ire_bucket->irb_lock);
20527 		}
20528 		mutex_exit(&connp->conn_lock);
20529 
20530 		/*
20531 		 * We can continue to use the ire but since it was
20532 		 * not cached, we should drop the extra reference.
20533 		 */
20534 		if (!cached)
20535 			IRE_REFRELE_NOTR(ire);
20536 	}
20537 
20538 
20539 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20540 	    "ip_wput_end: q %p (%S)", q, "end");
20541 
20542 	/*
20543 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20544 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20545 	 */
20546 	if (ire->ire_flags & RTF_MULTIRT) {
20547 
20548 		/*
20549 		 * Force the TTL of multirouted packets if required.
20550 		 * The TTL of such packets is bounded by the
20551 		 * ip_multirt_ttl ndd variable.
20552 		 */
20553 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20554 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20555 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20556 			    "(was %d), dst 0x%08x\n",
20557 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20558 			    ntohl(ire->ire_addr)));
20559 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20560 		}
20561 
20562 		/*
20563 		 * At this point, we check to see if there are any pending
20564 		 * unresolved routes. ire_multirt_resolvable()
20565 		 * checks in O(n) that all IRE_OFFSUBNET ire
20566 		 * entries for the packet's destination and
20567 		 * flagged RTF_MULTIRT are currently resolved.
20568 		 * If some remain unresolved, we make a copy
20569 		 * of the current message. It will be used
20570 		 * to initiate additional route resolutions.
20571 		 */
20572 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20573 		    MBLK_GETLABEL(first_mp), ipst);
20574 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20575 		    "multirt_need_resolve %d, first_mp %p\n",
20576 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20577 		if (multirt_need_resolve) {
20578 			copy_mp = copymsg(first_mp);
20579 			if (copy_mp != NULL) {
20580 				MULTIRT_DEBUG_TAG(copy_mp);
20581 			}
20582 		}
20583 	}
20584 
20585 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20586 
20587 	/*
20588 	 * Try to resolve another multiroute if
20589 	 * ire_multirt_resolvable() deemed it necessary
20590 	 */
20591 	if (copy_mp != NULL)
20592 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20593 	if (need_decref)
20594 		CONN_DEC_REF(connp);
20595 	return;
20596 
20597 qnext:
20598 	/*
20599 	 * Upper Level Protocols pass down complete IP datagrams
20600 	 * as M_DATA messages.	Everything else is a sideshow.
20601 	 *
20602 	 * 1) We could be re-entering ip_wput because of ip_neworute
20603 	 *    in which case we could have a IPSEC_OUT message. We
20604 	 *    need to pass through ip_wput like other datagrams and
20605 	 *    hence cannot branch to ip_wput_nondata.
20606 	 *
20607 	 * 2) ARP, AH, ESP, and other clients who are on the module
20608 	 *    instance of IP stream, give us something to deal with.
20609 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20610 	 *
20611 	 * 3) ICMP replies also could come here.
20612 	 */
20613 	ipst = ILLQ_TO_IPST(q);
20614 
20615 	if (DB_TYPE(mp) != M_DATA) {
20616 notdata:
20617 		if (DB_TYPE(mp) == M_CTL) {
20618 			/*
20619 			 * M_CTL messages are used by ARP, AH and ESP to
20620 			 * communicate with IP. We deal with IPSEC_IN and
20621 			 * IPSEC_OUT here. ip_wput_nondata handles other
20622 			 * cases.
20623 			 */
20624 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20625 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20626 				first_mp = mp->b_cont;
20627 				first_mp->b_flag &= ~MSGHASREF;
20628 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20629 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20630 				CONN_DEC_REF(connp);
20631 				connp = NULL;
20632 			}
20633 			if (ii->ipsec_info_type == IPSEC_IN) {
20634 				/*
20635 				 * Either this message goes back to
20636 				 * IPsec for further processing or to
20637 				 * ULP after policy checks.
20638 				 */
20639 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20640 				return;
20641 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20642 				io = (ipsec_out_t *)ii;
20643 				if (io->ipsec_out_proc_begin) {
20644 					/*
20645 					 * IPsec processing has already started.
20646 					 * Complete it.
20647 					 * IPQoS notes: We don't care what is
20648 					 * in ipsec_out_ill_index since this
20649 					 * won't be processed for IPQoS policies
20650 					 * in ipsec_out_process.
20651 					 */
20652 					ipsec_out_process(q, mp, NULL,
20653 					    io->ipsec_out_ill_index);
20654 					return;
20655 				} else {
20656 					connp = (q->q_next != NULL) ?
20657 					    NULL : Q_TO_CONN(q);
20658 					first_mp = mp;
20659 					mp = mp->b_cont;
20660 					mctl_present = B_TRUE;
20661 				}
20662 				zoneid = io->ipsec_out_zoneid;
20663 				ASSERT(zoneid != ALL_ZONES);
20664 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20665 				/*
20666 				 * It's an IPsec control message requesting
20667 				 * an SADB update to be sent to the IPsec
20668 				 * hardware acceleration capable ills.
20669 				 */
20670 				ipsec_ctl_t *ipsec_ctl =
20671 				    (ipsec_ctl_t *)mp->b_rptr;
20672 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20673 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20674 				mblk_t *cmp = mp->b_cont;
20675 
20676 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20677 				ASSERT(cmp != NULL);
20678 
20679 				freeb(mp);
20680 				ill_ipsec_capab_send_all(satype, cmp, sa,
20681 				    ipst->ips_netstack);
20682 				return;
20683 			} else {
20684 				/*
20685 				 * This must be ARP or special TSOL signaling.
20686 				 */
20687 				ip_wput_nondata(NULL, q, mp, NULL);
20688 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20689 				    "ip_wput_end: q %p (%S)", q, "nondata");
20690 				return;
20691 			}
20692 		} else {
20693 			/*
20694 			 * This must be non-(ARP/AH/ESP) messages.
20695 			 */
20696 			ASSERT(!need_decref);
20697 			ip_wput_nondata(NULL, q, mp, NULL);
20698 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20699 			    "ip_wput_end: q %p (%S)", q, "nondata");
20700 			return;
20701 		}
20702 	} else {
20703 		first_mp = mp;
20704 		mctl_present = B_FALSE;
20705 	}
20706 
20707 	ASSERT(first_mp != NULL);
20708 	/*
20709 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20710 	 * to make sure that this packet goes out on the same interface it
20711 	 * came in. We handle that here.
20712 	 */
20713 	if (mctl_present) {
20714 		uint_t ifindex;
20715 
20716 		io = (ipsec_out_t *)first_mp->b_rptr;
20717 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20718 			/*
20719 			 * We may have lost the conn context if we are
20720 			 * coming here from ip_newroute(). Copy the
20721 			 * nexthop information.
20722 			 */
20723 			if (io->ipsec_out_ip_nexthop) {
20724 				ip_nexthop = B_TRUE;
20725 				nexthop_addr = io->ipsec_out_nexthop_addr;
20726 
20727 				ipha = (ipha_t *)mp->b_rptr;
20728 				dst = ipha->ipha_dst;
20729 				goto send_from_ill;
20730 			} else {
20731 				ASSERT(io->ipsec_out_ill_index != 0);
20732 				ifindex = io->ipsec_out_ill_index;
20733 				attach_ill = ill_lookup_on_ifindex(ifindex,
20734 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20735 				if (attach_ill == NULL) {
20736 					ASSERT(xmit_ill == NULL);
20737 					ip1dbg(("ip_output: bad ifindex for "
20738 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20739 					    ifindex));
20740 					freemsg(first_mp);
20741 					BUMP_MIB(&ipst->ips_ip_mib,
20742 					    ipIfStatsOutDiscards);
20743 					ASSERT(!need_decref);
20744 					return;
20745 				}
20746 			}
20747 		}
20748 	}
20749 
20750 	ASSERT(xmit_ill == NULL);
20751 
20752 	/* We have a complete IP datagram heading outbound. */
20753 	ipha = (ipha_t *)mp->b_rptr;
20754 
20755 #ifndef SPEED_BEFORE_SAFETY
20756 	/*
20757 	 * Make sure we have a full-word aligned message and that at least
20758 	 * a simple IP header is accessible in the first message.  If not,
20759 	 * try a pullup.  For labeled systems we need to always take this
20760 	 * path as M_CTLs are "notdata" but have trailing data to process.
20761 	 */
20762 	if (!OK_32PTR(rptr) ||
20763 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20764 hdrtoosmall:
20765 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20766 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20767 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20768 			if (first_mp == NULL)
20769 				first_mp = mp;
20770 			goto discard_pkt;
20771 		}
20772 
20773 		/* This function assumes that mp points to an IPv4 packet. */
20774 		if (is_system_labeled() && q->q_next == NULL &&
20775 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20776 		    !connp->conn_ulp_labeled) {
20777 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20778 			    connp->conn_mac_exempt, ipst);
20779 			ipha = (ipha_t *)mp->b_rptr;
20780 			if (first_mp != NULL)
20781 				first_mp->b_cont = mp;
20782 			if (err != 0) {
20783 				if (first_mp == NULL)
20784 					first_mp = mp;
20785 				if (err == EINVAL)
20786 					goto icmp_parameter_problem;
20787 				ip2dbg(("ip_wput: label check failed (%d)\n",
20788 				    err));
20789 				goto discard_pkt;
20790 			}
20791 		}
20792 
20793 		ipha = (ipha_t *)mp->b_rptr;
20794 		if (first_mp == NULL) {
20795 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20796 			/*
20797 			 * If we got here because of "goto hdrtoosmall"
20798 			 * We need to attach a IPSEC_OUT.
20799 			 */
20800 			if (connp->conn_out_enforce_policy) {
20801 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20802 				    NULL, ipha->ipha_protocol,
20803 				    ipst->ips_netstack)) == NULL)) {
20804 					BUMP_MIB(&ipst->ips_ip_mib,
20805 					    ipIfStatsOutDiscards);
20806 					if (need_decref)
20807 						CONN_DEC_REF(connp);
20808 					return;
20809 				} else {
20810 					ASSERT(mp->b_datap->db_type == M_CTL);
20811 					first_mp = mp;
20812 					mp = mp->b_cont;
20813 					mctl_present = B_TRUE;
20814 				}
20815 			} else {
20816 				first_mp = mp;
20817 				mctl_present = B_FALSE;
20818 			}
20819 		}
20820 	}
20821 #endif
20822 
20823 	/* Most of the code below is written for speed, not readability */
20824 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20825 
20826 	/*
20827 	 * If ip_newroute() fails, we're going to need a full
20828 	 * header for the icmp wraparound.
20829 	 */
20830 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20831 		uint_t	v_hlen;
20832 version_hdrlen_check:
20833 		ASSERT(first_mp != NULL);
20834 		v_hlen = V_HLEN;
20835 		/*
20836 		 * siphon off IPv6 packets coming down from transport
20837 		 * layer modules here.
20838 		 * Note: high-order bit carries NUD reachability confirmation
20839 		 */
20840 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20841 			/*
20842 			 * FIXME: assume that callers of ip_output* call
20843 			 * the right version?
20844 			 */
20845 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20846 			ASSERT(xmit_ill == NULL);
20847 			if (attach_ill != NULL)
20848 				ill_refrele(attach_ill);
20849 			if (need_decref)
20850 				mp->b_flag |= MSGHASREF;
20851 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20852 			return;
20853 		}
20854 
20855 		if ((v_hlen >> 4) != IP_VERSION) {
20856 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20857 			    "ip_wput_end: q %p (%S)", q, "badvers");
20858 			goto discard_pkt;
20859 		}
20860 		/*
20861 		 * Is the header length at least 20 bytes?
20862 		 *
20863 		 * Are there enough bytes accessible in the header?  If
20864 		 * not, try a pullup.
20865 		 */
20866 		v_hlen &= 0xF;
20867 		v_hlen <<= 2;
20868 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20869 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20870 			    "ip_wput_end: q %p (%S)", q, "badlen");
20871 			goto discard_pkt;
20872 		}
20873 		if (v_hlen > (mp->b_wptr - rptr)) {
20874 			if (!pullupmsg(mp, v_hlen)) {
20875 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20876 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20877 				goto discard_pkt;
20878 			}
20879 			ipha = (ipha_t *)mp->b_rptr;
20880 		}
20881 		/*
20882 		 * Move first entry from any source route into ipha_dst and
20883 		 * verify the options
20884 		 */
20885 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20886 		    zoneid, ipst)) {
20887 			ASSERT(xmit_ill == NULL);
20888 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20889 			if (attach_ill != NULL)
20890 				ill_refrele(attach_ill);
20891 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20892 			    "ip_wput_end: q %p (%S)", q, "badopts");
20893 			if (need_decref)
20894 				CONN_DEC_REF(connp);
20895 			return;
20896 		}
20897 	}
20898 	dst = ipha->ipha_dst;
20899 
20900 	/*
20901 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20902 	 * we have to run the packet through ip_newroute which will take
20903 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20904 	 * a resolver, or assigning a default gateway, etc.
20905 	 */
20906 	if (CLASSD(dst)) {
20907 		ipif_t	*ipif;
20908 		uint32_t setsrc = 0;
20909 
20910 multicast:
20911 		ASSERT(first_mp != NULL);
20912 		ip2dbg(("ip_wput: CLASSD\n"));
20913 		if (connp == NULL) {
20914 			/*
20915 			 * Use the first good ipif on the ill.
20916 			 * XXX Should this ever happen? (Appears
20917 			 * to show up with just ppp and no ethernet due
20918 			 * to in.rdisc.)
20919 			 * However, ire_send should be able to
20920 			 * call ip_wput_ire directly.
20921 			 *
20922 			 * XXX Also, this can happen for ICMP and other packets
20923 			 * with multicast source addresses.  Perhaps we should
20924 			 * fix things so that we drop the packet in question,
20925 			 * but for now, just run with it.
20926 			 */
20927 			ill_t *ill = (ill_t *)q->q_ptr;
20928 
20929 			/*
20930 			 * Don't honor attach_if for this case. If ill
20931 			 * is part of the group, ipif could belong to
20932 			 * any ill and we cannot maintain attach_ill
20933 			 * and ipif_ill same anymore and the assert
20934 			 * below would fail.
20935 			 */
20936 			if (mctl_present && io->ipsec_out_attach_if) {
20937 				io->ipsec_out_ill_index = 0;
20938 				io->ipsec_out_attach_if = B_FALSE;
20939 				ASSERT(attach_ill != NULL);
20940 				ill_refrele(attach_ill);
20941 				attach_ill = NULL;
20942 			}
20943 
20944 			ASSERT(attach_ill == NULL);
20945 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20946 			if (ipif == NULL) {
20947 				if (need_decref)
20948 					CONN_DEC_REF(connp);
20949 				freemsg(first_mp);
20950 				return;
20951 			}
20952 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20953 			    ntohl(dst), ill->ill_name));
20954 		} else {
20955 			/*
20956 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20957 			 * and IP_MULTICAST_IF.  The block comment above this
20958 			 * function explains the locking mechanism used here.
20959 			 */
20960 			if (xmit_ill == NULL) {
20961 				xmit_ill = conn_get_held_ill(connp,
20962 				    &connp->conn_outgoing_ill, &err);
20963 				if (err == ILL_LOOKUP_FAILED) {
20964 					ip1dbg(("ip_wput: No ill for "
20965 					    "IP_BOUND_IF\n"));
20966 					BUMP_MIB(&ipst->ips_ip_mib,
20967 					    ipIfStatsOutNoRoutes);
20968 					goto drop_pkt;
20969 				}
20970 			}
20971 
20972 			if (xmit_ill == NULL) {
20973 				ipif = conn_get_held_ipif(connp,
20974 				    &connp->conn_multicast_ipif, &err);
20975 				if (err == IPIF_LOOKUP_FAILED) {
20976 					ip1dbg(("ip_wput: No ipif for "
20977 					    "multicast\n"));
20978 					BUMP_MIB(&ipst->ips_ip_mib,
20979 					    ipIfStatsOutNoRoutes);
20980 					goto drop_pkt;
20981 				}
20982 			}
20983 			if (xmit_ill != NULL) {
20984 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20985 				if (ipif == NULL) {
20986 					ip1dbg(("ip_wput: No ipif for "
20987 					    "xmit_ill\n"));
20988 					BUMP_MIB(&ipst->ips_ip_mib,
20989 					    ipIfStatsOutNoRoutes);
20990 					goto drop_pkt;
20991 				}
20992 			} else if (ipif == NULL || ipif->ipif_isv6) {
20993 				/*
20994 				 * We must do this ipif determination here
20995 				 * else we could pass through ip_newroute
20996 				 * and come back here without the conn context.
20997 				 *
20998 				 * Note: we do late binding i.e. we bind to
20999 				 * the interface when the first packet is sent.
21000 				 * For performance reasons we do not rebind on
21001 				 * each packet but keep the binding until the
21002 				 * next IP_MULTICAST_IF option.
21003 				 *
21004 				 * conn_multicast_{ipif,ill} are shared between
21005 				 * IPv4 and IPv6 and AF_INET6 sockets can
21006 				 * send both IPv4 and IPv6 packets. Hence
21007 				 * we have to check that "isv6" matches above.
21008 				 */
21009 				if (ipif != NULL)
21010 					ipif_refrele(ipif);
21011 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21012 				if (ipif == NULL) {
21013 					ip1dbg(("ip_wput: No ipif for "
21014 					    "multicast\n"));
21015 					BUMP_MIB(&ipst->ips_ip_mib,
21016 					    ipIfStatsOutNoRoutes);
21017 					goto drop_pkt;
21018 				}
21019 				err = conn_set_held_ipif(connp,
21020 				    &connp->conn_multicast_ipif, ipif);
21021 				if (err == IPIF_LOOKUP_FAILED) {
21022 					ipif_refrele(ipif);
21023 					ip1dbg(("ip_wput: No ipif for "
21024 					    "multicast\n"));
21025 					BUMP_MIB(&ipst->ips_ip_mib,
21026 					    ipIfStatsOutNoRoutes);
21027 					goto drop_pkt;
21028 				}
21029 			}
21030 		}
21031 		ASSERT(!ipif->ipif_isv6);
21032 		/*
21033 		 * As we may lose the conn by the time we reach ip_wput_ire,
21034 		 * we copy conn_multicast_loop and conn_dontroute on to an
21035 		 * ipsec_out. In case if this datagram goes out secure,
21036 		 * we need the ill_index also. Copy that also into the
21037 		 * ipsec_out.
21038 		 */
21039 		if (mctl_present) {
21040 			io = (ipsec_out_t *)first_mp->b_rptr;
21041 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21042 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21043 		} else {
21044 			ASSERT(mp == first_mp);
21045 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21046 			    BPRI_HI)) == NULL) {
21047 				ipif_refrele(ipif);
21048 				first_mp = mp;
21049 				goto discard_pkt;
21050 			}
21051 			first_mp->b_datap->db_type = M_CTL;
21052 			first_mp->b_wptr += sizeof (ipsec_info_t);
21053 			/* ipsec_out_secure is B_FALSE now */
21054 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21055 			io = (ipsec_out_t *)first_mp->b_rptr;
21056 			io->ipsec_out_type = IPSEC_OUT;
21057 			io->ipsec_out_len = sizeof (ipsec_out_t);
21058 			io->ipsec_out_use_global_policy = B_TRUE;
21059 			io->ipsec_out_ns = ipst->ips_netstack;
21060 			first_mp->b_cont = mp;
21061 			mctl_present = B_TRUE;
21062 		}
21063 		if (attach_ill != NULL) {
21064 			ASSERT(attach_ill == ipif->ipif_ill);
21065 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21066 
21067 			/*
21068 			 * Check if we need an ire that will not be
21069 			 * looked up by anybody else i.e. HIDDEN.
21070 			 */
21071 			if (ill_is_probeonly(attach_ill)) {
21072 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21073 			}
21074 			io->ipsec_out_ill_index =
21075 			    attach_ill->ill_phyint->phyint_ifindex;
21076 			io->ipsec_out_attach_if = B_TRUE;
21077 		} else {
21078 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21079 			io->ipsec_out_ill_index =
21080 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21081 		}
21082 		if (connp != NULL) {
21083 			io->ipsec_out_multicast_loop =
21084 			    connp->conn_multicast_loop;
21085 			io->ipsec_out_dontroute = connp->conn_dontroute;
21086 			io->ipsec_out_zoneid = connp->conn_zoneid;
21087 		}
21088 		/*
21089 		 * If the application uses IP_MULTICAST_IF with
21090 		 * different logical addresses of the same ILL, we
21091 		 * need to make sure that the soruce address of
21092 		 * the packet matches the logical IP address used
21093 		 * in the option. We do it by initializing ipha_src
21094 		 * here. This should keep IPsec also happy as
21095 		 * when we return from IPsec processing, we don't
21096 		 * have to worry about getting the right address on
21097 		 * the packet. Thus it is sufficient to look for
21098 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21099 		 * MATCH_IRE_IPIF.
21100 		 *
21101 		 * NOTE : We need to do it for non-secure case also as
21102 		 * this might go out secure if there is a global policy
21103 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21104 		 * address, the source should be initialized already and
21105 		 * hence we won't be initializing here.
21106 		 *
21107 		 * As we do not have the ire yet, it is possible that
21108 		 * we set the source address here and then later discover
21109 		 * that the ire implies the source address to be assigned
21110 		 * through the RTF_SETSRC flag.
21111 		 * In that case, the setsrc variable will remind us
21112 		 * that overwritting the source address by the one
21113 		 * of the RTF_SETSRC-flagged ire is allowed.
21114 		 */
21115 		if (ipha->ipha_src == INADDR_ANY &&
21116 		    (connp == NULL || !connp->conn_unspec_src)) {
21117 			ipha->ipha_src = ipif->ipif_src_addr;
21118 			setsrc = RTF_SETSRC;
21119 		}
21120 		/*
21121 		 * Find an IRE which matches the destination and the outgoing
21122 		 * queue (i.e. the outgoing interface.)
21123 		 * For loopback use a unicast IP address for
21124 		 * the ire lookup.
21125 		 */
21126 		if (IS_LOOPBACK(ipif->ipif_ill))
21127 			dst = ipif->ipif_lcl_addr;
21128 
21129 		/*
21130 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21131 		 * We don't need to lookup ire in ctable as the packet
21132 		 * needs to be sent to the destination through the specified
21133 		 * ill irrespective of ires in the cache table.
21134 		 */
21135 		ire = NULL;
21136 		if (xmit_ill == NULL) {
21137 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21138 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21139 		}
21140 
21141 		/*
21142 		 * refrele attach_ill as its not needed anymore.
21143 		 */
21144 		if (attach_ill != NULL) {
21145 			ill_refrele(attach_ill);
21146 			attach_ill = NULL;
21147 		}
21148 
21149 		if (ire == NULL) {
21150 			/*
21151 			 * Multicast loopback and multicast forwarding is
21152 			 * done in ip_wput_ire.
21153 			 *
21154 			 * Mark this packet to make it be delivered to
21155 			 * ip_wput_ire after the new ire has been
21156 			 * created.
21157 			 *
21158 			 * The call to ip_newroute_ipif takes into account
21159 			 * the setsrc reminder. In any case, we take care
21160 			 * of the RTF_MULTIRT flag.
21161 			 */
21162 			mp->b_prev = mp->b_next = NULL;
21163 			if (xmit_ill == NULL ||
21164 			    xmit_ill->ill_ipif_up_count > 0) {
21165 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21166 				    setsrc | RTF_MULTIRT, zoneid, infop);
21167 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21168 				    "ip_wput_end: q %p (%S)", q, "noire");
21169 			} else {
21170 				freemsg(first_mp);
21171 			}
21172 			ipif_refrele(ipif);
21173 			if (xmit_ill != NULL)
21174 				ill_refrele(xmit_ill);
21175 			if (need_decref)
21176 				CONN_DEC_REF(connp);
21177 			return;
21178 		}
21179 
21180 		ipif_refrele(ipif);
21181 		ipif = NULL;
21182 		ASSERT(xmit_ill == NULL);
21183 
21184 		/*
21185 		 * Honor the RTF_SETSRC flag for multicast packets,
21186 		 * if allowed by the setsrc reminder.
21187 		 */
21188 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21189 			ipha->ipha_src = ire->ire_src_addr;
21190 		}
21191 
21192 		/*
21193 		 * Unconditionally force the TTL to 1 for
21194 		 * multirouted multicast packets:
21195 		 * multirouted multicast should not cross
21196 		 * multicast routers.
21197 		 */
21198 		if (ire->ire_flags & RTF_MULTIRT) {
21199 			if (ipha->ipha_ttl > 1) {
21200 				ip2dbg(("ip_wput: forcing multicast "
21201 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21202 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21203 				ipha->ipha_ttl = 1;
21204 			}
21205 		}
21206 	} else {
21207 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21208 		if ((ire != NULL) && (ire->ire_type &
21209 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21210 			ignore_dontroute = B_TRUE;
21211 			ignore_nexthop = B_TRUE;
21212 		}
21213 		if (ire != NULL) {
21214 			ire_refrele(ire);
21215 			ire = NULL;
21216 		}
21217 		/*
21218 		 * Guard against coming in from arp in which case conn is NULL.
21219 		 * Also guard against non M_DATA with dontroute set but
21220 		 * destined to local, loopback or broadcast addresses.
21221 		 */
21222 		if (connp != NULL && connp->conn_dontroute &&
21223 		    !ignore_dontroute) {
21224 dontroute:
21225 			/*
21226 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21227 			 * routing protocols from seeing false direct
21228 			 * connectivity.
21229 			 */
21230 			ipha->ipha_ttl = 1;
21231 
21232 			/* If suitable ipif not found, drop packet */
21233 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21234 			if (dst_ipif == NULL) {
21235 noroute:
21236 				ip1dbg(("ip_wput: no route for dst using"
21237 				    " SO_DONTROUTE\n"));
21238 				BUMP_MIB(&ipst->ips_ip_mib,
21239 				    ipIfStatsOutNoRoutes);
21240 				mp->b_prev = mp->b_next = NULL;
21241 				if (first_mp == NULL)
21242 					first_mp = mp;
21243 				goto drop_pkt;
21244 			} else {
21245 				/*
21246 				 * If suitable ipif has been found, set
21247 				 * xmit_ill to the corresponding
21248 				 * ipif_ill because we'll be using the
21249 				 * send_from_ill logic below.
21250 				 */
21251 				ASSERT(xmit_ill == NULL);
21252 				xmit_ill = dst_ipif->ipif_ill;
21253 				mutex_enter(&xmit_ill->ill_lock);
21254 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21255 					mutex_exit(&xmit_ill->ill_lock);
21256 					xmit_ill = NULL;
21257 					ipif_refrele(dst_ipif);
21258 					goto noroute;
21259 				}
21260 				ill_refhold_locked(xmit_ill);
21261 				mutex_exit(&xmit_ill->ill_lock);
21262 				ipif_refrele(dst_ipif);
21263 			}
21264 		}
21265 		/*
21266 		 * If we are bound to IPIF_NOFAILOVER address, look for
21267 		 * an IRE_CACHE matching the ill.
21268 		 */
21269 send_from_ill:
21270 		if (attach_ill != NULL) {
21271 			ipif_t	*attach_ipif;
21272 
21273 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21274 
21275 			/*
21276 			 * Check if we need an ire that will not be
21277 			 * looked up by anybody else i.e. HIDDEN.
21278 			 */
21279 			if (ill_is_probeonly(attach_ill)) {
21280 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21281 			}
21282 
21283 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21284 			if (attach_ipif == NULL) {
21285 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21286 				goto discard_pkt;
21287 			}
21288 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21289 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21290 			ipif_refrele(attach_ipif);
21291 		} else if (xmit_ill != NULL) {
21292 			ipif_t *ipif;
21293 
21294 			/*
21295 			 * Mark this packet as originated locally
21296 			 */
21297 			mp->b_prev = mp->b_next = NULL;
21298 
21299 			/*
21300 			 * Could be SO_DONTROUTE case also.
21301 			 * Verify that at least one ipif is up on the ill.
21302 			 */
21303 			if (xmit_ill->ill_ipif_up_count == 0) {
21304 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21305 				    xmit_ill->ill_name));
21306 				goto drop_pkt;
21307 			}
21308 
21309 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21310 			if (ipif == NULL) {
21311 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21312 				    xmit_ill->ill_name));
21313 				goto drop_pkt;
21314 			}
21315 
21316 			/*
21317 			 * Look for a ire that is part of the group,
21318 			 * if found use it else call ip_newroute_ipif.
21319 			 * IPCL_ZONEID is not used for matching because
21320 			 * IP_ALLZONES option is valid only when the
21321 			 * ill is accessible from all zones i.e has a
21322 			 * valid ipif in all zones.
21323 			 */
21324 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21325 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21326 			    MBLK_GETLABEL(mp), match_flags, ipst);
21327 			/*
21328 			 * If an ire exists use it or else create
21329 			 * an ire but don't add it to the cache.
21330 			 * Adding an ire may cause issues with
21331 			 * asymmetric routing.
21332 			 * In case of multiroute always act as if
21333 			 * ire does not exist.
21334 			 */
21335 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21336 				if (ire != NULL)
21337 					ire_refrele(ire);
21338 				ip_newroute_ipif(q, first_mp, ipif,
21339 				    dst, connp, 0, zoneid, infop);
21340 				ipif_refrele(ipif);
21341 				ip1dbg(("ip_output: xmit_ill via %s\n",
21342 				    xmit_ill->ill_name));
21343 				ill_refrele(xmit_ill);
21344 				if (need_decref)
21345 					CONN_DEC_REF(connp);
21346 				return;
21347 			}
21348 			ipif_refrele(ipif);
21349 		} else if (ip_nexthop || (connp != NULL &&
21350 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21351 			if (!ip_nexthop) {
21352 				ip_nexthop = B_TRUE;
21353 				nexthop_addr = connp->conn_nexthop_v4;
21354 			}
21355 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21356 			    MATCH_IRE_GW;
21357 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21358 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21359 		} else {
21360 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21361 			    ipst);
21362 		}
21363 		if (!ire) {
21364 			/*
21365 			 * Make sure we don't load spread if this
21366 			 * is IPIF_NOFAILOVER case.
21367 			 */
21368 			if ((attach_ill != NULL) ||
21369 			    (ip_nexthop && !ignore_nexthop)) {
21370 				if (mctl_present) {
21371 					io = (ipsec_out_t *)first_mp->b_rptr;
21372 					ASSERT(first_mp->b_datap->db_type ==
21373 					    M_CTL);
21374 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21375 				} else {
21376 					ASSERT(mp == first_mp);
21377 					first_mp = allocb(
21378 					    sizeof (ipsec_info_t), BPRI_HI);
21379 					if (first_mp == NULL) {
21380 						first_mp = mp;
21381 						goto discard_pkt;
21382 					}
21383 					first_mp->b_datap->db_type = M_CTL;
21384 					first_mp->b_wptr +=
21385 					    sizeof (ipsec_info_t);
21386 					/* ipsec_out_secure is B_FALSE now */
21387 					bzero(first_mp->b_rptr,
21388 					    sizeof (ipsec_info_t));
21389 					io = (ipsec_out_t *)first_mp->b_rptr;
21390 					io->ipsec_out_type = IPSEC_OUT;
21391 					io->ipsec_out_len =
21392 					    sizeof (ipsec_out_t);
21393 					io->ipsec_out_use_global_policy =
21394 					    B_TRUE;
21395 					io->ipsec_out_ns = ipst->ips_netstack;
21396 					first_mp->b_cont = mp;
21397 					mctl_present = B_TRUE;
21398 				}
21399 				if (attach_ill != NULL) {
21400 					io->ipsec_out_ill_index = attach_ill->
21401 					    ill_phyint->phyint_ifindex;
21402 					io->ipsec_out_attach_if = B_TRUE;
21403 				} else {
21404 					io->ipsec_out_ip_nexthop = ip_nexthop;
21405 					io->ipsec_out_nexthop_addr =
21406 					    nexthop_addr;
21407 				}
21408 			}
21409 noirefound:
21410 			/*
21411 			 * Mark this packet as having originated on
21412 			 * this machine.  This will be noted in
21413 			 * ire_add_then_send, which needs to know
21414 			 * whether to run it back through ip_wput or
21415 			 * ip_rput following successful resolution.
21416 			 */
21417 			mp->b_prev = NULL;
21418 			mp->b_next = NULL;
21419 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21420 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21421 			    "ip_wput_end: q %p (%S)", q, "newroute");
21422 			if (attach_ill != NULL)
21423 				ill_refrele(attach_ill);
21424 			if (xmit_ill != NULL)
21425 				ill_refrele(xmit_ill);
21426 			if (need_decref)
21427 				CONN_DEC_REF(connp);
21428 			return;
21429 		}
21430 	}
21431 
21432 	/* We now know where we are going with it. */
21433 
21434 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21435 	    "ip_wput_end: q %p (%S)", q, "end");
21436 
21437 	/*
21438 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21439 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21440 	 */
21441 	if (ire->ire_flags & RTF_MULTIRT) {
21442 		/*
21443 		 * Force the TTL of multirouted packets if required.
21444 		 * The TTL of such packets is bounded by the
21445 		 * ip_multirt_ttl ndd variable.
21446 		 */
21447 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21448 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21449 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21450 			    "(was %d), dst 0x%08x\n",
21451 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21452 			    ntohl(ire->ire_addr)));
21453 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21454 		}
21455 		/*
21456 		 * At this point, we check to see if there are any pending
21457 		 * unresolved routes. ire_multirt_resolvable()
21458 		 * checks in O(n) that all IRE_OFFSUBNET ire
21459 		 * entries for the packet's destination and
21460 		 * flagged RTF_MULTIRT are currently resolved.
21461 		 * If some remain unresolved, we make a copy
21462 		 * of the current message. It will be used
21463 		 * to initiate additional route resolutions.
21464 		 */
21465 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21466 		    MBLK_GETLABEL(first_mp), ipst);
21467 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21468 		    "multirt_need_resolve %d, first_mp %p\n",
21469 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21470 		if (multirt_need_resolve) {
21471 			copy_mp = copymsg(first_mp);
21472 			if (copy_mp != NULL) {
21473 				MULTIRT_DEBUG_TAG(copy_mp);
21474 			}
21475 		}
21476 	}
21477 
21478 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21479 	/*
21480 	 * Try to resolve another multiroute if
21481 	 * ire_multirt_resolvable() deemed it necessary.
21482 	 * At this point, we need to distinguish
21483 	 * multicasts from other packets. For multicasts,
21484 	 * we call ip_newroute_ipif() and request that both
21485 	 * multirouting and setsrc flags are checked.
21486 	 */
21487 	if (copy_mp != NULL) {
21488 		if (CLASSD(dst)) {
21489 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21490 			if (ipif) {
21491 				ASSERT(infop->ip_opt_ill_index == 0);
21492 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21493 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21494 				ipif_refrele(ipif);
21495 			} else {
21496 				MULTIRT_DEBUG_UNTAG(copy_mp);
21497 				freemsg(copy_mp);
21498 				copy_mp = NULL;
21499 			}
21500 		} else {
21501 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21502 		}
21503 	}
21504 	if (attach_ill != NULL)
21505 		ill_refrele(attach_ill);
21506 	if (xmit_ill != NULL)
21507 		ill_refrele(xmit_ill);
21508 	if (need_decref)
21509 		CONN_DEC_REF(connp);
21510 	return;
21511 
21512 icmp_parameter_problem:
21513 	/* could not have originated externally */
21514 	ASSERT(mp->b_prev == NULL);
21515 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21516 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21517 		/* it's the IP header length that's in trouble */
21518 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21519 		first_mp = NULL;
21520 	}
21521 
21522 discard_pkt:
21523 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21524 drop_pkt:
21525 	ip1dbg(("ip_wput: dropped packet\n"));
21526 	if (ire != NULL)
21527 		ire_refrele(ire);
21528 	if (need_decref)
21529 		CONN_DEC_REF(connp);
21530 	freemsg(first_mp);
21531 	if (attach_ill != NULL)
21532 		ill_refrele(attach_ill);
21533 	if (xmit_ill != NULL)
21534 		ill_refrele(xmit_ill);
21535 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21536 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21537 }
21538 
21539 /*
21540  * If this is a conn_t queue, then we pass in the conn. This includes the
21541  * zoneid.
21542  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21543  * in which case we use the global zoneid since those are all part of
21544  * the global zone.
21545  */
21546 void
21547 ip_wput(queue_t *q, mblk_t *mp)
21548 {
21549 	if (CONN_Q(q))
21550 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21551 	else
21552 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21553 }
21554 
21555 /*
21556  *
21557  * The following rules must be observed when accessing any ipif or ill
21558  * that has been cached in the conn. Typically conn_nofailover_ill,
21559  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21560  *
21561  * Access: The ipif or ill pointed to from the conn can be accessed under
21562  * the protection of the conn_lock or after it has been refheld under the
21563  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21564  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21565  * The reason for this is that a concurrent unplumb could actually be
21566  * cleaning up these cached pointers by walking the conns and might have
21567  * finished cleaning up the conn in question. The macros check that an
21568  * unplumb has not yet started on the ipif or ill.
21569  *
21570  * Caching: An ipif or ill pointer may be cached in the conn only after
21571  * making sure that an unplumb has not started. So the caching is done
21572  * while holding both the conn_lock and the ill_lock and after using the
21573  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21574  * flag before starting the cleanup of conns.
21575  *
21576  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21577  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21578  * or a reference to the ipif or a reference to an ire that references the
21579  * ipif. An ipif does not change its ill except for failover/failback. Since
21580  * failover/failback happens only after bringing down the ipif and making sure
21581  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21582  * the above holds.
21583  */
21584 ipif_t *
21585 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21586 {
21587 	ipif_t	*ipif;
21588 	ill_t	*ill;
21589 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21590 
21591 	*err = 0;
21592 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21593 	mutex_enter(&connp->conn_lock);
21594 	ipif = *ipifp;
21595 	if (ipif != NULL) {
21596 		ill = ipif->ipif_ill;
21597 		mutex_enter(&ill->ill_lock);
21598 		if (IPIF_CAN_LOOKUP(ipif)) {
21599 			ipif_refhold_locked(ipif);
21600 			mutex_exit(&ill->ill_lock);
21601 			mutex_exit(&connp->conn_lock);
21602 			rw_exit(&ipst->ips_ill_g_lock);
21603 			return (ipif);
21604 		} else {
21605 			*err = IPIF_LOOKUP_FAILED;
21606 		}
21607 		mutex_exit(&ill->ill_lock);
21608 	}
21609 	mutex_exit(&connp->conn_lock);
21610 	rw_exit(&ipst->ips_ill_g_lock);
21611 	return (NULL);
21612 }
21613 
21614 ill_t *
21615 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21616 {
21617 	ill_t	*ill;
21618 
21619 	*err = 0;
21620 	mutex_enter(&connp->conn_lock);
21621 	ill = *illp;
21622 	if (ill != NULL) {
21623 		mutex_enter(&ill->ill_lock);
21624 		if (ILL_CAN_LOOKUP(ill)) {
21625 			ill_refhold_locked(ill);
21626 			mutex_exit(&ill->ill_lock);
21627 			mutex_exit(&connp->conn_lock);
21628 			return (ill);
21629 		} else {
21630 			*err = ILL_LOOKUP_FAILED;
21631 		}
21632 		mutex_exit(&ill->ill_lock);
21633 	}
21634 	mutex_exit(&connp->conn_lock);
21635 	return (NULL);
21636 }
21637 
21638 static int
21639 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21640 {
21641 	ill_t	*ill;
21642 
21643 	ill = ipif->ipif_ill;
21644 	mutex_enter(&connp->conn_lock);
21645 	mutex_enter(&ill->ill_lock);
21646 	if (IPIF_CAN_LOOKUP(ipif)) {
21647 		*ipifp = ipif;
21648 		mutex_exit(&ill->ill_lock);
21649 		mutex_exit(&connp->conn_lock);
21650 		return (0);
21651 	}
21652 	mutex_exit(&ill->ill_lock);
21653 	mutex_exit(&connp->conn_lock);
21654 	return (IPIF_LOOKUP_FAILED);
21655 }
21656 
21657 /*
21658  * This is called if the outbound datagram needs fragmentation.
21659  *
21660  * NOTE : This function does not ire_refrele the ire argument passed in.
21661  */
21662 static void
21663 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21664     ip_stack_t *ipst)
21665 {
21666 	ipha_t		*ipha;
21667 	mblk_t		*mp;
21668 	uint32_t	v_hlen_tos_len;
21669 	uint32_t	max_frag;
21670 	uint32_t	frag_flag;
21671 	boolean_t	dont_use;
21672 
21673 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21674 		mp = ipsec_mp->b_cont;
21675 	} else {
21676 		mp = ipsec_mp;
21677 	}
21678 
21679 	ipha = (ipha_t *)mp->b_rptr;
21680 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21681 
21682 #ifdef	_BIG_ENDIAN
21683 #define	V_HLEN	(v_hlen_tos_len >> 24)
21684 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21685 #else
21686 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21687 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21688 #endif
21689 
21690 #ifndef SPEED_BEFORE_SAFETY
21691 	/*
21692 	 * Check that ipha_length is consistent with
21693 	 * the mblk length
21694 	 */
21695 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21696 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21697 		    LENGTH, msgdsize(mp)));
21698 		freemsg(ipsec_mp);
21699 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21700 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21701 		    "packet length mismatch");
21702 		return;
21703 	}
21704 #endif
21705 	/*
21706 	 * Don't use frag_flag if pre-built packet or source
21707 	 * routed or if multicast (since multicast packets do not solicit
21708 	 * ICMP "packet too big" messages). Get the values of
21709 	 * max_frag and frag_flag atomically by acquiring the
21710 	 * ire_lock.
21711 	 */
21712 	mutex_enter(&ire->ire_lock);
21713 	max_frag = ire->ire_max_frag;
21714 	frag_flag = ire->ire_frag_flag;
21715 	mutex_exit(&ire->ire_lock);
21716 
21717 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21718 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21719 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21720 
21721 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21722 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21723 }
21724 
21725 /*
21726  * Used for deciding the MSS size for the upper layer. Thus
21727  * we need to check the outbound policy values in the conn.
21728  */
21729 int
21730 conn_ipsec_length(conn_t *connp)
21731 {
21732 	ipsec_latch_t *ipl;
21733 
21734 	ipl = connp->conn_latch;
21735 	if (ipl == NULL)
21736 		return (0);
21737 
21738 	if (ipl->ipl_out_policy == NULL)
21739 		return (0);
21740 
21741 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21742 }
21743 
21744 /*
21745  * Returns an estimate of the IPsec headers size. This is used if
21746  * we don't want to call into IPsec to get the exact size.
21747  */
21748 int
21749 ipsec_out_extra_length(mblk_t *ipsec_mp)
21750 {
21751 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21752 	ipsec_action_t *a;
21753 
21754 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21755 	if (!io->ipsec_out_secure)
21756 		return (0);
21757 
21758 	a = io->ipsec_out_act;
21759 
21760 	if (a == NULL) {
21761 		ASSERT(io->ipsec_out_policy != NULL);
21762 		a = io->ipsec_out_policy->ipsp_act;
21763 	}
21764 	ASSERT(a != NULL);
21765 
21766 	return (a->ipa_ovhd);
21767 }
21768 
21769 /*
21770  * Returns an estimate of the IPsec headers size. This is used if
21771  * we don't want to call into IPsec to get the exact size.
21772  */
21773 int
21774 ipsec_in_extra_length(mblk_t *ipsec_mp)
21775 {
21776 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21777 	ipsec_action_t *a;
21778 
21779 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21780 
21781 	a = ii->ipsec_in_action;
21782 	return (a == NULL ? 0 : a->ipa_ovhd);
21783 }
21784 
21785 /*
21786  * If there are any source route options, return the true final
21787  * destination. Otherwise, return the destination.
21788  */
21789 ipaddr_t
21790 ip_get_dst(ipha_t *ipha)
21791 {
21792 	ipoptp_t	opts;
21793 	uchar_t		*opt;
21794 	uint8_t		optval;
21795 	uint8_t		optlen;
21796 	ipaddr_t	dst;
21797 	uint32_t off;
21798 
21799 	dst = ipha->ipha_dst;
21800 
21801 	if (IS_SIMPLE_IPH(ipha))
21802 		return (dst);
21803 
21804 	for (optval = ipoptp_first(&opts, ipha);
21805 	    optval != IPOPT_EOL;
21806 	    optval = ipoptp_next(&opts)) {
21807 		opt = opts.ipoptp_cur;
21808 		optlen = opts.ipoptp_len;
21809 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21810 		switch (optval) {
21811 		case IPOPT_SSRR:
21812 		case IPOPT_LSRR:
21813 			off = opt[IPOPT_OFFSET];
21814 			/*
21815 			 * If one of the conditions is true, it means
21816 			 * end of options and dst already has the right
21817 			 * value.
21818 			 */
21819 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21820 				off = optlen - IP_ADDR_LEN;
21821 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21822 			}
21823 			return (dst);
21824 		default:
21825 			break;
21826 		}
21827 	}
21828 
21829 	return (dst);
21830 }
21831 
21832 mblk_t *
21833 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21834     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21835 {
21836 	ipsec_out_t	*io;
21837 	mblk_t		*first_mp;
21838 	boolean_t policy_present;
21839 	ip_stack_t	*ipst;
21840 	ipsec_stack_t	*ipss;
21841 
21842 	ASSERT(ire != NULL);
21843 	ipst = ire->ire_ipst;
21844 	ipss = ipst->ips_netstack->netstack_ipsec;
21845 
21846 	first_mp = mp;
21847 	if (mp->b_datap->db_type == M_CTL) {
21848 		io = (ipsec_out_t *)first_mp->b_rptr;
21849 		/*
21850 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21851 		 *
21852 		 * 1) There is per-socket policy (including cached global
21853 		 *    policy) or a policy on the IP-in-IP tunnel.
21854 		 * 2) There is no per-socket policy, but it is
21855 		 *    a multicast packet that needs to go out
21856 		 *    on a specific interface. This is the case
21857 		 *    where (ip_wput and ip_wput_multicast) attaches
21858 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21859 		 *
21860 		 * In case (2) we check with global policy to
21861 		 * see if there is a match and set the ill_index
21862 		 * appropriately so that we can lookup the ire
21863 		 * properly in ip_wput_ipsec_out.
21864 		 */
21865 
21866 		/*
21867 		 * ipsec_out_use_global_policy is set to B_FALSE
21868 		 * in ipsec_in_to_out(). Refer to that function for
21869 		 * details.
21870 		 */
21871 		if ((io->ipsec_out_latch == NULL) &&
21872 		    (io->ipsec_out_use_global_policy)) {
21873 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21874 			    ire, connp, unspec_src, zoneid));
21875 		}
21876 		if (!io->ipsec_out_secure) {
21877 			/*
21878 			 * If this is not a secure packet, drop
21879 			 * the IPSEC_OUT mp and treat it as a clear
21880 			 * packet. This happens when we are sending
21881 			 * a ICMP reply back to a clear packet. See
21882 			 * ipsec_in_to_out() for details.
21883 			 */
21884 			mp = first_mp->b_cont;
21885 			freeb(first_mp);
21886 		}
21887 		return (mp);
21888 	}
21889 	/*
21890 	 * See whether we need to attach a global policy here. We
21891 	 * don't depend on the conn (as it could be null) for deciding
21892 	 * what policy this datagram should go through because it
21893 	 * should have happened in ip_wput if there was some
21894 	 * policy. This normally happens for connections which are not
21895 	 * fully bound preventing us from caching policies in
21896 	 * ip_bind. Packets coming from the TCP listener/global queue
21897 	 * - which are non-hard_bound - could also be affected by
21898 	 * applying policy here.
21899 	 *
21900 	 * If this packet is coming from tcp global queue or listener,
21901 	 * we will be applying policy here.  This may not be *right*
21902 	 * if these packets are coming from the detached connection as
21903 	 * it could have gone in clear before. This happens only if a
21904 	 * TCP connection started when there is no policy and somebody
21905 	 * added policy before it became detached. Thus packets of the
21906 	 * detached connection could go out secure and the other end
21907 	 * would drop it because it will be expecting in clear. The
21908 	 * converse is not true i.e if somebody starts a TCP
21909 	 * connection and deletes the policy, all the packets will
21910 	 * still go out with the policy that existed before deleting
21911 	 * because ip_unbind sends up policy information which is used
21912 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21913 	 * TCP to attach a dummy IPSEC_OUT and set
21914 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21915 	 * affect performance for normal cases, we are not doing it.
21916 	 * Thus, set policy before starting any TCP connections.
21917 	 *
21918 	 * NOTE - We might apply policy even for a hard bound connection
21919 	 * - for which we cached policy in ip_bind - if somebody added
21920 	 * global policy after we inherited the policy in ip_bind.
21921 	 * This means that the packets that were going out in clear
21922 	 * previously would start going secure and hence get dropped
21923 	 * on the other side. To fix this, TCP attaches a dummy
21924 	 * ipsec_out and make sure that we don't apply global policy.
21925 	 */
21926 	if (ipha != NULL)
21927 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21928 	else
21929 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21930 	if (!policy_present)
21931 		return (mp);
21932 
21933 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21934 	    zoneid));
21935 }
21936 
21937 ire_t *
21938 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21939 {
21940 	ipaddr_t addr;
21941 	ire_t *save_ire;
21942 	irb_t *irb;
21943 	ill_group_t *illgrp;
21944 	int	err;
21945 
21946 	save_ire = ire;
21947 	addr = ire->ire_addr;
21948 
21949 	ASSERT(ire->ire_type == IRE_BROADCAST);
21950 
21951 	illgrp = connp->conn_outgoing_ill->ill_group;
21952 	if (illgrp == NULL) {
21953 		*conn_outgoing_ill = conn_get_held_ill(connp,
21954 		    &connp->conn_outgoing_ill, &err);
21955 		if (err == ILL_LOOKUP_FAILED) {
21956 			ire_refrele(save_ire);
21957 			return (NULL);
21958 		}
21959 		return (save_ire);
21960 	}
21961 	/*
21962 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21963 	 * If it is part of the group, we need to send on the ire
21964 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21965 	 * to this group. This is okay as IP_BOUND_IF really means
21966 	 * any ill in the group. We depend on the fact that the
21967 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21968 	 * if such an ire exists. This is possible only if you have
21969 	 * at least one ill in the group that has not failed.
21970 	 *
21971 	 * First get to the ire that matches the address and group.
21972 	 *
21973 	 * We don't look for an ire with a matching zoneid because a given zone
21974 	 * won't always have broadcast ires on all ills in the group.
21975 	 */
21976 	irb = ire->ire_bucket;
21977 	rw_enter(&irb->irb_lock, RW_READER);
21978 	if (ire->ire_marks & IRE_MARK_NORECV) {
21979 		/*
21980 		 * If the current zone only has an ire broadcast for this
21981 		 * address marked NORECV, the ire we want is ahead in the
21982 		 * bucket, so we look it up deliberately ignoring the zoneid.
21983 		 */
21984 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21985 			if (ire->ire_addr != addr)
21986 				continue;
21987 			/* skip over deleted ires */
21988 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21989 				continue;
21990 		}
21991 	}
21992 	while (ire != NULL) {
21993 		/*
21994 		 * If a new interface is coming up, we could end up
21995 		 * seeing the loopback ire and the non-loopback ire
21996 		 * may not have been added yet. So check for ire_stq
21997 		 */
21998 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21999 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22000 			break;
22001 		}
22002 		ire = ire->ire_next;
22003 	}
22004 	if (ire != NULL && ire->ire_addr == addr &&
22005 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22006 		IRE_REFHOLD(ire);
22007 		rw_exit(&irb->irb_lock);
22008 		ire_refrele(save_ire);
22009 		*conn_outgoing_ill = ire_to_ill(ire);
22010 		/*
22011 		 * Refhold the ill to make the conn_outgoing_ill
22012 		 * independent of the ire. ip_wput_ire goes in a loop
22013 		 * and may refrele the ire. Since we have an ire at this
22014 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22015 		 */
22016 		ill_refhold(*conn_outgoing_ill);
22017 		return (ire);
22018 	}
22019 	rw_exit(&irb->irb_lock);
22020 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22021 	/*
22022 	 * If we can't find a suitable ire, return the original ire.
22023 	 */
22024 	return (save_ire);
22025 }
22026 
22027 /*
22028  * This function does the ire_refrele of the ire passed in as the
22029  * argument. As this function looks up more ires i.e broadcast ires,
22030  * it needs to REFRELE them. Currently, for simplicity we don't
22031  * differentiate the one passed in and looked up here. We always
22032  * REFRELE.
22033  * IPQoS Notes:
22034  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22035  * IPsec packets are done in ipsec_out_process.
22036  *
22037  */
22038 void
22039 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22040     zoneid_t zoneid)
22041 {
22042 	ipha_t		*ipha;
22043 #define	rptr	((uchar_t *)ipha)
22044 	queue_t		*stq;
22045 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22046 	uint32_t	v_hlen_tos_len;
22047 	uint32_t	ttl_protocol;
22048 	ipaddr_t	src;
22049 	ipaddr_t	dst;
22050 	uint32_t	cksum;
22051 	ipaddr_t	orig_src;
22052 	ire_t		*ire1;
22053 	mblk_t		*next_mp;
22054 	uint_t		hlen;
22055 	uint16_t	*up;
22056 	uint32_t	max_frag = ire->ire_max_frag;
22057 	ill_t		*ill = ire_to_ill(ire);
22058 	int		clusterwide;
22059 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22060 	int		ipsec_len;
22061 	mblk_t		*first_mp;
22062 	ipsec_out_t	*io;
22063 	boolean_t	conn_dontroute;		/* conn value for multicast */
22064 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22065 	boolean_t	multicast_forward;	/* Should we forward ? */
22066 	boolean_t	unspec_src;
22067 	ill_t		*conn_outgoing_ill = NULL;
22068 	ill_t		*ire_ill;
22069 	ill_t		*ire1_ill;
22070 	ill_t		*out_ill;
22071 	uint32_t 	ill_index = 0;
22072 	boolean_t	multirt_send = B_FALSE;
22073 	int		err;
22074 	ipxmit_state_t	pktxmit_state;
22075 	ip_stack_t	*ipst = ire->ire_ipst;
22076 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22077 
22078 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22079 	    "ip_wput_ire_start: q %p", q);
22080 
22081 	multicast_forward = B_FALSE;
22082 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22083 
22084 	if (ire->ire_flags & RTF_MULTIRT) {
22085 		/*
22086 		 * Multirouting case. The bucket where ire is stored
22087 		 * probably holds other RTF_MULTIRT flagged ire
22088 		 * to the destination. In this call to ip_wput_ire,
22089 		 * we attempt to send the packet through all
22090 		 * those ires. Thus, we first ensure that ire is the
22091 		 * first RTF_MULTIRT ire in the bucket,
22092 		 * before walking the ire list.
22093 		 */
22094 		ire_t *first_ire;
22095 		irb_t *irb = ire->ire_bucket;
22096 		ASSERT(irb != NULL);
22097 
22098 		/* Make sure we do not omit any multiroute ire. */
22099 		IRB_REFHOLD(irb);
22100 		for (first_ire = irb->irb_ire;
22101 		    first_ire != NULL;
22102 		    first_ire = first_ire->ire_next) {
22103 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22104 			    (first_ire->ire_addr == ire->ire_addr) &&
22105 			    !(first_ire->ire_marks &
22106 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22107 				break;
22108 			}
22109 		}
22110 
22111 		if ((first_ire != NULL) && (first_ire != ire)) {
22112 			IRE_REFHOLD(first_ire);
22113 			ire_refrele(ire);
22114 			ire = first_ire;
22115 			ill = ire_to_ill(ire);
22116 		}
22117 		IRB_REFRELE(irb);
22118 	}
22119 
22120 	/*
22121 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22122 	 * for performance we don't grab the mutexs in the fastpath
22123 	 */
22124 	if ((connp != NULL) &&
22125 	    (ire->ire_type == IRE_BROADCAST) &&
22126 	    ((connp->conn_nofailover_ill != NULL) ||
22127 	    (connp->conn_outgoing_ill != NULL))) {
22128 		/*
22129 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22130 		 * option. So, see if this endpoint is bound to a
22131 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22132 		 * that if the interface is failed, we will still send
22133 		 * the packet on the same ill which is what we want.
22134 		 */
22135 		conn_outgoing_ill = conn_get_held_ill(connp,
22136 		    &connp->conn_nofailover_ill, &err);
22137 		if (err == ILL_LOOKUP_FAILED) {
22138 			ire_refrele(ire);
22139 			freemsg(mp);
22140 			return;
22141 		}
22142 		if (conn_outgoing_ill == NULL) {
22143 			/*
22144 			 * Choose a good ill in the group to send the
22145 			 * packets on.
22146 			 */
22147 			ire = conn_set_outgoing_ill(connp, ire,
22148 			    &conn_outgoing_ill);
22149 			if (ire == NULL) {
22150 				freemsg(mp);
22151 				return;
22152 			}
22153 		}
22154 	}
22155 
22156 	if (mp->b_datap->db_type != M_CTL) {
22157 		ipha = (ipha_t *)mp->b_rptr;
22158 	} else {
22159 		io = (ipsec_out_t *)mp->b_rptr;
22160 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22161 		ASSERT(zoneid == io->ipsec_out_zoneid);
22162 		ASSERT(zoneid != ALL_ZONES);
22163 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22164 		dst = ipha->ipha_dst;
22165 		/*
22166 		 * For the multicast case, ipsec_out carries conn_dontroute and
22167 		 * conn_multicast_loop as conn may not be available here. We
22168 		 * need this for multicast loopback and forwarding which is done
22169 		 * later in the code.
22170 		 */
22171 		if (CLASSD(dst)) {
22172 			conn_dontroute = io->ipsec_out_dontroute;
22173 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22174 			/*
22175 			 * If conn_dontroute is not set or conn_multicast_loop
22176 			 * is set, we need to do forwarding/loopback. For
22177 			 * datagrams from ip_wput_multicast, conn_dontroute is
22178 			 * set to B_TRUE and conn_multicast_loop is set to
22179 			 * B_FALSE so that we neither do forwarding nor
22180 			 * loopback.
22181 			 */
22182 			if (!conn_dontroute || conn_multicast_loop)
22183 				multicast_forward = B_TRUE;
22184 		}
22185 	}
22186 
22187 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22188 	    ire->ire_zoneid != ALL_ZONES) {
22189 		/*
22190 		 * When a zone sends a packet to another zone, we try to deliver
22191 		 * the packet under the same conditions as if the destination
22192 		 * was a real node on the network. To do so, we look for a
22193 		 * matching route in the forwarding table.
22194 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22195 		 * ip_newroute() does.
22196 		 * Note that IRE_LOCAL are special, since they are used
22197 		 * when the zoneid doesn't match in some cases. This means that
22198 		 * we need to handle ipha_src differently since ire_src_addr
22199 		 * belongs to the receiving zone instead of the sending zone.
22200 		 * When ip_restrict_interzone_loopback is set, then
22201 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22202 		 * for loopback between zones when the logical "Ethernet" would
22203 		 * have looped them back.
22204 		 */
22205 		ire_t *src_ire;
22206 
22207 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22208 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22209 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22210 		if (src_ire != NULL &&
22211 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22212 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22213 		    ire_local_same_ill_group(ire, src_ire))) {
22214 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22215 				ipha->ipha_src = src_ire->ire_src_addr;
22216 			ire_refrele(src_ire);
22217 		} else {
22218 			ire_refrele(ire);
22219 			if (conn_outgoing_ill != NULL)
22220 				ill_refrele(conn_outgoing_ill);
22221 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22222 			if (src_ire != NULL) {
22223 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22224 					ire_refrele(src_ire);
22225 					freemsg(mp);
22226 					return;
22227 				}
22228 				ire_refrele(src_ire);
22229 			}
22230 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22231 				/* Failed */
22232 				freemsg(mp);
22233 				return;
22234 			}
22235 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22236 			    ipst);
22237 			return;
22238 		}
22239 	}
22240 
22241 	if (mp->b_datap->db_type == M_CTL ||
22242 	    ipss->ipsec_outbound_v4_policy_present) {
22243 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22244 		    unspec_src, zoneid);
22245 		if (mp == NULL) {
22246 			ire_refrele(ire);
22247 			if (conn_outgoing_ill != NULL)
22248 				ill_refrele(conn_outgoing_ill);
22249 			return;
22250 		}
22251 		/*
22252 		 * Trusted Extensions supports all-zones interfaces, so
22253 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22254 		 * the global zone.
22255 		 */
22256 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22257 			io = (ipsec_out_t *)mp->b_rptr;
22258 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22259 			zoneid = io->ipsec_out_zoneid;
22260 		}
22261 	}
22262 
22263 	first_mp = mp;
22264 	ipsec_len = 0;
22265 
22266 	if (first_mp->b_datap->db_type == M_CTL) {
22267 		io = (ipsec_out_t *)first_mp->b_rptr;
22268 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22269 		mp = first_mp->b_cont;
22270 		ipsec_len = ipsec_out_extra_length(first_mp);
22271 		ASSERT(ipsec_len >= 0);
22272 		/* We already picked up the zoneid from the M_CTL above */
22273 		ASSERT(zoneid == io->ipsec_out_zoneid);
22274 		ASSERT(zoneid != ALL_ZONES);
22275 
22276 		/*
22277 		 * Drop M_CTL here if IPsec processing is not needed.
22278 		 * (Non-IPsec use of M_CTL extracted any information it
22279 		 * needed above).
22280 		 */
22281 		if (ipsec_len == 0) {
22282 			freeb(first_mp);
22283 			first_mp = mp;
22284 		}
22285 	}
22286 
22287 	/*
22288 	 * Fast path for ip_wput_ire
22289 	 */
22290 
22291 	ipha = (ipha_t *)mp->b_rptr;
22292 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22293 	dst = ipha->ipha_dst;
22294 
22295 	/*
22296 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22297 	 * if the socket is a SOCK_RAW type. The transport checksum should
22298 	 * be provided in the pre-built packet, so we don't need to compute it.
22299 	 * Also, other application set flags, like DF, should not be altered.
22300 	 * Other transport MUST pass down zero.
22301 	 */
22302 	ip_hdr_included = ipha->ipha_ident;
22303 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22304 
22305 	if (CLASSD(dst)) {
22306 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22307 		    ntohl(dst),
22308 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22309 		    ntohl(ire->ire_addr)));
22310 	}
22311 
22312 /* Macros to extract header fields from data already in registers */
22313 #ifdef	_BIG_ENDIAN
22314 #define	V_HLEN	(v_hlen_tos_len >> 24)
22315 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22316 #define	PROTO	(ttl_protocol & 0xFF)
22317 #else
22318 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22319 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22320 #define	PROTO	(ttl_protocol >> 8)
22321 #endif
22322 
22323 
22324 	orig_src = src = ipha->ipha_src;
22325 	/* (The loop back to "another" is explained down below.) */
22326 another:;
22327 	/*
22328 	 * Assign an ident value for this packet.  We assign idents on
22329 	 * a per destination basis out of the IRE.  There could be
22330 	 * other threads targeting the same destination, so we have to
22331 	 * arrange for a atomic increment.  Note that we use a 32-bit
22332 	 * atomic add because it has better performance than its
22333 	 * 16-bit sibling.
22334 	 *
22335 	 * If running in cluster mode and if the source address
22336 	 * belongs to a replicated service then vector through
22337 	 * cl_inet_ipident vector to allocate ip identifier
22338 	 * NOTE: This is a contract private interface with the
22339 	 * clustering group.
22340 	 */
22341 	clusterwide = 0;
22342 	if (cl_inet_ipident) {
22343 		ASSERT(cl_inet_isclusterwide);
22344 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22345 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22346 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22347 			    AF_INET, (uint8_t *)(uintptr_t)src,
22348 			    (uint8_t *)(uintptr_t)dst);
22349 			clusterwide = 1;
22350 		}
22351 	}
22352 	if (!clusterwide) {
22353 		ipha->ipha_ident =
22354 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22355 	}
22356 
22357 #ifndef _BIG_ENDIAN
22358 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22359 #endif
22360 
22361 	/*
22362 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22363 	 * This is needed to obey conn_unspec_src when packets go through
22364 	 * ip_newroute + arp.
22365 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22366 	 */
22367 	if (src == INADDR_ANY && !unspec_src) {
22368 		/*
22369 		 * Assign the appropriate source address from the IRE if none
22370 		 * was specified.
22371 		 */
22372 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22373 
22374 		/*
22375 		 * With IP multipathing, broadcast packets are sent on the ire
22376 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22377 		 * the group. However, this ire might not be in the same zone so
22378 		 * we can't always use its source address. We look for a
22379 		 * broadcast ire in the same group and in the right zone.
22380 		 */
22381 		if (ire->ire_type == IRE_BROADCAST &&
22382 		    ire->ire_zoneid != zoneid) {
22383 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22384 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22385 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22386 			if (src_ire != NULL) {
22387 				src = src_ire->ire_src_addr;
22388 				ire_refrele(src_ire);
22389 			} else {
22390 				ire_refrele(ire);
22391 				if (conn_outgoing_ill != NULL)
22392 					ill_refrele(conn_outgoing_ill);
22393 				freemsg(first_mp);
22394 				if (ill != NULL) {
22395 					BUMP_MIB(ill->ill_ip_mib,
22396 					    ipIfStatsOutDiscards);
22397 				} else {
22398 					BUMP_MIB(&ipst->ips_ip_mib,
22399 					    ipIfStatsOutDiscards);
22400 				}
22401 				return;
22402 			}
22403 		} else {
22404 			src = ire->ire_src_addr;
22405 		}
22406 
22407 		if (connp == NULL) {
22408 			ip1dbg(("ip_wput_ire: no connp and no src "
22409 			    "address for dst 0x%x, using src 0x%x\n",
22410 			    ntohl(dst),
22411 			    ntohl(src)));
22412 		}
22413 		ipha->ipha_src = src;
22414 	}
22415 	stq = ire->ire_stq;
22416 
22417 	/*
22418 	 * We only allow ire chains for broadcasts since there will
22419 	 * be multiple IRE_CACHE entries for the same multicast
22420 	 * address (one per ipif).
22421 	 */
22422 	next_mp = NULL;
22423 
22424 	/* broadcast packet */
22425 	if (ire->ire_type == IRE_BROADCAST)
22426 		goto broadcast;
22427 
22428 	/* loopback ? */
22429 	if (stq == NULL)
22430 		goto nullstq;
22431 
22432 	/* The ill_index for outbound ILL */
22433 	ill_index = Q_TO_INDEX(stq);
22434 
22435 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22436 	ttl_protocol = ((uint16_t *)ipha)[4];
22437 
22438 	/* pseudo checksum (do it in parts for IP header checksum) */
22439 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22440 
22441 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22442 		queue_t *dev_q = stq->q_next;
22443 
22444 		/* flow controlled */
22445 		if ((dev_q->q_next || dev_q->q_first) &&
22446 		    !canput(dev_q))
22447 			goto blocked;
22448 		if ((PROTO == IPPROTO_UDP) &&
22449 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22450 			hlen = (V_HLEN & 0xF) << 2;
22451 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22452 			if (*up != 0) {
22453 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22454 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22455 				/* Software checksum? */
22456 				if (DB_CKSUMFLAGS(mp) == 0) {
22457 					IP_STAT(ipst, ip_out_sw_cksum);
22458 					IP_STAT_UPDATE(ipst,
22459 					    ip_udp_out_sw_cksum_bytes,
22460 					    LENGTH - hlen);
22461 				}
22462 			}
22463 		}
22464 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22465 		hlen = (V_HLEN & 0xF) << 2;
22466 		if (PROTO == IPPROTO_TCP) {
22467 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22468 			/*
22469 			 * The packet header is processed once and for all, even
22470 			 * in the multirouting case. We disable hardware
22471 			 * checksum if the packet is multirouted, as it will be
22472 			 * replicated via several interfaces, and not all of
22473 			 * them may have this capability.
22474 			 */
22475 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22476 			    LENGTH, max_frag, ipsec_len, cksum);
22477 			/* Software checksum? */
22478 			if (DB_CKSUMFLAGS(mp) == 0) {
22479 				IP_STAT(ipst, ip_out_sw_cksum);
22480 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22481 				    LENGTH - hlen);
22482 			}
22483 		} else {
22484 			sctp_hdr_t	*sctph;
22485 
22486 			ASSERT(PROTO == IPPROTO_SCTP);
22487 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22488 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22489 			/*
22490 			 * Zero out the checksum field to ensure proper
22491 			 * checksum calculation.
22492 			 */
22493 			sctph->sh_chksum = 0;
22494 #ifdef	DEBUG
22495 			if (!skip_sctp_cksum)
22496 #endif
22497 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22498 		}
22499 	}
22500 
22501 	/*
22502 	 * If this is a multicast packet and originated from ip_wput
22503 	 * we need to do loopback and forwarding checks. If it comes
22504 	 * from ip_wput_multicast, we SHOULD not do this.
22505 	 */
22506 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22507 
22508 	/* checksum */
22509 	cksum += ttl_protocol;
22510 
22511 	/* fragment the packet */
22512 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22513 		goto fragmentit;
22514 	/*
22515 	 * Don't use frag_flag if packet is pre-built or source
22516 	 * routed or if multicast (since multicast packets do
22517 	 * not solicit ICMP "packet too big" messages).
22518 	 */
22519 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22520 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22521 	    !ip_source_route_included(ipha)) &&
22522 	    !CLASSD(ipha->ipha_dst))
22523 		ipha->ipha_fragment_offset_and_flags |=
22524 		    htons(ire->ire_frag_flag);
22525 
22526 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22527 		/* calculate IP header checksum */
22528 		cksum += ipha->ipha_ident;
22529 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22530 		cksum += ipha->ipha_fragment_offset_and_flags;
22531 
22532 		/* IP options present */
22533 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22534 		if (hlen)
22535 			goto checksumoptions;
22536 
22537 		/* calculate hdr checksum */
22538 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22539 		cksum = ~(cksum + (cksum >> 16));
22540 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22541 	}
22542 	if (ipsec_len != 0) {
22543 		/*
22544 		 * We will do the rest of the processing after
22545 		 * we come back from IPsec in ip_wput_ipsec_out().
22546 		 */
22547 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22548 
22549 		io = (ipsec_out_t *)first_mp->b_rptr;
22550 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22551 		    ill_phyint->phyint_ifindex;
22552 
22553 		ipsec_out_process(q, first_mp, ire, ill_index);
22554 		ire_refrele(ire);
22555 		if (conn_outgoing_ill != NULL)
22556 			ill_refrele(conn_outgoing_ill);
22557 		return;
22558 	}
22559 
22560 	/*
22561 	 * In most cases, the emission loop below is entered only
22562 	 * once. Only in the case where the ire holds the
22563 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22564 	 * flagged ires in the bucket, and send the packet
22565 	 * through all crossed RTF_MULTIRT routes.
22566 	 */
22567 	if (ire->ire_flags & RTF_MULTIRT) {
22568 		multirt_send = B_TRUE;
22569 	}
22570 	do {
22571 		if (multirt_send) {
22572 			irb_t *irb;
22573 			/*
22574 			 * We are in a multiple send case, need to get
22575 			 * the next ire and make a duplicate of the packet.
22576 			 * ire1 holds here the next ire to process in the
22577 			 * bucket. If multirouting is expected,
22578 			 * any non-RTF_MULTIRT ire that has the
22579 			 * right destination address is ignored.
22580 			 */
22581 			irb = ire->ire_bucket;
22582 			ASSERT(irb != NULL);
22583 
22584 			IRB_REFHOLD(irb);
22585 			for (ire1 = ire->ire_next;
22586 			    ire1 != NULL;
22587 			    ire1 = ire1->ire_next) {
22588 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22589 					continue;
22590 				if (ire1->ire_addr != ire->ire_addr)
22591 					continue;
22592 				if (ire1->ire_marks &
22593 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22594 					continue;
22595 
22596 				/* Got one */
22597 				IRE_REFHOLD(ire1);
22598 				break;
22599 			}
22600 			IRB_REFRELE(irb);
22601 
22602 			if (ire1 != NULL) {
22603 				next_mp = copyb(mp);
22604 				if ((next_mp == NULL) ||
22605 				    ((mp->b_cont != NULL) &&
22606 				    ((next_mp->b_cont =
22607 				    dupmsg(mp->b_cont)) == NULL))) {
22608 					freemsg(next_mp);
22609 					next_mp = NULL;
22610 					ire_refrele(ire1);
22611 					ire1 = NULL;
22612 				}
22613 			}
22614 
22615 			/* Last multiroute ire; don't loop anymore. */
22616 			if (ire1 == NULL) {
22617 				multirt_send = B_FALSE;
22618 			}
22619 		}
22620 
22621 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22622 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22623 		    mblk_t *, mp);
22624 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22625 		    ipst->ips_ipv4firewall_physical_out,
22626 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22627 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22628 		if (mp == NULL)
22629 			goto release_ire_and_ill;
22630 
22631 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22632 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22633 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22634 		if ((pktxmit_state == SEND_FAILED) ||
22635 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22636 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22637 			    "- packet dropped\n"));
22638 release_ire_and_ill:
22639 			ire_refrele(ire);
22640 			if (next_mp != NULL) {
22641 				freemsg(next_mp);
22642 				ire_refrele(ire1);
22643 			}
22644 			if (conn_outgoing_ill != NULL)
22645 				ill_refrele(conn_outgoing_ill);
22646 			return;
22647 		}
22648 
22649 		if (CLASSD(dst)) {
22650 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22651 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22652 			    LENGTH);
22653 		}
22654 
22655 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22656 		    "ip_wput_ire_end: q %p (%S)",
22657 		    q, "last copy out");
22658 		IRE_REFRELE(ire);
22659 
22660 		if (multirt_send) {
22661 			ASSERT(ire1);
22662 			/*
22663 			 * Proceed with the next RTF_MULTIRT ire,
22664 			 * Also set up the send-to queue accordingly.
22665 			 */
22666 			ire = ire1;
22667 			ire1 = NULL;
22668 			stq = ire->ire_stq;
22669 			mp = next_mp;
22670 			next_mp = NULL;
22671 			ipha = (ipha_t *)mp->b_rptr;
22672 			ill_index = Q_TO_INDEX(stq);
22673 			ill = (ill_t *)stq->q_ptr;
22674 		}
22675 	} while (multirt_send);
22676 	if (conn_outgoing_ill != NULL)
22677 		ill_refrele(conn_outgoing_ill);
22678 	return;
22679 
22680 	/*
22681 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22682 	 */
22683 broadcast:
22684 	{
22685 		/*
22686 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22687 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22688 		 * can be overridden stack-wide through the ip_broadcast_ttl
22689 		 * ndd tunable, or on a per-connection basis through the
22690 		 * IP_BROADCAST_TTL socket option.
22691 		 *
22692 		 * In the event that we are replying to incoming ICMP packets,
22693 		 * connp could be NULL.
22694 		 */
22695 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22696 		if (connp != NULL) {
22697 			if (connp->conn_dontroute)
22698 				ipha->ipha_ttl = 1;
22699 			else if (connp->conn_broadcast_ttl != 0)
22700 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22701 		}
22702 
22703 		/*
22704 		 * Note that we are not doing a IRB_REFHOLD here.
22705 		 * Actually we don't care if the list changes i.e
22706 		 * if somebody deletes an IRE from the list while
22707 		 * we drop the lock, the next time we come around
22708 		 * ire_next will be NULL and hence we won't send
22709 		 * out multiple copies which is fine.
22710 		 */
22711 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22712 		ire1 = ire->ire_next;
22713 		if (conn_outgoing_ill != NULL) {
22714 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22715 				ASSERT(ire1 == ire->ire_next);
22716 				if (ire1 != NULL && ire1->ire_addr == dst) {
22717 					ire_refrele(ire);
22718 					ire = ire1;
22719 					IRE_REFHOLD(ire);
22720 					ire1 = ire->ire_next;
22721 					continue;
22722 				}
22723 				rw_exit(&ire->ire_bucket->irb_lock);
22724 				/* Did not find a matching ill */
22725 				ip1dbg(("ip_wput_ire: broadcast with no "
22726 				    "matching IP_BOUND_IF ill %s dst %x\n",
22727 				    conn_outgoing_ill->ill_name, dst));
22728 				freemsg(first_mp);
22729 				if (ire != NULL)
22730 					ire_refrele(ire);
22731 				ill_refrele(conn_outgoing_ill);
22732 				return;
22733 			}
22734 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22735 			/*
22736 			 * If the next IRE has the same address and is not one
22737 			 * of the two copies that we need to send, try to see
22738 			 * whether this copy should be sent at all. This
22739 			 * assumes that we insert loopbacks first and then
22740 			 * non-loopbacks. This is acheived by inserting the
22741 			 * loopback always before non-loopback.
22742 			 * This is used to send a single copy of a broadcast
22743 			 * packet out all physical interfaces that have an
22744 			 * matching IRE_BROADCAST while also looping
22745 			 * back one copy (to ip_wput_local) for each
22746 			 * matching physical interface. However, we avoid
22747 			 * sending packets out different logical that match by
22748 			 * having ipif_up/ipif_down supress duplicate
22749 			 * IRE_BROADCASTS.
22750 			 *
22751 			 * This feature is currently used to get broadcasts
22752 			 * sent to multiple interfaces, when the broadcast
22753 			 * address being used applies to multiple interfaces.
22754 			 * For example, a whole net broadcast will be
22755 			 * replicated on every connected subnet of
22756 			 * the target net.
22757 			 *
22758 			 * Each zone has its own set of IRE_BROADCASTs, so that
22759 			 * we're able to distribute inbound packets to multiple
22760 			 * zones who share a broadcast address. We avoid looping
22761 			 * back outbound packets in different zones but on the
22762 			 * same ill, as the application would see duplicates.
22763 			 *
22764 			 * If the interfaces are part of the same group,
22765 			 * we would want to send only one copy out for
22766 			 * whole group.
22767 			 *
22768 			 * This logic assumes that ire_add_v4() groups the
22769 			 * IRE_BROADCAST entries so that those with the same
22770 			 * ire_addr and ill_group are kept together.
22771 			 */
22772 			ire_ill = ire->ire_ipif->ipif_ill;
22773 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22774 				if (ire_ill->ill_group != NULL &&
22775 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22776 					/*
22777 					 * If the current zone only has an ire
22778 					 * broadcast for this address marked
22779 					 * NORECV, the ire we want is ahead in
22780 					 * the bucket, so we look it up
22781 					 * deliberately ignoring the zoneid.
22782 					 */
22783 					for (ire1 = ire->ire_bucket->irb_ire;
22784 					    ire1 != NULL;
22785 					    ire1 = ire1->ire_next) {
22786 						ire1_ill =
22787 						    ire1->ire_ipif->ipif_ill;
22788 						if (ire1->ire_addr != dst)
22789 							continue;
22790 						/* skip over the current ire */
22791 						if (ire1 == ire)
22792 							continue;
22793 						/* skip over deleted ires */
22794 						if (ire1->ire_marks &
22795 						    IRE_MARK_CONDEMNED)
22796 							continue;
22797 						/*
22798 						 * non-loopback ire in our
22799 						 * group: use it for the next
22800 						 * pass in the loop
22801 						 */
22802 						if (ire1->ire_stq != NULL &&
22803 						    ire1_ill->ill_group ==
22804 						    ire_ill->ill_group)
22805 							break;
22806 					}
22807 				}
22808 			} else {
22809 				while (ire1 != NULL && ire1->ire_addr == dst) {
22810 					ire1_ill = ire1->ire_ipif->ipif_ill;
22811 					/*
22812 					 * We can have two broadcast ires on the
22813 					 * same ill in different zones; here
22814 					 * we'll send a copy of the packet on
22815 					 * each ill and the fanout code will
22816 					 * call conn_wantpacket() to check that
22817 					 * the zone has the broadcast address
22818 					 * configured on the ill. If the two
22819 					 * ires are in the same group we only
22820 					 * send one copy up.
22821 					 */
22822 					if (ire1_ill != ire_ill &&
22823 					    (ire1_ill->ill_group == NULL ||
22824 					    ire_ill->ill_group == NULL ||
22825 					    ire1_ill->ill_group !=
22826 					    ire_ill->ill_group)) {
22827 						break;
22828 					}
22829 					ire1 = ire1->ire_next;
22830 				}
22831 			}
22832 		}
22833 		ASSERT(multirt_send == B_FALSE);
22834 		if (ire1 != NULL && ire1->ire_addr == dst) {
22835 			if ((ire->ire_flags & RTF_MULTIRT) &&
22836 			    (ire1->ire_flags & RTF_MULTIRT)) {
22837 				/*
22838 				 * We are in the multirouting case.
22839 				 * The message must be sent at least
22840 				 * on both ires. These ires have been
22841 				 * inserted AFTER the standard ones
22842 				 * in ip_rt_add(). There are thus no
22843 				 * other ire entries for the destination
22844 				 * address in the rest of the bucket
22845 				 * that do not have the RTF_MULTIRT
22846 				 * flag. We don't process a copy
22847 				 * of the message here. This will be
22848 				 * done in the final sending loop.
22849 				 */
22850 				multirt_send = B_TRUE;
22851 			} else {
22852 				next_mp = ip_copymsg(first_mp);
22853 				if (next_mp != NULL)
22854 					IRE_REFHOLD(ire1);
22855 			}
22856 		}
22857 		rw_exit(&ire->ire_bucket->irb_lock);
22858 	}
22859 
22860 	if (stq) {
22861 		/*
22862 		 * A non-NULL send-to queue means this packet is going
22863 		 * out of this machine.
22864 		 */
22865 		out_ill = (ill_t *)stq->q_ptr;
22866 
22867 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22868 		ttl_protocol = ((uint16_t *)ipha)[4];
22869 		/*
22870 		 * We accumulate the pseudo header checksum in cksum.
22871 		 * This is pretty hairy code, so watch close.  One
22872 		 * thing to keep in mind is that UDP and TCP have
22873 		 * stored their respective datagram lengths in their
22874 		 * checksum fields.  This lines things up real nice.
22875 		 */
22876 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22877 		    (src >> 16) + (src & 0xFFFF);
22878 		/*
22879 		 * We assume the udp checksum field contains the
22880 		 * length, so to compute the pseudo header checksum,
22881 		 * all we need is the protocol number and src/dst.
22882 		 */
22883 		/* Provide the checksums for UDP and TCP. */
22884 		if ((PROTO == IPPROTO_TCP) &&
22885 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22886 			/* hlen gets the number of uchar_ts in the IP header */
22887 			hlen = (V_HLEN & 0xF) << 2;
22888 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22889 			IP_STAT(ipst, ip_out_sw_cksum);
22890 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22891 			    LENGTH - hlen);
22892 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22893 		} else if (PROTO == IPPROTO_SCTP &&
22894 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22895 			sctp_hdr_t	*sctph;
22896 
22897 			hlen = (V_HLEN & 0xF) << 2;
22898 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22899 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22900 			sctph->sh_chksum = 0;
22901 #ifdef	DEBUG
22902 			if (!skip_sctp_cksum)
22903 #endif
22904 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22905 		} else {
22906 			queue_t *dev_q = stq->q_next;
22907 
22908 			if ((dev_q->q_next || dev_q->q_first) &&
22909 			    !canput(dev_q)) {
22910 blocked:
22911 				ipha->ipha_ident = ip_hdr_included;
22912 				/*
22913 				 * If we don't have a conn to apply
22914 				 * backpressure, free the message.
22915 				 * In the ire_send path, we don't know
22916 				 * the position to requeue the packet. Rather
22917 				 * than reorder packets, we just drop this
22918 				 * packet.
22919 				 */
22920 				if (ipst->ips_ip_output_queue &&
22921 				    connp != NULL &&
22922 				    caller != IRE_SEND) {
22923 					if (caller == IP_WSRV) {
22924 						connp->conn_did_putbq = 1;
22925 						(void) putbq(connp->conn_wq,
22926 						    first_mp);
22927 						conn_drain_insert(connp);
22928 						/*
22929 						 * This is the service thread,
22930 						 * and the queue is already
22931 						 * noenabled. The check for
22932 						 * canput and the putbq is not
22933 						 * atomic. So we need to check
22934 						 * again.
22935 						 */
22936 						if (canput(stq->q_next))
22937 							connp->conn_did_putbq
22938 							    = 0;
22939 						IP_STAT(ipst, ip_conn_flputbq);
22940 					} else {
22941 						/*
22942 						 * We are not the service proc.
22943 						 * ip_wsrv will be scheduled or
22944 						 * is already running.
22945 						 */
22946 						(void) putq(connp->conn_wq,
22947 						    first_mp);
22948 					}
22949 				} else {
22950 					out_ill = (ill_t *)stq->q_ptr;
22951 					BUMP_MIB(out_ill->ill_ip_mib,
22952 					    ipIfStatsOutDiscards);
22953 					freemsg(first_mp);
22954 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22955 					    "ip_wput_ire_end: q %p (%S)",
22956 					    q, "discard");
22957 				}
22958 				ire_refrele(ire);
22959 				if (next_mp) {
22960 					ire_refrele(ire1);
22961 					freemsg(next_mp);
22962 				}
22963 				if (conn_outgoing_ill != NULL)
22964 					ill_refrele(conn_outgoing_ill);
22965 				return;
22966 			}
22967 			if ((PROTO == IPPROTO_UDP) &&
22968 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22969 				/*
22970 				 * hlen gets the number of uchar_ts in the
22971 				 * IP header
22972 				 */
22973 				hlen = (V_HLEN & 0xF) << 2;
22974 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22975 				max_frag = ire->ire_max_frag;
22976 				if (*up != 0) {
22977 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22978 					    up, PROTO, hlen, LENGTH, max_frag,
22979 					    ipsec_len, cksum);
22980 					/* Software checksum? */
22981 					if (DB_CKSUMFLAGS(mp) == 0) {
22982 						IP_STAT(ipst, ip_out_sw_cksum);
22983 						IP_STAT_UPDATE(ipst,
22984 						    ip_udp_out_sw_cksum_bytes,
22985 						    LENGTH - hlen);
22986 					}
22987 				}
22988 			}
22989 		}
22990 		/*
22991 		 * Need to do this even when fragmenting. The local
22992 		 * loopback can be done without computing checksums
22993 		 * but forwarding out other interface must be done
22994 		 * after the IP checksum (and ULP checksums) have been
22995 		 * computed.
22996 		 *
22997 		 * NOTE : multicast_forward is set only if this packet
22998 		 * originated from ip_wput. For packets originating from
22999 		 * ip_wput_multicast, it is not set.
23000 		 */
23001 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23002 multi_loopback:
23003 			ip2dbg(("ip_wput: multicast, loop %d\n",
23004 			    conn_multicast_loop));
23005 
23006 			/*  Forget header checksum offload */
23007 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23008 
23009 			/*
23010 			 * Local loopback of multicasts?  Check the
23011 			 * ill.
23012 			 *
23013 			 * Note that the loopback function will not come
23014 			 * in through ip_rput - it will only do the
23015 			 * client fanout thus we need to do an mforward
23016 			 * as well.  The is different from the BSD
23017 			 * logic.
23018 			 */
23019 			if (ill != NULL) {
23020 				ilm_t	*ilm;
23021 
23022 				ILM_WALKER_HOLD(ill);
23023 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23024 				    ALL_ZONES);
23025 				ILM_WALKER_RELE(ill);
23026 				if (ilm != NULL) {
23027 					/*
23028 					 * Pass along the virtual output q.
23029 					 * ip_wput_local() will distribute the
23030 					 * packet to all the matching zones,
23031 					 * except the sending zone when
23032 					 * IP_MULTICAST_LOOP is false.
23033 					 */
23034 					ip_multicast_loopback(q, ill, first_mp,
23035 					    conn_multicast_loop ? 0 :
23036 					    IP_FF_NO_MCAST_LOOP, zoneid);
23037 				}
23038 			}
23039 			if (ipha->ipha_ttl == 0) {
23040 				/*
23041 				 * 0 => only to this host i.e. we are
23042 				 * done. We are also done if this was the
23043 				 * loopback interface since it is sufficient
23044 				 * to loopback one copy of a multicast packet.
23045 				 */
23046 				freemsg(first_mp);
23047 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23048 				    "ip_wput_ire_end: q %p (%S)",
23049 				    q, "loopback");
23050 				ire_refrele(ire);
23051 				if (conn_outgoing_ill != NULL)
23052 					ill_refrele(conn_outgoing_ill);
23053 				return;
23054 			}
23055 			/*
23056 			 * ILLF_MULTICAST is checked in ip_newroute
23057 			 * i.e. we don't need to check it here since
23058 			 * all IRE_CACHEs come from ip_newroute.
23059 			 * For multicast traffic, SO_DONTROUTE is interpreted
23060 			 * to mean only send the packet out the interface
23061 			 * (optionally specified with IP_MULTICAST_IF)
23062 			 * and do not forward it out additional interfaces.
23063 			 * RSVP and the rsvp daemon is an example of a
23064 			 * protocol and user level process that
23065 			 * handles it's own routing. Hence, it uses the
23066 			 * SO_DONTROUTE option to accomplish this.
23067 			 */
23068 
23069 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23070 			    ill != NULL) {
23071 				/* Unconditionally redo the checksum */
23072 				ipha->ipha_hdr_checksum = 0;
23073 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23074 
23075 				/*
23076 				 * If this needs to go out secure, we need
23077 				 * to wait till we finish the IPsec
23078 				 * processing.
23079 				 */
23080 				if (ipsec_len == 0 &&
23081 				    ip_mforward(ill, ipha, mp)) {
23082 					freemsg(first_mp);
23083 					ip1dbg(("ip_wput: mforward failed\n"));
23084 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23085 					    "ip_wput_ire_end: q %p (%S)",
23086 					    q, "mforward failed");
23087 					ire_refrele(ire);
23088 					if (conn_outgoing_ill != NULL)
23089 						ill_refrele(conn_outgoing_ill);
23090 					return;
23091 				}
23092 			}
23093 		}
23094 		max_frag = ire->ire_max_frag;
23095 		cksum += ttl_protocol;
23096 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23097 			/* No fragmentation required for this one. */
23098 			/*
23099 			 * Don't use frag_flag if packet is pre-built or source
23100 			 * routed or if multicast (since multicast packets do
23101 			 * not solicit ICMP "packet too big" messages).
23102 			 */
23103 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23104 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23105 			    !ip_source_route_included(ipha)) &&
23106 			    !CLASSD(ipha->ipha_dst))
23107 				ipha->ipha_fragment_offset_and_flags |=
23108 				    htons(ire->ire_frag_flag);
23109 
23110 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23111 				/* Complete the IP header checksum. */
23112 				cksum += ipha->ipha_ident;
23113 				cksum += (v_hlen_tos_len >> 16)+
23114 				    (v_hlen_tos_len & 0xFFFF);
23115 				cksum += ipha->ipha_fragment_offset_and_flags;
23116 				hlen = (V_HLEN & 0xF) -
23117 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23118 				if (hlen) {
23119 checksumoptions:
23120 					/*
23121 					 * Account for the IP Options in the IP
23122 					 * header checksum.
23123 					 */
23124 					up = (uint16_t *)(rptr+
23125 					    IP_SIMPLE_HDR_LENGTH);
23126 					do {
23127 						cksum += up[0];
23128 						cksum += up[1];
23129 						up += 2;
23130 					} while (--hlen);
23131 				}
23132 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23133 				cksum = ~(cksum + (cksum >> 16));
23134 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23135 			}
23136 			if (ipsec_len != 0) {
23137 				ipsec_out_process(q, first_mp, ire, ill_index);
23138 				if (!next_mp) {
23139 					ire_refrele(ire);
23140 					if (conn_outgoing_ill != NULL)
23141 						ill_refrele(conn_outgoing_ill);
23142 					return;
23143 				}
23144 				goto next;
23145 			}
23146 
23147 			/*
23148 			 * multirt_send has already been handled
23149 			 * for broadcast, but not yet for multicast
23150 			 * or IP options.
23151 			 */
23152 			if (next_mp == NULL) {
23153 				if (ire->ire_flags & RTF_MULTIRT) {
23154 					multirt_send = B_TRUE;
23155 				}
23156 			}
23157 
23158 			/*
23159 			 * In most cases, the emission loop below is
23160 			 * entered only once. Only in the case where
23161 			 * the ire holds the RTF_MULTIRT flag, do we loop
23162 			 * to process all RTF_MULTIRT ires in the bucket,
23163 			 * and send the packet through all crossed
23164 			 * RTF_MULTIRT routes.
23165 			 */
23166 			do {
23167 				if (multirt_send) {
23168 					irb_t *irb;
23169 
23170 					irb = ire->ire_bucket;
23171 					ASSERT(irb != NULL);
23172 					/*
23173 					 * We are in a multiple send case,
23174 					 * need to get the next IRE and make
23175 					 * a duplicate of the packet.
23176 					 */
23177 					IRB_REFHOLD(irb);
23178 					for (ire1 = ire->ire_next;
23179 					    ire1 != NULL;
23180 					    ire1 = ire1->ire_next) {
23181 						if (!(ire1->ire_flags &
23182 						    RTF_MULTIRT)) {
23183 							continue;
23184 						}
23185 						if (ire1->ire_addr !=
23186 						    ire->ire_addr) {
23187 							continue;
23188 						}
23189 						if (ire1->ire_marks &
23190 						    (IRE_MARK_CONDEMNED|
23191 						    IRE_MARK_HIDDEN)) {
23192 							continue;
23193 						}
23194 
23195 						/* Got one */
23196 						IRE_REFHOLD(ire1);
23197 						break;
23198 					}
23199 					IRB_REFRELE(irb);
23200 
23201 					if (ire1 != NULL) {
23202 						next_mp = copyb(mp);
23203 						if ((next_mp == NULL) ||
23204 						    ((mp->b_cont != NULL) &&
23205 						    ((next_mp->b_cont =
23206 						    dupmsg(mp->b_cont))
23207 						    == NULL))) {
23208 							freemsg(next_mp);
23209 							next_mp = NULL;
23210 							ire_refrele(ire1);
23211 							ire1 = NULL;
23212 						}
23213 					}
23214 
23215 					/*
23216 					 * Last multiroute ire; don't loop
23217 					 * anymore. The emission is over
23218 					 * and next_mp is NULL.
23219 					 */
23220 					if (ire1 == NULL) {
23221 						multirt_send = B_FALSE;
23222 					}
23223 				}
23224 
23225 				out_ill = ire_to_ill(ire);
23226 				DTRACE_PROBE4(ip4__physical__out__start,
23227 				    ill_t *, NULL,
23228 				    ill_t *, out_ill,
23229 				    ipha_t *, ipha, mblk_t *, mp);
23230 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23231 				    ipst->ips_ipv4firewall_physical_out,
23232 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23233 				DTRACE_PROBE1(ip4__physical__out__end,
23234 				    mblk_t *, mp);
23235 				if (mp == NULL)
23236 					goto release_ire_and_ill_2;
23237 
23238 				ASSERT(ipsec_len == 0);
23239 				mp->b_prev =
23240 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23241 				DTRACE_PROBE2(ip__xmit__2,
23242 				    mblk_t *, mp, ire_t *, ire);
23243 				pktxmit_state = ip_xmit_v4(mp, ire,
23244 				    NULL, B_TRUE);
23245 				if ((pktxmit_state == SEND_FAILED) ||
23246 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23247 release_ire_and_ill_2:
23248 					if (next_mp) {
23249 						freemsg(next_mp);
23250 						ire_refrele(ire1);
23251 					}
23252 					ire_refrele(ire);
23253 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23254 					    "ip_wput_ire_end: q %p (%S)",
23255 					    q, "discard MDATA");
23256 					if (conn_outgoing_ill != NULL)
23257 						ill_refrele(conn_outgoing_ill);
23258 					return;
23259 				}
23260 
23261 				if (CLASSD(dst)) {
23262 					BUMP_MIB(out_ill->ill_ip_mib,
23263 					    ipIfStatsHCOutMcastPkts);
23264 					UPDATE_MIB(out_ill->ill_ip_mib,
23265 					    ipIfStatsHCOutMcastOctets,
23266 					    LENGTH);
23267 				} else if (ire->ire_type == IRE_BROADCAST) {
23268 					BUMP_MIB(out_ill->ill_ip_mib,
23269 					    ipIfStatsHCOutBcastPkts);
23270 				}
23271 
23272 				if (multirt_send) {
23273 					/*
23274 					 * We are in a multiple send case,
23275 					 * need to re-enter the sending loop
23276 					 * using the next ire.
23277 					 */
23278 					ire_refrele(ire);
23279 					ire = ire1;
23280 					stq = ire->ire_stq;
23281 					mp = next_mp;
23282 					next_mp = NULL;
23283 					ipha = (ipha_t *)mp->b_rptr;
23284 					ill_index = Q_TO_INDEX(stq);
23285 				}
23286 			} while (multirt_send);
23287 
23288 			if (!next_mp) {
23289 				/*
23290 				 * Last copy going out (the ultra-common
23291 				 * case).  Note that we intentionally replicate
23292 				 * the putnext rather than calling it before
23293 				 * the next_mp check in hopes of a little
23294 				 * tail-call action out of the compiler.
23295 				 */
23296 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23297 				    "ip_wput_ire_end: q %p (%S)",
23298 				    q, "last copy out(1)");
23299 				ire_refrele(ire);
23300 				if (conn_outgoing_ill != NULL)
23301 					ill_refrele(conn_outgoing_ill);
23302 				return;
23303 			}
23304 			/* More copies going out below. */
23305 		} else {
23306 			int offset;
23307 fragmentit:
23308 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23309 			/*
23310 			 * If this would generate a icmp_frag_needed message,
23311 			 * we need to handle it before we do the IPsec
23312 			 * processing. Otherwise, we need to strip the IPsec
23313 			 * headers before we send up the message to the ULPs
23314 			 * which becomes messy and difficult.
23315 			 */
23316 			if (ipsec_len != 0) {
23317 				if ((max_frag < (unsigned int)(LENGTH +
23318 				    ipsec_len)) && (offset & IPH_DF)) {
23319 					out_ill = (ill_t *)stq->q_ptr;
23320 					BUMP_MIB(out_ill->ill_ip_mib,
23321 					    ipIfStatsOutFragFails);
23322 					BUMP_MIB(out_ill->ill_ip_mib,
23323 					    ipIfStatsOutFragReqds);
23324 					ipha->ipha_hdr_checksum = 0;
23325 					ipha->ipha_hdr_checksum =
23326 					    (uint16_t)ip_csum_hdr(ipha);
23327 					icmp_frag_needed(ire->ire_stq, first_mp,
23328 					    max_frag, zoneid, ipst);
23329 					if (!next_mp) {
23330 						ire_refrele(ire);
23331 						if (conn_outgoing_ill != NULL) {
23332 							ill_refrele(
23333 							    conn_outgoing_ill);
23334 						}
23335 						return;
23336 					}
23337 				} else {
23338 					/*
23339 					 * This won't cause a icmp_frag_needed
23340 					 * message. to be generated. Send it on
23341 					 * the wire. Note that this could still
23342 					 * cause fragmentation and all we
23343 					 * do is the generation of the message
23344 					 * to the ULP if needed before IPsec.
23345 					 */
23346 					if (!next_mp) {
23347 						ipsec_out_process(q, first_mp,
23348 						    ire, ill_index);
23349 						TRACE_2(TR_FAC_IP,
23350 						    TR_IP_WPUT_IRE_END,
23351 						    "ip_wput_ire_end: q %p "
23352 						    "(%S)", q,
23353 						    "last ipsec_out_process");
23354 						ire_refrele(ire);
23355 						if (conn_outgoing_ill != NULL) {
23356 							ill_refrele(
23357 							    conn_outgoing_ill);
23358 						}
23359 						return;
23360 					}
23361 					ipsec_out_process(q, first_mp,
23362 					    ire, ill_index);
23363 				}
23364 			} else {
23365 				/*
23366 				 * Initiate IPPF processing. For
23367 				 * fragmentable packets we finish
23368 				 * all QOS packet processing before
23369 				 * calling:
23370 				 * ip_wput_ire_fragmentit->ip_wput_frag
23371 				 */
23372 
23373 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23374 					ip_process(IPP_LOCAL_OUT, &mp,
23375 					    ill_index);
23376 					if (mp == NULL) {
23377 						out_ill = (ill_t *)stq->q_ptr;
23378 						BUMP_MIB(out_ill->ill_ip_mib,
23379 						    ipIfStatsOutDiscards);
23380 						if (next_mp != NULL) {
23381 							freemsg(next_mp);
23382 							ire_refrele(ire1);
23383 						}
23384 						ire_refrele(ire);
23385 						TRACE_2(TR_FAC_IP,
23386 						    TR_IP_WPUT_IRE_END,
23387 						    "ip_wput_ire: q %p (%S)",
23388 						    q, "discard MDATA");
23389 						if (conn_outgoing_ill != NULL) {
23390 							ill_refrele(
23391 							    conn_outgoing_ill);
23392 						}
23393 						return;
23394 					}
23395 				}
23396 				if (!next_mp) {
23397 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23398 					    "ip_wput_ire_end: q %p (%S)",
23399 					    q, "last fragmentation");
23400 					ip_wput_ire_fragmentit(mp, ire,
23401 					    zoneid, ipst);
23402 					ire_refrele(ire);
23403 					if (conn_outgoing_ill != NULL)
23404 						ill_refrele(conn_outgoing_ill);
23405 					return;
23406 				}
23407 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23408 			}
23409 		}
23410 	} else {
23411 nullstq:
23412 		/* A NULL stq means the destination address is local. */
23413 		UPDATE_OB_PKT_COUNT(ire);
23414 		ire->ire_last_used_time = lbolt;
23415 		ASSERT(ire->ire_ipif != NULL);
23416 		if (!next_mp) {
23417 			/*
23418 			 * Is there an "in" and "out" for traffic local
23419 			 * to a host (loopback)?  The code in Solaris doesn't
23420 			 * explicitly draw a line in its code for in vs out,
23421 			 * so we've had to draw a line in the sand: ip_wput_ire
23422 			 * is considered to be the "output" side and
23423 			 * ip_wput_local to be the "input" side.
23424 			 */
23425 			out_ill = ire_to_ill(ire);
23426 
23427 			DTRACE_PROBE4(ip4__loopback__out__start,
23428 			    ill_t *, NULL, ill_t *, out_ill,
23429 			    ipha_t *, ipha, mblk_t *, first_mp);
23430 
23431 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23432 			    ipst->ips_ipv4firewall_loopback_out,
23433 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23434 
23435 			DTRACE_PROBE1(ip4__loopback__out_end,
23436 			    mblk_t *, first_mp);
23437 
23438 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23439 			    "ip_wput_ire_end: q %p (%S)",
23440 			    q, "local address");
23441 
23442 			if (first_mp != NULL)
23443 				ip_wput_local(q, out_ill, ipha,
23444 				    first_mp, ire, 0, ire->ire_zoneid);
23445 			ire_refrele(ire);
23446 			if (conn_outgoing_ill != NULL)
23447 				ill_refrele(conn_outgoing_ill);
23448 			return;
23449 		}
23450 
23451 		out_ill = ire_to_ill(ire);
23452 
23453 		DTRACE_PROBE4(ip4__loopback__out__start,
23454 		    ill_t *, NULL, ill_t *, out_ill,
23455 		    ipha_t *, ipha, mblk_t *, first_mp);
23456 
23457 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23458 		    ipst->ips_ipv4firewall_loopback_out,
23459 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23460 
23461 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23462 
23463 		if (first_mp != NULL)
23464 			ip_wput_local(q, out_ill, ipha,
23465 			    first_mp, ire, 0, ire->ire_zoneid);
23466 	}
23467 next:
23468 	/*
23469 	 * More copies going out to additional interfaces.
23470 	 * ire1 has already been held. We don't need the
23471 	 * "ire" anymore.
23472 	 */
23473 	ire_refrele(ire);
23474 	ire = ire1;
23475 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23476 	mp = next_mp;
23477 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23478 	ill = ire_to_ill(ire);
23479 	first_mp = mp;
23480 	if (ipsec_len != 0) {
23481 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23482 		mp = mp->b_cont;
23483 	}
23484 	dst = ire->ire_addr;
23485 	ipha = (ipha_t *)mp->b_rptr;
23486 	/*
23487 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23488 	 * Restore ipha_ident "no checksum" flag.
23489 	 */
23490 	src = orig_src;
23491 	ipha->ipha_ident = ip_hdr_included;
23492 	goto another;
23493 
23494 #undef	rptr
23495 #undef	Q_TO_INDEX
23496 }
23497 
23498 /*
23499  * Routine to allocate a message that is used to notify the ULP about MDT.
23500  * The caller may provide a pointer to the link-layer MDT capabilities,
23501  * or NULL if MDT is to be disabled on the stream.
23502  */
23503 mblk_t *
23504 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23505 {
23506 	mblk_t *mp;
23507 	ip_mdt_info_t *mdti;
23508 	ill_mdt_capab_t *idst;
23509 
23510 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23511 		DB_TYPE(mp) = M_CTL;
23512 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23513 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23514 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23515 		idst = &(mdti->mdt_capab);
23516 
23517 		/*
23518 		 * If the caller provides us with the capability, copy
23519 		 * it over into our notification message; otherwise
23520 		 * we zero out the capability portion.
23521 		 */
23522 		if (isrc != NULL)
23523 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23524 		else
23525 			bzero((caddr_t)idst, sizeof (*idst));
23526 	}
23527 	return (mp);
23528 }
23529 
23530 /*
23531  * Routine which determines whether MDT can be enabled on the destination
23532  * IRE and IPC combination, and if so, allocates and returns the MDT
23533  * notification mblk that may be used by ULP.  We also check if we need to
23534  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23535  * MDT usage in the past have been lifted.  This gets called during IP
23536  * and ULP binding.
23537  */
23538 mblk_t *
23539 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23540     ill_mdt_capab_t *mdt_cap)
23541 {
23542 	mblk_t *mp;
23543 	boolean_t rc = B_FALSE;
23544 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23545 
23546 	ASSERT(dst_ire != NULL);
23547 	ASSERT(connp != NULL);
23548 	ASSERT(mdt_cap != NULL);
23549 
23550 	/*
23551 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23552 	 * Multidata, which is handled in tcp_multisend().  This
23553 	 * is the reason why we do all these checks here, to ensure
23554 	 * that we don't enable Multidata for the cases which we
23555 	 * can't handle at the moment.
23556 	 */
23557 	do {
23558 		/* Only do TCP at the moment */
23559 		if (connp->conn_ulp != IPPROTO_TCP)
23560 			break;
23561 
23562 		/*
23563 		 * IPsec outbound policy present?  Note that we get here
23564 		 * after calling ipsec_conn_cache_policy() where the global
23565 		 * policy checking is performed.  conn_latch will be
23566 		 * non-NULL as long as there's a policy defined,
23567 		 * i.e. conn_out_enforce_policy may be NULL in such case
23568 		 * when the connection is non-secure, and hence we check
23569 		 * further if the latch refers to an outbound policy.
23570 		 */
23571 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23572 			break;
23573 
23574 		/* CGTP (multiroute) is enabled? */
23575 		if (dst_ire->ire_flags & RTF_MULTIRT)
23576 			break;
23577 
23578 		/* Outbound IPQoS enabled? */
23579 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23580 			/*
23581 			 * In this case, we disable MDT for this and all
23582 			 * future connections going over the interface.
23583 			 */
23584 			mdt_cap->ill_mdt_on = 0;
23585 			break;
23586 		}
23587 
23588 		/* socket option(s) present? */
23589 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23590 			break;
23591 
23592 		rc = B_TRUE;
23593 	/* CONSTCOND */
23594 	} while (0);
23595 
23596 	/* Remember the result */
23597 	connp->conn_mdt_ok = rc;
23598 
23599 	if (!rc)
23600 		return (NULL);
23601 	else if (!mdt_cap->ill_mdt_on) {
23602 		/*
23603 		 * If MDT has been previously turned off in the past, and we
23604 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23605 		 * then enable it for this interface.
23606 		 */
23607 		mdt_cap->ill_mdt_on = 1;
23608 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23609 		    "interface %s\n", ill_name));
23610 	}
23611 
23612 	/* Allocate the MDT info mblk */
23613 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23614 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23615 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23616 		return (NULL);
23617 	}
23618 	return (mp);
23619 }
23620 
23621 /*
23622  * Routine to allocate a message that is used to notify the ULP about LSO.
23623  * The caller may provide a pointer to the link-layer LSO capabilities,
23624  * or NULL if LSO is to be disabled on the stream.
23625  */
23626 mblk_t *
23627 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23628 {
23629 	mblk_t *mp;
23630 	ip_lso_info_t *lsoi;
23631 	ill_lso_capab_t *idst;
23632 
23633 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23634 		DB_TYPE(mp) = M_CTL;
23635 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23636 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23637 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23638 		idst = &(lsoi->lso_capab);
23639 
23640 		/*
23641 		 * If the caller provides us with the capability, copy
23642 		 * it over into our notification message; otherwise
23643 		 * we zero out the capability portion.
23644 		 */
23645 		if (isrc != NULL)
23646 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23647 		else
23648 			bzero((caddr_t)idst, sizeof (*idst));
23649 	}
23650 	return (mp);
23651 }
23652 
23653 /*
23654  * Routine which determines whether LSO can be enabled on the destination
23655  * IRE and IPC combination, and if so, allocates and returns the LSO
23656  * notification mblk that may be used by ULP.  We also check if we need to
23657  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23658  * LSO usage in the past have been lifted.  This gets called during IP
23659  * and ULP binding.
23660  */
23661 mblk_t *
23662 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23663     ill_lso_capab_t *lso_cap)
23664 {
23665 	mblk_t *mp;
23666 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23667 
23668 	ASSERT(dst_ire != NULL);
23669 	ASSERT(connp != NULL);
23670 	ASSERT(lso_cap != NULL);
23671 
23672 	connp->conn_lso_ok = B_TRUE;
23673 
23674 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23675 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23676 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23677 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23678 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23679 		connp->conn_lso_ok = B_FALSE;
23680 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23681 			/*
23682 			 * Disable LSO for this and all future connections going
23683 			 * over the interface.
23684 			 */
23685 			lso_cap->ill_lso_on = 0;
23686 		}
23687 	}
23688 
23689 	if (!connp->conn_lso_ok)
23690 		return (NULL);
23691 	else if (!lso_cap->ill_lso_on) {
23692 		/*
23693 		 * If LSO has been previously turned off in the past, and we
23694 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23695 		 * then enable it for this interface.
23696 		 */
23697 		lso_cap->ill_lso_on = 1;
23698 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23699 		    ill_name));
23700 	}
23701 
23702 	/* Allocate the LSO info mblk */
23703 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23704 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23705 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23706 
23707 	return (mp);
23708 }
23709 
23710 /*
23711  * Create destination address attribute, and fill it with the physical
23712  * destination address and SAP taken from the template DL_UNITDATA_REQ
23713  * message block.
23714  */
23715 boolean_t
23716 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23717 {
23718 	dl_unitdata_req_t *dlurp;
23719 	pattr_t *pa;
23720 	pattrinfo_t pa_info;
23721 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23722 	uint_t das_len, das_off;
23723 
23724 	ASSERT(dlmp != NULL);
23725 
23726 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23727 	das_len = dlurp->dl_dest_addr_length;
23728 	das_off = dlurp->dl_dest_addr_offset;
23729 
23730 	pa_info.type = PATTR_DSTADDRSAP;
23731 	pa_info.len = sizeof (**das) + das_len - 1;
23732 
23733 	/* create and associate the attribute */
23734 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23735 	if (pa != NULL) {
23736 		ASSERT(*das != NULL);
23737 		(*das)->addr_is_group = 0;
23738 		(*das)->addr_len = (uint8_t)das_len;
23739 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23740 	}
23741 
23742 	return (pa != NULL);
23743 }
23744 
23745 /*
23746  * Create hardware checksum attribute and fill it with the values passed.
23747  */
23748 boolean_t
23749 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23750     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23751 {
23752 	pattr_t *pa;
23753 	pattrinfo_t pa_info;
23754 
23755 	ASSERT(mmd != NULL);
23756 
23757 	pa_info.type = PATTR_HCKSUM;
23758 	pa_info.len = sizeof (pattr_hcksum_t);
23759 
23760 	/* create and associate the attribute */
23761 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23762 	if (pa != NULL) {
23763 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23764 
23765 		hck->hcksum_start_offset = start_offset;
23766 		hck->hcksum_stuff_offset = stuff_offset;
23767 		hck->hcksum_end_offset = end_offset;
23768 		hck->hcksum_flags = flags;
23769 	}
23770 	return (pa != NULL);
23771 }
23772 
23773 /*
23774  * Create zerocopy attribute and fill it with the specified flags
23775  */
23776 boolean_t
23777 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23778 {
23779 	pattr_t *pa;
23780 	pattrinfo_t pa_info;
23781 
23782 	ASSERT(mmd != NULL);
23783 	pa_info.type = PATTR_ZCOPY;
23784 	pa_info.len = sizeof (pattr_zcopy_t);
23785 
23786 	/* create and associate the attribute */
23787 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23788 	if (pa != NULL) {
23789 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23790 
23791 		zcopy->zcopy_flags = flags;
23792 	}
23793 	return (pa != NULL);
23794 }
23795 
23796 /*
23797  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23798  * block chain. We could rewrite to handle arbitrary message block chains but
23799  * that would make the code complicated and slow. Right now there three
23800  * restrictions:
23801  *
23802  *   1. The first message block must contain the complete IP header and
23803  *	at least 1 byte of payload data.
23804  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23805  *	so that we can use a single Multidata message.
23806  *   3. No frag must be distributed over two or more message blocks so
23807  *	that we don't need more than two packet descriptors per frag.
23808  *
23809  * The above restrictions allow us to support userland applications (which
23810  * will send down a single message block) and NFS over UDP (which will
23811  * send down a chain of at most three message blocks).
23812  *
23813  * We also don't use MDT for payloads with less than or equal to
23814  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23815  */
23816 boolean_t
23817 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23818 {
23819 	int	blocks;
23820 	ssize_t	total, missing, size;
23821 
23822 	ASSERT(mp != NULL);
23823 	ASSERT(hdr_len > 0);
23824 
23825 	size = MBLKL(mp) - hdr_len;
23826 	if (size <= 0)
23827 		return (B_FALSE);
23828 
23829 	/* The first mblk contains the header and some payload. */
23830 	blocks = 1;
23831 	total = size;
23832 	size %= len;
23833 	missing = (size == 0) ? 0 : (len - size);
23834 	mp = mp->b_cont;
23835 
23836 	while (mp != NULL) {
23837 		/*
23838 		 * Give up if we encounter a zero length message block.
23839 		 * In practice, this should rarely happen and therefore
23840 		 * not worth the trouble of freeing and re-linking the
23841 		 * mblk from the chain to handle such case.
23842 		 */
23843 		if ((size = MBLKL(mp)) == 0)
23844 			return (B_FALSE);
23845 
23846 		/* Too many payload buffers for a single Multidata message? */
23847 		if (++blocks > MULTIDATA_MAX_PBUFS)
23848 			return (B_FALSE);
23849 
23850 		total += size;
23851 		/* Is a frag distributed over two or more message blocks? */
23852 		if (missing > size)
23853 			return (B_FALSE);
23854 		size -= missing;
23855 
23856 		size %= len;
23857 		missing = (size == 0) ? 0 : (len - size);
23858 
23859 		mp = mp->b_cont;
23860 	}
23861 
23862 	return (total > ip_wput_frag_mdt_min);
23863 }
23864 
23865 /*
23866  * Outbound IPv4 fragmentation routine using MDT.
23867  */
23868 static void
23869 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23870     uint32_t frag_flag, int offset)
23871 {
23872 	ipha_t		*ipha_orig;
23873 	int		i1, ip_data_end;
23874 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23875 	mblk_t		*hdr_mp, *md_mp = NULL;
23876 	unsigned char	*hdr_ptr, *pld_ptr;
23877 	multidata_t	*mmd;
23878 	ip_pdescinfo_t	pdi;
23879 	ill_t		*ill;
23880 	ip_stack_t	*ipst = ire->ire_ipst;
23881 
23882 	ASSERT(DB_TYPE(mp) == M_DATA);
23883 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23884 
23885 	ill = ire_to_ill(ire);
23886 	ASSERT(ill != NULL);
23887 
23888 	ipha_orig = (ipha_t *)mp->b_rptr;
23889 	mp->b_rptr += sizeof (ipha_t);
23890 
23891 	/* Calculate how many packets we will send out */
23892 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23893 	pkts = (i1 + len - 1) / len;
23894 	ASSERT(pkts > 1);
23895 
23896 	/* Allocate a message block which will hold all the IP Headers. */
23897 	wroff = ipst->ips_ip_wroff_extra;
23898 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23899 
23900 	i1 = pkts * hdr_chunk_len;
23901 	/*
23902 	 * Create the header buffer, Multidata and destination address
23903 	 * and SAP attribute that should be associated with it.
23904 	 */
23905 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23906 	    ((hdr_mp->b_wptr += i1),
23907 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23908 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23909 		freemsg(mp);
23910 		if (md_mp == NULL) {
23911 			freemsg(hdr_mp);
23912 		} else {
23913 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23914 			freemsg(md_mp);
23915 		}
23916 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23917 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23918 		return;
23919 	}
23920 	IP_STAT(ipst, ip_frag_mdt_allocd);
23921 
23922 	/*
23923 	 * Add a payload buffer to the Multidata; this operation must not
23924 	 * fail, or otherwise our logic in this routine is broken.  There
23925 	 * is no memory allocation done by the routine, so any returned
23926 	 * failure simply tells us that we've done something wrong.
23927 	 *
23928 	 * A failure tells us that either we're adding the same payload
23929 	 * buffer more than once, or we're trying to add more buffers than
23930 	 * allowed.  None of the above cases should happen, and we panic
23931 	 * because either there's horrible heap corruption, and/or
23932 	 * programming mistake.
23933 	 */
23934 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23935 		goto pbuf_panic;
23936 
23937 	hdr_ptr = hdr_mp->b_rptr;
23938 	pld_ptr = mp->b_rptr;
23939 
23940 	/* Establish the ending byte offset, based on the starting offset. */
23941 	offset <<= 3;
23942 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23943 	    IP_SIMPLE_HDR_LENGTH;
23944 
23945 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23946 
23947 	while (pld_ptr < mp->b_wptr) {
23948 		ipha_t		*ipha;
23949 		uint16_t	offset_and_flags;
23950 		uint16_t	ip_len;
23951 		int		error;
23952 
23953 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23954 		ipha = (ipha_t *)(hdr_ptr + wroff);
23955 		ASSERT(OK_32PTR(ipha));
23956 		*ipha = *ipha_orig;
23957 
23958 		if (ip_data_end - offset > len) {
23959 			offset_and_flags = IPH_MF;
23960 		} else {
23961 			/*
23962 			 * Last frag. Set len to the length of this last piece.
23963 			 */
23964 			len = ip_data_end - offset;
23965 			/* A frag of a frag might have IPH_MF non-zero */
23966 			offset_and_flags =
23967 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23968 			    IPH_MF;
23969 		}
23970 		offset_and_flags |= (uint16_t)(offset >> 3);
23971 		offset_and_flags |= (uint16_t)frag_flag;
23972 		/* Store the offset and flags in the IP header. */
23973 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23974 
23975 		/* Store the length in the IP header. */
23976 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23977 		ipha->ipha_length = htons(ip_len);
23978 
23979 		/*
23980 		 * Set the IP header checksum.  Note that mp is just
23981 		 * the header, so this is easy to pass to ip_csum.
23982 		 */
23983 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23984 
23985 		/*
23986 		 * Record offset and size of header and data of the next packet
23987 		 * in the multidata message.
23988 		 */
23989 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23990 		PDESC_PLD_INIT(&pdi);
23991 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23992 		ASSERT(i1 > 0);
23993 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23994 		if (i1 == len) {
23995 			pld_ptr += len;
23996 		} else {
23997 			i1 = len - i1;
23998 			mp = mp->b_cont;
23999 			ASSERT(mp != NULL);
24000 			ASSERT(MBLKL(mp) >= i1);
24001 			/*
24002 			 * Attach the next payload message block to the
24003 			 * multidata message.
24004 			 */
24005 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24006 				goto pbuf_panic;
24007 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24008 			pld_ptr = mp->b_rptr + i1;
24009 		}
24010 
24011 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24012 		    KM_NOSLEEP)) == NULL) {
24013 			/*
24014 			 * Any failure other than ENOMEM indicates that we
24015 			 * have passed in invalid pdesc info or parameters
24016 			 * to mmd_addpdesc, which must not happen.
24017 			 *
24018 			 * EINVAL is a result of failure on boundary checks
24019 			 * against the pdesc info contents.  It should not
24020 			 * happen, and we panic because either there's
24021 			 * horrible heap corruption, and/or programming
24022 			 * mistake.
24023 			 */
24024 			if (error != ENOMEM) {
24025 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24026 				    "pdesc logic error detected for "
24027 				    "mmd %p pinfo %p (%d)\n",
24028 				    (void *)mmd, (void *)&pdi, error);
24029 				/* NOTREACHED */
24030 			}
24031 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24032 			/* Free unattached payload message blocks as well */
24033 			md_mp->b_cont = mp->b_cont;
24034 			goto free_mmd;
24035 		}
24036 
24037 		/* Advance fragment offset. */
24038 		offset += len;
24039 
24040 		/* Advance to location for next header in the buffer. */
24041 		hdr_ptr += hdr_chunk_len;
24042 
24043 		/* Did we reach the next payload message block? */
24044 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24045 			mp = mp->b_cont;
24046 			/*
24047 			 * Attach the next message block with payload
24048 			 * data to the multidata message.
24049 			 */
24050 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24051 				goto pbuf_panic;
24052 			pld_ptr = mp->b_rptr;
24053 		}
24054 	}
24055 
24056 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24057 	ASSERT(mp->b_wptr == pld_ptr);
24058 
24059 	/* Update IP statistics */
24060 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24061 
24062 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24063 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24064 
24065 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24066 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24067 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24068 
24069 	if (pkt_type == OB_PKT) {
24070 		ire->ire_ob_pkt_count += pkts;
24071 		if (ire->ire_ipif != NULL)
24072 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24073 	} else {
24074 		/* The type is IB_PKT in the forwarding path. */
24075 		ire->ire_ib_pkt_count += pkts;
24076 		ASSERT(!IRE_IS_LOCAL(ire));
24077 		if (ire->ire_type & IRE_BROADCAST) {
24078 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24079 		} else {
24080 			UPDATE_MIB(ill->ill_ip_mib,
24081 			    ipIfStatsHCOutForwDatagrams, pkts);
24082 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24083 		}
24084 	}
24085 	ire->ire_last_used_time = lbolt;
24086 	/* Send it down */
24087 	putnext(ire->ire_stq, md_mp);
24088 	return;
24089 
24090 pbuf_panic:
24091 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24092 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24093 	    pbuf_idx);
24094 	/* NOTREACHED */
24095 }
24096 
24097 /*
24098  * Outbound IP fragmentation routine.
24099  *
24100  * NOTE : This routine does not ire_refrele the ire that is passed in
24101  * as the argument.
24102  */
24103 static void
24104 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24105     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24106 {
24107 	int		i1;
24108 	mblk_t		*ll_hdr_mp;
24109 	int 		ll_hdr_len;
24110 	int		hdr_len;
24111 	mblk_t		*hdr_mp;
24112 	ipha_t		*ipha;
24113 	int		ip_data_end;
24114 	int		len;
24115 	mblk_t		*mp = mp_orig, *mp1;
24116 	int		offset;
24117 	queue_t		*q;
24118 	uint32_t	v_hlen_tos_len;
24119 	mblk_t		*first_mp;
24120 	boolean_t	mctl_present;
24121 	ill_t		*ill;
24122 	ill_t		*out_ill;
24123 	mblk_t		*xmit_mp;
24124 	mblk_t		*carve_mp;
24125 	ire_t		*ire1 = NULL;
24126 	ire_t		*save_ire = NULL;
24127 	mblk_t  	*next_mp = NULL;
24128 	boolean_t	last_frag = B_FALSE;
24129 	boolean_t	multirt_send = B_FALSE;
24130 	ire_t		*first_ire = NULL;
24131 	irb_t		*irb = NULL;
24132 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24133 
24134 	ill = ire_to_ill(ire);
24135 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24136 
24137 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24138 
24139 	if (max_frag == 0) {
24140 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24141 		    " -  dropping packet\n"));
24142 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24143 		freemsg(mp);
24144 		return;
24145 	}
24146 
24147 	/*
24148 	 * IPsec does not allow hw accelerated packets to be fragmented
24149 	 * This check is made in ip_wput_ipsec_out prior to coming here
24150 	 * via ip_wput_ire_fragmentit.
24151 	 *
24152 	 * If at this point we have an ire whose ARP request has not
24153 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24154 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24155 	 * This packet and all fragmentable packets for this ire will
24156 	 * continue to get dropped while ire_nce->nce_state remains in
24157 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24158 	 * ND_REACHABLE, all subsquent large packets for this ire will
24159 	 * get fragemented and sent out by this function.
24160 	 */
24161 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24162 		/* If nce_state is ND_INITIAL, trigger ARP query */
24163 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24164 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24165 		    " -  dropping packet\n"));
24166 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24167 		freemsg(mp);
24168 		return;
24169 	}
24170 
24171 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24172 	    "ip_wput_frag_start:");
24173 
24174 	if (mp->b_datap->db_type == M_CTL) {
24175 		first_mp = mp;
24176 		mp_orig = mp = mp->b_cont;
24177 		mctl_present = B_TRUE;
24178 	} else {
24179 		first_mp = mp;
24180 		mctl_present = B_FALSE;
24181 	}
24182 
24183 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24184 	ipha = (ipha_t *)mp->b_rptr;
24185 
24186 	/*
24187 	 * If the Don't Fragment flag is on, generate an ICMP destination
24188 	 * unreachable, fragmentation needed.
24189 	 */
24190 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24191 	if (offset & IPH_DF) {
24192 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24193 		if (is_system_labeled()) {
24194 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24195 			    ire->ire_max_frag - max_frag, AF_INET);
24196 		}
24197 		/*
24198 		 * Need to compute hdr checksum if called from ip_wput_ire.
24199 		 * Note that ip_rput_forward verifies the checksum before
24200 		 * calling this routine so in that case this is a noop.
24201 		 */
24202 		ipha->ipha_hdr_checksum = 0;
24203 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24204 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24205 		    ipst);
24206 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24207 		    "ip_wput_frag_end:(%S)",
24208 		    "don't fragment");
24209 		return;
24210 	}
24211 	/*
24212 	 * Labeled systems adjust max_frag if they add a label
24213 	 * to send the correct path mtu.  We need the real mtu since we
24214 	 * are fragmenting the packet after label adjustment.
24215 	 */
24216 	if (is_system_labeled())
24217 		max_frag = ire->ire_max_frag;
24218 	if (mctl_present)
24219 		freeb(first_mp);
24220 	/*
24221 	 * Establish the starting offset.  May not be zero if we are fragging
24222 	 * a fragment that is being forwarded.
24223 	 */
24224 	offset = offset & IPH_OFFSET;
24225 
24226 	/* TODO why is this test needed? */
24227 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24228 	if (((max_frag - LENGTH) & ~7) < 8) {
24229 		/* TODO: notify ulp somehow */
24230 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24231 		freemsg(mp);
24232 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24233 		    "ip_wput_frag_end:(%S)",
24234 		    "len < 8");
24235 		return;
24236 	}
24237 
24238 	hdr_len = (V_HLEN & 0xF) << 2;
24239 
24240 	ipha->ipha_hdr_checksum = 0;
24241 
24242 	/*
24243 	 * Establish the number of bytes maximum per frag, after putting
24244 	 * in the header.
24245 	 */
24246 	len = (max_frag - hdr_len) & ~7;
24247 
24248 	/* Check if we can use MDT to send out the frags. */
24249 	ASSERT(!IRE_IS_LOCAL(ire));
24250 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24251 	    ipst->ips_ip_multidata_outbound &&
24252 	    !(ire->ire_flags & RTF_MULTIRT) &&
24253 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24254 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24255 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24256 		ASSERT(ill->ill_mdt_capab != NULL);
24257 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24258 			/*
24259 			 * If MDT has been previously turned off in the past,
24260 			 * and we currently can do MDT (due to IPQoS policy
24261 			 * removal, etc.) then enable it for this interface.
24262 			 */
24263 			ill->ill_mdt_capab->ill_mdt_on = 1;
24264 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24265 			    ill->ill_name));
24266 		}
24267 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24268 		    offset);
24269 		return;
24270 	}
24271 
24272 	/* Get a copy of the header for the trailing frags */
24273 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24274 	if (!hdr_mp) {
24275 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24276 		freemsg(mp);
24277 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24278 		    "ip_wput_frag_end:(%S)",
24279 		    "couldn't copy hdr");
24280 		return;
24281 	}
24282 	if (DB_CRED(mp) != NULL)
24283 		mblk_setcred(hdr_mp, DB_CRED(mp));
24284 
24285 	/* Store the starting offset, with the MoreFrags flag. */
24286 	i1 = offset | IPH_MF | frag_flag;
24287 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24288 
24289 	/* Establish the ending byte offset, based on the starting offset. */
24290 	offset <<= 3;
24291 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24292 
24293 	/* Store the length of the first fragment in the IP header. */
24294 	i1 = len + hdr_len;
24295 	ASSERT(i1 <= IP_MAXPACKET);
24296 	ipha->ipha_length = htons((uint16_t)i1);
24297 
24298 	/*
24299 	 * Compute the IP header checksum for the first frag.  We have to
24300 	 * watch out that we stop at the end of the header.
24301 	 */
24302 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24303 
24304 	/*
24305 	 * Now carve off the first frag.  Note that this will include the
24306 	 * original IP header.
24307 	 */
24308 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24309 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24310 		freeb(hdr_mp);
24311 		freemsg(mp_orig);
24312 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24313 		    "ip_wput_frag_end:(%S)",
24314 		    "couldn't carve first");
24315 		return;
24316 	}
24317 
24318 	/*
24319 	 * Multirouting case. Each fragment is replicated
24320 	 * via all non-condemned RTF_MULTIRT routes
24321 	 * currently resolved.
24322 	 * We ensure that first_ire is the first RTF_MULTIRT
24323 	 * ire in the bucket.
24324 	 */
24325 	if (ire->ire_flags & RTF_MULTIRT) {
24326 		irb = ire->ire_bucket;
24327 		ASSERT(irb != NULL);
24328 
24329 		multirt_send = B_TRUE;
24330 
24331 		/* Make sure we do not omit any multiroute ire. */
24332 		IRB_REFHOLD(irb);
24333 		for (first_ire = irb->irb_ire;
24334 		    first_ire != NULL;
24335 		    first_ire = first_ire->ire_next) {
24336 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24337 			    (first_ire->ire_addr == ire->ire_addr) &&
24338 			    !(first_ire->ire_marks &
24339 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24340 				break;
24341 			}
24342 		}
24343 
24344 		if (first_ire != NULL) {
24345 			if (first_ire != ire) {
24346 				IRE_REFHOLD(first_ire);
24347 				/*
24348 				 * Do not release the ire passed in
24349 				 * as the argument.
24350 				 */
24351 				ire = first_ire;
24352 			} else {
24353 				first_ire = NULL;
24354 			}
24355 		}
24356 		IRB_REFRELE(irb);
24357 
24358 		/*
24359 		 * Save the first ire; we will need to restore it
24360 		 * for the trailing frags.
24361 		 * We REFHOLD save_ire, as each iterated ire will be
24362 		 * REFRELEd.
24363 		 */
24364 		save_ire = ire;
24365 		IRE_REFHOLD(save_ire);
24366 	}
24367 
24368 	/*
24369 	 * First fragment emission loop.
24370 	 * In most cases, the emission loop below is entered only
24371 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24372 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24373 	 * bucket, and send the fragment through all crossed
24374 	 * RTF_MULTIRT routes.
24375 	 */
24376 	do {
24377 		if (ire->ire_flags & RTF_MULTIRT) {
24378 			/*
24379 			 * We are in a multiple send case, need to get
24380 			 * the next ire and make a copy of the packet.
24381 			 * ire1 holds here the next ire to process in the
24382 			 * bucket. If multirouting is expected,
24383 			 * any non-RTF_MULTIRT ire that has the
24384 			 * right destination address is ignored.
24385 			 *
24386 			 * We have to take into account the MTU of
24387 			 * each walked ire. max_frag is set by the
24388 			 * the caller and generally refers to
24389 			 * the primary ire entry. Here we ensure that
24390 			 * no route with a lower MTU will be used, as
24391 			 * fragments are carved once for all ires,
24392 			 * then replicated.
24393 			 */
24394 			ASSERT(irb != NULL);
24395 			IRB_REFHOLD(irb);
24396 			for (ire1 = ire->ire_next;
24397 			    ire1 != NULL;
24398 			    ire1 = ire1->ire_next) {
24399 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24400 					continue;
24401 				if (ire1->ire_addr != ire->ire_addr)
24402 					continue;
24403 				if (ire1->ire_marks &
24404 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24405 					continue;
24406 				/*
24407 				 * Ensure we do not exceed the MTU
24408 				 * of the next route.
24409 				 */
24410 				if (ire1->ire_max_frag < max_frag) {
24411 					ip_multirt_bad_mtu(ire1, max_frag);
24412 					continue;
24413 				}
24414 
24415 				/* Got one. */
24416 				IRE_REFHOLD(ire1);
24417 				break;
24418 			}
24419 			IRB_REFRELE(irb);
24420 
24421 			if (ire1 != NULL) {
24422 				next_mp = copyb(mp);
24423 				if ((next_mp == NULL) ||
24424 				    ((mp->b_cont != NULL) &&
24425 				    ((next_mp->b_cont =
24426 				    dupmsg(mp->b_cont)) == NULL))) {
24427 					freemsg(next_mp);
24428 					next_mp = NULL;
24429 					ire_refrele(ire1);
24430 					ire1 = NULL;
24431 				}
24432 			}
24433 
24434 			/* Last multiroute ire; don't loop anymore. */
24435 			if (ire1 == NULL) {
24436 				multirt_send = B_FALSE;
24437 			}
24438 		}
24439 
24440 		ll_hdr_len = 0;
24441 		LOCK_IRE_FP_MP(ire);
24442 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24443 		if (ll_hdr_mp != NULL) {
24444 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24445 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24446 		} else {
24447 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24448 		}
24449 
24450 		/* If there is a transmit header, get a copy for this frag. */
24451 		/*
24452 		 * TODO: should check db_ref before calling ip_carve_mp since
24453 		 * it might give us a dup.
24454 		 */
24455 		if (!ll_hdr_mp) {
24456 			/* No xmit header. */
24457 			xmit_mp = mp;
24458 
24459 		/* We have a link-layer header that can fit in our mblk. */
24460 		} else if (mp->b_datap->db_ref == 1 &&
24461 		    ll_hdr_len != 0 &&
24462 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24463 			/* M_DATA fastpath */
24464 			mp->b_rptr -= ll_hdr_len;
24465 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24466 			xmit_mp = mp;
24467 
24468 		/* Corner case if copyb has failed */
24469 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24470 			UNLOCK_IRE_FP_MP(ire);
24471 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24472 			freeb(hdr_mp);
24473 			freemsg(mp);
24474 			freemsg(mp_orig);
24475 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24476 			    "ip_wput_frag_end:(%S)",
24477 			    "discard");
24478 
24479 			if (multirt_send) {
24480 				ASSERT(ire1);
24481 				ASSERT(next_mp);
24482 
24483 				freemsg(next_mp);
24484 				ire_refrele(ire1);
24485 			}
24486 			if (save_ire != NULL)
24487 				IRE_REFRELE(save_ire);
24488 
24489 			if (first_ire != NULL)
24490 				ire_refrele(first_ire);
24491 			return;
24492 
24493 		/*
24494 		 * Case of res_mp OR the fastpath mp can't fit
24495 		 * in the mblk
24496 		 */
24497 		} else {
24498 			xmit_mp->b_cont = mp;
24499 			if (DB_CRED(mp) != NULL)
24500 				mblk_setcred(xmit_mp, DB_CRED(mp));
24501 			/*
24502 			 * Get priority marking, if any.
24503 			 * We propagate the CoS marking from the
24504 			 * original packet that went to QoS processing
24505 			 * in ip_wput_ire to the newly carved mp.
24506 			 */
24507 			if (DB_TYPE(xmit_mp) == M_DATA)
24508 				xmit_mp->b_band = mp->b_band;
24509 		}
24510 		UNLOCK_IRE_FP_MP(ire);
24511 
24512 		q = ire->ire_stq;
24513 		out_ill = (ill_t *)q->q_ptr;
24514 
24515 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24516 
24517 		DTRACE_PROBE4(ip4__physical__out__start,
24518 		    ill_t *, NULL, ill_t *, out_ill,
24519 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24520 
24521 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24522 		    ipst->ips_ipv4firewall_physical_out,
24523 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24524 
24525 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24526 
24527 		if (xmit_mp != NULL) {
24528 			putnext(q, xmit_mp);
24529 
24530 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24531 			UPDATE_MIB(out_ill->ill_ip_mib,
24532 			    ipIfStatsHCOutOctets, i1);
24533 
24534 			if (pkt_type != OB_PKT) {
24535 				/*
24536 				 * Update the packet count and MIB stats
24537 				 * of trailing RTF_MULTIRT ires.
24538 				 */
24539 				UPDATE_OB_PKT_COUNT(ire);
24540 				BUMP_MIB(out_ill->ill_ip_mib,
24541 				    ipIfStatsOutFragReqds);
24542 			}
24543 		}
24544 
24545 		if (multirt_send) {
24546 			/*
24547 			 * We are in a multiple send case; look for
24548 			 * the next ire and re-enter the loop.
24549 			 */
24550 			ASSERT(ire1);
24551 			ASSERT(next_mp);
24552 			/* REFRELE the current ire before looping */
24553 			ire_refrele(ire);
24554 			ire = ire1;
24555 			ire1 = NULL;
24556 			mp = next_mp;
24557 			next_mp = NULL;
24558 		}
24559 	} while (multirt_send);
24560 
24561 	ASSERT(ire1 == NULL);
24562 
24563 	/* Restore the original ire; we need it for the trailing frags */
24564 	if (save_ire != NULL) {
24565 		/* REFRELE the last iterated ire */
24566 		ire_refrele(ire);
24567 		/* save_ire has been REFHOLDed */
24568 		ire = save_ire;
24569 		save_ire = NULL;
24570 		q = ire->ire_stq;
24571 	}
24572 
24573 	if (pkt_type == OB_PKT) {
24574 		UPDATE_OB_PKT_COUNT(ire);
24575 	} else {
24576 		out_ill = (ill_t *)q->q_ptr;
24577 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24578 		UPDATE_IB_PKT_COUNT(ire);
24579 	}
24580 
24581 	/* Advance the offset to the second frag starting point. */
24582 	offset += len;
24583 	/*
24584 	 * Update hdr_len from the copied header - there might be less options
24585 	 * in the later fragments.
24586 	 */
24587 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24588 	/* Loop until done. */
24589 	for (;;) {
24590 		uint16_t	offset_and_flags;
24591 		uint16_t	ip_len;
24592 
24593 		if (ip_data_end - offset > len) {
24594 			/*
24595 			 * Carve off the appropriate amount from the original
24596 			 * datagram.
24597 			 */
24598 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24599 				mp = NULL;
24600 				break;
24601 			}
24602 			/*
24603 			 * More frags after this one.  Get another copy
24604 			 * of the header.
24605 			 */
24606 			if (carve_mp->b_datap->db_ref == 1 &&
24607 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24608 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24609 				/* Inline IP header */
24610 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24611 				    hdr_mp->b_rptr;
24612 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24613 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24614 				mp = carve_mp;
24615 			} else {
24616 				if (!(mp = copyb(hdr_mp))) {
24617 					freemsg(carve_mp);
24618 					break;
24619 				}
24620 				/* Get priority marking, if any. */
24621 				mp->b_band = carve_mp->b_band;
24622 				mp->b_cont = carve_mp;
24623 			}
24624 			ipha = (ipha_t *)mp->b_rptr;
24625 			offset_and_flags = IPH_MF;
24626 		} else {
24627 			/*
24628 			 * Last frag.  Consume the header. Set len to
24629 			 * the length of this last piece.
24630 			 */
24631 			len = ip_data_end - offset;
24632 
24633 			/*
24634 			 * Carve off the appropriate amount from the original
24635 			 * datagram.
24636 			 */
24637 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24638 				mp = NULL;
24639 				break;
24640 			}
24641 			if (carve_mp->b_datap->db_ref == 1 &&
24642 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24643 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24644 				/* Inline IP header */
24645 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24646 				    hdr_mp->b_rptr;
24647 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24648 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24649 				mp = carve_mp;
24650 				freeb(hdr_mp);
24651 				hdr_mp = mp;
24652 			} else {
24653 				mp = hdr_mp;
24654 				/* Get priority marking, if any. */
24655 				mp->b_band = carve_mp->b_band;
24656 				mp->b_cont = carve_mp;
24657 			}
24658 			ipha = (ipha_t *)mp->b_rptr;
24659 			/* A frag of a frag might have IPH_MF non-zero */
24660 			offset_and_flags =
24661 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24662 			    IPH_MF;
24663 		}
24664 		offset_and_flags |= (uint16_t)(offset >> 3);
24665 		offset_and_flags |= (uint16_t)frag_flag;
24666 		/* Store the offset and flags in the IP header. */
24667 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24668 
24669 		/* Store the length in the IP header. */
24670 		ip_len = (uint16_t)(len + hdr_len);
24671 		ipha->ipha_length = htons(ip_len);
24672 
24673 		/*
24674 		 * Set the IP header checksum.	Note that mp is just
24675 		 * the header, so this is easy to pass to ip_csum.
24676 		 */
24677 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24678 
24679 		/* Attach a transmit header, if any, and ship it. */
24680 		if (pkt_type == OB_PKT) {
24681 			UPDATE_OB_PKT_COUNT(ire);
24682 		} else {
24683 			out_ill = (ill_t *)q->q_ptr;
24684 			BUMP_MIB(out_ill->ill_ip_mib,
24685 			    ipIfStatsHCOutForwDatagrams);
24686 			UPDATE_IB_PKT_COUNT(ire);
24687 		}
24688 
24689 		if (ire->ire_flags & RTF_MULTIRT) {
24690 			irb = ire->ire_bucket;
24691 			ASSERT(irb != NULL);
24692 
24693 			multirt_send = B_TRUE;
24694 
24695 			/*
24696 			 * Save the original ire; we will need to restore it
24697 			 * for the tailing frags.
24698 			 */
24699 			save_ire = ire;
24700 			IRE_REFHOLD(save_ire);
24701 		}
24702 		/*
24703 		 * Emission loop for this fragment, similar
24704 		 * to what is done for the first fragment.
24705 		 */
24706 		do {
24707 			if (multirt_send) {
24708 				/*
24709 				 * We are in a multiple send case, need to get
24710 				 * the next ire and make a copy of the packet.
24711 				 */
24712 				ASSERT(irb != NULL);
24713 				IRB_REFHOLD(irb);
24714 				for (ire1 = ire->ire_next;
24715 				    ire1 != NULL;
24716 				    ire1 = ire1->ire_next) {
24717 					if (!(ire1->ire_flags & RTF_MULTIRT))
24718 						continue;
24719 					if (ire1->ire_addr != ire->ire_addr)
24720 						continue;
24721 					if (ire1->ire_marks &
24722 					    (IRE_MARK_CONDEMNED|
24723 					    IRE_MARK_HIDDEN)) {
24724 						continue;
24725 					}
24726 					/*
24727 					 * Ensure we do not exceed the MTU
24728 					 * of the next route.
24729 					 */
24730 					if (ire1->ire_max_frag < max_frag) {
24731 						ip_multirt_bad_mtu(ire1,
24732 						    max_frag);
24733 						continue;
24734 					}
24735 
24736 					/* Got one. */
24737 					IRE_REFHOLD(ire1);
24738 					break;
24739 				}
24740 				IRB_REFRELE(irb);
24741 
24742 				if (ire1 != NULL) {
24743 					next_mp = copyb(mp);
24744 					if ((next_mp == NULL) ||
24745 					    ((mp->b_cont != NULL) &&
24746 					    ((next_mp->b_cont =
24747 					    dupmsg(mp->b_cont)) == NULL))) {
24748 						freemsg(next_mp);
24749 						next_mp = NULL;
24750 						ire_refrele(ire1);
24751 						ire1 = NULL;
24752 					}
24753 				}
24754 
24755 				/* Last multiroute ire; don't loop anymore. */
24756 				if (ire1 == NULL) {
24757 					multirt_send = B_FALSE;
24758 				}
24759 			}
24760 
24761 			/* Update transmit header */
24762 			ll_hdr_len = 0;
24763 			LOCK_IRE_FP_MP(ire);
24764 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24765 			if (ll_hdr_mp != NULL) {
24766 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24767 				ll_hdr_len = MBLKL(ll_hdr_mp);
24768 			} else {
24769 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24770 			}
24771 
24772 			if (!ll_hdr_mp) {
24773 				xmit_mp = mp;
24774 
24775 			/*
24776 			 * We have link-layer header that can fit in
24777 			 * our mblk.
24778 			 */
24779 			} else if (mp->b_datap->db_ref == 1 &&
24780 			    ll_hdr_len != 0 &&
24781 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24782 				/* M_DATA fastpath */
24783 				mp->b_rptr -= ll_hdr_len;
24784 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24785 				    ll_hdr_len);
24786 				xmit_mp = mp;
24787 
24788 			/*
24789 			 * Case of res_mp OR the fastpath mp can't fit
24790 			 * in the mblk
24791 			 */
24792 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24793 				xmit_mp->b_cont = mp;
24794 				if (DB_CRED(mp) != NULL)
24795 					mblk_setcred(xmit_mp, DB_CRED(mp));
24796 				/* Get priority marking, if any. */
24797 				if (DB_TYPE(xmit_mp) == M_DATA)
24798 					xmit_mp->b_band = mp->b_band;
24799 
24800 			/* Corner case if copyb failed */
24801 			} else {
24802 				/*
24803 				 * Exit both the replication and
24804 				 * fragmentation loops.
24805 				 */
24806 				UNLOCK_IRE_FP_MP(ire);
24807 				goto drop_pkt;
24808 			}
24809 			UNLOCK_IRE_FP_MP(ire);
24810 
24811 			mp1 = mp;
24812 			out_ill = (ill_t *)q->q_ptr;
24813 
24814 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24815 
24816 			DTRACE_PROBE4(ip4__physical__out__start,
24817 			    ill_t *, NULL, ill_t *, out_ill,
24818 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24819 
24820 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24821 			    ipst->ips_ipv4firewall_physical_out,
24822 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24823 
24824 			DTRACE_PROBE1(ip4__physical__out__end,
24825 			    mblk_t *, xmit_mp);
24826 
24827 			if (mp != mp1 && hdr_mp == mp1)
24828 				hdr_mp = mp;
24829 			if (mp != mp1 && mp_orig == mp1)
24830 				mp_orig = mp;
24831 
24832 			if (xmit_mp != NULL) {
24833 				putnext(q, xmit_mp);
24834 
24835 				BUMP_MIB(out_ill->ill_ip_mib,
24836 				    ipIfStatsHCOutTransmits);
24837 				UPDATE_MIB(out_ill->ill_ip_mib,
24838 				    ipIfStatsHCOutOctets, ip_len);
24839 
24840 				if (pkt_type != OB_PKT) {
24841 					/*
24842 					 * Update the packet count of trailing
24843 					 * RTF_MULTIRT ires.
24844 					 */
24845 					UPDATE_OB_PKT_COUNT(ire);
24846 				}
24847 			}
24848 
24849 			/* All done if we just consumed the hdr_mp. */
24850 			if (mp == hdr_mp) {
24851 				last_frag = B_TRUE;
24852 				BUMP_MIB(out_ill->ill_ip_mib,
24853 				    ipIfStatsOutFragOKs);
24854 			}
24855 
24856 			if (multirt_send) {
24857 				/*
24858 				 * We are in a multiple send case; look for
24859 				 * the next ire and re-enter the loop.
24860 				 */
24861 				ASSERT(ire1);
24862 				ASSERT(next_mp);
24863 				/* REFRELE the current ire before looping */
24864 				ire_refrele(ire);
24865 				ire = ire1;
24866 				ire1 = NULL;
24867 				q = ire->ire_stq;
24868 				mp = next_mp;
24869 				next_mp = NULL;
24870 			}
24871 		} while (multirt_send);
24872 		/*
24873 		 * Restore the original ire; we need it for the
24874 		 * trailing frags
24875 		 */
24876 		if (save_ire != NULL) {
24877 			ASSERT(ire1 == NULL);
24878 			/* REFRELE the last iterated ire */
24879 			ire_refrele(ire);
24880 			/* save_ire has been REFHOLDed */
24881 			ire = save_ire;
24882 			q = ire->ire_stq;
24883 			save_ire = NULL;
24884 		}
24885 
24886 		if (last_frag) {
24887 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24888 			    "ip_wput_frag_end:(%S)",
24889 			    "consumed hdr_mp");
24890 
24891 			if (first_ire != NULL)
24892 				ire_refrele(first_ire);
24893 			return;
24894 		}
24895 		/* Otherwise, advance and loop. */
24896 		offset += len;
24897 	}
24898 
24899 drop_pkt:
24900 	/* Clean up following allocation failure. */
24901 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24902 	freemsg(mp);
24903 	if (mp != hdr_mp)
24904 		freeb(hdr_mp);
24905 	if (mp != mp_orig)
24906 		freemsg(mp_orig);
24907 
24908 	if (save_ire != NULL)
24909 		IRE_REFRELE(save_ire);
24910 	if (first_ire != NULL)
24911 		ire_refrele(first_ire);
24912 
24913 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24914 	    "ip_wput_frag_end:(%S)",
24915 	    "end--alloc failure");
24916 }
24917 
24918 /*
24919  * Copy the header plus those options which have the copy bit set
24920  */
24921 static mblk_t *
24922 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24923 {
24924 	mblk_t	*mp;
24925 	uchar_t	*up;
24926 
24927 	/*
24928 	 * Quick check if we need to look for options without the copy bit
24929 	 * set
24930 	 */
24931 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24932 	if (!mp)
24933 		return (mp);
24934 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24935 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24936 		bcopy(rptr, mp->b_rptr, hdr_len);
24937 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24938 		return (mp);
24939 	}
24940 	up  = mp->b_rptr;
24941 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24942 	up += IP_SIMPLE_HDR_LENGTH;
24943 	rptr += IP_SIMPLE_HDR_LENGTH;
24944 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24945 	while (hdr_len > 0) {
24946 		uint32_t optval;
24947 		uint32_t optlen;
24948 
24949 		optval = *rptr;
24950 		if (optval == IPOPT_EOL)
24951 			break;
24952 		if (optval == IPOPT_NOP)
24953 			optlen = 1;
24954 		else
24955 			optlen = rptr[1];
24956 		if (optval & IPOPT_COPY) {
24957 			bcopy(rptr, up, optlen);
24958 			up += optlen;
24959 		}
24960 		rptr += optlen;
24961 		hdr_len -= optlen;
24962 	}
24963 	/*
24964 	 * Make sure that we drop an even number of words by filling
24965 	 * with EOL to the next word boundary.
24966 	 */
24967 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24968 	    hdr_len & 0x3; hdr_len++)
24969 		*up++ = IPOPT_EOL;
24970 	mp->b_wptr = up;
24971 	/* Update header length */
24972 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24973 	return (mp);
24974 }
24975 
24976 /*
24977  * Delivery to local recipients including fanout to multiple recipients.
24978  * Does not do checksumming of UDP/TCP.
24979  * Note: q should be the read side queue for either the ill or conn.
24980  * Note: rq should be the read side q for the lower (ill) stream.
24981  * We don't send packets to IPPF processing, thus the last argument
24982  * to all the fanout calls are B_FALSE.
24983  */
24984 void
24985 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24986     int fanout_flags, zoneid_t zoneid)
24987 {
24988 	uint32_t	protocol;
24989 	mblk_t		*first_mp;
24990 	boolean_t	mctl_present;
24991 	int		ire_type;
24992 #define	rptr	((uchar_t *)ipha)
24993 	ip_stack_t	*ipst = ill->ill_ipst;
24994 
24995 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24996 	    "ip_wput_local_start: q %p", q);
24997 
24998 	if (ire != NULL) {
24999 		ire_type = ire->ire_type;
25000 	} else {
25001 		/*
25002 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25003 		 * packet is not multicast, we can't tell the ire type.
25004 		 */
25005 		ASSERT(CLASSD(ipha->ipha_dst));
25006 		ire_type = IRE_BROADCAST;
25007 	}
25008 
25009 	first_mp = mp;
25010 	if (first_mp->b_datap->db_type == M_CTL) {
25011 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25012 		if (!io->ipsec_out_secure) {
25013 			/*
25014 			 * This ipsec_out_t was allocated in ip_wput
25015 			 * for multicast packets to store the ill_index.
25016 			 * As this is being delivered locally, we don't
25017 			 * need this anymore.
25018 			 */
25019 			mp = first_mp->b_cont;
25020 			freeb(first_mp);
25021 			first_mp = mp;
25022 			mctl_present = B_FALSE;
25023 		} else {
25024 			/*
25025 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25026 			 * security properties for the looped-back packet.
25027 			 */
25028 			mctl_present = B_TRUE;
25029 			mp = first_mp->b_cont;
25030 			ASSERT(mp != NULL);
25031 			ipsec_out_to_in(first_mp);
25032 		}
25033 	} else {
25034 		mctl_present = B_FALSE;
25035 	}
25036 
25037 	DTRACE_PROBE4(ip4__loopback__in__start,
25038 	    ill_t *, ill, ill_t *, NULL,
25039 	    ipha_t *, ipha, mblk_t *, first_mp);
25040 
25041 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25042 	    ipst->ips_ipv4firewall_loopback_in,
25043 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25044 
25045 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25046 
25047 	if (first_mp == NULL)
25048 		return;
25049 
25050 	ipst->ips_loopback_packets++;
25051 
25052 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25053 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25054 	if (!IS_SIMPLE_IPH(ipha)) {
25055 		ip_wput_local_options(ipha, ipst);
25056 	}
25057 
25058 	protocol = ipha->ipha_protocol;
25059 	switch (protocol) {
25060 	case IPPROTO_ICMP: {
25061 		ire_t		*ire_zone;
25062 		ilm_t		*ilm;
25063 		mblk_t		*mp1;
25064 		zoneid_t	last_zoneid;
25065 
25066 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25067 			ASSERT(ire_type == IRE_BROADCAST);
25068 			/*
25069 			 * In the multicast case, applications may have joined
25070 			 * the group from different zones, so we need to deliver
25071 			 * the packet to each of them. Loop through the
25072 			 * multicast memberships structures (ilm) on the receive
25073 			 * ill and send a copy of the packet up each matching
25074 			 * one. However, we don't do this for multicasts sent on
25075 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25076 			 * they must stay in the sender's zone.
25077 			 *
25078 			 * ilm_add_v6() ensures that ilms in the same zone are
25079 			 * contiguous in the ill_ilm list. We use this property
25080 			 * to avoid sending duplicates needed when two
25081 			 * applications in the same zone join the same group on
25082 			 * different logical interfaces: we ignore the ilm if
25083 			 * it's zoneid is the same as the last matching one.
25084 			 * In addition, the sending of the packet for
25085 			 * ire_zoneid is delayed until all of the other ilms
25086 			 * have been exhausted.
25087 			 */
25088 			last_zoneid = -1;
25089 			ILM_WALKER_HOLD(ill);
25090 			for (ilm = ill->ill_ilm; ilm != NULL;
25091 			    ilm = ilm->ilm_next) {
25092 				if ((ilm->ilm_flags & ILM_DELETED) ||
25093 				    ipha->ipha_dst != ilm->ilm_addr ||
25094 				    ilm->ilm_zoneid == last_zoneid ||
25095 				    ilm->ilm_zoneid == zoneid ||
25096 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25097 					continue;
25098 				mp1 = ip_copymsg(first_mp);
25099 				if (mp1 == NULL)
25100 					continue;
25101 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25102 				    mctl_present, B_FALSE, ill,
25103 				    ilm->ilm_zoneid);
25104 				last_zoneid = ilm->ilm_zoneid;
25105 			}
25106 			ILM_WALKER_RELE(ill);
25107 			/*
25108 			 * Loopback case: the sending endpoint has
25109 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25110 			 * dispatch the multicast packet to the sending zone.
25111 			 */
25112 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25113 				freemsg(first_mp);
25114 				return;
25115 			}
25116 		} else if (ire_type == IRE_BROADCAST) {
25117 			/*
25118 			 * In the broadcast case, there may be many zones
25119 			 * which need a copy of the packet delivered to them.
25120 			 * There is one IRE_BROADCAST per broadcast address
25121 			 * and per zone; we walk those using a helper function.
25122 			 * In addition, the sending of the packet for zoneid is
25123 			 * delayed until all of the other ires have been
25124 			 * processed.
25125 			 */
25126 			IRB_REFHOLD(ire->ire_bucket);
25127 			ire_zone = NULL;
25128 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25129 			    ire)) != NULL) {
25130 				mp1 = ip_copymsg(first_mp);
25131 				if (mp1 == NULL)
25132 					continue;
25133 
25134 				UPDATE_IB_PKT_COUNT(ire_zone);
25135 				ire_zone->ire_last_used_time = lbolt;
25136 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25137 				    mctl_present, B_FALSE, ill,
25138 				    ire_zone->ire_zoneid);
25139 			}
25140 			IRB_REFRELE(ire->ire_bucket);
25141 		}
25142 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25143 		    0, mctl_present, B_FALSE, ill, zoneid);
25144 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25145 		    "ip_wput_local_end: q %p (%S)",
25146 		    q, "icmp");
25147 		return;
25148 	}
25149 	case IPPROTO_IGMP:
25150 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25151 			/* Bad packet - discarded by igmp_input */
25152 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25153 			    "ip_wput_local_end: q %p (%S)",
25154 			    q, "igmp_input--bad packet");
25155 			if (mctl_present)
25156 				freeb(first_mp);
25157 			return;
25158 		}
25159 		/*
25160 		 * igmp_input() may have returned the pulled up message.
25161 		 * So first_mp and ipha need to be reinitialized.
25162 		 */
25163 		ipha = (ipha_t *)mp->b_rptr;
25164 		if (mctl_present)
25165 			first_mp->b_cont = mp;
25166 		else
25167 			first_mp = mp;
25168 		/* deliver to local raw users */
25169 		break;
25170 	case IPPROTO_ENCAP:
25171 		/*
25172 		 * This case is covered by either ip_fanout_proto, or by
25173 		 * the above security processing for self-tunneled packets.
25174 		 */
25175 		break;
25176 	case IPPROTO_UDP: {
25177 		uint16_t	*up;
25178 		uint32_t	ports;
25179 
25180 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25181 		    UDP_PORTS_OFFSET);
25182 		/* Force a 'valid' checksum. */
25183 		up[3] = 0;
25184 
25185 		ports = *(uint32_t *)up;
25186 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25187 		    (ire_type == IRE_BROADCAST),
25188 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25189 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25190 		    ill, zoneid);
25191 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25192 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25193 		return;
25194 	}
25195 	case IPPROTO_TCP: {
25196 
25197 		/*
25198 		 * For TCP, discard broadcast packets.
25199 		 */
25200 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25201 			freemsg(first_mp);
25202 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25203 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25204 			return;
25205 		}
25206 
25207 		if (mp->b_datap->db_type == M_DATA) {
25208 			/*
25209 			 * M_DATA mblk, so init mblk (chain) for no struio().
25210 			 */
25211 			mblk_t	*mp1 = mp;
25212 
25213 			do {
25214 				mp1->b_datap->db_struioflag = 0;
25215 			} while ((mp1 = mp1->b_cont) != NULL);
25216 		}
25217 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25218 		    <= mp->b_wptr);
25219 		ip_fanout_tcp(q, first_mp, ill, ipha,
25220 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25221 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25222 		    mctl_present, B_FALSE, zoneid);
25223 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25224 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25225 		return;
25226 	}
25227 	case IPPROTO_SCTP:
25228 	{
25229 		uint32_t	ports;
25230 
25231 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25232 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25233 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25234 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25235 		return;
25236 	}
25237 
25238 	default:
25239 		break;
25240 	}
25241 	/*
25242 	 * Find a client for some other protocol.  We give
25243 	 * copies to multiple clients, if more than one is
25244 	 * bound.
25245 	 */
25246 	ip_fanout_proto(q, first_mp, ill, ipha,
25247 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25248 	    mctl_present, B_FALSE, ill, zoneid);
25249 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25250 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25251 #undef	rptr
25252 }
25253 
25254 /*
25255  * Update any source route, record route, or timestamp options.
25256  * Check that we are at end of strict source route.
25257  * The options have been sanity checked by ip_wput_options().
25258  */
25259 static void
25260 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25261 {
25262 	ipoptp_t	opts;
25263 	uchar_t		*opt;
25264 	uint8_t		optval;
25265 	uint8_t		optlen;
25266 	ipaddr_t	dst;
25267 	uint32_t	ts;
25268 	ire_t		*ire;
25269 	timestruc_t	now;
25270 
25271 	ip2dbg(("ip_wput_local_options\n"));
25272 	for (optval = ipoptp_first(&opts, ipha);
25273 	    optval != IPOPT_EOL;
25274 	    optval = ipoptp_next(&opts)) {
25275 		opt = opts.ipoptp_cur;
25276 		optlen = opts.ipoptp_len;
25277 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25278 		switch (optval) {
25279 			uint32_t off;
25280 		case IPOPT_SSRR:
25281 		case IPOPT_LSRR:
25282 			off = opt[IPOPT_OFFSET];
25283 			off--;
25284 			if (optlen < IP_ADDR_LEN ||
25285 			    off > optlen - IP_ADDR_LEN) {
25286 				/* End of source route */
25287 				break;
25288 			}
25289 			/*
25290 			 * This will only happen if two consecutive entries
25291 			 * in the source route contains our address or if
25292 			 * it is a packet with a loose source route which
25293 			 * reaches us before consuming the whole source route
25294 			 */
25295 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25296 			if (optval == IPOPT_SSRR) {
25297 				return;
25298 			}
25299 			/*
25300 			 * Hack: instead of dropping the packet truncate the
25301 			 * source route to what has been used by filling the
25302 			 * rest with IPOPT_NOP.
25303 			 */
25304 			opt[IPOPT_OLEN] = (uint8_t)off;
25305 			while (off < optlen) {
25306 				opt[off++] = IPOPT_NOP;
25307 			}
25308 			break;
25309 		case IPOPT_RR:
25310 			off = opt[IPOPT_OFFSET];
25311 			off--;
25312 			if (optlen < IP_ADDR_LEN ||
25313 			    off > optlen - IP_ADDR_LEN) {
25314 				/* No more room - ignore */
25315 				ip1dbg((
25316 				    "ip_wput_forward_options: end of RR\n"));
25317 				break;
25318 			}
25319 			dst = htonl(INADDR_LOOPBACK);
25320 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25321 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25322 			break;
25323 		case IPOPT_TS:
25324 			/* Insert timestamp if there is romm */
25325 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25326 			case IPOPT_TS_TSONLY:
25327 				off = IPOPT_TS_TIMELEN;
25328 				break;
25329 			case IPOPT_TS_PRESPEC:
25330 			case IPOPT_TS_PRESPEC_RFC791:
25331 				/* Verify that the address matched */
25332 				off = opt[IPOPT_OFFSET] - 1;
25333 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25334 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25335 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25336 				    ipst);
25337 				if (ire == NULL) {
25338 					/* Not for us */
25339 					break;
25340 				}
25341 				ire_refrele(ire);
25342 				/* FALLTHRU */
25343 			case IPOPT_TS_TSANDADDR:
25344 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25345 				break;
25346 			default:
25347 				/*
25348 				 * ip_*put_options should have already
25349 				 * dropped this packet.
25350 				 */
25351 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25352 				    "unknown IT - bug in ip_wput_options?\n");
25353 				return;	/* Keep "lint" happy */
25354 			}
25355 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25356 				/* Increase overflow counter */
25357 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25358 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25359 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25360 				    (off << 4);
25361 				break;
25362 			}
25363 			off = opt[IPOPT_OFFSET] - 1;
25364 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25365 			case IPOPT_TS_PRESPEC:
25366 			case IPOPT_TS_PRESPEC_RFC791:
25367 			case IPOPT_TS_TSANDADDR:
25368 				dst = htonl(INADDR_LOOPBACK);
25369 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25370 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25371 				/* FALLTHRU */
25372 			case IPOPT_TS_TSONLY:
25373 				off = opt[IPOPT_OFFSET] - 1;
25374 				/* Compute # of milliseconds since midnight */
25375 				gethrestime(&now);
25376 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25377 				    now.tv_nsec / (NANOSEC / MILLISEC);
25378 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25379 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25380 				break;
25381 			}
25382 			break;
25383 		}
25384 	}
25385 }
25386 
25387 /*
25388  * Send out a multicast packet on interface ipif.
25389  * The sender does not have an conn.
25390  * Caller verifies that this isn't a PHYI_LOOPBACK.
25391  */
25392 void
25393 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25394 {
25395 	ipha_t	*ipha;
25396 	ire_t	*ire;
25397 	ipaddr_t	dst;
25398 	mblk_t		*first_mp;
25399 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25400 
25401 	/* igmp_sendpkt always allocates a ipsec_out_t */
25402 	ASSERT(mp->b_datap->db_type == M_CTL);
25403 	ASSERT(!ipif->ipif_isv6);
25404 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25405 
25406 	first_mp = mp;
25407 	mp = first_mp->b_cont;
25408 	ASSERT(mp->b_datap->db_type == M_DATA);
25409 	ipha = (ipha_t *)mp->b_rptr;
25410 
25411 	/*
25412 	 * Find an IRE which matches the destination and the outgoing
25413 	 * queue (i.e. the outgoing interface.)
25414 	 */
25415 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25416 		dst = ipif->ipif_pp_dst_addr;
25417 	else
25418 		dst = ipha->ipha_dst;
25419 	/*
25420 	 * The source address has already been initialized by the
25421 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25422 	 * be sufficient rather than MATCH_IRE_IPIF.
25423 	 *
25424 	 * This function is used for sending IGMP packets. We need
25425 	 * to make sure that we send the packet out of the interface
25426 	 * (ipif->ipif_ill) where we joined the group. This is to
25427 	 * prevent from switches doing IGMP snooping to send us multicast
25428 	 * packets for a given group on the interface we have joined.
25429 	 * If we can't find an ire, igmp_sendpkt has already initialized
25430 	 * ipsec_out_attach_if so that this will not be load spread in
25431 	 * ip_newroute_ipif.
25432 	 */
25433 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25434 	    MATCH_IRE_ILL, ipst);
25435 	if (!ire) {
25436 		/*
25437 		 * Mark this packet to make it be delivered to
25438 		 * ip_wput_ire after the new ire has been
25439 		 * created.
25440 		 */
25441 		mp->b_prev = NULL;
25442 		mp->b_next = NULL;
25443 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25444 		    zoneid, &zero_info);
25445 		return;
25446 	}
25447 
25448 	/*
25449 	 * Honor the RTF_SETSRC flag; this is the only case
25450 	 * where we force this addr whatever the current src addr is,
25451 	 * because this address is set by igmp_sendpkt(), and
25452 	 * cannot be specified by any user.
25453 	 */
25454 	if (ire->ire_flags & RTF_SETSRC) {
25455 		ipha->ipha_src = ire->ire_src_addr;
25456 	}
25457 
25458 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25459 }
25460 
25461 /*
25462  * NOTE : This function does not ire_refrele the ire argument passed in.
25463  *
25464  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25465  * failure. The nce_fp_mp can vanish any time in the case of
25466  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25467  * the ire_lock to access the nce_fp_mp in this case.
25468  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25469  * prepending a fastpath message IPQoS processing must precede it, we also set
25470  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25471  * (IPQoS might have set the b_band for CoS marking).
25472  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25473  * must follow it so that IPQoS can mark the dl_priority field for CoS
25474  * marking, if needed.
25475  */
25476 static mblk_t *
25477 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25478 {
25479 	uint_t	hlen;
25480 	ipha_t *ipha;
25481 	mblk_t *mp1;
25482 	boolean_t qos_done = B_FALSE;
25483 	uchar_t	*ll_hdr;
25484 	ip_stack_t	*ipst = ire->ire_ipst;
25485 
25486 #define	rptr	((uchar_t *)ipha)
25487 
25488 	ipha = (ipha_t *)mp->b_rptr;
25489 	hlen = 0;
25490 	LOCK_IRE_FP_MP(ire);
25491 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25492 		ASSERT(DB_TYPE(mp1) == M_DATA);
25493 		/* Initiate IPPF processing */
25494 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25495 			UNLOCK_IRE_FP_MP(ire);
25496 			ip_process(proc, &mp, ill_index);
25497 			if (mp == NULL)
25498 				return (NULL);
25499 
25500 			ipha = (ipha_t *)mp->b_rptr;
25501 			LOCK_IRE_FP_MP(ire);
25502 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25503 				qos_done = B_TRUE;
25504 				goto no_fp_mp;
25505 			}
25506 			ASSERT(DB_TYPE(mp1) == M_DATA);
25507 		}
25508 		hlen = MBLKL(mp1);
25509 		/*
25510 		 * Check if we have enough room to prepend fastpath
25511 		 * header
25512 		 */
25513 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25514 			ll_hdr = rptr - hlen;
25515 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25516 			/*
25517 			 * Set the b_rptr to the start of the link layer
25518 			 * header
25519 			 */
25520 			mp->b_rptr = ll_hdr;
25521 			mp1 = mp;
25522 		} else {
25523 			mp1 = copyb(mp1);
25524 			if (mp1 == NULL)
25525 				goto unlock_err;
25526 			mp1->b_band = mp->b_band;
25527 			mp1->b_cont = mp;
25528 			/*
25529 			 * certain system generated traffic may not
25530 			 * have cred/label in ip header block. This
25531 			 * is true even for a labeled system. But for
25532 			 * labeled traffic, inherit the label in the
25533 			 * new header.
25534 			 */
25535 			if (DB_CRED(mp) != NULL)
25536 				mblk_setcred(mp1, DB_CRED(mp));
25537 			/*
25538 			 * XXX disable ICK_VALID and compute checksum
25539 			 * here; can happen if nce_fp_mp changes and
25540 			 * it can't be copied now due to insufficient
25541 			 * space. (unlikely, fp mp can change, but it
25542 			 * does not increase in length)
25543 			 */
25544 		}
25545 		UNLOCK_IRE_FP_MP(ire);
25546 	} else {
25547 no_fp_mp:
25548 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25549 		if (mp1 == NULL) {
25550 unlock_err:
25551 			UNLOCK_IRE_FP_MP(ire);
25552 			freemsg(mp);
25553 			return (NULL);
25554 		}
25555 		UNLOCK_IRE_FP_MP(ire);
25556 		mp1->b_cont = mp;
25557 		/*
25558 		 * certain system generated traffic may not
25559 		 * have cred/label in ip header block. This
25560 		 * is true even for a labeled system. But for
25561 		 * labeled traffic, inherit the label in the
25562 		 * new header.
25563 		 */
25564 		if (DB_CRED(mp) != NULL)
25565 			mblk_setcred(mp1, DB_CRED(mp));
25566 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25567 			ip_process(proc, &mp1, ill_index);
25568 			if (mp1 == NULL)
25569 				return (NULL);
25570 		}
25571 	}
25572 	return (mp1);
25573 #undef rptr
25574 }
25575 
25576 /*
25577  * Finish the outbound IPsec processing for an IPv6 packet. This function
25578  * is called from ipsec_out_process() if the IPsec packet was processed
25579  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25580  * asynchronously.
25581  */
25582 void
25583 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25584     ire_t *ire_arg)
25585 {
25586 	in6_addr_t *v6dstp;
25587 	ire_t *ire;
25588 	mblk_t *mp;
25589 	ip6_t *ip6h1;
25590 	uint_t	ill_index;
25591 	ipsec_out_t *io;
25592 	boolean_t attach_if, hwaccel;
25593 	uint32_t flags = IP6_NO_IPPOLICY;
25594 	int match_flags;
25595 	zoneid_t zoneid;
25596 	boolean_t ill_need_rele = B_FALSE;
25597 	boolean_t ire_need_rele = B_FALSE;
25598 	ip_stack_t	*ipst;
25599 
25600 	mp = ipsec_mp->b_cont;
25601 	ip6h1 = (ip6_t *)mp->b_rptr;
25602 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25603 	ASSERT(io->ipsec_out_ns != NULL);
25604 	ipst = io->ipsec_out_ns->netstack_ip;
25605 	ill_index = io->ipsec_out_ill_index;
25606 	if (io->ipsec_out_reachable) {
25607 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25608 	}
25609 	attach_if = io->ipsec_out_attach_if;
25610 	hwaccel = io->ipsec_out_accelerated;
25611 	zoneid = io->ipsec_out_zoneid;
25612 	ASSERT(zoneid != ALL_ZONES);
25613 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25614 	/* Multicast addresses should have non-zero ill_index. */
25615 	v6dstp = &ip6h->ip6_dst;
25616 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25617 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25618 	ASSERT(!attach_if || ill_index != 0);
25619 	if (ill_index != 0) {
25620 		if (ill == NULL) {
25621 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25622 			    B_TRUE, ipst);
25623 
25624 			/* Failure case frees things for us. */
25625 			if (ill == NULL)
25626 				return;
25627 
25628 			ill_need_rele = B_TRUE;
25629 		}
25630 		/*
25631 		 * If this packet needs to go out on a particular interface
25632 		 * honor it.
25633 		 */
25634 		if (attach_if) {
25635 			match_flags = MATCH_IRE_ILL;
25636 
25637 			/*
25638 			 * Check if we need an ire that will not be
25639 			 * looked up by anybody else i.e. HIDDEN.
25640 			 */
25641 			if (ill_is_probeonly(ill)) {
25642 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25643 			}
25644 		}
25645 	}
25646 	ASSERT(mp != NULL);
25647 
25648 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25649 		boolean_t unspec_src;
25650 		ipif_t	*ipif;
25651 
25652 		/*
25653 		 * Use the ill_index to get the right ill.
25654 		 */
25655 		unspec_src = io->ipsec_out_unspec_src;
25656 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25657 		if (ipif == NULL) {
25658 			if (ill_need_rele)
25659 				ill_refrele(ill);
25660 			freemsg(ipsec_mp);
25661 			return;
25662 		}
25663 
25664 		if (ire_arg != NULL) {
25665 			ire = ire_arg;
25666 		} else {
25667 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25668 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25669 			ire_need_rele = B_TRUE;
25670 		}
25671 		if (ire != NULL) {
25672 			ipif_refrele(ipif);
25673 			/*
25674 			 * XXX Do the multicast forwarding now, as the IPsec
25675 			 * processing has been done.
25676 			 */
25677 			goto send;
25678 		}
25679 
25680 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25681 		mp->b_prev = NULL;
25682 		mp->b_next = NULL;
25683 
25684 		/*
25685 		 * If the IPsec packet was processed asynchronously,
25686 		 * drop it now.
25687 		 */
25688 		if (q == NULL) {
25689 			if (ill_need_rele)
25690 				ill_refrele(ill);
25691 			freemsg(ipsec_mp);
25692 			return;
25693 		}
25694 
25695 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25696 		    unspec_src, zoneid);
25697 		ipif_refrele(ipif);
25698 	} else {
25699 		if (attach_if) {
25700 			ipif_t	*ipif;
25701 
25702 			ipif = ipif_get_next_ipif(NULL, ill);
25703 			if (ipif == NULL) {
25704 				if (ill_need_rele)
25705 					ill_refrele(ill);
25706 				freemsg(ipsec_mp);
25707 				return;
25708 			}
25709 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25710 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25711 			ire_need_rele = B_TRUE;
25712 			ipif_refrele(ipif);
25713 		} else {
25714 			if (ire_arg != NULL) {
25715 				ire = ire_arg;
25716 			} else {
25717 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25718 				    ipst);
25719 				ire_need_rele = B_TRUE;
25720 			}
25721 		}
25722 		if (ire != NULL)
25723 			goto send;
25724 		/*
25725 		 * ire disappeared underneath.
25726 		 *
25727 		 * What we need to do here is the ip_newroute
25728 		 * logic to get the ire without doing the IPsec
25729 		 * processing. Follow the same old path. But this
25730 		 * time, ip_wput or ire_add_then_send will call us
25731 		 * directly as all the IPsec operations are done.
25732 		 */
25733 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25734 		mp->b_prev = NULL;
25735 		mp->b_next = NULL;
25736 
25737 		/*
25738 		 * If the IPsec packet was processed asynchronously,
25739 		 * drop it now.
25740 		 */
25741 		if (q == NULL) {
25742 			if (ill_need_rele)
25743 				ill_refrele(ill);
25744 			freemsg(ipsec_mp);
25745 			return;
25746 		}
25747 
25748 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25749 		    zoneid, ipst);
25750 	}
25751 	if (ill != NULL && ill_need_rele)
25752 		ill_refrele(ill);
25753 	return;
25754 send:
25755 	if (ill != NULL && ill_need_rele)
25756 		ill_refrele(ill);
25757 
25758 	/* Local delivery */
25759 	if (ire->ire_stq == NULL) {
25760 		ill_t	*out_ill;
25761 		ASSERT(q != NULL);
25762 
25763 		/* PFHooks: LOOPBACK_OUT */
25764 		out_ill = ire_to_ill(ire);
25765 
25766 		DTRACE_PROBE4(ip6__loopback__out__start,
25767 		    ill_t *, NULL, ill_t *, out_ill,
25768 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25769 
25770 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25771 		    ipst->ips_ipv6firewall_loopback_out,
25772 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25773 
25774 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25775 
25776 		if (ipsec_mp != NULL)
25777 			ip_wput_local_v6(RD(q), out_ill,
25778 			    ip6h, ipsec_mp, ire, 0);
25779 		if (ire_need_rele)
25780 			ire_refrele(ire);
25781 		return;
25782 	}
25783 	/*
25784 	 * Everything is done. Send it out on the wire.
25785 	 * We force the insertion of a fragment header using the
25786 	 * IPH_FRAG_HDR flag in two cases:
25787 	 * - after reception of an ICMPv6 "packet too big" message
25788 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25789 	 * - for multirouted IPv6 packets, so that the receiver can
25790 	 *   discard duplicates according to their fragment identifier
25791 	 */
25792 	/* XXX fix flow control problems. */
25793 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25794 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25795 		if (hwaccel) {
25796 			/*
25797 			 * hardware acceleration does not handle these
25798 			 * "slow path" cases.
25799 			 */
25800 			/* IPsec KSTATS: should bump bean counter here. */
25801 			if (ire_need_rele)
25802 				ire_refrele(ire);
25803 			freemsg(ipsec_mp);
25804 			return;
25805 		}
25806 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25807 		    (mp->b_cont ? msgdsize(mp) :
25808 		    mp->b_wptr - (uchar_t *)ip6h)) {
25809 			/* IPsec KSTATS: should bump bean counter here. */
25810 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25811 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25812 			    msgdsize(mp)));
25813 			if (ire_need_rele)
25814 				ire_refrele(ire);
25815 			freemsg(ipsec_mp);
25816 			return;
25817 		}
25818 		ASSERT(mp->b_prev == NULL);
25819 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25820 		    ntohs(ip6h->ip6_plen) +
25821 		    IPV6_HDR_LEN, ire->ire_max_frag));
25822 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25823 		    ire->ire_max_frag);
25824 	} else {
25825 		UPDATE_OB_PKT_COUNT(ire);
25826 		ire->ire_last_used_time = lbolt;
25827 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25828 	}
25829 	if (ire_need_rele)
25830 		ire_refrele(ire);
25831 	freeb(ipsec_mp);
25832 }
25833 
25834 void
25835 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25836 {
25837 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25838 	da_ipsec_t *hada;	/* data attributes */
25839 	ill_t *ill = (ill_t *)q->q_ptr;
25840 
25841 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25842 
25843 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25844 		/* IPsec KSTATS: Bump lose counter here! */
25845 		freemsg(mp);
25846 		return;
25847 	}
25848 
25849 	/*
25850 	 * It's an IPsec packet that must be
25851 	 * accelerated by the Provider, and the
25852 	 * outbound ill is IPsec acceleration capable.
25853 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25854 	 * to the ill.
25855 	 * IPsec KSTATS: should bump packet counter here.
25856 	 */
25857 
25858 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25859 	if (hada_mp == NULL) {
25860 		/* IPsec KSTATS: should bump packet counter here. */
25861 		freemsg(mp);
25862 		return;
25863 	}
25864 
25865 	hada_mp->b_datap->db_type = M_CTL;
25866 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25867 	hada_mp->b_cont = mp;
25868 
25869 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25870 	bzero(hada, sizeof (da_ipsec_t));
25871 	hada->da_type = IPHADA_M_CTL;
25872 
25873 	putnext(q, hada_mp);
25874 }
25875 
25876 /*
25877  * Finish the outbound IPsec processing. This function is called from
25878  * ipsec_out_process() if the IPsec packet was processed
25879  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25880  * asynchronously.
25881  */
25882 void
25883 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25884     ire_t *ire_arg)
25885 {
25886 	uint32_t v_hlen_tos_len;
25887 	ipaddr_t	dst;
25888 	ipif_t	*ipif = NULL;
25889 	ire_t *ire;
25890 	ire_t *ire1 = NULL;
25891 	mblk_t *next_mp = NULL;
25892 	uint32_t max_frag;
25893 	boolean_t multirt_send = B_FALSE;
25894 	mblk_t *mp;
25895 	ipha_t *ipha1;
25896 	uint_t	ill_index;
25897 	ipsec_out_t *io;
25898 	boolean_t attach_if;
25899 	int match_flags;
25900 	irb_t *irb = NULL;
25901 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25902 	zoneid_t zoneid;
25903 	ipxmit_state_t	pktxmit_state;
25904 	ip_stack_t	*ipst;
25905 
25906 #ifdef	_BIG_ENDIAN
25907 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25908 #else
25909 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25910 #endif
25911 
25912 	mp = ipsec_mp->b_cont;
25913 	ipha1 = (ipha_t *)mp->b_rptr;
25914 	ASSERT(mp != NULL);
25915 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25916 	dst = ipha->ipha_dst;
25917 
25918 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25919 	ill_index = io->ipsec_out_ill_index;
25920 	attach_if = io->ipsec_out_attach_if;
25921 	zoneid = io->ipsec_out_zoneid;
25922 	ASSERT(zoneid != ALL_ZONES);
25923 	ipst = io->ipsec_out_ns->netstack_ip;
25924 	ASSERT(io->ipsec_out_ns != NULL);
25925 
25926 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25927 	if (ill_index != 0) {
25928 		if (ill == NULL) {
25929 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25930 			    ill_index, B_FALSE, ipst);
25931 
25932 			/* Failure case frees things for us. */
25933 			if (ill == NULL)
25934 				return;
25935 
25936 			ill_need_rele = B_TRUE;
25937 		}
25938 		/*
25939 		 * If this packet needs to go out on a particular interface
25940 		 * honor it.
25941 		 */
25942 		if (attach_if) {
25943 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25944 
25945 			/*
25946 			 * Check if we need an ire that will not be
25947 			 * looked up by anybody else i.e. HIDDEN.
25948 			 */
25949 			if (ill_is_probeonly(ill)) {
25950 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25951 			}
25952 		}
25953 	}
25954 
25955 	if (CLASSD(dst)) {
25956 		boolean_t conn_dontroute;
25957 		/*
25958 		 * Use the ill_index to get the right ipif.
25959 		 */
25960 		conn_dontroute = io->ipsec_out_dontroute;
25961 		if (ill_index == 0)
25962 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25963 		else
25964 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25965 		if (ipif == NULL) {
25966 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25967 			    " multicast\n"));
25968 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25969 			freemsg(ipsec_mp);
25970 			goto done;
25971 		}
25972 		/*
25973 		 * ipha_src has already been intialized with the
25974 		 * value of the ipif in ip_wput. All we need now is
25975 		 * an ire to send this downstream.
25976 		 */
25977 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25978 		    MBLK_GETLABEL(mp), match_flags, ipst);
25979 		if (ire != NULL) {
25980 			ill_t *ill1;
25981 			/*
25982 			 * Do the multicast forwarding now, as the IPsec
25983 			 * processing has been done.
25984 			 */
25985 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25986 			    (ill1 = ire_to_ill(ire))) {
25987 				if (ip_mforward(ill1, ipha, mp)) {
25988 					freemsg(ipsec_mp);
25989 					ip1dbg(("ip_wput_ipsec_out: mforward "
25990 					    "failed\n"));
25991 					ire_refrele(ire);
25992 					goto done;
25993 				}
25994 			}
25995 			goto send;
25996 		}
25997 
25998 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25999 		mp->b_prev = NULL;
26000 		mp->b_next = NULL;
26001 
26002 		/*
26003 		 * If the IPsec packet was processed asynchronously,
26004 		 * drop it now.
26005 		 */
26006 		if (q == NULL) {
26007 			freemsg(ipsec_mp);
26008 			goto done;
26009 		}
26010 
26011 		/*
26012 		 * We may be using a wrong ipif to create the ire.
26013 		 * But it is okay as the source address is assigned
26014 		 * for the packet already. Next outbound packet would
26015 		 * create the IRE with the right IPIF in ip_wput.
26016 		 *
26017 		 * Also handle RTF_MULTIRT routes.
26018 		 */
26019 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26020 		    zoneid, &zero_info);
26021 	} else {
26022 		if (attach_if) {
26023 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26024 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26025 		} else {
26026 			if (ire_arg != NULL) {
26027 				ire = ire_arg;
26028 				ire_need_rele = B_FALSE;
26029 			} else {
26030 				ire = ire_cache_lookup(dst, zoneid,
26031 				    MBLK_GETLABEL(mp), ipst);
26032 			}
26033 		}
26034 		if (ire != NULL) {
26035 			goto send;
26036 		}
26037 
26038 		/*
26039 		 * ire disappeared underneath.
26040 		 *
26041 		 * What we need to do here is the ip_newroute
26042 		 * logic to get the ire without doing the IPsec
26043 		 * processing. Follow the same old path. But this
26044 		 * time, ip_wput or ire_add_then_put will call us
26045 		 * directly as all the IPsec operations are done.
26046 		 */
26047 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26048 		mp->b_prev = NULL;
26049 		mp->b_next = NULL;
26050 
26051 		/*
26052 		 * If the IPsec packet was processed asynchronously,
26053 		 * drop it now.
26054 		 */
26055 		if (q == NULL) {
26056 			freemsg(ipsec_mp);
26057 			goto done;
26058 		}
26059 
26060 		/*
26061 		 * Since we're going through ip_newroute() again, we
26062 		 * need to make sure we don't:
26063 		 *
26064 		 *	1.) Trigger the ASSERT() with the ipha_ident
26065 		 *	    overloading.
26066 		 *	2.) Redo transport-layer checksumming, since we've
26067 		 *	    already done all that to get this far.
26068 		 *
26069 		 * The easiest way not do either of the above is to set
26070 		 * the ipha_ident field to IP_HDR_INCLUDED.
26071 		 */
26072 		ipha->ipha_ident = IP_HDR_INCLUDED;
26073 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26074 		    zoneid, ipst);
26075 	}
26076 	goto done;
26077 send:
26078 	if (ire->ire_stq == NULL) {
26079 		ill_t	*out_ill;
26080 		/*
26081 		 * Loopbacks go through ip_wput_local except for one case.
26082 		 * We come here if we generate a icmp_frag_needed message
26083 		 * after IPsec processing is over. When this function calls
26084 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26085 		 * icmp_frag_needed. The message generated comes back here
26086 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26087 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26088 		 * source address as it is usually set in ip_wput_ire. As
26089 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26090 		 * and we end up here. We can't enter ip_wput_ire once the
26091 		 * IPsec processing is over and hence we need to do it here.
26092 		 */
26093 		ASSERT(q != NULL);
26094 		UPDATE_OB_PKT_COUNT(ire);
26095 		ire->ire_last_used_time = lbolt;
26096 		if (ipha->ipha_src == 0)
26097 			ipha->ipha_src = ire->ire_src_addr;
26098 
26099 		/* PFHooks: LOOPBACK_OUT */
26100 		out_ill = ire_to_ill(ire);
26101 
26102 		DTRACE_PROBE4(ip4__loopback__out__start,
26103 		    ill_t *, NULL, ill_t *, out_ill,
26104 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26105 
26106 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26107 		    ipst->ips_ipv4firewall_loopback_out,
26108 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26109 
26110 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26111 
26112 		if (ipsec_mp != NULL)
26113 			ip_wput_local(RD(q), out_ill,
26114 			    ipha, ipsec_mp, ire, 0, zoneid);
26115 		if (ire_need_rele)
26116 			ire_refrele(ire);
26117 		goto done;
26118 	}
26119 
26120 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26121 		/*
26122 		 * We are through with IPsec processing.
26123 		 * Fragment this and send it on the wire.
26124 		 */
26125 		if (io->ipsec_out_accelerated) {
26126 			/*
26127 			 * The packet has been accelerated but must
26128 			 * be fragmented. This should not happen
26129 			 * since AH and ESP must not accelerate
26130 			 * packets that need fragmentation, however
26131 			 * the configuration could have changed
26132 			 * since the AH or ESP processing.
26133 			 * Drop packet.
26134 			 * IPsec KSTATS: bump bean counter here.
26135 			 */
26136 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26137 			    "fragmented accelerated packet!\n"));
26138 			freemsg(ipsec_mp);
26139 		} else {
26140 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26141 		}
26142 		if (ire_need_rele)
26143 			ire_refrele(ire);
26144 		goto done;
26145 	}
26146 
26147 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26148 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26149 	    (void *)ire->ire_ipif, (void *)ipif));
26150 
26151 	/*
26152 	 * Multiroute the secured packet, unless IPsec really
26153 	 * requires the packet to go out only through a particular
26154 	 * interface.
26155 	 */
26156 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26157 		ire_t *first_ire;
26158 		irb = ire->ire_bucket;
26159 		ASSERT(irb != NULL);
26160 		/*
26161 		 * This ire has been looked up as the one that
26162 		 * goes through the given ipif;
26163 		 * make sure we do not omit any other multiroute ire
26164 		 * that may be present in the bucket before this one.
26165 		 */
26166 		IRB_REFHOLD(irb);
26167 		for (first_ire = irb->irb_ire;
26168 		    first_ire != NULL;
26169 		    first_ire = first_ire->ire_next) {
26170 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26171 			    (first_ire->ire_addr == ire->ire_addr) &&
26172 			    !(first_ire->ire_marks &
26173 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26174 				break;
26175 			}
26176 		}
26177 
26178 		if ((first_ire != NULL) && (first_ire != ire)) {
26179 			/*
26180 			 * Don't change the ire if the packet must
26181 			 * be fragmented if sent via this new one.
26182 			 */
26183 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26184 				IRE_REFHOLD(first_ire);
26185 				if (ire_need_rele)
26186 					ire_refrele(ire);
26187 				else
26188 					ire_need_rele = B_TRUE;
26189 				ire = first_ire;
26190 			}
26191 		}
26192 		IRB_REFRELE(irb);
26193 
26194 		multirt_send = B_TRUE;
26195 		max_frag = ire->ire_max_frag;
26196 	} else {
26197 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26198 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26199 			    "flag, attach_if %d\n", attach_if));
26200 		}
26201 	}
26202 
26203 	/*
26204 	 * In most cases, the emission loop below is entered only once.
26205 	 * Only in the case where the ire holds the RTF_MULTIRT
26206 	 * flag, we loop to process all RTF_MULTIRT ires in the
26207 	 * bucket, and send the packet through all crossed
26208 	 * RTF_MULTIRT routes.
26209 	 */
26210 	do {
26211 		if (multirt_send) {
26212 			/*
26213 			 * ire1 holds here the next ire to process in the
26214 			 * bucket. If multirouting is expected,
26215 			 * any non-RTF_MULTIRT ire that has the
26216 			 * right destination address is ignored.
26217 			 */
26218 			ASSERT(irb != NULL);
26219 			IRB_REFHOLD(irb);
26220 			for (ire1 = ire->ire_next;
26221 			    ire1 != NULL;
26222 			    ire1 = ire1->ire_next) {
26223 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26224 					continue;
26225 				if (ire1->ire_addr != ire->ire_addr)
26226 					continue;
26227 				if (ire1->ire_marks &
26228 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26229 					continue;
26230 				/* No loopback here */
26231 				if (ire1->ire_stq == NULL)
26232 					continue;
26233 				/*
26234 				 * Ensure we do not exceed the MTU
26235 				 * of the next route.
26236 				 */
26237 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26238 					ip_multirt_bad_mtu(ire1, max_frag);
26239 					continue;
26240 				}
26241 
26242 				IRE_REFHOLD(ire1);
26243 				break;
26244 			}
26245 			IRB_REFRELE(irb);
26246 			if (ire1 != NULL) {
26247 				/*
26248 				 * We are in a multiple send case, need to
26249 				 * make a copy of the packet.
26250 				 */
26251 				next_mp = copymsg(ipsec_mp);
26252 				if (next_mp == NULL) {
26253 					ire_refrele(ire1);
26254 					ire1 = NULL;
26255 				}
26256 			}
26257 		}
26258 		/*
26259 		 * Everything is done. Send it out on the wire
26260 		 *
26261 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26262 		 * either send it on the wire or, in the case of
26263 		 * HW acceleration, call ipsec_hw_putnext.
26264 		 */
26265 		if (ire->ire_nce &&
26266 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26267 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26268 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26269 			/*
26270 			 * If ire's link-layer is unresolved (this
26271 			 * would only happen if the incomplete ire
26272 			 * was added to cachetable via forwarding path)
26273 			 * don't bother going to ip_xmit_v4. Just drop the
26274 			 * packet.
26275 			 * There is a slight risk here, in that, if we
26276 			 * have the forwarding path create an incomplete
26277 			 * IRE, then until the IRE is completed, any
26278 			 * transmitted IPsec packets will be dropped
26279 			 * instead of being queued waiting for resolution.
26280 			 *
26281 			 * But the likelihood of a forwarding packet and a wput
26282 			 * packet sending to the same dst at the same time
26283 			 * and there not yet be an ARP entry for it is small.
26284 			 * Furthermore, if this actually happens, it might
26285 			 * be likely that wput would generate multiple
26286 			 * packets (and forwarding would also have a train
26287 			 * of packets) for that destination. If this is
26288 			 * the case, some of them would have been dropped
26289 			 * anyway, since ARP only queues a few packets while
26290 			 * waiting for resolution
26291 			 *
26292 			 * NOTE: We should really call ip_xmit_v4,
26293 			 * and let it queue the packet and send the
26294 			 * ARP query and have ARP come back thus:
26295 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26296 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26297 			 * hw accel work. But it's too complex to get
26298 			 * the IPsec hw  acceleration approach to fit
26299 			 * well with ip_xmit_v4 doing ARP without
26300 			 * doing IPsec simplification. For now, we just
26301 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26302 			 * that we can continue with the send on the next
26303 			 * attempt.
26304 			 *
26305 			 * XXX THis should be revisited, when
26306 			 * the IPsec/IP interaction is cleaned up
26307 			 */
26308 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26309 			    " - dropping packet\n"));
26310 			freemsg(ipsec_mp);
26311 			/*
26312 			 * Call ip_xmit_v4() to trigger ARP query
26313 			 * in case the nce_state is ND_INITIAL
26314 			 */
26315 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26316 			goto drop_pkt;
26317 		}
26318 
26319 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26320 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26321 		    mblk_t *, ipsec_mp);
26322 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26323 		    ipst->ips_ipv4firewall_physical_out, NULL,
26324 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26325 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26326 		if (ipsec_mp == NULL)
26327 			goto drop_pkt;
26328 
26329 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26330 		pktxmit_state = ip_xmit_v4(mp, ire,
26331 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26332 
26333 		if ((pktxmit_state ==  SEND_FAILED) ||
26334 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26335 
26336 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26337 drop_pkt:
26338 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26339 			    ipIfStatsOutDiscards);
26340 			if (ire_need_rele)
26341 				ire_refrele(ire);
26342 			if (ire1 != NULL) {
26343 				ire_refrele(ire1);
26344 				freemsg(next_mp);
26345 			}
26346 			goto done;
26347 		}
26348 
26349 		freeb(ipsec_mp);
26350 		if (ire_need_rele)
26351 			ire_refrele(ire);
26352 
26353 		if (ire1 != NULL) {
26354 			ire = ire1;
26355 			ire_need_rele = B_TRUE;
26356 			ASSERT(next_mp);
26357 			ipsec_mp = next_mp;
26358 			mp = ipsec_mp->b_cont;
26359 			ire1 = NULL;
26360 			next_mp = NULL;
26361 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26362 		} else {
26363 			multirt_send = B_FALSE;
26364 		}
26365 	} while (multirt_send);
26366 done:
26367 	if (ill != NULL && ill_need_rele)
26368 		ill_refrele(ill);
26369 	if (ipif != NULL)
26370 		ipif_refrele(ipif);
26371 }
26372 
26373 /*
26374  * Get the ill corresponding to the specified ire, and compare its
26375  * capabilities with the protocol and algorithms specified by the
26376  * the SA obtained from ipsec_out. If they match, annotate the
26377  * ipsec_out structure to indicate that the packet needs acceleration.
26378  *
26379  *
26380  * A packet is eligible for outbound hardware acceleration if the
26381  * following conditions are satisfied:
26382  *
26383  * 1. the packet will not be fragmented
26384  * 2. the provider supports the algorithm
26385  * 3. there is no pending control message being exchanged
26386  * 4. snoop is not attached
26387  * 5. the destination address is not a broadcast or multicast address.
26388  *
26389  * Rationale:
26390  *	- Hardware drivers do not support fragmentation with
26391  *	  the current interface.
26392  *	- snoop, multicast, and broadcast may result in exposure of
26393  *	  a cleartext datagram.
26394  * We check all five of these conditions here.
26395  *
26396  * XXX would like to nuke "ire_t *" parameter here; problem is that
26397  * IRE is only way to figure out if a v4 address is a broadcast and
26398  * thus ineligible for acceleration...
26399  */
26400 static void
26401 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26402 {
26403 	ipsec_out_t *io;
26404 	mblk_t *data_mp;
26405 	uint_t plen, overhead;
26406 	ip_stack_t	*ipst;
26407 
26408 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26409 		return;
26410 
26411 	if (ill == NULL)
26412 		return;
26413 	ipst = ill->ill_ipst;
26414 	/*
26415 	 * Destination address is a broadcast or multicast.  Punt.
26416 	 */
26417 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26418 	    IRE_LOCAL)))
26419 		return;
26420 
26421 	data_mp = ipsec_mp->b_cont;
26422 
26423 	if (ill->ill_isv6) {
26424 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26425 
26426 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26427 			return;
26428 
26429 		plen = ip6h->ip6_plen;
26430 	} else {
26431 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26432 
26433 		if (CLASSD(ipha->ipha_dst))
26434 			return;
26435 
26436 		plen = ipha->ipha_length;
26437 	}
26438 	/*
26439 	 * Is there a pending DLPI control message being exchanged
26440 	 * between IP/IPsec and the DLS Provider? If there is, it
26441 	 * could be a SADB update, and the state of the DLS Provider
26442 	 * SADB might not be in sync with the SADB maintained by
26443 	 * IPsec. To avoid dropping packets or using the wrong keying
26444 	 * material, we do not accelerate this packet.
26445 	 */
26446 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26447 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26448 		    "ill_dlpi_pending! don't accelerate packet\n"));
26449 		return;
26450 	}
26451 
26452 	/*
26453 	 * Is the Provider in promiscous mode? If it does, we don't
26454 	 * accelerate the packet since it will bounce back up to the
26455 	 * listeners in the clear.
26456 	 */
26457 	if (ill->ill_promisc_on_phys) {
26458 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26459 		    "ill in promiscous mode, don't accelerate packet\n"));
26460 		return;
26461 	}
26462 
26463 	/*
26464 	 * Will the packet require fragmentation?
26465 	 */
26466 
26467 	/*
26468 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26469 	 * as is used elsewhere.
26470 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26471 	 *	+ 2-byte trailer
26472 	 */
26473 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26474 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26475 
26476 	if ((plen + overhead) > ill->ill_max_mtu)
26477 		return;
26478 
26479 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26480 
26481 	/*
26482 	 * Can the ill accelerate this IPsec protocol and algorithm
26483 	 * specified by the SA?
26484 	 */
26485 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26486 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26487 		return;
26488 	}
26489 
26490 	/*
26491 	 * Tell AH or ESP that the outbound ill is capable of
26492 	 * accelerating this packet.
26493 	 */
26494 	io->ipsec_out_is_capab_ill = B_TRUE;
26495 }
26496 
26497 /*
26498  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26499  *
26500  * If this function returns B_TRUE, the requested SA's have been filled
26501  * into the ipsec_out_*_sa pointers.
26502  *
26503  * If the function returns B_FALSE, the packet has been "consumed", most
26504  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26505  *
26506  * The SA references created by the protocol-specific "select"
26507  * function will be released when the ipsec_mp is freed, thanks to the
26508  * ipsec_out_free destructor -- see spd.c.
26509  */
26510 static boolean_t
26511 ipsec_out_select_sa(mblk_t *ipsec_mp)
26512 {
26513 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26514 	ipsec_out_t *io;
26515 	ipsec_policy_t *pp;
26516 	ipsec_action_t *ap;
26517 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26518 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26519 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26520 
26521 	if (!io->ipsec_out_secure) {
26522 		/*
26523 		 * We came here by mistake.
26524 		 * Don't bother with ipsec processing
26525 		 * We should "discourage" this path in the future.
26526 		 */
26527 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26528 		return (B_FALSE);
26529 	}
26530 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26531 	ASSERT((io->ipsec_out_policy != NULL) ||
26532 	    (io->ipsec_out_act != NULL));
26533 
26534 	ASSERT(io->ipsec_out_failed == B_FALSE);
26535 
26536 	/*
26537 	 * IPsec processing has started.
26538 	 */
26539 	io->ipsec_out_proc_begin = B_TRUE;
26540 	ap = io->ipsec_out_act;
26541 	if (ap == NULL) {
26542 		pp = io->ipsec_out_policy;
26543 		ASSERT(pp != NULL);
26544 		ap = pp->ipsp_act;
26545 		ASSERT(ap != NULL);
26546 	}
26547 
26548 	/*
26549 	 * We have an action.  now, let's select SA's.
26550 	 * (In the future, we can cache this in the conn_t..)
26551 	 */
26552 	if (ap->ipa_want_esp) {
26553 		if (io->ipsec_out_esp_sa == NULL) {
26554 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26555 			    IPPROTO_ESP);
26556 		}
26557 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26558 	}
26559 
26560 	if (ap->ipa_want_ah) {
26561 		if (io->ipsec_out_ah_sa == NULL) {
26562 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26563 			    IPPROTO_AH);
26564 		}
26565 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26566 		/*
26567 		 * The ESP and AH processing order needs to be preserved
26568 		 * when both protocols are required (ESP should be applied
26569 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26570 		 * when both ESP and AH are required, and an AH ACQUIRE
26571 		 * is needed.
26572 		 */
26573 		if (ap->ipa_want_esp && need_ah_acquire)
26574 			need_esp_acquire = B_TRUE;
26575 	}
26576 
26577 	/*
26578 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26579 	 * Release SAs that got referenced, but will not be used until we
26580 	 * acquire _all_ of the SAs we need.
26581 	 */
26582 	if (need_ah_acquire || need_esp_acquire) {
26583 		if (io->ipsec_out_ah_sa != NULL) {
26584 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26585 			io->ipsec_out_ah_sa = NULL;
26586 		}
26587 		if (io->ipsec_out_esp_sa != NULL) {
26588 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26589 			io->ipsec_out_esp_sa = NULL;
26590 		}
26591 
26592 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26593 		return (B_FALSE);
26594 	}
26595 
26596 	return (B_TRUE);
26597 }
26598 
26599 /*
26600  * Process an IPSEC_OUT message and see what you can
26601  * do with it.
26602  * IPQoS Notes:
26603  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26604  * IPsec.
26605  * XXX would like to nuke ire_t.
26606  * XXX ill_index better be "real"
26607  */
26608 void
26609 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26610 {
26611 	ipsec_out_t *io;
26612 	ipsec_policy_t *pp;
26613 	ipsec_action_t *ap;
26614 	ipha_t *ipha;
26615 	ip6_t *ip6h;
26616 	mblk_t *mp;
26617 	ill_t *ill;
26618 	zoneid_t zoneid;
26619 	ipsec_status_t ipsec_rc;
26620 	boolean_t ill_need_rele = B_FALSE;
26621 	ip_stack_t	*ipst;
26622 	ipsec_stack_t	*ipss;
26623 
26624 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26625 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26626 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26627 	ipst = io->ipsec_out_ns->netstack_ip;
26628 	mp = ipsec_mp->b_cont;
26629 
26630 	/*
26631 	 * Initiate IPPF processing. We do it here to account for packets
26632 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26633 	 * We can check for ipsec_out_proc_begin even for such packets, as
26634 	 * they will always be false (asserted below).
26635 	 */
26636 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26637 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26638 		    io->ipsec_out_ill_index : ill_index);
26639 		if (mp == NULL) {
26640 			ip2dbg(("ipsec_out_process: packet dropped "\
26641 			    "during IPPF processing\n"));
26642 			freeb(ipsec_mp);
26643 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26644 			return;
26645 		}
26646 	}
26647 
26648 	if (!io->ipsec_out_secure) {
26649 		/*
26650 		 * We came here by mistake.
26651 		 * Don't bother with ipsec processing
26652 		 * Should "discourage" this path in the future.
26653 		 */
26654 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26655 		goto done;
26656 	}
26657 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26658 	ASSERT((io->ipsec_out_policy != NULL) ||
26659 	    (io->ipsec_out_act != NULL));
26660 	ASSERT(io->ipsec_out_failed == B_FALSE);
26661 
26662 	ipss = ipst->ips_netstack->netstack_ipsec;
26663 	if (!ipsec_loaded(ipss)) {
26664 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26665 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26666 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26667 		} else {
26668 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26669 		}
26670 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26671 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26672 		    &ipss->ipsec_dropper);
26673 		return;
26674 	}
26675 
26676 	/*
26677 	 * IPsec processing has started.
26678 	 */
26679 	io->ipsec_out_proc_begin = B_TRUE;
26680 	ap = io->ipsec_out_act;
26681 	if (ap == NULL) {
26682 		pp = io->ipsec_out_policy;
26683 		ASSERT(pp != NULL);
26684 		ap = pp->ipsp_act;
26685 		ASSERT(ap != NULL);
26686 	}
26687 
26688 	/*
26689 	 * Save the outbound ill index. When the packet comes back
26690 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26691 	 * before sending it the accelerated packet.
26692 	 */
26693 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26694 		int ifindex;
26695 		ill = ire_to_ill(ire);
26696 		ifindex = ill->ill_phyint->phyint_ifindex;
26697 		io->ipsec_out_capab_ill_index = ifindex;
26698 	}
26699 
26700 	/*
26701 	 * The order of processing is first insert a IP header if needed.
26702 	 * Then insert the ESP header and then the AH header.
26703 	 */
26704 	if ((io->ipsec_out_se_done == B_FALSE) &&
26705 	    (ap->ipa_want_se)) {
26706 		/*
26707 		 * First get the outer IP header before sending
26708 		 * it to ESP.
26709 		 */
26710 		ipha_t *oipha, *iipha;
26711 		mblk_t *outer_mp, *inner_mp;
26712 
26713 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26714 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26715 			    "ipsec_out_process: "
26716 			    "Self-Encapsulation failed: Out of memory\n");
26717 			freemsg(ipsec_mp);
26718 			if (ill != NULL) {
26719 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26720 			} else {
26721 				BUMP_MIB(&ipst->ips_ip_mib,
26722 				    ipIfStatsOutDiscards);
26723 			}
26724 			return;
26725 		}
26726 		inner_mp = ipsec_mp->b_cont;
26727 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26728 		oipha = (ipha_t *)outer_mp->b_rptr;
26729 		iipha = (ipha_t *)inner_mp->b_rptr;
26730 		*oipha = *iipha;
26731 		outer_mp->b_wptr += sizeof (ipha_t);
26732 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26733 		    sizeof (ipha_t));
26734 		oipha->ipha_protocol = IPPROTO_ENCAP;
26735 		oipha->ipha_version_and_hdr_length =
26736 		    IP_SIMPLE_HDR_VERSION;
26737 		oipha->ipha_hdr_checksum = 0;
26738 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26739 		outer_mp->b_cont = inner_mp;
26740 		ipsec_mp->b_cont = outer_mp;
26741 
26742 		io->ipsec_out_se_done = B_TRUE;
26743 		io->ipsec_out_tunnel = B_TRUE;
26744 	}
26745 
26746 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26747 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26748 	    !ipsec_out_select_sa(ipsec_mp))
26749 		return;
26750 
26751 	/*
26752 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26753 	 * to do the heavy lifting.
26754 	 */
26755 	zoneid = io->ipsec_out_zoneid;
26756 	ASSERT(zoneid != ALL_ZONES);
26757 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26758 		ASSERT(io->ipsec_out_esp_sa != NULL);
26759 		io->ipsec_out_esp_done = B_TRUE;
26760 		/*
26761 		 * Note that since hw accel can only apply one transform,
26762 		 * not two, we skip hw accel for ESP if we also have AH
26763 		 * This is an design limitation of the interface
26764 		 * which should be revisited.
26765 		 */
26766 		ASSERT(ire != NULL);
26767 		if (io->ipsec_out_ah_sa == NULL) {
26768 			ill = (ill_t *)ire->ire_stq->q_ptr;
26769 			ipsec_out_is_accelerated(ipsec_mp,
26770 			    io->ipsec_out_esp_sa, ill, ire);
26771 		}
26772 
26773 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26774 		switch (ipsec_rc) {
26775 		case IPSEC_STATUS_SUCCESS:
26776 			break;
26777 		case IPSEC_STATUS_FAILED:
26778 			if (ill != NULL) {
26779 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26780 			} else {
26781 				BUMP_MIB(&ipst->ips_ip_mib,
26782 				    ipIfStatsOutDiscards);
26783 			}
26784 			/* FALLTHRU */
26785 		case IPSEC_STATUS_PENDING:
26786 			return;
26787 		}
26788 	}
26789 
26790 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26791 		ASSERT(io->ipsec_out_ah_sa != NULL);
26792 		io->ipsec_out_ah_done = B_TRUE;
26793 		if (ire == NULL) {
26794 			int idx = io->ipsec_out_capab_ill_index;
26795 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26796 			    NULL, NULL, NULL, NULL, ipst);
26797 			ill_need_rele = B_TRUE;
26798 		} else {
26799 			ill = (ill_t *)ire->ire_stq->q_ptr;
26800 		}
26801 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26802 		    ire);
26803 
26804 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26805 		switch (ipsec_rc) {
26806 		case IPSEC_STATUS_SUCCESS:
26807 			break;
26808 		case IPSEC_STATUS_FAILED:
26809 			if (ill != NULL) {
26810 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26811 			} else {
26812 				BUMP_MIB(&ipst->ips_ip_mib,
26813 				    ipIfStatsOutDiscards);
26814 			}
26815 			/* FALLTHRU */
26816 		case IPSEC_STATUS_PENDING:
26817 			if (ill != NULL && ill_need_rele)
26818 				ill_refrele(ill);
26819 			return;
26820 		}
26821 	}
26822 	/*
26823 	 * We are done with IPsec processing. Send it over
26824 	 * the wire.
26825 	 */
26826 done:
26827 	mp = ipsec_mp->b_cont;
26828 	ipha = (ipha_t *)mp->b_rptr;
26829 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26830 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26831 	} else {
26832 		ip6h = (ip6_t *)ipha;
26833 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26834 	}
26835 	if (ill != NULL && ill_need_rele)
26836 		ill_refrele(ill);
26837 }
26838 
26839 /* ARGSUSED */
26840 void
26841 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26842 {
26843 	opt_restart_t	*or;
26844 	int	err;
26845 	conn_t	*connp;
26846 
26847 	ASSERT(CONN_Q(q));
26848 	connp = Q_TO_CONN(q);
26849 
26850 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26851 	or = (opt_restart_t *)first_mp->b_rptr;
26852 	/*
26853 	 * We don't need to pass any credentials here since this is just
26854 	 * a restart. The credentials are passed in when svr4_optcom_req
26855 	 * is called the first time (from ip_wput_nondata).
26856 	 */
26857 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26858 		err = svr4_optcom_req(q, first_mp, NULL,
26859 		    &ip_opt_obj, B_FALSE);
26860 	} else {
26861 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26862 		err = tpi_optcom_req(q, first_mp, NULL,
26863 		    &ip_opt_obj, B_FALSE);
26864 	}
26865 	if (err != EINPROGRESS) {
26866 		/* operation is done */
26867 		CONN_OPER_PENDING_DONE(connp);
26868 	}
26869 }
26870 
26871 /*
26872  * ioctls that go through a down/up sequence may need to wait for the down
26873  * to complete. This involves waiting for the ire and ipif refcnts to go down
26874  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26875  */
26876 /* ARGSUSED */
26877 void
26878 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26879 {
26880 	struct iocblk *iocp;
26881 	mblk_t *mp1;
26882 	ip_ioctl_cmd_t *ipip;
26883 	int err;
26884 	sin_t	*sin;
26885 	struct lifreq *lifr;
26886 	struct ifreq *ifr;
26887 
26888 	iocp = (struct iocblk *)mp->b_rptr;
26889 	ASSERT(ipsq != NULL);
26890 	/* Existence of mp1 verified in ip_wput_nondata */
26891 	mp1 = mp->b_cont->b_cont;
26892 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26893 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26894 		/*
26895 		 * Special case where ipsq_current_ipif is not set:
26896 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26897 		 * ill could also have become part of a ipmp group in the
26898 		 * process, we are here as were not able to complete the
26899 		 * operation in ipif_set_values because we could not become
26900 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26901 		 * will not be set so we need to set it.
26902 		 */
26903 		ill_t *ill = q->q_ptr;
26904 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26905 	}
26906 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26907 
26908 	if (ipip->ipi_cmd_type == IF_CMD) {
26909 		/* This a old style SIOC[GS]IF* command */
26910 		ifr = (struct ifreq *)mp1->b_rptr;
26911 		sin = (sin_t *)&ifr->ifr_addr;
26912 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26913 		/* This a new style SIOC[GS]LIF* command */
26914 		lifr = (struct lifreq *)mp1->b_rptr;
26915 		sin = (sin_t *)&lifr->lifr_addr;
26916 	} else {
26917 		sin = NULL;
26918 	}
26919 
26920 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26921 	    ipip, mp1->b_rptr);
26922 
26923 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26924 }
26925 
26926 /*
26927  * ioctl processing
26928  *
26929  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26930  * the ioctl command in the ioctl tables, determines the copyin data size
26931  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26932  *
26933  * ioctl processing then continues when the M_IOCDATA makes its way down to
26934  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26935  * associated 'conn' is refheld till the end of the ioctl and the general
26936  * ioctl processing function ip_process_ioctl() is called to extract the
26937  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26938  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26939  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26940  * is used to extract the ioctl's arguments.
26941  *
26942  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26943  * so goes thru the serialization primitive ipsq_try_enter. Then the
26944  * appropriate function to handle the ioctl is called based on the entry in
26945  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26946  * which also refreleases the 'conn' that was refheld at the start of the
26947  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26948  *
26949  * Many exclusive ioctls go thru an internal down up sequence as part of
26950  * the operation. For example an attempt to change the IP address of an
26951  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26952  * does all the cleanup such as deleting all ires that use this address.
26953  * Then we need to wait till all references to the interface go away.
26954  */
26955 void
26956 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26957 {
26958 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26959 	ip_ioctl_cmd_t *ipip = arg;
26960 	ip_extract_func_t *extract_funcp;
26961 	cmd_info_t ci;
26962 	int err;
26963 	boolean_t entered_ipsq = B_FALSE;
26964 
26965 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26966 
26967 	if (ipip == NULL)
26968 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26969 
26970 	/*
26971 	 * SIOCLIFADDIF needs to go thru a special path since the
26972 	 * ill may not exist yet. This happens in the case of lo0
26973 	 * which is created using this ioctl.
26974 	 */
26975 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26976 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26977 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26978 		return;
26979 	}
26980 
26981 	ci.ci_ipif = NULL;
26982 	if (ipip->ipi_cmd_type == MISC_CMD) {
26983 		/*
26984 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26985 		 */
26986 		if (ipip->ipi_cmd == IF_UNITSEL) {
26987 			/* ioctl comes down the ill */
26988 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26989 			ipif_refhold(ci.ci_ipif);
26990 		}
26991 		err = 0;
26992 		ci.ci_sin = NULL;
26993 		ci.ci_sin6 = NULL;
26994 		ci.ci_lifr = NULL;
26995 	} else {
26996 		switch (ipip->ipi_cmd_type) {
26997 		case IF_CMD:
26998 		case LIF_CMD:
26999 			extract_funcp = ip_extract_lifreq;
27000 			break;
27001 
27002 		case ARP_CMD:
27003 		case XARP_CMD:
27004 			extract_funcp = ip_extract_arpreq;
27005 			break;
27006 
27007 		case TUN_CMD:
27008 			extract_funcp = ip_extract_tunreq;
27009 			break;
27010 
27011 		case MSFILT_CMD:
27012 			extract_funcp = ip_extract_msfilter;
27013 			break;
27014 
27015 		default:
27016 			ASSERT(0);
27017 		}
27018 
27019 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27020 		if (err != 0) {
27021 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27022 			return;
27023 		}
27024 
27025 		/*
27026 		 * All of the extraction functions return a refheld ipif.
27027 		 */
27028 		ASSERT(ci.ci_ipif != NULL);
27029 	}
27030 
27031 	/*
27032 	 * If ipsq is non-null, we are already being called exclusively
27033 	 */
27034 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27035 	if (!(ipip->ipi_flags & IPI_WR)) {
27036 		/*
27037 		 * A return value of EINPROGRESS means the ioctl is
27038 		 * either queued and waiting for some reason or has
27039 		 * already completed.
27040 		 */
27041 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27042 		    ci.ci_lifr);
27043 		if (ci.ci_ipif != NULL)
27044 			ipif_refrele(ci.ci_ipif);
27045 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27046 		return;
27047 	}
27048 
27049 	ASSERT(ci.ci_ipif != NULL);
27050 
27051 	if (ipsq == NULL) {
27052 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27053 		    ip_process_ioctl, NEW_OP, B_TRUE);
27054 		entered_ipsq = B_TRUE;
27055 	}
27056 	/*
27057 	 * Release the ipif so that ipif_down and friends that wait for
27058 	 * references to go away are not misled about the current ipif_refcnt
27059 	 * values. We are writer so we can access the ipif even after releasing
27060 	 * the ipif.
27061 	 */
27062 	ipif_refrele(ci.ci_ipif);
27063 	if (ipsq == NULL)
27064 		return;
27065 
27066 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27067 
27068 	/*
27069 	 * For most set ioctls that come here, this serves as a single point
27070 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27071 	 * be any new references to the ipif. This helps functions that go
27072 	 * through this path and end up trying to wait for the refcnts
27073 	 * associated with the ipif to go down to zero. Some exceptions are
27074 	 * Failover, Failback, and Groupname commands that operate on more than
27075 	 * just the ci.ci_ipif. These commands internally determine the
27076 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27077 	 * flags on that set. Another exception is the Removeif command that
27078 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27079 	 * ipif to operate on.
27080 	 */
27081 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27082 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27083 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27084 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27085 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27086 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27087 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27088 
27089 	/*
27090 	 * A return value of EINPROGRESS means the ioctl is
27091 	 * either queued and waiting for some reason or has
27092 	 * already completed.
27093 	 */
27094 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27095 
27096 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27097 
27098 	if (entered_ipsq)
27099 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27100 }
27101 
27102 /*
27103  * Complete the ioctl. Typically ioctls use the mi package and need to
27104  * do mi_copyout/mi_copy_done.
27105  */
27106 void
27107 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27108 {
27109 	conn_t	*connp = NULL;
27110 
27111 	if (err == EINPROGRESS)
27112 		return;
27113 
27114 	if (CONN_Q(q)) {
27115 		connp = Q_TO_CONN(q);
27116 		ASSERT(connp->conn_ref >= 2);
27117 	}
27118 
27119 	switch (mode) {
27120 	case COPYOUT:
27121 		if (err == 0)
27122 			mi_copyout(q, mp);
27123 		else
27124 			mi_copy_done(q, mp, err);
27125 		break;
27126 
27127 	case NO_COPYOUT:
27128 		mi_copy_done(q, mp, err);
27129 		break;
27130 
27131 	default:
27132 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27133 		break;
27134 	}
27135 
27136 	/*
27137 	 * The refhold placed at the start of the ioctl is released here.
27138 	 */
27139 	if (connp != NULL)
27140 		CONN_OPER_PENDING_DONE(connp);
27141 
27142 	if (ipsq != NULL)
27143 		ipsq_current_finish(ipsq);
27144 }
27145 
27146 /*
27147  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27148  */
27149 /* ARGSUSED */
27150 void
27151 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27152 {
27153 	conn_t *connp = arg;
27154 	tcp_t	*tcp;
27155 
27156 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27157 	tcp = connp->conn_tcp;
27158 
27159 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27160 		freemsg(mp);
27161 	else
27162 		tcp_rput_other(tcp, mp);
27163 	CONN_OPER_PENDING_DONE(connp);
27164 }
27165 
27166 /* Called from ip_wput for all non data messages */
27167 /* ARGSUSED */
27168 void
27169 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27170 {
27171 	mblk_t		*mp1;
27172 	ire_t		*ire, *fake_ire;
27173 	ill_t		*ill;
27174 	struct iocblk	*iocp;
27175 	ip_ioctl_cmd_t	*ipip;
27176 	cred_t		*cr;
27177 	conn_t		*connp;
27178 	int		err;
27179 	nce_t		*nce;
27180 	ipif_t		*ipif;
27181 	ip_stack_t	*ipst;
27182 	char		*proto_str;
27183 
27184 	if (CONN_Q(q)) {
27185 		connp = Q_TO_CONN(q);
27186 		ipst = connp->conn_netstack->netstack_ip;
27187 	} else {
27188 		connp = NULL;
27189 		ipst = ILLQ_TO_IPST(q);
27190 	}
27191 
27192 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27193 
27194 	switch (DB_TYPE(mp)) {
27195 	case M_IOCTL:
27196 		/*
27197 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27198 		 * will arrange to copy in associated control structures.
27199 		 */
27200 		ip_sioctl_copyin_setup(q, mp);
27201 		return;
27202 	case M_IOCDATA:
27203 		/*
27204 		 * Ensure that this is associated with one of our trans-
27205 		 * parent ioctls.  If it's not ours, discard it if we're
27206 		 * running as a driver, or pass it on if we're a module.
27207 		 */
27208 		iocp = (struct iocblk *)mp->b_rptr;
27209 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27210 		if (ipip == NULL) {
27211 			if (q->q_next == NULL) {
27212 				goto nak;
27213 			} else {
27214 				putnext(q, mp);
27215 			}
27216 			return;
27217 		}
27218 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27219 			/*
27220 			 * the ioctl is one we recognise, but is not
27221 			 * consumed by IP as a module, pass M_IOCDATA
27222 			 * for processing downstream, but only for
27223 			 * common Streams ioctls.
27224 			 */
27225 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27226 				putnext(q, mp);
27227 				return;
27228 			} else {
27229 				goto nak;
27230 			}
27231 		}
27232 
27233 		/* IOCTL continuation following copyin or copyout. */
27234 		if (mi_copy_state(q, mp, NULL) == -1) {
27235 			/*
27236 			 * The copy operation failed.  mi_copy_state already
27237 			 * cleaned up, so we're out of here.
27238 			 */
27239 			return;
27240 		}
27241 		/*
27242 		 * If we just completed a copy in, we become writer and
27243 		 * continue processing in ip_sioctl_copyin_done.  If it
27244 		 * was a copy out, we call mi_copyout again.  If there is
27245 		 * nothing more to copy out, it will complete the IOCTL.
27246 		 */
27247 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27248 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27249 				mi_copy_done(q, mp, EPROTO);
27250 				return;
27251 			}
27252 			/*
27253 			 * Check for cases that need more copying.  A return
27254 			 * value of 0 means a second copyin has been started,
27255 			 * so we return; a return value of 1 means no more
27256 			 * copying is needed, so we continue.
27257 			 */
27258 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27259 			    MI_COPY_COUNT(mp) == 1) {
27260 				if (ip_copyin_msfilter(q, mp) == 0)
27261 					return;
27262 			}
27263 			/*
27264 			 * Refhold the conn, till the ioctl completes. This is
27265 			 * needed in case the ioctl ends up in the pending mp
27266 			 * list. Every mp in the ill_pending_mp list and
27267 			 * the ipsq_pending_mp must have a refhold on the conn
27268 			 * to resume processing. The refhold is released when
27269 			 * the ioctl completes. (normally or abnormally)
27270 			 * In all cases ip_ioctl_finish is called to finish
27271 			 * the ioctl.
27272 			 */
27273 			if (connp != NULL) {
27274 				/* This is not a reentry */
27275 				ASSERT(ipsq == NULL);
27276 				CONN_INC_REF(connp);
27277 			} else {
27278 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27279 					mi_copy_done(q, mp, EINVAL);
27280 					return;
27281 				}
27282 			}
27283 
27284 			ip_process_ioctl(ipsq, q, mp, ipip);
27285 
27286 		} else {
27287 			mi_copyout(q, mp);
27288 		}
27289 		return;
27290 nak:
27291 		iocp->ioc_error = EINVAL;
27292 		mp->b_datap->db_type = M_IOCNAK;
27293 		iocp->ioc_count = 0;
27294 		qreply(q, mp);
27295 		return;
27296 
27297 	case M_IOCNAK:
27298 		/*
27299 		 * The only way we could get here is if a resolver didn't like
27300 		 * an IOCTL we sent it.	 This shouldn't happen.
27301 		 */
27302 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27303 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27304 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27305 		freemsg(mp);
27306 		return;
27307 	case M_IOCACK:
27308 		/* /dev/ip shouldn't see this */
27309 		if (CONN_Q(q))
27310 			goto nak;
27311 
27312 		/* Finish socket ioctls passed through to ARP. */
27313 		ip_sioctl_iocack(q, mp);
27314 		return;
27315 	case M_FLUSH:
27316 		if (*mp->b_rptr & FLUSHW)
27317 			flushq(q, FLUSHALL);
27318 		if (q->q_next) {
27319 			putnext(q, mp);
27320 			return;
27321 		}
27322 		if (*mp->b_rptr & FLUSHR) {
27323 			*mp->b_rptr &= ~FLUSHW;
27324 			qreply(q, mp);
27325 			return;
27326 		}
27327 		freemsg(mp);
27328 		return;
27329 	case IRE_DB_REQ_TYPE:
27330 		if (connp == NULL) {
27331 			proto_str = "IRE_DB_REQ_TYPE";
27332 			goto protonak;
27333 		}
27334 		/* An Upper Level Protocol wants a copy of an IRE. */
27335 		ip_ire_req(q, mp);
27336 		return;
27337 	case M_CTL:
27338 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27339 			break;
27340 
27341 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27342 		    TUN_HELLO) {
27343 			ASSERT(connp != NULL);
27344 			connp->conn_flags |= IPCL_IPTUN;
27345 			freeb(mp);
27346 			return;
27347 		}
27348 
27349 		/* M_CTL messages are used by ARP to tell us things. */
27350 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27351 			break;
27352 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27353 		case AR_ENTRY_SQUERY:
27354 			ip_wput_ctl(q, mp);
27355 			return;
27356 		case AR_CLIENT_NOTIFY:
27357 			ip_arp_news(q, mp);
27358 			return;
27359 		case AR_DLPIOP_DONE:
27360 			ASSERT(q->q_next != NULL);
27361 			ill = (ill_t *)q->q_ptr;
27362 			/* qwriter_ip releases the refhold */
27363 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27364 			ill_refhold(ill);
27365 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27366 			return;
27367 		case AR_ARP_CLOSING:
27368 			/*
27369 			 * ARP (above us) is closing. If no ARP bringup is
27370 			 * currently pending, ack the message so that ARP
27371 			 * can complete its close. Also mark ill_arp_closing
27372 			 * so that new ARP bringups will fail. If any
27373 			 * ARP bringup is currently in progress, we will
27374 			 * ack this when the current ARP bringup completes.
27375 			 */
27376 			ASSERT(q->q_next != NULL);
27377 			ill = (ill_t *)q->q_ptr;
27378 			mutex_enter(&ill->ill_lock);
27379 			ill->ill_arp_closing = 1;
27380 			if (!ill->ill_arp_bringup_pending) {
27381 				mutex_exit(&ill->ill_lock);
27382 				qreply(q, mp);
27383 			} else {
27384 				mutex_exit(&ill->ill_lock);
27385 				freemsg(mp);
27386 			}
27387 			return;
27388 		case AR_ARP_EXTEND:
27389 			/*
27390 			 * The ARP module above us is capable of duplicate
27391 			 * address detection.  Old ATM drivers will not send
27392 			 * this message.
27393 			 */
27394 			ASSERT(q->q_next != NULL);
27395 			ill = (ill_t *)q->q_ptr;
27396 			ill->ill_arp_extend = B_TRUE;
27397 			freemsg(mp);
27398 			return;
27399 		default:
27400 			break;
27401 		}
27402 		break;
27403 	case M_PROTO:
27404 	case M_PCPROTO:
27405 		/*
27406 		 * The only PROTO messages we expect are ULP binds and
27407 		 * copies of option negotiation acknowledgements.
27408 		 */
27409 		switch (((union T_primitives *)mp->b_rptr)->type) {
27410 		case O_T_BIND_REQ:
27411 		case T_BIND_REQ: {
27412 			/* Request can get queued in bind */
27413 			if (connp == NULL) {
27414 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27415 				goto protonak;
27416 			}
27417 			/*
27418 			 * The transports except SCTP call ip_bind_{v4,v6}()
27419 			 * directly instead of a a putnext. SCTP doesn't
27420 			 * generate any T_BIND_REQ since it has its own
27421 			 * fanout data structures. However, ESP and AH
27422 			 * come in for regular binds; all other cases are
27423 			 * bind retries.
27424 			 */
27425 			ASSERT(!IPCL_IS_SCTP(connp));
27426 
27427 			/* Don't increment refcnt if this is a re-entry */
27428 			if (ipsq == NULL)
27429 				CONN_INC_REF(connp);
27430 
27431 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27432 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27433 			if (mp == NULL)
27434 				return;
27435 			if (IPCL_IS_TCP(connp)) {
27436 				/*
27437 				 * In the case of TCP endpoint we
27438 				 * come here only for bind retries
27439 				 */
27440 				ASSERT(ipsq != NULL);
27441 				CONN_INC_REF(connp);
27442 				squeue_fill(connp->conn_sqp, mp,
27443 				    ip_resume_tcp_bind, connp,
27444 				    SQTAG_BIND_RETRY);
27445 			} else if (IPCL_IS_UDP(connp)) {
27446 				/*
27447 				 * In the case of UDP endpoint we
27448 				 * come here only for bind retries
27449 				 */
27450 				ASSERT(ipsq != NULL);
27451 				udp_resume_bind(connp, mp);
27452 			} else if (IPCL_IS_RAWIP(connp)) {
27453 				/*
27454 				 * In the case of RAWIP endpoint we
27455 				 * come here only for bind retries
27456 				 */
27457 				ASSERT(ipsq != NULL);
27458 				rawip_resume_bind(connp, mp);
27459 			} else {
27460 				/* The case of AH and ESP */
27461 				qreply(q, mp);
27462 				CONN_OPER_PENDING_DONE(connp);
27463 			}
27464 			return;
27465 		}
27466 		case T_SVR4_OPTMGMT_REQ:
27467 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27468 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27469 
27470 			if (connp == NULL) {
27471 				proto_str = "T_SVR4_OPTMGMT_REQ";
27472 				goto protonak;
27473 			}
27474 
27475 			if (!snmpcom_req(q, mp, ip_snmp_set,
27476 			    ip_snmp_get, cr)) {
27477 				/*
27478 				 * Call svr4_optcom_req so that it can
27479 				 * generate the ack. We don't come here
27480 				 * if this operation is being restarted.
27481 				 * ip_restart_optmgmt will drop the conn ref.
27482 				 * In the case of ipsec option after the ipsec
27483 				 * load is complete conn_restart_ipsec_waiter
27484 				 * drops the conn ref.
27485 				 */
27486 				ASSERT(ipsq == NULL);
27487 				CONN_INC_REF(connp);
27488 				if (ip_check_for_ipsec_opt(q, mp))
27489 					return;
27490 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27491 				    B_FALSE);
27492 				if (err != EINPROGRESS) {
27493 					/* Operation is done */
27494 					CONN_OPER_PENDING_DONE(connp);
27495 				}
27496 			}
27497 			return;
27498 		case T_OPTMGMT_REQ:
27499 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27500 			/*
27501 			 * Note: No snmpcom_req support through new
27502 			 * T_OPTMGMT_REQ.
27503 			 * Call tpi_optcom_req so that it can
27504 			 * generate the ack.
27505 			 */
27506 			if (connp == NULL) {
27507 				proto_str = "T_OPTMGMT_REQ";
27508 				goto protonak;
27509 			}
27510 
27511 			ASSERT(ipsq == NULL);
27512 			/*
27513 			 * We don't come here for restart. ip_restart_optmgmt
27514 			 * will drop the conn ref. In the case of ipsec option
27515 			 * after the ipsec load is complete
27516 			 * conn_restart_ipsec_waiter drops the conn ref.
27517 			 */
27518 			CONN_INC_REF(connp);
27519 			if (ip_check_for_ipsec_opt(q, mp))
27520 				return;
27521 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27522 			if (err != EINPROGRESS) {
27523 				/* Operation is done */
27524 				CONN_OPER_PENDING_DONE(connp);
27525 			}
27526 			return;
27527 		case T_UNBIND_REQ:
27528 			if (connp == NULL) {
27529 				proto_str = "T_UNBIND_REQ";
27530 				goto protonak;
27531 			}
27532 			mp = ip_unbind(q, mp);
27533 			qreply(q, mp);
27534 			return;
27535 		default:
27536 			/*
27537 			 * Have to drop any DLPI messages coming down from
27538 			 * arp (such as an info_req which would cause ip
27539 			 * to receive an extra info_ack if it was passed
27540 			 * through.
27541 			 */
27542 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27543 			    (int)*(uint_t *)mp->b_rptr));
27544 			freemsg(mp);
27545 			return;
27546 		}
27547 		/* NOTREACHED */
27548 	case IRE_DB_TYPE: {
27549 		nce_t		*nce;
27550 		ill_t		*ill;
27551 		in6_addr_t	gw_addr_v6;
27552 
27553 
27554 		/*
27555 		 * This is a response back from a resolver.  It
27556 		 * consists of a message chain containing:
27557 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27558 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27559 		 * The LL_HDR_MBLK is the DLPI header to use to get
27560 		 * the attached packet, and subsequent ones for the
27561 		 * same destination, transmitted.
27562 		 */
27563 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27564 			break;
27565 		/*
27566 		 * First, check to make sure the resolution succeeded.
27567 		 * If it failed, the second mblk will be empty.
27568 		 * If it is, free the chain, dropping the packet.
27569 		 * (We must ire_delete the ire; that frees the ire mblk)
27570 		 * We're doing this now to support PVCs for ATM; it's
27571 		 * a partial xresolv implementation. When we fully implement
27572 		 * xresolv interfaces, instead of freeing everything here
27573 		 * we'll initiate neighbor discovery.
27574 		 *
27575 		 * For v4 (ARP and other external resolvers) the resolver
27576 		 * frees the message, so no check is needed. This check
27577 		 * is required, though, for a full xresolve implementation.
27578 		 * Including this code here now both shows how external
27579 		 * resolvers can NACK a resolution request using an
27580 		 * existing design that has no specific provisions for NACKs,
27581 		 * and also takes into account that the current non-ARP
27582 		 * external resolver has been coded to use this method of
27583 		 * NACKing for all IPv6 (xresolv) cases,
27584 		 * whether our xresolv implementation is complete or not.
27585 		 *
27586 		 */
27587 		ire = (ire_t *)mp->b_rptr;
27588 		ill = ire_to_ill(ire);
27589 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27590 		if (mp1->b_rptr == mp1->b_wptr) {
27591 			if (ire->ire_ipversion == IPV6_VERSION) {
27592 				/*
27593 				 * XRESOLV interface.
27594 				 */
27595 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27596 				mutex_enter(&ire->ire_lock);
27597 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27598 				mutex_exit(&ire->ire_lock);
27599 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27600 					nce = ndp_lookup_v6(ill,
27601 					    &ire->ire_addr_v6, B_FALSE);
27602 				} else {
27603 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27604 					    B_FALSE);
27605 				}
27606 				if (nce != NULL) {
27607 					nce_resolv_failed(nce);
27608 					ndp_delete(nce);
27609 					NCE_REFRELE(nce);
27610 				}
27611 			}
27612 			mp->b_cont = NULL;
27613 			freemsg(mp1);		/* frees the pkt as well */
27614 			ASSERT(ire->ire_nce == NULL);
27615 			ire_delete((ire_t *)mp->b_rptr);
27616 			return;
27617 		}
27618 
27619 		/*
27620 		 * Split them into IRE_MBLK and pkt and feed it into
27621 		 * ire_add_then_send. Then in ire_add_then_send
27622 		 * the IRE will be added, and then the packet will be
27623 		 * run back through ip_wput. This time it will make
27624 		 * it to the wire.
27625 		 */
27626 		mp->b_cont = NULL;
27627 		mp = mp1->b_cont;		/* now, mp points to pkt */
27628 		mp1->b_cont = NULL;
27629 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27630 		if (ire->ire_ipversion == IPV6_VERSION) {
27631 			/*
27632 			 * XRESOLV interface. Find the nce and put a copy
27633 			 * of the dl_unitdata_req in nce_res_mp
27634 			 */
27635 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27636 			mutex_enter(&ire->ire_lock);
27637 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27638 			mutex_exit(&ire->ire_lock);
27639 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27640 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27641 				    B_FALSE);
27642 			} else {
27643 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27644 			}
27645 			if (nce != NULL) {
27646 				/*
27647 				 * We have to protect nce_res_mp here
27648 				 * from being accessed by other threads
27649 				 * while we change the mblk pointer.
27650 				 * Other functions will also lock the nce when
27651 				 * accessing nce_res_mp.
27652 				 *
27653 				 * The reason we change the mblk pointer
27654 				 * here rather than copying the resolved address
27655 				 * into the template is that, unlike with
27656 				 * ethernet, we have no guarantee that the
27657 				 * resolved address length will be
27658 				 * smaller than or equal to the lla length
27659 				 * with which the template was allocated,
27660 				 * (for ethernet, they're equal)
27661 				 * so we have to use the actual resolved
27662 				 * address mblk - which holds the real
27663 				 * dl_unitdata_req with the resolved address.
27664 				 *
27665 				 * Doing this is the same behavior as was
27666 				 * previously used in the v4 ARP case.
27667 				 */
27668 				mutex_enter(&nce->nce_lock);
27669 				if (nce->nce_res_mp != NULL)
27670 					freemsg(nce->nce_res_mp);
27671 				nce->nce_res_mp = mp1;
27672 				mutex_exit(&nce->nce_lock);
27673 				/*
27674 				 * We do a fastpath probe here because
27675 				 * we have resolved the address without
27676 				 * using Neighbor Discovery.
27677 				 * In the non-XRESOLV v6 case, the fastpath
27678 				 * probe is done right after neighbor
27679 				 * discovery completes.
27680 				 */
27681 				if (nce->nce_res_mp != NULL) {
27682 					int res;
27683 					nce_fastpath_list_add(nce);
27684 					res = ill_fastpath_probe(ill,
27685 					    nce->nce_res_mp);
27686 					if (res != 0 && res != EAGAIN)
27687 						nce_fastpath_list_delete(nce);
27688 				}
27689 
27690 				ire_add_then_send(q, ire, mp);
27691 				/*
27692 				 * Now we have to clean out any packets
27693 				 * that may have been queued on the nce
27694 				 * while it was waiting for address resolution
27695 				 * to complete.
27696 				 */
27697 				mutex_enter(&nce->nce_lock);
27698 				mp1 = nce->nce_qd_mp;
27699 				nce->nce_qd_mp = NULL;
27700 				mutex_exit(&nce->nce_lock);
27701 				while (mp1 != NULL) {
27702 					mblk_t *nxt_mp;
27703 					queue_t *fwdq = NULL;
27704 					ill_t   *inbound_ill;
27705 					uint_t ifindex;
27706 
27707 					nxt_mp = mp1->b_next;
27708 					mp1->b_next = NULL;
27709 					/*
27710 					 * Retrieve ifindex stored in
27711 					 * ip_rput_data_v6()
27712 					 */
27713 					ifindex =
27714 					    (uint_t)(uintptr_t)mp1->b_prev;
27715 					inbound_ill =
27716 					    ill_lookup_on_ifindex(ifindex,
27717 					    B_TRUE, NULL, NULL, NULL,
27718 					    NULL, ipst);
27719 					mp1->b_prev = NULL;
27720 					if (inbound_ill != NULL)
27721 						fwdq = inbound_ill->ill_rq;
27722 
27723 					if (fwdq != NULL) {
27724 						put(fwdq, mp1);
27725 						ill_refrele(inbound_ill);
27726 					} else
27727 						put(WR(ill->ill_rq), mp1);
27728 					mp1 = nxt_mp;
27729 				}
27730 				NCE_REFRELE(nce);
27731 			} else {	/* nce is NULL; clean up */
27732 				ire_delete(ire);
27733 				freemsg(mp);
27734 				freemsg(mp1);
27735 				return;
27736 			}
27737 		} else {
27738 			nce_t *arpce;
27739 			/*
27740 			 * Link layer resolution succeeded. Recompute the
27741 			 * ire_nce.
27742 			 */
27743 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27744 			if ((arpce = ndp_lookup_v4(ill,
27745 			    (ire->ire_gateway_addr != INADDR_ANY ?
27746 			    &ire->ire_gateway_addr : &ire->ire_addr),
27747 			    B_FALSE)) == NULL) {
27748 				freeb(ire->ire_mp);
27749 				freeb(mp1);
27750 				freemsg(mp);
27751 				return;
27752 			}
27753 			mutex_enter(&arpce->nce_lock);
27754 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27755 			if (arpce->nce_state == ND_REACHABLE) {
27756 				/*
27757 				 * Someone resolved this before us;
27758 				 * cleanup the res_mp. Since ire has
27759 				 * not been added yet, the call to ire_add_v4
27760 				 * from ire_add_then_send (when a dup is
27761 				 * detected) will clean up the ire.
27762 				 */
27763 				freeb(mp1);
27764 			} else {
27765 				ASSERT(arpce->nce_res_mp == NULL);
27766 				arpce->nce_res_mp = mp1;
27767 				arpce->nce_state = ND_REACHABLE;
27768 			}
27769 			mutex_exit(&arpce->nce_lock);
27770 			if (ire->ire_marks & IRE_MARK_NOADD) {
27771 				/*
27772 				 * this ire will not be added to the ire
27773 				 * cache table, so we can set the ire_nce
27774 				 * here, as there are no atomicity constraints.
27775 				 */
27776 				ire->ire_nce = arpce;
27777 				/*
27778 				 * We are associating this nce with the ire
27779 				 * so change the nce ref taken in
27780 				 * ndp_lookup_v4() from
27781 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27782 				 */
27783 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27784 			} else {
27785 				NCE_REFRELE(arpce);
27786 			}
27787 			ire_add_then_send(q, ire, mp);
27788 		}
27789 		return;	/* All is well, the packet has been sent. */
27790 	}
27791 	case IRE_ARPRESOLVE_TYPE: {
27792 
27793 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27794 			break;
27795 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27796 		mp->b_cont = NULL;
27797 		/*
27798 		 * First, check to make sure the resolution succeeded.
27799 		 * If it failed, the second mblk will be empty.
27800 		 */
27801 		if (mp1->b_rptr == mp1->b_wptr) {
27802 			/* cleanup  the incomplete ire, free queued packets */
27803 			freemsg(mp); /* fake ire */
27804 			freeb(mp1);  /* dl_unitdata response */
27805 			return;
27806 		}
27807 
27808 		/*
27809 		 * update any incomplete nce_t found. we lookup the ctable
27810 		 * and find the nce from the ire->ire_nce because we need
27811 		 * to pass the ire to ip_xmit_v4 later, and can find both
27812 		 * ire and nce in one lookup from the ctable.
27813 		 */
27814 		fake_ire = (ire_t *)mp->b_rptr;
27815 		/*
27816 		 * By the time we come back here from ARP
27817 		 * the logical outgoing interface  of the incomplete ire
27818 		 * we added in ire_forward could have disappeared,
27819 		 * causing the incomplete ire to also have
27820 		 * dissapeared. So we need to retreive the
27821 		 * proper ipif for the ire  before looking
27822 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27823 		 */
27824 		ill = q->q_ptr;
27825 
27826 		/* Get the outgoing ipif */
27827 		mutex_enter(&ill->ill_lock);
27828 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27829 			mutex_exit(&ill->ill_lock);
27830 			freemsg(mp); /* fake ire */
27831 			freeb(mp1);  /* dl_unitdata response */
27832 			return;
27833 		}
27834 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27835 
27836 		if (ipif == NULL) {
27837 			mutex_exit(&ill->ill_lock);
27838 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27839 			freemsg(mp);
27840 			freeb(mp1);
27841 			return;
27842 		}
27843 		ipif_refhold_locked(ipif);
27844 		mutex_exit(&ill->ill_lock);
27845 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27846 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27847 		    ipif, fake_ire->ire_zoneid, NULL,
27848 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY|
27849 		    MATCH_IRE_TYPE), ipst);
27850 		ipif_refrele(ipif);
27851 		if (ire == NULL) {
27852 			/*
27853 			 * no ire was found; check if there is an nce
27854 			 * for this lookup; if it has no ire's pointing at it
27855 			 * cleanup.
27856 			 */
27857 			if ((nce = ndp_lookup_v4(ill,
27858 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27859 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27860 			    B_FALSE)) != NULL) {
27861 				/*
27862 				 * cleanup:
27863 				 * We check for refcnt 2 (one for the nce
27864 				 * hash list + 1 for the ref taken by
27865 				 * ndp_lookup_v4) to check that there are
27866 				 * no ire's pointing at the nce.
27867 				 */
27868 				if (nce->nce_refcnt == 2)
27869 					ndp_delete(nce);
27870 				NCE_REFRELE(nce);
27871 			}
27872 			freeb(mp1);  /* dl_unitdata response */
27873 			freemsg(mp); /* fake ire */
27874 			return;
27875 		}
27876 		nce = ire->ire_nce;
27877 		DTRACE_PROBE2(ire__arpresolve__type,
27878 		    ire_t *, ire, nce_t *, nce);
27879 		ASSERT(nce->nce_state != ND_INITIAL);
27880 		mutex_enter(&nce->nce_lock);
27881 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27882 		if (nce->nce_state == ND_REACHABLE) {
27883 			/*
27884 			 * Someone resolved this before us;
27885 			 * our response is not needed any more.
27886 			 */
27887 			mutex_exit(&nce->nce_lock);
27888 			freeb(mp1);  /* dl_unitdata response */
27889 		} else {
27890 			ASSERT(nce->nce_res_mp == NULL);
27891 			nce->nce_res_mp = mp1;
27892 			nce->nce_state = ND_REACHABLE;
27893 			mutex_exit(&nce->nce_lock);
27894 			nce_fastpath(nce);
27895 		}
27896 		/*
27897 		 * The cached nce_t has been updated to be reachable;
27898 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27899 		 */
27900 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27901 		freemsg(mp);
27902 		/*
27903 		 * send out queued packets.
27904 		 */
27905 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27906 
27907 		IRE_REFRELE(ire);
27908 		return;
27909 	}
27910 	default:
27911 		break;
27912 	}
27913 	if (q->q_next) {
27914 		putnext(q, mp);
27915 	} else
27916 		freemsg(mp);
27917 	return;
27918 
27919 protonak:
27920 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27921 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27922 		qreply(q, mp);
27923 }
27924 
27925 /*
27926  * Process IP options in an outbound packet.  Modify the destination if there
27927  * is a source route option.
27928  * Returns non-zero if something fails in which case an ICMP error has been
27929  * sent and mp freed.
27930  */
27931 static int
27932 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27933     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27934 {
27935 	ipoptp_t	opts;
27936 	uchar_t		*opt;
27937 	uint8_t		optval;
27938 	uint8_t		optlen;
27939 	ipaddr_t	dst;
27940 	intptr_t	code = 0;
27941 	mblk_t		*mp;
27942 	ire_t		*ire = NULL;
27943 
27944 	ip2dbg(("ip_wput_options\n"));
27945 	mp = ipsec_mp;
27946 	if (mctl_present) {
27947 		mp = ipsec_mp->b_cont;
27948 	}
27949 
27950 	dst = ipha->ipha_dst;
27951 	for (optval = ipoptp_first(&opts, ipha);
27952 	    optval != IPOPT_EOL;
27953 	    optval = ipoptp_next(&opts)) {
27954 		opt = opts.ipoptp_cur;
27955 		optlen = opts.ipoptp_len;
27956 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27957 		    optval, optlen));
27958 		switch (optval) {
27959 			uint32_t off;
27960 		case IPOPT_SSRR:
27961 		case IPOPT_LSRR:
27962 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27963 				ip1dbg((
27964 				    "ip_wput_options: bad option offset\n"));
27965 				code = (char *)&opt[IPOPT_OLEN] -
27966 				    (char *)ipha;
27967 				goto param_prob;
27968 			}
27969 			off = opt[IPOPT_OFFSET];
27970 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27971 			    ntohl(dst)));
27972 			/*
27973 			 * For strict: verify that dst is directly
27974 			 * reachable.
27975 			 */
27976 			if (optval == IPOPT_SSRR) {
27977 				ire = ire_ftable_lookup(dst, 0, 0,
27978 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27979 				    MBLK_GETLABEL(mp),
27980 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27981 				if (ire == NULL) {
27982 					ip1dbg(("ip_wput_options: SSRR not"
27983 					    " directly reachable: 0x%x\n",
27984 					    ntohl(dst)));
27985 					goto bad_src_route;
27986 				}
27987 				ire_refrele(ire);
27988 			}
27989 			break;
27990 		case IPOPT_RR:
27991 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27992 				ip1dbg((
27993 				    "ip_wput_options: bad option offset\n"));
27994 				code = (char *)&opt[IPOPT_OLEN] -
27995 				    (char *)ipha;
27996 				goto param_prob;
27997 			}
27998 			break;
27999 		case IPOPT_TS:
28000 			/*
28001 			 * Verify that length >=5 and that there is either
28002 			 * room for another timestamp or that the overflow
28003 			 * counter is not maxed out.
28004 			 */
28005 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28006 			if (optlen < IPOPT_MINLEN_IT) {
28007 				goto param_prob;
28008 			}
28009 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28010 				ip1dbg((
28011 				    "ip_wput_options: bad option offset\n"));
28012 				code = (char *)&opt[IPOPT_OFFSET] -
28013 				    (char *)ipha;
28014 				goto param_prob;
28015 			}
28016 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28017 			case IPOPT_TS_TSONLY:
28018 				off = IPOPT_TS_TIMELEN;
28019 				break;
28020 			case IPOPT_TS_TSANDADDR:
28021 			case IPOPT_TS_PRESPEC:
28022 			case IPOPT_TS_PRESPEC_RFC791:
28023 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28024 				break;
28025 			default:
28026 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28027 				    (char *)ipha;
28028 				goto param_prob;
28029 			}
28030 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28031 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28032 				/*
28033 				 * No room and the overflow counter is 15
28034 				 * already.
28035 				 */
28036 				goto param_prob;
28037 			}
28038 			break;
28039 		}
28040 	}
28041 
28042 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28043 		return (0);
28044 
28045 	ip1dbg(("ip_wput_options: error processing IP options."));
28046 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28047 
28048 param_prob:
28049 	/*
28050 	 * Since ip_wput() isn't close to finished, we fill
28051 	 * in enough of the header for credible error reporting.
28052 	 */
28053 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28054 		/* Failed */
28055 		freemsg(ipsec_mp);
28056 		return (-1);
28057 	}
28058 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28059 	return (-1);
28060 
28061 bad_src_route:
28062 	/*
28063 	 * Since ip_wput() isn't close to finished, we fill
28064 	 * in enough of the header for credible error reporting.
28065 	 */
28066 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28067 		/* Failed */
28068 		freemsg(ipsec_mp);
28069 		return (-1);
28070 	}
28071 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28072 	return (-1);
28073 }
28074 
28075 /*
28076  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28077  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28078  * thru /etc/system.
28079  */
28080 #define	CONN_MAXDRAINCNT	64
28081 
28082 static void
28083 conn_drain_init(ip_stack_t *ipst)
28084 {
28085 	int i;
28086 
28087 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28088 
28089 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28090 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28091 		/*
28092 		 * Default value of the number of drainers is the
28093 		 * number of cpus, subject to maximum of 8 drainers.
28094 		 */
28095 		if (boot_max_ncpus != -1)
28096 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28097 		else
28098 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28099 	}
28100 
28101 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28102 	    sizeof (idl_t), KM_SLEEP);
28103 
28104 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28105 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28106 		    MUTEX_DEFAULT, NULL);
28107 	}
28108 }
28109 
28110 static void
28111 conn_drain_fini(ip_stack_t *ipst)
28112 {
28113 	int i;
28114 
28115 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28116 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28117 	kmem_free(ipst->ips_conn_drain_list,
28118 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28119 	ipst->ips_conn_drain_list = NULL;
28120 }
28121 
28122 /*
28123  * Note: For an overview of how flowcontrol is handled in IP please see the
28124  * IP Flowcontrol notes at the top of this file.
28125  *
28126  * Flow control has blocked us from proceeding. Insert the given conn in one
28127  * of the conn drain lists. These conn wq's will be qenabled later on when
28128  * STREAMS flow control does a backenable. conn_walk_drain will enable
28129  * the first conn in each of these drain lists. Each of these qenabled conns
28130  * in turn enables the next in the list, after it runs, or when it closes,
28131  * thus sustaining the drain process.
28132  *
28133  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28134  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28135  * running at any time, on a given conn, since there can be only 1 service proc
28136  * running on a queue at any time.
28137  */
28138 void
28139 conn_drain_insert(conn_t *connp)
28140 {
28141 	idl_t	*idl;
28142 	uint_t	index;
28143 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28144 
28145 	mutex_enter(&connp->conn_lock);
28146 	if (connp->conn_state_flags & CONN_CLOSING) {
28147 		/*
28148 		 * The conn is closing as a result of which CONN_CLOSING
28149 		 * is set. Return.
28150 		 */
28151 		mutex_exit(&connp->conn_lock);
28152 		return;
28153 	} else if (connp->conn_idl == NULL) {
28154 		/*
28155 		 * Assign the next drain list round robin. We dont' use
28156 		 * a lock, and thus it may not be strictly round robin.
28157 		 * Atomicity of load/stores is enough to make sure that
28158 		 * conn_drain_list_index is always within bounds.
28159 		 */
28160 		index = ipst->ips_conn_drain_list_index;
28161 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28162 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28163 		index++;
28164 		if (index == ipst->ips_conn_drain_list_cnt)
28165 			index = 0;
28166 		ipst->ips_conn_drain_list_index = index;
28167 	}
28168 	mutex_exit(&connp->conn_lock);
28169 
28170 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28171 	if ((connp->conn_drain_prev != NULL) ||
28172 	    (connp->conn_state_flags & CONN_CLOSING)) {
28173 		/*
28174 		 * The conn is already in the drain list, OR
28175 		 * the conn is closing. We need to check again for
28176 		 * the closing case again since close can happen
28177 		 * after we drop the conn_lock, and before we
28178 		 * acquire the CONN_DRAIN_LIST_LOCK.
28179 		 */
28180 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28181 		return;
28182 	} else {
28183 		idl = connp->conn_idl;
28184 	}
28185 
28186 	/*
28187 	 * The conn is not in the drain list. Insert it at the
28188 	 * tail of the drain list. The drain list is circular
28189 	 * and doubly linked. idl_conn points to the 1st element
28190 	 * in the list.
28191 	 */
28192 	if (idl->idl_conn == NULL) {
28193 		idl->idl_conn = connp;
28194 		connp->conn_drain_next = connp;
28195 		connp->conn_drain_prev = connp;
28196 	} else {
28197 		conn_t *head = idl->idl_conn;
28198 
28199 		connp->conn_drain_next = head;
28200 		connp->conn_drain_prev = head->conn_drain_prev;
28201 		head->conn_drain_prev->conn_drain_next = connp;
28202 		head->conn_drain_prev = connp;
28203 	}
28204 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28205 }
28206 
28207 /*
28208  * This conn is closing, and we are called from ip_close. OR
28209  * This conn has been serviced by ip_wsrv, and we need to do the tail
28210  * processing.
28211  * If this conn is part of the drain list, we may need to sustain the drain
28212  * process by qenabling the next conn in the drain list. We may also need to
28213  * remove this conn from the list, if it is done.
28214  */
28215 static void
28216 conn_drain_tail(conn_t *connp, boolean_t closing)
28217 {
28218 	idl_t *idl;
28219 
28220 	/*
28221 	 * connp->conn_idl is stable at this point, and no lock is needed
28222 	 * to check it. If we are called from ip_close, close has already
28223 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28224 	 * called us only because conn_idl is non-null. If we are called thru
28225 	 * service, conn_idl could be null, but it cannot change because
28226 	 * service is single-threaded per queue, and there cannot be another
28227 	 * instance of service trying to call conn_drain_insert on this conn
28228 	 * now.
28229 	 */
28230 	ASSERT(!closing || (connp->conn_idl != NULL));
28231 
28232 	/*
28233 	 * If connp->conn_idl is null, the conn has not been inserted into any
28234 	 * drain list even once since creation of the conn. Just return.
28235 	 */
28236 	if (connp->conn_idl == NULL)
28237 		return;
28238 
28239 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28240 
28241 	if (connp->conn_drain_prev == NULL) {
28242 		/* This conn is currently not in the drain list.  */
28243 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28244 		return;
28245 	}
28246 	idl = connp->conn_idl;
28247 	if (idl->idl_conn_draining == connp) {
28248 		/*
28249 		 * This conn is the current drainer. If this is the last conn
28250 		 * in the drain list, we need to do more checks, in the 'if'
28251 		 * below. Otherwwise we need to just qenable the next conn,
28252 		 * to sustain the draining, and is handled in the 'else'
28253 		 * below.
28254 		 */
28255 		if (connp->conn_drain_next == idl->idl_conn) {
28256 			/*
28257 			 * This conn is the last in this list. This round
28258 			 * of draining is complete. If idl_repeat is set,
28259 			 * it means another flow enabling has happened from
28260 			 * the driver/streams and we need to another round
28261 			 * of draining.
28262 			 * If there are more than 2 conns in the drain list,
28263 			 * do a left rotate by 1, so that all conns except the
28264 			 * conn at the head move towards the head by 1, and the
28265 			 * the conn at the head goes to the tail. This attempts
28266 			 * a more even share for all queues that are being
28267 			 * drained.
28268 			 */
28269 			if ((connp->conn_drain_next != connp) &&
28270 			    (idl->idl_conn->conn_drain_next != connp)) {
28271 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28272 			}
28273 			if (idl->idl_repeat) {
28274 				qenable(idl->idl_conn->conn_wq);
28275 				idl->idl_conn_draining = idl->idl_conn;
28276 				idl->idl_repeat = 0;
28277 			} else {
28278 				idl->idl_conn_draining = NULL;
28279 			}
28280 		} else {
28281 			/*
28282 			 * If the next queue that we are now qenable'ing,
28283 			 * is closing, it will remove itself from this list
28284 			 * and qenable the subsequent queue in ip_close().
28285 			 * Serialization is acheived thru idl_lock.
28286 			 */
28287 			qenable(connp->conn_drain_next->conn_wq);
28288 			idl->idl_conn_draining = connp->conn_drain_next;
28289 		}
28290 	}
28291 	if (!connp->conn_did_putbq || closing) {
28292 		/*
28293 		 * Remove ourself from the drain list, if we did not do
28294 		 * a putbq, or if the conn is closing.
28295 		 * Note: It is possible that q->q_first is non-null. It means
28296 		 * that these messages landed after we did a enableok() in
28297 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28298 		 * service them.
28299 		 */
28300 		if (connp->conn_drain_next == connp) {
28301 			/* Singleton in the list */
28302 			ASSERT(connp->conn_drain_prev == connp);
28303 			idl->idl_conn = NULL;
28304 			idl->idl_conn_draining = NULL;
28305 		} else {
28306 			connp->conn_drain_prev->conn_drain_next =
28307 			    connp->conn_drain_next;
28308 			connp->conn_drain_next->conn_drain_prev =
28309 			    connp->conn_drain_prev;
28310 			if (idl->idl_conn == connp)
28311 				idl->idl_conn = connp->conn_drain_next;
28312 			ASSERT(idl->idl_conn_draining != connp);
28313 
28314 		}
28315 		connp->conn_drain_next = NULL;
28316 		connp->conn_drain_prev = NULL;
28317 	}
28318 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28319 }
28320 
28321 /*
28322  * Write service routine. Shared perimeter entry point.
28323  * ip_wsrv can be called in any of the following ways.
28324  * 1. The device queue's messages has fallen below the low water mark
28325  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28326  *    the drain lists and backenable the first conn in each list.
28327  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28328  *    qenabled non-tcp upper layers. We start dequeing messages and call
28329  *    ip_wput for each message.
28330  */
28331 
28332 void
28333 ip_wsrv(queue_t *q)
28334 {
28335 	conn_t	*connp;
28336 	ill_t	*ill;
28337 	mblk_t	*mp;
28338 
28339 	if (q->q_next) {
28340 		ill = (ill_t *)q->q_ptr;
28341 		if (ill->ill_state_flags == 0) {
28342 			/*
28343 			 * The device flow control has opened up.
28344 			 * Walk through conn drain lists and qenable the
28345 			 * first conn in each list. This makes sense only
28346 			 * if the stream is fully plumbed and setup.
28347 			 * Hence the if check above.
28348 			 */
28349 			ip1dbg(("ip_wsrv: walking\n"));
28350 			conn_walk_drain(ill->ill_ipst);
28351 		}
28352 		return;
28353 	}
28354 
28355 	connp = Q_TO_CONN(q);
28356 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28357 
28358 	/*
28359 	 * 1. Set conn_draining flag to signal that service is active.
28360 	 *
28361 	 * 2. ip_output determines whether it has been called from service,
28362 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28363 	 *    has been called from service.
28364 	 *
28365 	 * 3. Message ordering is preserved by the following logic.
28366 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28367 	 *    the message at the tail, if conn_draining is set (i.e. service
28368 	 *    is running) or if q->q_first is non-null.
28369 	 *
28370 	 *    ii. If ip_output is called from service, and if ip_output cannot
28371 	 *    putnext due to flow control, it does a putbq.
28372 	 *
28373 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28374 	 *    (causing an infinite loop).
28375 	 */
28376 	ASSERT(!connp->conn_did_putbq);
28377 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28378 		connp->conn_draining = 1;
28379 		noenable(q);
28380 		while ((mp = getq(q)) != NULL) {
28381 			ASSERT(CONN_Q(q));
28382 
28383 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28384 			if (connp->conn_did_putbq) {
28385 				/* ip_wput did a putbq */
28386 				break;
28387 			}
28388 		}
28389 		/*
28390 		 * At this point, a thread coming down from top, calling
28391 		 * ip_wput, may end up queueing the message. We have not yet
28392 		 * enabled the queue, so ip_wsrv won't be called again.
28393 		 * To avoid this race, check q->q_first again (in the loop)
28394 		 * If the other thread queued the message before we call
28395 		 * enableok(), we will catch it in the q->q_first check.
28396 		 * If the other thread queues the message after we call
28397 		 * enableok(), ip_wsrv will be called again by STREAMS.
28398 		 */
28399 		connp->conn_draining = 0;
28400 		enableok(q);
28401 	}
28402 
28403 	/* Enable the next conn for draining */
28404 	conn_drain_tail(connp, B_FALSE);
28405 
28406 	connp->conn_did_putbq = 0;
28407 }
28408 
28409 /*
28410  * Walk the list of all conn's calling the function provided with the
28411  * specified argument for each.	 Note that this only walks conn's that
28412  * have been bound.
28413  * Applies to both IPv4 and IPv6.
28414  */
28415 static void
28416 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28417 {
28418 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28419 	    ipst->ips_ipcl_udp_fanout_size,
28420 	    func, arg, zoneid);
28421 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28422 	    ipst->ips_ipcl_conn_fanout_size,
28423 	    func, arg, zoneid);
28424 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28425 	    ipst->ips_ipcl_bind_fanout_size,
28426 	    func, arg, zoneid);
28427 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28428 	    IPPROTO_MAX, func, arg, zoneid);
28429 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28430 	    IPPROTO_MAX, func, arg, zoneid);
28431 }
28432 
28433 /*
28434  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28435  * of conns that need to be drained, check if drain is already in progress.
28436  * If so set the idl_repeat bit, indicating that the last conn in the list
28437  * needs to reinitiate the drain once again, for the list. If drain is not
28438  * in progress for the list, initiate the draining, by qenabling the 1st
28439  * conn in the list. The drain is self-sustaining, each qenabled conn will
28440  * in turn qenable the next conn, when it is done/blocked/closing.
28441  */
28442 static void
28443 conn_walk_drain(ip_stack_t *ipst)
28444 {
28445 	int i;
28446 	idl_t *idl;
28447 
28448 	IP_STAT(ipst, ip_conn_walk_drain);
28449 
28450 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28451 		idl = &ipst->ips_conn_drain_list[i];
28452 		mutex_enter(&idl->idl_lock);
28453 		if (idl->idl_conn == NULL) {
28454 			mutex_exit(&idl->idl_lock);
28455 			continue;
28456 		}
28457 		/*
28458 		 * If this list is not being drained currently by
28459 		 * an ip_wsrv thread, start the process.
28460 		 */
28461 		if (idl->idl_conn_draining == NULL) {
28462 			ASSERT(idl->idl_repeat == 0);
28463 			qenable(idl->idl_conn->conn_wq);
28464 			idl->idl_conn_draining = idl->idl_conn;
28465 		} else {
28466 			idl->idl_repeat = 1;
28467 		}
28468 		mutex_exit(&idl->idl_lock);
28469 	}
28470 }
28471 
28472 /*
28473  * Walk an conn hash table of `count' buckets, calling func for each entry.
28474  */
28475 static void
28476 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28477     zoneid_t zoneid)
28478 {
28479 	conn_t	*connp;
28480 
28481 	while (count-- > 0) {
28482 		mutex_enter(&connfp->connf_lock);
28483 		for (connp = connfp->connf_head; connp != NULL;
28484 		    connp = connp->conn_next) {
28485 			if (zoneid == GLOBAL_ZONEID ||
28486 			    zoneid == connp->conn_zoneid) {
28487 				CONN_INC_REF(connp);
28488 				mutex_exit(&connfp->connf_lock);
28489 				(*func)(connp, arg);
28490 				mutex_enter(&connfp->connf_lock);
28491 				CONN_DEC_REF(connp);
28492 			}
28493 		}
28494 		mutex_exit(&connfp->connf_lock);
28495 		connfp++;
28496 	}
28497 }
28498 
28499 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28500 static void
28501 conn_report1(conn_t *connp, void *mp)
28502 {
28503 	char	buf1[INET6_ADDRSTRLEN];
28504 	char	buf2[INET6_ADDRSTRLEN];
28505 	uint_t	print_len, buf_len;
28506 
28507 	ASSERT(connp != NULL);
28508 
28509 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28510 	if (buf_len <= 0)
28511 		return;
28512 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28513 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28514 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28515 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28516 	    "%5d %s/%05d %s/%05d\n",
28517 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28518 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28519 	    buf1, connp->conn_lport,
28520 	    buf2, connp->conn_fport);
28521 	if (print_len < buf_len) {
28522 		((mblk_t *)mp)->b_wptr += print_len;
28523 	} else {
28524 		((mblk_t *)mp)->b_wptr += buf_len;
28525 	}
28526 }
28527 
28528 /*
28529  * Named Dispatch routine to produce a formatted report on all conns
28530  * that are listed in one of the fanout tables.
28531  * This report is accessed by using the ndd utility to "get" ND variable
28532  * "ip_conn_status".
28533  */
28534 /* ARGSUSED */
28535 static int
28536 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28537 {
28538 	conn_t *connp = Q_TO_CONN(q);
28539 
28540 	(void) mi_mpprintf(mp,
28541 	    "CONN      " MI_COL_HDRPAD_STR
28542 	    "rfq      " MI_COL_HDRPAD_STR
28543 	    "stq      " MI_COL_HDRPAD_STR
28544 	    " zone local                 remote");
28545 
28546 	/*
28547 	 * Because of the ndd constraint, at most we can have 64K buffer
28548 	 * to put in all conn info.  So to be more efficient, just
28549 	 * allocate a 64K buffer here, assuming we need that large buffer.
28550 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28551 	 */
28552 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28553 		/* The following may work even if we cannot get a large buf. */
28554 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28555 		return (0);
28556 	}
28557 
28558 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28559 	    connp->conn_netstack->netstack_ip);
28560 	return (0);
28561 }
28562 
28563 /*
28564  * Determine if the ill and multicast aspects of that packets
28565  * "matches" the conn.
28566  */
28567 boolean_t
28568 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28569     zoneid_t zoneid)
28570 {
28571 	ill_t *in_ill;
28572 	boolean_t found;
28573 	ipif_t *ipif;
28574 	ire_t *ire;
28575 	ipaddr_t dst, src;
28576 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28577 
28578 	dst = ipha->ipha_dst;
28579 	src = ipha->ipha_src;
28580 
28581 	/*
28582 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28583 	 * unicast, broadcast and multicast reception to
28584 	 * conn_incoming_ill. conn_wantpacket itself is called
28585 	 * only for BROADCAST and multicast.
28586 	 *
28587 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28588 	 *    is part of a group. Hence, we should be receiving
28589 	 *    just one copy of broadcast for the whole group.
28590 	 *    Thus, if it is part of the group the packet could
28591 	 *    come on any ill of the group and hence we need a
28592 	 *    match on the group. Otherwise, match on ill should
28593 	 *    be sufficient.
28594 	 *
28595 	 * 2) ip_rput does not suppress duplicate multicast packets.
28596 	 *    If there are two interfaces in a ill group and we have
28597 	 *    2 applications (conns) joined a multicast group G on
28598 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28599 	 *    will give us two packets because we join G on both the
28600 	 *    interfaces rather than nominating just one interface
28601 	 *    for receiving multicast like broadcast above. So,
28602 	 *    we have to call ilg_lookup_ill to filter out duplicate
28603 	 *    copies, if ill is part of a group.
28604 	 */
28605 	in_ill = connp->conn_incoming_ill;
28606 	if (in_ill != NULL) {
28607 		if (in_ill->ill_group == NULL) {
28608 			if (in_ill != ill)
28609 				return (B_FALSE);
28610 		} else if (in_ill->ill_group != ill->ill_group) {
28611 			return (B_FALSE);
28612 		}
28613 	}
28614 
28615 	if (!CLASSD(dst)) {
28616 		if (IPCL_ZONE_MATCH(connp, zoneid))
28617 			return (B_TRUE);
28618 		/*
28619 		 * The conn is in a different zone; we need to check that this
28620 		 * broadcast address is configured in the application's zone and
28621 		 * on one ill in the group.
28622 		 */
28623 		ipif = ipif_get_next_ipif(NULL, ill);
28624 		if (ipif == NULL)
28625 			return (B_FALSE);
28626 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28627 		    connp->conn_zoneid, NULL,
28628 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28629 		ipif_refrele(ipif);
28630 		if (ire != NULL) {
28631 			ire_refrele(ire);
28632 			return (B_TRUE);
28633 		} else {
28634 			return (B_FALSE);
28635 		}
28636 	}
28637 
28638 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28639 	    connp->conn_zoneid == zoneid) {
28640 		/*
28641 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28642 		 * disabled, therefore we don't dispatch the multicast packet to
28643 		 * the sending zone.
28644 		 */
28645 		return (B_FALSE);
28646 	}
28647 
28648 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28649 		/*
28650 		 * Multicast packet on the loopback interface: we only match
28651 		 * conns who joined the group in the specified zone.
28652 		 */
28653 		return (B_FALSE);
28654 	}
28655 
28656 	if (connp->conn_multi_router) {
28657 		/* multicast packet and multicast router socket: send up */
28658 		return (B_TRUE);
28659 	}
28660 
28661 	mutex_enter(&connp->conn_lock);
28662 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28663 	mutex_exit(&connp->conn_lock);
28664 	return (found);
28665 }
28666 
28667 /*
28668  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28669  */
28670 /* ARGSUSED */
28671 static void
28672 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28673 {
28674 	ill_t *ill = (ill_t *)q->q_ptr;
28675 	mblk_t	*mp1, *mp2;
28676 	ipif_t  *ipif;
28677 	int err = 0;
28678 	conn_t *connp = NULL;
28679 	ipsq_t	*ipsq;
28680 	arc_t	*arc;
28681 
28682 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28683 
28684 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28685 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28686 
28687 	ASSERT(IAM_WRITER_ILL(ill));
28688 	mp2 = mp->b_cont;
28689 	mp->b_cont = NULL;
28690 
28691 	/*
28692 	 * We have now received the arp bringup completion message
28693 	 * from ARP. Mark the arp bringup as done. Also if the arp
28694 	 * stream has already started closing, send up the AR_ARP_CLOSING
28695 	 * ack now since ARP is waiting in close for this ack.
28696 	 */
28697 	mutex_enter(&ill->ill_lock);
28698 	ill->ill_arp_bringup_pending = 0;
28699 	if (ill->ill_arp_closing) {
28700 		mutex_exit(&ill->ill_lock);
28701 		/* Let's reuse the mp for sending the ack */
28702 		arc = (arc_t *)mp->b_rptr;
28703 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28704 		arc->arc_cmd = AR_ARP_CLOSING;
28705 		qreply(q, mp);
28706 	} else {
28707 		mutex_exit(&ill->ill_lock);
28708 		freeb(mp);
28709 	}
28710 
28711 	ipsq = ill->ill_phyint->phyint_ipsq;
28712 	ipif = ipsq->ipsq_pending_ipif;
28713 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28714 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28715 	if (mp1 == NULL) {
28716 		/* bringup was aborted by the user */
28717 		freemsg(mp2);
28718 		return;
28719 	}
28720 
28721 	/*
28722 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28723 	 * must have an associated conn_t.  Otherwise, we're bringing this
28724 	 * interface back up as part of handling an asynchronous event (e.g.,
28725 	 * physical address change).
28726 	 */
28727 	if (ipsq->ipsq_current_ioctl != 0) {
28728 		ASSERT(connp != NULL);
28729 		q = CONNP_TO_WQ(connp);
28730 	} else {
28731 		ASSERT(connp == NULL);
28732 		q = ill->ill_rq;
28733 	}
28734 
28735 	/*
28736 	 * If the DL_BIND_REQ fails, it is noted
28737 	 * in arc_name_offset.
28738 	 */
28739 	err = *((int *)mp2->b_rptr);
28740 	if (err == 0) {
28741 		if (ipif->ipif_isv6) {
28742 			if ((err = ipif_up_done_v6(ipif)) != 0)
28743 				ip0dbg(("ip_arp_done: init failed\n"));
28744 		} else {
28745 			if ((err = ipif_up_done(ipif)) != 0)
28746 				ip0dbg(("ip_arp_done: init failed\n"));
28747 		}
28748 	} else {
28749 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28750 	}
28751 
28752 	freemsg(mp2);
28753 
28754 	if ((err == 0) && (ill->ill_up_ipifs)) {
28755 		err = ill_up_ipifs(ill, q, mp1);
28756 		if (err == EINPROGRESS)
28757 			return;
28758 	}
28759 
28760 	if (ill->ill_up_ipifs)
28761 		ill_group_cleanup(ill);
28762 
28763 	/*
28764 	 * The operation must complete without EINPROGRESS since
28765 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28766 	 * Otherwise, the operation will be stuck forever in the ipsq.
28767 	 */
28768 	ASSERT(err != EINPROGRESS);
28769 	if (ipsq->ipsq_current_ioctl != 0)
28770 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28771 	else
28772 		ipsq_current_finish(ipsq);
28773 }
28774 
28775 /* Allocate the private structure */
28776 static int
28777 ip_priv_alloc(void **bufp)
28778 {
28779 	void	*buf;
28780 
28781 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28782 		return (ENOMEM);
28783 
28784 	*bufp = buf;
28785 	return (0);
28786 }
28787 
28788 /* Function to delete the private structure */
28789 void
28790 ip_priv_free(void *buf)
28791 {
28792 	ASSERT(buf != NULL);
28793 	kmem_free(buf, sizeof (ip_priv_t));
28794 }
28795 
28796 /*
28797  * The entry point for IPPF processing.
28798  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28799  * routine just returns.
28800  *
28801  * When called, ip_process generates an ipp_packet_t structure
28802  * which holds the state information for this packet and invokes the
28803  * the classifier (via ipp_packet_process). The classification, depending on
28804  * configured filters, results in a list of actions for this packet. Invoking
28805  * an action may cause the packet to be dropped, in which case the resulting
28806  * mblk (*mpp) is NULL. proc indicates the callout position for
28807  * this packet and ill_index is the interface this packet on or will leave
28808  * on (inbound and outbound resp.).
28809  */
28810 void
28811 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28812 {
28813 	mblk_t		*mp;
28814 	ip_priv_t	*priv;
28815 	ipp_action_id_t	aid;
28816 	int		rc = 0;
28817 	ipp_packet_t	*pp;
28818 #define	IP_CLASS	"ip"
28819 
28820 	/* If the classifier is not loaded, return  */
28821 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28822 		return;
28823 	}
28824 
28825 	mp = *mpp;
28826 	ASSERT(mp != NULL);
28827 
28828 	/* Allocate the packet structure */
28829 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28830 	if (rc != 0) {
28831 		*mpp = NULL;
28832 		freemsg(mp);
28833 		return;
28834 	}
28835 
28836 	/* Allocate the private structure */
28837 	rc = ip_priv_alloc((void **)&priv);
28838 	if (rc != 0) {
28839 		*mpp = NULL;
28840 		freemsg(mp);
28841 		ipp_packet_free(pp);
28842 		return;
28843 	}
28844 	priv->proc = proc;
28845 	priv->ill_index = ill_index;
28846 	ipp_packet_set_private(pp, priv, ip_priv_free);
28847 	ipp_packet_set_data(pp, mp);
28848 
28849 	/* Invoke the classifier */
28850 	rc = ipp_packet_process(&pp);
28851 	if (pp != NULL) {
28852 		mp = ipp_packet_get_data(pp);
28853 		ipp_packet_free(pp);
28854 		if (rc != 0) {
28855 			freemsg(mp);
28856 			*mpp = NULL;
28857 		}
28858 	} else {
28859 		*mpp = NULL;
28860 	}
28861 #undef	IP_CLASS
28862 }
28863 
28864 /*
28865  * Propagate a multicast group membership operation (add/drop) on
28866  * all the interfaces crossed by the related multirt routes.
28867  * The call is considered successful if the operation succeeds
28868  * on at least one interface.
28869  */
28870 static int
28871 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28872     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28873     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28874     mblk_t *first_mp)
28875 {
28876 	ire_t		*ire_gw;
28877 	irb_t		*irb;
28878 	int		error = 0;
28879 	opt_restart_t	*or;
28880 	ip_stack_t	*ipst = ire->ire_ipst;
28881 
28882 	irb = ire->ire_bucket;
28883 	ASSERT(irb != NULL);
28884 
28885 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28886 
28887 	or = (opt_restart_t *)first_mp->b_rptr;
28888 	IRB_REFHOLD(irb);
28889 	for (; ire != NULL; ire = ire->ire_next) {
28890 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28891 			continue;
28892 		if (ire->ire_addr != group)
28893 			continue;
28894 
28895 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28896 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28897 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28898 		/* No resolver exists for the gateway; skip this ire. */
28899 		if (ire_gw == NULL)
28900 			continue;
28901 
28902 		/*
28903 		 * This function can return EINPROGRESS. If so the operation
28904 		 * will be restarted from ip_restart_optmgmt which will
28905 		 * call ip_opt_set and option processing will restart for
28906 		 * this option. So we may end up calling 'fn' more than once.
28907 		 * This requires that 'fn' is idempotent except for the
28908 		 * return value. The operation is considered a success if
28909 		 * it succeeds at least once on any one interface.
28910 		 */
28911 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28912 		    NULL, fmode, src, first_mp);
28913 		if (error == 0)
28914 			or->or_private = CGTP_MCAST_SUCCESS;
28915 
28916 		if (ip_debug > 0) {
28917 			ulong_t	off;
28918 			char	*ksym;
28919 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28920 			ip2dbg(("ip_multirt_apply_membership: "
28921 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28922 			    "error %d [success %u]\n",
28923 			    ksym ? ksym : "?",
28924 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28925 			    error, or->or_private));
28926 		}
28927 
28928 		ire_refrele(ire_gw);
28929 		if (error == EINPROGRESS) {
28930 			IRB_REFRELE(irb);
28931 			return (error);
28932 		}
28933 	}
28934 	IRB_REFRELE(irb);
28935 	/*
28936 	 * Consider the call as successful if we succeeded on at least
28937 	 * one interface. Otherwise, return the last encountered error.
28938 	 */
28939 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28940 }
28941 
28942 
28943 /*
28944  * Issue a warning regarding a route crossing an interface with an
28945  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28946  * amount of time is logged.
28947  */
28948 static void
28949 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28950 {
28951 	hrtime_t	current = gethrtime();
28952 	char		buf[INET_ADDRSTRLEN];
28953 	ip_stack_t	*ipst = ire->ire_ipst;
28954 
28955 	/* Convert interval in ms to hrtime in ns */
28956 	if (ipst->ips_multirt_bad_mtu_last_time +
28957 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28958 	    current) {
28959 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28960 		    "to %s, incorrect MTU %u (expected %u)\n",
28961 		    ip_dot_addr(ire->ire_addr, buf),
28962 		    ire->ire_max_frag, max_frag);
28963 
28964 		ipst->ips_multirt_bad_mtu_last_time = current;
28965 	}
28966 }
28967 
28968 
28969 /*
28970  * Get the CGTP (multirouting) filtering status.
28971  * If 0, the CGTP hooks are transparent.
28972  */
28973 /* ARGSUSED */
28974 static int
28975 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28976 {
28977 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28978 
28979 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28980 	return (0);
28981 }
28982 
28983 
28984 /*
28985  * Set the CGTP (multirouting) filtering status.
28986  * If the status is changed from active to transparent
28987  * or from transparent to active, forward the new status
28988  * to the filtering module (if loaded).
28989  */
28990 /* ARGSUSED */
28991 static int
28992 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28993     cred_t *ioc_cr)
28994 {
28995 	long		new_value;
28996 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28997 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28998 
28999 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29000 		return (EPERM);
29001 
29002 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29003 	    new_value < 0 || new_value > 1) {
29004 		return (EINVAL);
29005 	}
29006 
29007 	if ((!*ip_cgtp_filter_value) && new_value) {
29008 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29009 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29010 		    " (module not loaded)" : "");
29011 	}
29012 	if (*ip_cgtp_filter_value && (!new_value)) {
29013 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29014 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29015 		    " (module not loaded)" : "");
29016 	}
29017 
29018 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29019 		int	res;
29020 		netstackid_t stackid;
29021 
29022 		stackid = ipst->ips_netstack->netstack_stackid;
29023 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29024 		    new_value);
29025 		if (res)
29026 			return (res);
29027 	}
29028 
29029 	*ip_cgtp_filter_value = (boolean_t)new_value;
29030 
29031 	return (0);
29032 }
29033 
29034 
29035 /*
29036  * Return the expected CGTP hooks version number.
29037  */
29038 int
29039 ip_cgtp_filter_supported(void)
29040 {
29041 	return (ip_cgtp_filter_rev);
29042 }
29043 
29044 
29045 /*
29046  * CGTP hooks can be registered by invoking this function.
29047  * Checks that the version number matches.
29048  */
29049 int
29050 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29051 {
29052 	netstack_t *ns;
29053 	ip_stack_t *ipst;
29054 
29055 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29056 		return (ENOTSUP);
29057 
29058 	ns = netstack_find_by_stackid(stackid);
29059 	if (ns == NULL)
29060 		return (EINVAL);
29061 	ipst = ns->netstack_ip;
29062 	ASSERT(ipst != NULL);
29063 
29064 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29065 		netstack_rele(ns);
29066 		return (EALREADY);
29067 	}
29068 
29069 	ipst->ips_ip_cgtp_filter_ops = ops;
29070 	netstack_rele(ns);
29071 	return (0);
29072 }
29073 
29074 /*
29075  * CGTP hooks can be unregistered by invoking this function.
29076  * Returns ENXIO if there was no registration.
29077  * Returns EBUSY if the ndd variable has not been turned off.
29078  */
29079 int
29080 ip_cgtp_filter_unregister(netstackid_t stackid)
29081 {
29082 	netstack_t *ns;
29083 	ip_stack_t *ipst;
29084 
29085 	ns = netstack_find_by_stackid(stackid);
29086 	if (ns == NULL)
29087 		return (EINVAL);
29088 	ipst = ns->netstack_ip;
29089 	ASSERT(ipst != NULL);
29090 
29091 	if (ipst->ips_ip_cgtp_filter) {
29092 		netstack_rele(ns);
29093 		return (EBUSY);
29094 	}
29095 
29096 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29097 		netstack_rele(ns);
29098 		return (ENXIO);
29099 	}
29100 	ipst->ips_ip_cgtp_filter_ops = NULL;
29101 	netstack_rele(ns);
29102 	return (0);
29103 }
29104 
29105 /*
29106  * Check whether there is a CGTP filter registration.
29107  * Returns non-zero if there is a registration, otherwise returns zero.
29108  * Note: returns zero if bad stackid.
29109  */
29110 int
29111 ip_cgtp_filter_is_registered(netstackid_t stackid)
29112 {
29113 	netstack_t *ns;
29114 	ip_stack_t *ipst;
29115 	int ret;
29116 
29117 	ns = netstack_find_by_stackid(stackid);
29118 	if (ns == NULL)
29119 		return (0);
29120 	ipst = ns->netstack_ip;
29121 	ASSERT(ipst != NULL);
29122 
29123 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29124 		ret = 1;
29125 	else
29126 		ret = 0;
29127 
29128 	netstack_rele(ns);
29129 	return (ret);
29130 }
29131 
29132 static squeue_func_t
29133 ip_squeue_switch(int val)
29134 {
29135 	squeue_func_t rval = squeue_fill;
29136 
29137 	switch (val) {
29138 	case IP_SQUEUE_ENTER_NODRAIN:
29139 		rval = squeue_enter_nodrain;
29140 		break;
29141 	case IP_SQUEUE_ENTER:
29142 		rval = squeue_enter;
29143 		break;
29144 	default:
29145 		break;
29146 	}
29147 	return (rval);
29148 }
29149 
29150 /* ARGSUSED */
29151 static int
29152 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29153     caddr_t addr, cred_t *cr)
29154 {
29155 	int *v = (int *)addr;
29156 	long new_value;
29157 
29158 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29159 		return (EPERM);
29160 
29161 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29162 		return (EINVAL);
29163 
29164 	ip_input_proc = ip_squeue_switch(new_value);
29165 	*v = new_value;
29166 	return (0);
29167 }
29168 
29169 /*
29170  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29171  * ip_debug.
29172  */
29173 /* ARGSUSED */
29174 static int
29175 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29176     caddr_t addr, cred_t *cr)
29177 {
29178 	int *v = (int *)addr;
29179 	long new_value;
29180 
29181 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29182 		return (EPERM);
29183 
29184 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29185 		return (EINVAL);
29186 
29187 	*v = new_value;
29188 	return (0);
29189 }
29190 
29191 /*
29192  * Handle changes to ipmp_hook_emulation ndd variable.
29193  * Need to update phyint_hook_ifindex.
29194  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29195  */
29196 static void
29197 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29198 {
29199 	phyint_t *phyi;
29200 	phyint_t *phyi_tmp;
29201 	char *groupname;
29202 	int namelen;
29203 	ill_t	*ill;
29204 	boolean_t new_group;
29205 
29206 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29207 	/*
29208 	 * Group indicies are stored in the phyint - a common structure
29209 	 * to both IPv4 and IPv6.
29210 	 */
29211 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29212 	for (; phyi != NULL;
29213 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29214 	    phyi, AVL_AFTER)) {
29215 		/* Ignore the ones that do not have a group */
29216 		if (phyi->phyint_groupname_len == 0)
29217 			continue;
29218 
29219 		/*
29220 		 * Look for other phyint in group.
29221 		 * Clear name/namelen so the lookup doesn't find ourselves.
29222 		 */
29223 		namelen = phyi->phyint_groupname_len;
29224 		groupname = phyi->phyint_groupname;
29225 		phyi->phyint_groupname_len = 0;
29226 		phyi->phyint_groupname = NULL;
29227 
29228 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29229 		/* Restore */
29230 		phyi->phyint_groupname_len = namelen;
29231 		phyi->phyint_groupname = groupname;
29232 
29233 		new_group = B_FALSE;
29234 		if (ipst->ips_ipmp_hook_emulation) {
29235 			/*
29236 			 * If the group already exists and has already
29237 			 * been assigned a group ifindex, we use the existing
29238 			 * group_ifindex, otherwise we pick a new group_ifindex
29239 			 * here.
29240 			 */
29241 			if (phyi_tmp != NULL &&
29242 			    phyi_tmp->phyint_group_ifindex != 0) {
29243 				phyi->phyint_group_ifindex =
29244 				    phyi_tmp->phyint_group_ifindex;
29245 			} else {
29246 				/* XXX We need a recovery strategy here. */
29247 				if (!ip_assign_ifindex(
29248 				    &phyi->phyint_group_ifindex, ipst))
29249 					cmn_err(CE_PANIC,
29250 					    "ip_assign_ifindex() failed");
29251 				new_group = B_TRUE;
29252 			}
29253 		} else {
29254 			phyi->phyint_group_ifindex = 0;
29255 		}
29256 		if (ipst->ips_ipmp_hook_emulation)
29257 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29258 		else
29259 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29260 
29261 		/*
29262 		 * For IP Filter to find out the relationship between
29263 		 * names and interface indicies, we need to generate
29264 		 * a NE_PLUMB event when a new group can appear.
29265 		 * We always generate events when a new interface appears
29266 		 * (even when ipmp_hook_emulation is set) so there
29267 		 * is no need to generate NE_PLUMB events when
29268 		 * ipmp_hook_emulation is turned off.
29269 		 * And since it isn't critical for IP Filter to get
29270 		 * the NE_UNPLUMB events we skip those here.
29271 		 */
29272 		if (new_group) {
29273 			/*
29274 			 * First phyint in group - generate group PLUMB event.
29275 			 * Since we are not running inside the ipsq we do
29276 			 * the dispatch immediately.
29277 			 */
29278 			if (phyi->phyint_illv4 != NULL)
29279 				ill = phyi->phyint_illv4;
29280 			else
29281 				ill = phyi->phyint_illv6;
29282 
29283 			if (ill != NULL) {
29284 				mutex_enter(&ill->ill_lock);
29285 				ill_nic_info_plumb(ill, B_TRUE);
29286 				ill_nic_info_dispatch(ill);
29287 				mutex_exit(&ill->ill_lock);
29288 			}
29289 		}
29290 	}
29291 	rw_exit(&ipst->ips_ill_g_lock);
29292 }
29293 
29294 /* ARGSUSED */
29295 static int
29296 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29297     caddr_t addr, cred_t *cr)
29298 {
29299 	int *v = (int *)addr;
29300 	long new_value;
29301 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29302 
29303 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29304 		return (EINVAL);
29305 
29306 	if (*v != new_value) {
29307 		*v = new_value;
29308 		ipmp_hook_emulation_changed(ipst);
29309 	}
29310 	return (0);
29311 }
29312 
29313 static void *
29314 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29315 {
29316 	kstat_t *ksp;
29317 
29318 	ip_stat_t template = {
29319 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29320 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29321 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29322 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29323 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29324 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29325 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29326 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29327 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29328 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29329 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29330 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29331 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29332 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29333 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29334 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29335 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29336 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29337 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29338 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29339 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29340 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29341 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29342 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29343 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29344 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29345 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29346 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29347 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29348 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29349 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29350 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29351 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29352 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29353 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29354 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29355 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29356 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29357 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29358 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29359 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29360 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29361 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29362 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29363 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29364 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29365 	};
29366 
29367 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29368 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29369 	    KSTAT_FLAG_VIRTUAL, stackid);
29370 
29371 	if (ksp == NULL)
29372 		return (NULL);
29373 
29374 	bcopy(&template, ip_statisticsp, sizeof (template));
29375 	ksp->ks_data = (void *)ip_statisticsp;
29376 	ksp->ks_private = (void *)(uintptr_t)stackid;
29377 
29378 	kstat_install(ksp);
29379 	return (ksp);
29380 }
29381 
29382 static void
29383 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29384 {
29385 	if (ksp != NULL) {
29386 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29387 		kstat_delete_netstack(ksp, stackid);
29388 	}
29389 }
29390 
29391 static void *
29392 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29393 {
29394 	kstat_t	*ksp;
29395 
29396 	ip_named_kstat_t template = {
29397 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29398 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29399 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29400 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29401 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29402 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29403 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29404 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29405 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29406 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29407 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29408 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29409 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29410 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29411 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29412 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29413 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29414 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29415 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29416 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29417 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29418 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29419 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29420 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29421 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29422 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29423 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29424 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29425 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29426 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29427 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29428 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29429 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29430 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29431 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29432 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29433 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29434 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29435 	};
29436 
29437 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29438 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29439 	if (ksp == NULL || ksp->ks_data == NULL)
29440 		return (NULL);
29441 
29442 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29443 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29444 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29445 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29446 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29447 
29448 	template.netToMediaEntrySize.value.i32 =
29449 	    sizeof (mib2_ipNetToMediaEntry_t);
29450 
29451 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29452 
29453 	bcopy(&template, ksp->ks_data, sizeof (template));
29454 	ksp->ks_update = ip_kstat_update;
29455 	ksp->ks_private = (void *)(uintptr_t)stackid;
29456 
29457 	kstat_install(ksp);
29458 	return (ksp);
29459 }
29460 
29461 static void
29462 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29463 {
29464 	if (ksp != NULL) {
29465 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29466 		kstat_delete_netstack(ksp, stackid);
29467 	}
29468 }
29469 
29470 static int
29471 ip_kstat_update(kstat_t *kp, int rw)
29472 {
29473 	ip_named_kstat_t *ipkp;
29474 	mib2_ipIfStatsEntry_t ipmib;
29475 	ill_walk_context_t ctx;
29476 	ill_t *ill;
29477 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29478 	netstack_t	*ns;
29479 	ip_stack_t	*ipst;
29480 
29481 	if (kp == NULL || kp->ks_data == NULL)
29482 		return (EIO);
29483 
29484 	if (rw == KSTAT_WRITE)
29485 		return (EACCES);
29486 
29487 	ns = netstack_find_by_stackid(stackid);
29488 	if (ns == NULL)
29489 		return (-1);
29490 	ipst = ns->netstack_ip;
29491 	if (ipst == NULL) {
29492 		netstack_rele(ns);
29493 		return (-1);
29494 	}
29495 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29496 
29497 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29498 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29499 	ill = ILL_START_WALK_V4(&ctx, ipst);
29500 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29501 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29502 	rw_exit(&ipst->ips_ill_g_lock);
29503 
29504 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29505 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29506 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29507 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29508 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29509 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29510 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29511 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29512 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29513 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29514 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29515 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29516 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29517 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29518 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29519 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29520 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29521 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29522 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29523 
29524 	ipkp->routingDiscards.value.ui32 =	0;
29525 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29526 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29527 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29528 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29529 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29530 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29531 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29532 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29533 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29534 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29535 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29536 
29537 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29538 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29539 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29540 
29541 	netstack_rele(ns);
29542 
29543 	return (0);
29544 }
29545 
29546 static void *
29547 icmp_kstat_init(netstackid_t stackid)
29548 {
29549 	kstat_t	*ksp;
29550 
29551 	icmp_named_kstat_t template = {
29552 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29553 		{ "inErrors",		KSTAT_DATA_UINT32 },
29554 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29555 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29556 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29557 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29558 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29559 		{ "inEchos",		KSTAT_DATA_UINT32 },
29560 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29561 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29562 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29563 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29564 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29565 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29566 		{ "outErrors",		KSTAT_DATA_UINT32 },
29567 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29568 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29569 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29570 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29571 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29572 		{ "outEchos",		KSTAT_DATA_UINT32 },
29573 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29574 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29575 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29576 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29577 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29578 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29579 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29580 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29581 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29582 		{ "outDrops",		KSTAT_DATA_UINT32 },
29583 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29584 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29585 	};
29586 
29587 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29588 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29589 	if (ksp == NULL || ksp->ks_data == NULL)
29590 		return (NULL);
29591 
29592 	bcopy(&template, ksp->ks_data, sizeof (template));
29593 
29594 	ksp->ks_update = icmp_kstat_update;
29595 	ksp->ks_private = (void *)(uintptr_t)stackid;
29596 
29597 	kstat_install(ksp);
29598 	return (ksp);
29599 }
29600 
29601 static void
29602 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29603 {
29604 	if (ksp != NULL) {
29605 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29606 		kstat_delete_netstack(ksp, stackid);
29607 	}
29608 }
29609 
29610 static int
29611 icmp_kstat_update(kstat_t *kp, int rw)
29612 {
29613 	icmp_named_kstat_t *icmpkp;
29614 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29615 	netstack_t	*ns;
29616 	ip_stack_t	*ipst;
29617 
29618 	if ((kp == NULL) || (kp->ks_data == NULL))
29619 		return (EIO);
29620 
29621 	if (rw == KSTAT_WRITE)
29622 		return (EACCES);
29623 
29624 	ns = netstack_find_by_stackid(stackid);
29625 	if (ns == NULL)
29626 		return (-1);
29627 	ipst = ns->netstack_ip;
29628 	if (ipst == NULL) {
29629 		netstack_rele(ns);
29630 		return (-1);
29631 	}
29632 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29633 
29634 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29635 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29636 	icmpkp->inDestUnreachs.value.ui32 =
29637 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29638 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29639 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29640 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29641 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29642 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29643 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29644 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29645 	icmpkp->inTimestampReps.value.ui32 =
29646 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29647 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29648 	icmpkp->inAddrMaskReps.value.ui32 =
29649 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29650 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29651 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29652 	icmpkp->outDestUnreachs.value.ui32 =
29653 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29654 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29655 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29656 	icmpkp->outSrcQuenchs.value.ui32 =
29657 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29658 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29659 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29660 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29661 	icmpkp->outTimestamps.value.ui32 =
29662 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29663 	icmpkp->outTimestampReps.value.ui32 =
29664 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29665 	icmpkp->outAddrMasks.value.ui32 =
29666 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29667 	icmpkp->outAddrMaskReps.value.ui32 =
29668 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29669 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29670 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29671 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29672 	icmpkp->outFragNeeded.value.ui32 =
29673 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29674 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29675 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29676 	icmpkp->inBadRedirects.value.ui32 =
29677 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29678 
29679 	netstack_rele(ns);
29680 	return (0);
29681 }
29682 
29683 /*
29684  * This is the fanout function for raw socket opened for SCTP.  Note
29685  * that it is called after SCTP checks that there is no socket which
29686  * wants a packet.  Then before SCTP handles this out of the blue packet,
29687  * this function is called to see if there is any raw socket for SCTP.
29688  * If there is and it is bound to the correct address, the packet will
29689  * be sent to that socket.  Note that only one raw socket can be bound to
29690  * a port.  This is assured in ipcl_sctp_hash_insert();
29691  */
29692 void
29693 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29694     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29695     zoneid_t zoneid)
29696 {
29697 	conn_t		*connp;
29698 	queue_t		*rq;
29699 	mblk_t		*first_mp;
29700 	boolean_t	secure;
29701 	ip6_t		*ip6h;
29702 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29703 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29704 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29705 	boolean_t	sctp_csum_err = B_FALSE;
29706 
29707 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29708 		sctp_csum_err = B_TRUE;
29709 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29710 	}
29711 
29712 	first_mp = mp;
29713 	if (mctl_present) {
29714 		mp = first_mp->b_cont;
29715 		secure = ipsec_in_is_secure(first_mp);
29716 		ASSERT(mp != NULL);
29717 	} else {
29718 		secure = B_FALSE;
29719 	}
29720 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29721 
29722 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29723 	if (connp == NULL) {
29724 		/*
29725 		 * Although raw sctp is not summed, OOB chunks must be.
29726 		 * Drop the packet here if the sctp checksum failed.
29727 		 */
29728 		if (sctp_csum_err) {
29729 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29730 			freemsg(first_mp);
29731 			return;
29732 		}
29733 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29734 		return;
29735 	}
29736 	rq = connp->conn_rq;
29737 	if (!canputnext(rq)) {
29738 		CONN_DEC_REF(connp);
29739 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29740 		freemsg(first_mp);
29741 		return;
29742 	}
29743 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29744 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29745 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29746 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29747 		if (first_mp == NULL) {
29748 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29749 			CONN_DEC_REF(connp);
29750 			return;
29751 		}
29752 	}
29753 	/*
29754 	 * We probably should not send M_CTL message up to
29755 	 * raw socket.
29756 	 */
29757 	if (mctl_present)
29758 		freeb(first_mp);
29759 
29760 	/* Initiate IPPF processing here if needed. */
29761 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29762 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29763 		ip_process(IPP_LOCAL_IN, &mp,
29764 		    recv_ill->ill_phyint->phyint_ifindex);
29765 		if (mp == NULL) {
29766 			CONN_DEC_REF(connp);
29767 			return;
29768 		}
29769 	}
29770 
29771 	if (connp->conn_recvif || connp->conn_recvslla ||
29772 	    ((connp->conn_ip_recvpktinfo ||
29773 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29774 	    (flags & IP_FF_IPINFO))) {
29775 		int in_flags = 0;
29776 
29777 		/*
29778 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29779 		 * IPF_RECVIF.
29780 		 */
29781 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29782 			in_flags = IPF_RECVIF;
29783 		}
29784 		if (connp->conn_recvslla) {
29785 			in_flags |= IPF_RECVSLLA;
29786 		}
29787 		if (isv4) {
29788 			mp = ip_add_info(mp, recv_ill, in_flags,
29789 			    IPCL_ZONEID(connp), ipst);
29790 		} else {
29791 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29792 			if (mp == NULL) {
29793 				BUMP_MIB(recv_ill->ill_ip_mib,
29794 				    ipIfStatsInDiscards);
29795 				CONN_DEC_REF(connp);
29796 				return;
29797 			}
29798 		}
29799 	}
29800 
29801 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29802 	/*
29803 	 * We are sending the IPSEC_IN message also up. Refer
29804 	 * to comments above this function.
29805 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29806 	 */
29807 	(connp->conn_recv)(connp, mp, NULL);
29808 	CONN_DEC_REF(connp);
29809 }
29810 
29811 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29812 {									\
29813 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29814 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29815 }
29816 /*
29817  * This function should be called only if all packet processing
29818  * including fragmentation is complete. Callers of this function
29819  * must set mp->b_prev to one of these values:
29820  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29821  * prior to handing over the mp as first argument to this function.
29822  *
29823  * If the ire passed by caller is incomplete, this function
29824  * queues the packet and if necessary, sends ARP request and bails.
29825  * If the ire passed is fully resolved, we simply prepend
29826  * the link-layer header to the packet, do ipsec hw acceleration
29827  * work if necessary, and send the packet out on the wire.
29828  *
29829  * NOTE: IPsec will only call this function with fully resolved
29830  * ires if hw acceleration is involved.
29831  * TODO list :
29832  * 	a Handle M_MULTIDATA so that
29833  *	  tcp_multisend->tcp_multisend_data can
29834  *	  call ip_xmit_v4 directly
29835  *	b Handle post-ARP work for fragments so that
29836  *	  ip_wput_frag can call this function.
29837  */
29838 ipxmit_state_t
29839 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29840 {
29841 	nce_t		*arpce;
29842 	queue_t		*q;
29843 	int		ill_index;
29844 	mblk_t		*nxt_mp, *first_mp;
29845 	boolean_t	xmit_drop = B_FALSE;
29846 	ip_proc_t	proc;
29847 	ill_t		*out_ill;
29848 	int		pkt_len;
29849 
29850 	arpce = ire->ire_nce;
29851 	ASSERT(arpce != NULL);
29852 
29853 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29854 
29855 	mutex_enter(&arpce->nce_lock);
29856 	switch (arpce->nce_state) {
29857 	case ND_REACHABLE:
29858 		/* If there are other queued packets, queue this packet */
29859 		if (arpce->nce_qd_mp != NULL) {
29860 			if (mp != NULL)
29861 				nce_queue_mp_common(arpce, mp, B_FALSE);
29862 			mp = arpce->nce_qd_mp;
29863 		}
29864 		arpce->nce_qd_mp = NULL;
29865 		mutex_exit(&arpce->nce_lock);
29866 
29867 		/*
29868 		 * Flush the queue.  In the common case, where the
29869 		 * ARP is already resolved,  it will go through the
29870 		 * while loop only once.
29871 		 */
29872 		while (mp != NULL) {
29873 
29874 			nxt_mp = mp->b_next;
29875 			mp->b_next = NULL;
29876 			ASSERT(mp->b_datap->db_type != M_CTL);
29877 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29878 			/*
29879 			 * This info is needed for IPQOS to do COS marking
29880 			 * in ip_wput_attach_llhdr->ip_process.
29881 			 */
29882 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29883 			mp->b_prev = NULL;
29884 
29885 			/* set up ill index for outbound qos processing */
29886 			out_ill = ire_to_ill(ire);
29887 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29888 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29889 			    ill_index);
29890 			if (first_mp == NULL) {
29891 				xmit_drop = B_TRUE;
29892 				BUMP_MIB(out_ill->ill_ip_mib,
29893 				    ipIfStatsOutDiscards);
29894 				goto next_mp;
29895 			}
29896 			/* non-ipsec hw accel case */
29897 			if (io == NULL || !io->ipsec_out_accelerated) {
29898 				/* send it */
29899 				q = ire->ire_stq;
29900 				if (proc == IPP_FWD_OUT) {
29901 					UPDATE_IB_PKT_COUNT(ire);
29902 				} else {
29903 					UPDATE_OB_PKT_COUNT(ire);
29904 				}
29905 				ire->ire_last_used_time = lbolt;
29906 
29907 				if (flow_ctl_enabled || canputnext(q)) {
29908 					if (proc == IPP_FWD_OUT) {
29909 
29910 					BUMP_MIB(out_ill->ill_ip_mib,
29911 					    ipIfStatsHCOutForwDatagrams);
29912 
29913 					}
29914 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29915 					    pkt_len);
29916 
29917 					putnext(q, first_mp);
29918 				} else {
29919 					BUMP_MIB(out_ill->ill_ip_mib,
29920 					    ipIfStatsOutDiscards);
29921 					xmit_drop = B_TRUE;
29922 					freemsg(first_mp);
29923 				}
29924 			} else {
29925 				/*
29926 				 * Safety Pup says: make sure this
29927 				 *  is going to the right interface!
29928 				 */
29929 				ill_t *ill1 =
29930 				    (ill_t *)ire->ire_stq->q_ptr;
29931 				int ifindex =
29932 				    ill1->ill_phyint->phyint_ifindex;
29933 				if (ifindex !=
29934 				    io->ipsec_out_capab_ill_index) {
29935 					xmit_drop = B_TRUE;
29936 					freemsg(mp);
29937 				} else {
29938 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29939 					    pkt_len);
29940 					ipsec_hw_putnext(ire->ire_stq, mp);
29941 				}
29942 			}
29943 next_mp:
29944 			mp = nxt_mp;
29945 		} /* while (mp != NULL) */
29946 		if (xmit_drop)
29947 			return (SEND_FAILED);
29948 		else
29949 			return (SEND_PASSED);
29950 
29951 	case ND_INITIAL:
29952 	case ND_INCOMPLETE:
29953 
29954 		/*
29955 		 * While we do send off packets to dests that
29956 		 * use fully-resolved CGTP routes, we do not
29957 		 * handle unresolved CGTP routes.
29958 		 */
29959 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29960 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29961 
29962 		if (mp != NULL) {
29963 			/* queue the packet */
29964 			nce_queue_mp_common(arpce, mp, B_FALSE);
29965 		}
29966 
29967 		if (arpce->nce_state == ND_INCOMPLETE) {
29968 			mutex_exit(&arpce->nce_lock);
29969 			DTRACE_PROBE3(ip__xmit__incomplete,
29970 			    (ire_t *), ire, (mblk_t *), mp,
29971 			    (ipsec_out_t *), io);
29972 			return (LOOKUP_IN_PROGRESS);
29973 		}
29974 
29975 		arpce->nce_state = ND_INCOMPLETE;
29976 		mutex_exit(&arpce->nce_lock);
29977 		/*
29978 		 * Note that ire_add() (called from ire_forward())
29979 		 * holds a ref on the ire until ARP is completed.
29980 		 */
29981 
29982 		ire_arpresolve(ire, ire_to_ill(ire));
29983 		return (LOOKUP_IN_PROGRESS);
29984 	default:
29985 		ASSERT(0);
29986 		mutex_exit(&arpce->nce_lock);
29987 		return (LLHDR_RESLV_FAILED);
29988 	}
29989 }
29990 
29991 #undef	UPDATE_IP_MIB_OB_COUNTERS
29992 
29993 /*
29994  * Return B_TRUE if the buffers differ in length or content.
29995  * This is used for comparing extension header buffers.
29996  * Note that an extension header would be declared different
29997  * even if all that changed was the next header value in that header i.e.
29998  * what really changed is the next extension header.
29999  */
30000 boolean_t
30001 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30002     uint_t blen)
30003 {
30004 	if (!b_valid)
30005 		blen = 0;
30006 
30007 	if (alen != blen)
30008 		return (B_TRUE);
30009 	if (alen == 0)
30010 		return (B_FALSE);	/* Both zero length */
30011 	return (bcmp(abuf, bbuf, alen));
30012 }
30013 
30014 /*
30015  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30016  * Return B_FALSE if memory allocation fails - don't change any state!
30017  */
30018 boolean_t
30019 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30020     const void *src, uint_t srclen)
30021 {
30022 	void *dst;
30023 
30024 	if (!src_valid)
30025 		srclen = 0;
30026 
30027 	ASSERT(*dstlenp == 0);
30028 	if (src != NULL && srclen != 0) {
30029 		dst = mi_alloc(srclen, BPRI_MED);
30030 		if (dst == NULL)
30031 			return (B_FALSE);
30032 	} else {
30033 		dst = NULL;
30034 	}
30035 	if (*dstp != NULL)
30036 		mi_free(*dstp);
30037 	*dstp = dst;
30038 	*dstlenp = dst == NULL ? 0 : srclen;
30039 	return (B_TRUE);
30040 }
30041 
30042 /*
30043  * Replace what is in *dst, *dstlen with the source.
30044  * Assumes ip_allocbuf has already been called.
30045  */
30046 void
30047 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30048     const void *src, uint_t srclen)
30049 {
30050 	if (!src_valid)
30051 		srclen = 0;
30052 
30053 	ASSERT(*dstlenp == srclen);
30054 	if (src != NULL && srclen != 0)
30055 		bcopy(src, *dstp, srclen);
30056 }
30057 
30058 /*
30059  * Free the storage pointed to by the members of an ip6_pkt_t.
30060  */
30061 void
30062 ip6_pkt_free(ip6_pkt_t *ipp)
30063 {
30064 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30065 
30066 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30067 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30068 		ipp->ipp_hopopts = NULL;
30069 		ipp->ipp_hopoptslen = 0;
30070 	}
30071 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30072 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30073 		ipp->ipp_rtdstopts = NULL;
30074 		ipp->ipp_rtdstoptslen = 0;
30075 	}
30076 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30077 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30078 		ipp->ipp_dstopts = NULL;
30079 		ipp->ipp_dstoptslen = 0;
30080 	}
30081 	if (ipp->ipp_fields & IPPF_RTHDR) {
30082 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30083 		ipp->ipp_rthdr = NULL;
30084 		ipp->ipp_rthdrlen = 0;
30085 	}
30086 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30087 	    IPPF_RTHDR);
30088 }
30089