xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision bea83d026ee1bd1b2a2419e1d0232f107a5d7d9b)
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_type & IRE_BROADCAST) &&
4974 			    ((dst_ill->ill_group != NULL) ||
4975 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4976 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4977 				/*
4978 				 * If the destination is reachable via a
4979 				 * given gateway, the selected source address
4980 				 * should be in the same subnet as the gateway.
4981 				 * Otherwise, the destination is not reachable.
4982 				 *
4983 				 * If there are no interfaces on the same subnet
4984 				 * as the destination, ipif_select_source gives
4985 				 * first non-deprecated interface which might be
4986 				 * on a different subnet than the gateway.
4987 				 * This is not desirable. Hence pass the dst_ire
4988 				 * source address to ipif_select_source.
4989 				 * It is sure that the destination is reachable
4990 				 * with the dst_ire source address subnet.
4991 				 * So passing dst_ire source address to
4992 				 * ipif_select_source will make sure that the
4993 				 * selected source will be on the same subnet
4994 				 * as dst_ire source address.
4995 				 */
4996 				ipaddr_t saddr =
4997 				    dst_ire->ire_ipif->ipif_src_addr;
4998 				src_ipif = ipif_select_source(dst_ill,
4999 				    saddr, zoneid);
5000 				if (src_ipif != NULL) {
5001 					if (IS_VNI(src_ipif->ipif_ill)) {
5002 						/*
5003 						 * For VNI there is no
5004 						 * interface route
5005 						 */
5006 						src_addr =
5007 						    src_ipif->ipif_src_addr;
5008 					} else {
5009 						ipif_ire =
5010 						    ipif_to_ire(src_ipif);
5011 						if (ipif_ire != NULL) {
5012 							IRE_REFRELE(dst_ire);
5013 							dst_ire = ipif_ire;
5014 						}
5015 						src_addr =
5016 						    dst_ire->ire_src_addr;
5017 					}
5018 					ipif_refrele(src_ipif);
5019 				} else {
5020 					src_addr = dst_ire->ire_src_addr;
5021 				}
5022 			} else {
5023 				src_addr = dst_ire->ire_src_addr;
5024 			}
5025 		}
5026 	}
5027 
5028 	/*
5029 	 * We do ire_route_lookup() here (and not
5030 	 * interface lookup as we assert that
5031 	 * src_addr should only come from an
5032 	 * UP interface for hard binding.
5033 	 */
5034 	ASSERT(src_ire == NULL);
5035 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5036 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5037 	/* src_ire must be a local|loopback */
5038 	if (!IRE_IS_LOCAL(src_ire)) {
5039 		if (ip_debug > 2) {
5040 			pr_addr_dbg("ip_bind_connected: bad connected "
5041 			    "src %s\n", AF_INET, &src_addr);
5042 		}
5043 		error = EADDRNOTAVAIL;
5044 		goto bad_addr;
5045 	}
5046 
5047 	/*
5048 	 * If the source address is a loopback address, the
5049 	 * destination had best be local or multicast.
5050 	 * The transports that can't handle multicast will reject
5051 	 * those addresses.
5052 	 */
5053 	if (src_ire->ire_type == IRE_LOOPBACK &&
5054 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5055 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5056 		error = -1;
5057 		goto bad_addr;
5058 	}
5059 
5060 	/*
5061 	 * Allow setting new policies. For example, disconnects come
5062 	 * down as ipa_t bind. As we would have set conn_policy_cached
5063 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5064 	 * can change after the disconnect.
5065 	 */
5066 	connp->conn_policy_cached = B_FALSE;
5067 
5068 	/*
5069 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5070 	 * can handle their passed-in conn's.
5071 	 */
5072 
5073 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5074 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5075 	connp->conn_lport = lport;
5076 	connp->conn_fport = fport;
5077 	*src_addrp = src_addr;
5078 
5079 	ASSERT(!(ipsec_policy_set && ire_requested));
5080 	if (ire_requested) {
5081 		iulp_t *ulp_info = NULL;
5082 
5083 		/*
5084 		 * Note that sire will not be NULL if this is an off-link
5085 		 * connection and there is not cache for that dest yet.
5086 		 *
5087 		 * XXX Because of an existing bug, if there are multiple
5088 		 * default routes, the IRE returned now may not be the actual
5089 		 * default route used (default routes are chosen in a
5090 		 * round robin fashion).  So if the metrics for different
5091 		 * default routes are different, we may return the wrong
5092 		 * metrics.  This will not be a problem if the existing
5093 		 * bug is fixed.
5094 		 */
5095 		if (sire != NULL) {
5096 			ulp_info = &(sire->ire_uinfo);
5097 		}
5098 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5099 			error = -1;
5100 			goto bad_addr;
5101 		}
5102 	} else if (ipsec_policy_set) {
5103 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5104 			error = -1;
5105 			goto bad_addr;
5106 		}
5107 	}
5108 
5109 	/*
5110 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5111 	 * we'll cache that.  If we don't, we'll inherit global policy.
5112 	 *
5113 	 * We can't insert until the conn reflects the policy. Note that
5114 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5115 	 * connections where we don't have a policy. This is to prevent
5116 	 * global policy lookups in the inbound path.
5117 	 *
5118 	 * If we insert before we set conn_policy_cached,
5119 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5120 	 * because global policy cound be non-empty. We normally call
5121 	 * ipsec_check_policy() for conn_policy_cached connections only if
5122 	 * ipc_in_enforce_policy is set. But in this case,
5123 	 * conn_policy_cached can get set anytime since we made the
5124 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5125 	 * called, which will make the above assumption false.  Thus, we
5126 	 * need to insert after we set conn_policy_cached.
5127 	 */
5128 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5129 		goto bad_addr;
5130 
5131 	if (fanout_insert) {
5132 		/*
5133 		 * The addresses have been verified. Time to insert in
5134 		 * the correct fanout list.
5135 		 */
5136 		error = ipcl_conn_insert(connp, protocol, src_addr,
5137 		    dst_addr, connp->conn_ports);
5138 	}
5139 
5140 	if (error == 0) {
5141 		connp->conn_fully_bound = B_TRUE;
5142 		/*
5143 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5144 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5145 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5146 		 * ip_xxinfo_return(), which performs further checks
5147 		 * against them and upon success, returns the LSO/MDT info
5148 		 * mblk which we will attach to the bind acknowledgment.
5149 		 */
5150 		if (lso_dst_ire != NULL) {
5151 			mblk_t *lsoinfo_mp;
5152 
5153 			ASSERT(ill->ill_lso_capab != NULL);
5154 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5155 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5156 				linkb(mp, lsoinfo_mp);
5157 		} else if (md_dst_ire != NULL) {
5158 			mblk_t *mdinfo_mp;
5159 
5160 			ASSERT(ill->ill_mdt_capab != NULL);
5161 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5162 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5163 				linkb(mp, mdinfo_mp);
5164 		}
5165 	}
5166 bad_addr:
5167 	if (ipsec_policy_set) {
5168 		ASSERT(policy_mp == mp->b_cont);
5169 		ASSERT(policy_mp != NULL);
5170 		freeb(policy_mp);
5171 		/*
5172 		 * As of now assume that nothing else accompanies
5173 		 * IPSEC_POLICY_SET.
5174 		 */
5175 		mp->b_cont = NULL;
5176 	}
5177 	if (src_ire != NULL)
5178 		IRE_REFRELE(src_ire);
5179 	if (dst_ire != NULL)
5180 		IRE_REFRELE(dst_ire);
5181 	if (sire != NULL)
5182 		IRE_REFRELE(sire);
5183 	if (md_dst_ire != NULL)
5184 		IRE_REFRELE(md_dst_ire);
5185 	if (lso_dst_ire != NULL)
5186 		IRE_REFRELE(lso_dst_ire);
5187 	return (error);
5188 }
5189 
5190 /*
5191  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5192  * Prefers dst_ire over src_ire.
5193  */
5194 static boolean_t
5195 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5196 {
5197 	mblk_t	*mp1;
5198 	ire_t *ret_ire = NULL;
5199 
5200 	mp1 = mp->b_cont;
5201 	ASSERT(mp1 != NULL);
5202 
5203 	if (ire != NULL) {
5204 		/*
5205 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5206 		 * appended mblk. Its <upper protocol>'s
5207 		 * job to make sure there is room.
5208 		 */
5209 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5210 			return (0);
5211 
5212 		mp1->b_datap->db_type = IRE_DB_TYPE;
5213 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5214 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5215 		ret_ire = (ire_t *)mp1->b_rptr;
5216 		/*
5217 		 * Pass the latest setting of the ip_path_mtu_discovery and
5218 		 * copy the ulp info if any.
5219 		 */
5220 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5221 		    IPH_DF : 0;
5222 		if (ulp_info != NULL) {
5223 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5224 			    sizeof (iulp_t));
5225 		}
5226 		ret_ire->ire_mp = mp1;
5227 	} else {
5228 		/*
5229 		 * No IRE was found. Remove IRE mblk.
5230 		 */
5231 		mp->b_cont = mp1->b_cont;
5232 		freeb(mp1);
5233 	}
5234 
5235 	return (1);
5236 }
5237 
5238 /*
5239  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5240  * the final piece where we don't.  Return a pointer to the first mblk in the
5241  * result, and update the pointer to the next mblk to chew on.  If anything
5242  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5243  * NULL pointer.
5244  */
5245 mblk_t *
5246 ip_carve_mp(mblk_t **mpp, ssize_t len)
5247 {
5248 	mblk_t	*mp0;
5249 	mblk_t	*mp1;
5250 	mblk_t	*mp2;
5251 
5252 	if (!len || !mpp || !(mp0 = *mpp))
5253 		return (NULL);
5254 	/* If we aren't going to consume the first mblk, we need a dup. */
5255 	if (mp0->b_wptr - mp0->b_rptr > len) {
5256 		mp1 = dupb(mp0);
5257 		if (mp1) {
5258 			/* Partition the data between the two mblks. */
5259 			mp1->b_wptr = mp1->b_rptr + len;
5260 			mp0->b_rptr = mp1->b_wptr;
5261 			/*
5262 			 * after adjustments if mblk not consumed is now
5263 			 * unaligned, try to align it. If this fails free
5264 			 * all messages and let upper layer recover.
5265 			 */
5266 			if (!OK_32PTR(mp0->b_rptr)) {
5267 				if (!pullupmsg(mp0, -1)) {
5268 					freemsg(mp0);
5269 					freemsg(mp1);
5270 					*mpp = NULL;
5271 					return (NULL);
5272 				}
5273 			}
5274 		}
5275 		return (mp1);
5276 	}
5277 	/* Eat through as many mblks as we need to get len bytes. */
5278 	len -= mp0->b_wptr - mp0->b_rptr;
5279 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5280 		if (mp2->b_wptr - mp2->b_rptr > len) {
5281 			/*
5282 			 * We won't consume the entire last mblk.  Like
5283 			 * above, dup and partition it.
5284 			 */
5285 			mp1->b_cont = dupb(mp2);
5286 			mp1 = mp1->b_cont;
5287 			if (!mp1) {
5288 				/*
5289 				 * Trouble.  Rather than go to a lot of
5290 				 * trouble to clean up, we free the messages.
5291 				 * This won't be any worse than losing it on
5292 				 * the wire.
5293 				 */
5294 				freemsg(mp0);
5295 				freemsg(mp2);
5296 				*mpp = NULL;
5297 				return (NULL);
5298 			}
5299 			mp1->b_wptr = mp1->b_rptr + len;
5300 			mp2->b_rptr = mp1->b_wptr;
5301 			/*
5302 			 * after adjustments if mblk not consumed is now
5303 			 * unaligned, try to align it. If this fails free
5304 			 * all messages and let upper layer recover.
5305 			 */
5306 			if (!OK_32PTR(mp2->b_rptr)) {
5307 				if (!pullupmsg(mp2, -1)) {
5308 					freemsg(mp0);
5309 					freemsg(mp2);
5310 					*mpp = NULL;
5311 					return (NULL);
5312 				}
5313 			}
5314 			*mpp = mp2;
5315 			return (mp0);
5316 		}
5317 		/* Decrement len by the amount we just got. */
5318 		len -= mp2->b_wptr - mp2->b_rptr;
5319 	}
5320 	/*
5321 	 * len should be reduced to zero now.  If not our caller has
5322 	 * screwed up.
5323 	 */
5324 	if (len) {
5325 		/* Shouldn't happen! */
5326 		freemsg(mp0);
5327 		*mpp = NULL;
5328 		return (NULL);
5329 	}
5330 	/*
5331 	 * We consumed up to exactly the end of an mblk.  Detach the part
5332 	 * we are returning from the rest of the chain.
5333 	 */
5334 	mp1->b_cont = NULL;
5335 	*mpp = mp2;
5336 	return (mp0);
5337 }
5338 
5339 /* The ill stream is being unplumbed. Called from ip_close */
5340 int
5341 ip_modclose(ill_t *ill)
5342 {
5343 	boolean_t success;
5344 	ipsq_t	*ipsq;
5345 	ipif_t	*ipif;
5346 	queue_t	*q = ill->ill_rq;
5347 	ip_stack_t	*ipst = ill->ill_ipst;
5348 	clock_t timeout;
5349 
5350 	/*
5351 	 * Wait for the ACKs of all deferred control messages to be processed.
5352 	 * In particular, we wait for a potential capability reset initiated
5353 	 * in ip_sioctl_plink() to complete before proceeding.
5354 	 *
5355 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5356 	 * in case the driver never replies.
5357 	 */
5358 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5359 	mutex_enter(&ill->ill_lock);
5360 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5361 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5362 			/* Timeout */
5363 			break;
5364 		}
5365 	}
5366 	mutex_exit(&ill->ill_lock);
5367 
5368 	/*
5369 	 * Forcibly enter the ipsq after some delay. This is to take
5370 	 * care of the case when some ioctl does not complete because
5371 	 * we sent a control message to the driver and it did not
5372 	 * send us a reply. We want to be able to at least unplumb
5373 	 * and replumb rather than force the user to reboot the system.
5374 	 */
5375 	success = ipsq_enter(ill, B_FALSE);
5376 
5377 	/*
5378 	 * Open/close/push/pop is guaranteed to be single threaded
5379 	 * per stream by STREAMS. FS guarantees that all references
5380 	 * from top are gone before close is called. So there can't
5381 	 * be another close thread that has set CONDEMNED on this ill.
5382 	 * and cause ipsq_enter to return failure.
5383 	 */
5384 	ASSERT(success);
5385 	ipsq = ill->ill_phyint->phyint_ipsq;
5386 
5387 	/*
5388 	 * Mark it condemned. No new reference will be made to this ill.
5389 	 * Lookup functions will return an error. Threads that try to
5390 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5391 	 * that the refcnt will drop down to zero.
5392 	 */
5393 	mutex_enter(&ill->ill_lock);
5394 	ill->ill_state_flags |= ILL_CONDEMNED;
5395 	for (ipif = ill->ill_ipif; ipif != NULL;
5396 	    ipif = ipif->ipif_next) {
5397 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5398 	}
5399 	/*
5400 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5401 	 * returns  error if ILL_CONDEMNED is set
5402 	 */
5403 	cv_broadcast(&ill->ill_cv);
5404 	mutex_exit(&ill->ill_lock);
5405 
5406 	/*
5407 	 * Send all the deferred DLPI messages downstream which came in
5408 	 * during the small window right before ipsq_enter(). We do this
5409 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5410 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5411 	 */
5412 	ill_dlpi_send_deferred(ill);
5413 
5414 	/*
5415 	 * Shut down fragmentation reassembly.
5416 	 * ill_frag_timer won't start a timer again.
5417 	 * Now cancel any existing timer
5418 	 */
5419 	(void) untimeout(ill->ill_frag_timer_id);
5420 	(void) ill_frag_timeout(ill, 0);
5421 
5422 	/*
5423 	 * If MOVE was in progress, clear the
5424 	 * move_in_progress fields also.
5425 	 */
5426 	if (ill->ill_move_in_progress) {
5427 		ILL_CLEAR_MOVE(ill);
5428 	}
5429 
5430 	/*
5431 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5432 	 * this ill. Then wait for the refcnts to drop to zero.
5433 	 * ill_is_quiescent checks whether the ill is really quiescent.
5434 	 * Then make sure that threads that are waiting to enter the
5435 	 * ipsq have seen the error returned by ipsq_enter and have
5436 	 * gone away. Then we call ill_delete_tail which does the
5437 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5438 	 */
5439 	ill_delete(ill);
5440 	mutex_enter(&ill->ill_lock);
5441 	while (!ill_is_quiescent(ill))
5442 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5443 	while (ill->ill_waiters)
5444 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5445 
5446 	mutex_exit(&ill->ill_lock);
5447 
5448 	/*
5449 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5450 	 * it held until the end of the function since the cleanup
5451 	 * below needs to be able to use the ip_stack_t.
5452 	 */
5453 	netstack_hold(ipst->ips_netstack);
5454 
5455 	/* qprocsoff is called in ill_delete_tail */
5456 	ill_delete_tail(ill);
5457 	ASSERT(ill->ill_ipst == NULL);
5458 
5459 	/*
5460 	 * Walk through all upper (conn) streams and qenable
5461 	 * those that have queued data.
5462 	 * close synchronization needs this to
5463 	 * be done to ensure that all upper layers blocked
5464 	 * due to flow control to the closing device
5465 	 * get unblocked.
5466 	 */
5467 	ip1dbg(("ip_wsrv: walking\n"));
5468 	conn_walk_drain(ipst);
5469 
5470 	mutex_enter(&ipst->ips_ip_mi_lock);
5471 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5472 	mutex_exit(&ipst->ips_ip_mi_lock);
5473 
5474 	/*
5475 	 * credp could be null if the open didn't succeed and ip_modopen
5476 	 * itself calls ip_close.
5477 	 */
5478 	if (ill->ill_credp != NULL)
5479 		crfree(ill->ill_credp);
5480 
5481 	mutex_enter(&ill->ill_lock);
5482 	ill_nic_info_dispatch(ill);
5483 	mutex_exit(&ill->ill_lock);
5484 
5485 	/*
5486 	 * Now we are done with the module close pieces that
5487 	 * need the netstack_t.
5488 	 */
5489 	netstack_rele(ipst->ips_netstack);
5490 
5491 	mi_close_free((IDP)ill);
5492 	q->q_ptr = WR(q)->q_ptr = NULL;
5493 
5494 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5495 
5496 	return (0);
5497 }
5498 
5499 /*
5500  * This is called as part of close() for IP, UDP, ICMP, and RTS
5501  * in order to quiesce the conn.
5502  */
5503 void
5504 ip_quiesce_conn(conn_t *connp)
5505 {
5506 	boolean_t	drain_cleanup_reqd = B_FALSE;
5507 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5508 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5509 	ip_stack_t	*ipst;
5510 
5511 	ASSERT(!IPCL_IS_TCP(connp));
5512 	ipst = connp->conn_netstack->netstack_ip;
5513 
5514 	/*
5515 	 * Mark the conn as closing, and this conn must not be
5516 	 * inserted in future into any list. Eg. conn_drain_insert(),
5517 	 * won't insert this conn into the conn_drain_list.
5518 	 * Similarly ill_pending_mp_add() will not add any mp to
5519 	 * the pending mp list, after this conn has started closing.
5520 	 *
5521 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5522 	 * cannot get set henceforth.
5523 	 */
5524 	mutex_enter(&connp->conn_lock);
5525 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5526 	connp->conn_state_flags |= CONN_CLOSING;
5527 	if (connp->conn_idl != NULL)
5528 		drain_cleanup_reqd = B_TRUE;
5529 	if (connp->conn_oper_pending_ill != NULL)
5530 		conn_ioctl_cleanup_reqd = B_TRUE;
5531 	if (connp->conn_dhcpinit_ill != NULL) {
5532 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5533 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5534 		connp->conn_dhcpinit_ill = NULL;
5535 	}
5536 	if (connp->conn_ilg_inuse != 0)
5537 		ilg_cleanup_reqd = B_TRUE;
5538 	mutex_exit(&connp->conn_lock);
5539 
5540 	if (conn_ioctl_cleanup_reqd)
5541 		conn_ioctl_cleanup(connp);
5542 
5543 	if (is_system_labeled() && connp->conn_anon_port) {
5544 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5545 		    connp->conn_mlp_type, connp->conn_ulp,
5546 		    ntohs(connp->conn_lport), B_FALSE);
5547 		connp->conn_anon_port = 0;
5548 	}
5549 	connp->conn_mlp_type = mlptSingle;
5550 
5551 	/*
5552 	 * Remove this conn from any fanout list it is on.
5553 	 * and then wait for any threads currently operating
5554 	 * on this endpoint to finish
5555 	 */
5556 	ipcl_hash_remove(connp);
5557 
5558 	/*
5559 	 * Remove this conn from the drain list, and do
5560 	 * any other cleanup that may be required.
5561 	 * (Only non-tcp streams may have a non-null conn_idl.
5562 	 * TCP streams are never flow controlled, and
5563 	 * conn_idl will be null)
5564 	 */
5565 	if (drain_cleanup_reqd)
5566 		conn_drain_tail(connp, B_TRUE);
5567 
5568 	if (connp == ipst->ips_ip_g_mrouter)
5569 		(void) ip_mrouter_done(NULL, ipst);
5570 
5571 	if (ilg_cleanup_reqd)
5572 		ilg_delete_all(connp);
5573 
5574 	conn_delete_ire(connp, NULL);
5575 
5576 	/*
5577 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5578 	 * callers from write side can't be there now because close
5579 	 * is in progress. The only other caller is ipcl_walk
5580 	 * which checks for the condemned flag.
5581 	 */
5582 	mutex_enter(&connp->conn_lock);
5583 	connp->conn_state_flags |= CONN_CONDEMNED;
5584 	while (connp->conn_ref != 1)
5585 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5586 	connp->conn_state_flags |= CONN_QUIESCED;
5587 	mutex_exit(&connp->conn_lock);
5588 }
5589 
5590 /* ARGSUSED */
5591 int
5592 ip_close(queue_t *q, int flags)
5593 {
5594 	conn_t		*connp;
5595 
5596 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5597 
5598 	/*
5599 	 * Call the appropriate delete routine depending on whether this is
5600 	 * a module or device.
5601 	 */
5602 	if (WR(q)->q_next != NULL) {
5603 		/* This is a module close */
5604 		return (ip_modclose((ill_t *)q->q_ptr));
5605 	}
5606 
5607 	connp = q->q_ptr;
5608 	ip_quiesce_conn(connp);
5609 
5610 	qprocsoff(q);
5611 
5612 	/*
5613 	 * Now we are truly single threaded on this stream, and can
5614 	 * delete the things hanging off the connp, and finally the connp.
5615 	 * We removed this connp from the fanout list, it cannot be
5616 	 * accessed thru the fanouts, and we already waited for the
5617 	 * conn_ref to drop to 0. We are already in close, so
5618 	 * there cannot be any other thread from the top. qprocsoff
5619 	 * has completed, and service has completed or won't run in
5620 	 * future.
5621 	 */
5622 	ASSERT(connp->conn_ref == 1);
5623 
5624 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5625 
5626 	connp->conn_ref--;
5627 	ipcl_conn_destroy(connp);
5628 
5629 	q->q_ptr = WR(q)->q_ptr = NULL;
5630 	return (0);
5631 }
5632 
5633 /*
5634  * Wapper around putnext() so that ip_rts_request can merely use
5635  * conn_recv.
5636  */
5637 /*ARGSUSED2*/
5638 static void
5639 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5640 {
5641 	conn_t *connp = (conn_t *)arg1;
5642 
5643 	putnext(connp->conn_rq, mp);
5644 }
5645 
5646 /* Return the IP checksum for the IP header at "iph". */
5647 uint16_t
5648 ip_csum_hdr(ipha_t *ipha)
5649 {
5650 	uint16_t	*uph;
5651 	uint32_t	sum;
5652 	int		opt_len;
5653 
5654 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5655 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5656 	uph = (uint16_t *)ipha;
5657 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5658 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5659 	if (opt_len > 0) {
5660 		do {
5661 			sum += uph[10];
5662 			sum += uph[11];
5663 			uph += 2;
5664 		} while (--opt_len);
5665 	}
5666 	sum = (sum & 0xFFFF) + (sum >> 16);
5667 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5668 	if (sum == 0xffff)
5669 		sum = 0;
5670 	return ((uint16_t)sum);
5671 }
5672 
5673 /*
5674  * Called when the module is about to be unloaded
5675  */
5676 void
5677 ip_ddi_destroy(void)
5678 {
5679 	tnet_fini();
5680 
5681 	icmp_ddi_destroy();
5682 	rts_ddi_destroy();
5683 	udp_ddi_destroy();
5684 	sctp_ddi_g_destroy();
5685 	tcp_ddi_g_destroy();
5686 	ipsec_policy_g_destroy();
5687 	ipcl_g_destroy();
5688 	ip_net_g_destroy();
5689 	ip_ire_g_fini();
5690 	inet_minor_destroy(ip_minor_arena_sa);
5691 #if defined(_LP64)
5692 	inet_minor_destroy(ip_minor_arena_la);
5693 #endif
5694 
5695 #ifdef DEBUG
5696 	list_destroy(&ip_thread_list);
5697 	rw_destroy(&ip_thread_rwlock);
5698 	tsd_destroy(&ip_thread_data);
5699 #endif
5700 
5701 	netstack_unregister(NS_IP);
5702 }
5703 
5704 /*
5705  * First step in cleanup.
5706  */
5707 /* ARGSUSED */
5708 static void
5709 ip_stack_shutdown(netstackid_t stackid, void *arg)
5710 {
5711 	ip_stack_t *ipst = (ip_stack_t *)arg;
5712 
5713 #ifdef NS_DEBUG
5714 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5715 #endif
5716 
5717 	/* Get rid of loopback interfaces and their IREs */
5718 	ip_loopback_cleanup(ipst);
5719 }
5720 
5721 /*
5722  * Free the IP stack instance.
5723  */
5724 static void
5725 ip_stack_fini(netstackid_t stackid, void *arg)
5726 {
5727 	ip_stack_t *ipst = (ip_stack_t *)arg;
5728 	int ret;
5729 
5730 #ifdef NS_DEBUG
5731 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5732 #endif
5733 	ipv4_hook_destroy(ipst);
5734 	ipv6_hook_destroy(ipst);
5735 	ip_net_destroy(ipst);
5736 
5737 	rw_destroy(&ipst->ips_srcid_lock);
5738 
5739 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5740 	ipst->ips_ip_mibkp = NULL;
5741 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5742 	ipst->ips_icmp_mibkp = NULL;
5743 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5744 	ipst->ips_ip_kstat = NULL;
5745 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5746 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5747 	ipst->ips_ip6_kstat = NULL;
5748 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5749 
5750 	nd_free(&ipst->ips_ip_g_nd);
5751 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5752 	ipst->ips_param_arr = NULL;
5753 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5754 	ipst->ips_ndp_arr = NULL;
5755 
5756 	ip_mrouter_stack_destroy(ipst);
5757 
5758 	mutex_destroy(&ipst->ips_ip_mi_lock);
5759 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5760 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5761 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5762 
5763 	ret = untimeout(ipst->ips_igmp_timeout_id);
5764 	if (ret == -1) {
5765 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5766 	} else {
5767 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5768 		ipst->ips_igmp_timeout_id = 0;
5769 	}
5770 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5771 	if (ret == -1) {
5772 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5773 	} else {
5774 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5775 		ipst->ips_igmp_slowtimeout_id = 0;
5776 	}
5777 	ret = untimeout(ipst->ips_mld_timeout_id);
5778 	if (ret == -1) {
5779 		ASSERT(ipst->ips_mld_timeout_id == 0);
5780 	} else {
5781 		ASSERT(ipst->ips_mld_timeout_id != 0);
5782 		ipst->ips_mld_timeout_id = 0;
5783 	}
5784 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5785 	if (ret == -1) {
5786 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5787 	} else {
5788 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5789 		ipst->ips_mld_slowtimeout_id = 0;
5790 	}
5791 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5792 	if (ret == -1) {
5793 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5794 	} else {
5795 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5796 		ipst->ips_ip_ire_expire_id = 0;
5797 	}
5798 
5799 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5800 	mutex_destroy(&ipst->ips_mld_timer_lock);
5801 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5802 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5803 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5804 	rw_destroy(&ipst->ips_ill_g_lock);
5805 
5806 	ip_ire_fini(ipst);
5807 	ip6_asp_free(ipst);
5808 	conn_drain_fini(ipst);
5809 	ipcl_destroy(ipst);
5810 
5811 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5812 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5813 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5814 	ipst->ips_ndp4 = NULL;
5815 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5816 	ipst->ips_ndp6 = NULL;
5817 
5818 	if (ipst->ips_loopback_ksp != NULL) {
5819 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5820 		ipst->ips_loopback_ksp = NULL;
5821 	}
5822 
5823 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5824 	ipst->ips_phyint_g_list = NULL;
5825 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5826 	ipst->ips_ill_g_heads = NULL;
5827 
5828 	kmem_free(ipst, sizeof (*ipst));
5829 }
5830 
5831 /*
5832  * This function is called from the TSD destructor, and is used to debug
5833  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5834  * details.
5835  */
5836 static void
5837 ip_thread_exit(void *phash)
5838 {
5839 	th_hash_t *thh = phash;
5840 
5841 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5842 	list_remove(&ip_thread_list, thh);
5843 	rw_exit(&ip_thread_rwlock);
5844 	mod_hash_destroy_hash(thh->thh_hash);
5845 	kmem_free(thh, sizeof (*thh));
5846 }
5847 
5848 /*
5849  * Called when the IP kernel module is loaded into the kernel
5850  */
5851 void
5852 ip_ddi_init(void)
5853 {
5854 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5855 
5856 	/*
5857 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5858 	 * initial devices: ip, ip6, tcp, tcp6.
5859 	 */
5860 	/*
5861 	 * If this is a 64-bit kernel, then create two separate arenas -
5862 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5863 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5864 	 */
5865 	ip_minor_arena_la = NULL;
5866 	ip_minor_arena_sa = NULL;
5867 #if defined(_LP64)
5868 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5869 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5870 		cmn_err(CE_PANIC,
5871 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5872 	}
5873 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5874 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5875 		cmn_err(CE_PANIC,
5876 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5877 	}
5878 #else
5879 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5880 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5881 		cmn_err(CE_PANIC,
5882 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5883 	}
5884 #endif
5885 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5886 
5887 	ipcl_g_init();
5888 	ip_ire_g_init();
5889 	ip_net_g_init();
5890 
5891 #ifdef DEBUG
5892 	tsd_create(&ip_thread_data, ip_thread_exit);
5893 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5894 	list_create(&ip_thread_list, sizeof (th_hash_t),
5895 	    offsetof(th_hash_t, thh_link));
5896 #endif
5897 
5898 	/*
5899 	 * We want to be informed each time a stack is created or
5900 	 * destroyed in the kernel, so we can maintain the
5901 	 * set of udp_stack_t's.
5902 	 */
5903 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5904 	    ip_stack_fini);
5905 
5906 	ipsec_policy_g_init();
5907 	tcp_ddi_g_init();
5908 	sctp_ddi_g_init();
5909 
5910 	tnet_init();
5911 
5912 	udp_ddi_init();
5913 	rts_ddi_init();
5914 	icmp_ddi_init();
5915 }
5916 
5917 /*
5918  * Initialize the IP stack instance.
5919  */
5920 static void *
5921 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5922 {
5923 	ip_stack_t	*ipst;
5924 	ipparam_t	*pa;
5925 	ipndp_t		*na;
5926 
5927 #ifdef NS_DEBUG
5928 	printf("ip_stack_init(stack %d)\n", stackid);
5929 #endif
5930 
5931 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5932 	ipst->ips_netstack = ns;
5933 
5934 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5935 	    KM_SLEEP);
5936 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5937 	    KM_SLEEP);
5938 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5939 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5940 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5941 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5942 
5943 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5944 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5945 	ipst->ips_igmp_deferred_next = INFINITY;
5946 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5947 	ipst->ips_mld_deferred_next = INFINITY;
5948 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5949 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5950 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5951 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5952 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5953 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5954 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5955 
5956 	ipcl_init(ipst);
5957 	ip_ire_init(ipst);
5958 	ip6_asp_init(ipst);
5959 	ipif_init(ipst);
5960 	conn_drain_init(ipst);
5961 	ip_mrouter_stack_init(ipst);
5962 
5963 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5964 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5965 
5966 	ipst->ips_ip_multirt_log_interval = 1000;
5967 
5968 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5969 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5970 	ipst->ips_ill_index = 1;
5971 
5972 	ipst->ips_saved_ip_g_forward = -1;
5973 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5974 
5975 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5976 	ipst->ips_param_arr = pa;
5977 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5978 
5979 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5980 	ipst->ips_ndp_arr = na;
5981 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5982 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5983 	    (caddr_t)&ipst->ips_ip_g_forward;
5984 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5985 	    (caddr_t)&ipst->ips_ipv6_forward;
5986 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5987 	    "ip_cgtp_filter") == 0);
5988 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5989 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5990 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5991 	    "ipmp_hook_emulation") == 0);
5992 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5993 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5994 
5995 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5996 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5997 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5998 
5999 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6000 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6001 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6002 	ipst->ips_ip6_kstat =
6003 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6004 
6005 	ipst->ips_ipmp_enable_failback = B_TRUE;
6006 
6007 	ipst->ips_ip_src_id = 1;
6008 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6009 
6010 	ip_net_init(ipst, ns);
6011 	ipv4_hook_init(ipst);
6012 	ipv6_hook_init(ipst);
6013 
6014 	return (ipst);
6015 }
6016 
6017 /*
6018  * Allocate and initialize a DLPI template of the specified length.  (May be
6019  * called as writer.)
6020  */
6021 mblk_t *
6022 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6023 {
6024 	mblk_t	*mp;
6025 
6026 	mp = allocb(len, BPRI_MED);
6027 	if (!mp)
6028 		return (NULL);
6029 
6030 	/*
6031 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6032 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6033 	 * that other DLPI are M_PROTO.
6034 	 */
6035 	if (prim == DL_INFO_REQ) {
6036 		mp->b_datap->db_type = M_PCPROTO;
6037 	} else {
6038 		mp->b_datap->db_type = M_PROTO;
6039 	}
6040 
6041 	mp->b_wptr = mp->b_rptr + len;
6042 	bzero(mp->b_rptr, len);
6043 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6044 	return (mp);
6045 }
6046 
6047 /*
6048  * Debug formatting routine.  Returns a character string representation of the
6049  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6050  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6051  *
6052  * Once the ndd table-printing interfaces are removed, this can be changed to
6053  * standard dotted-decimal form.
6054  */
6055 char *
6056 ip_dot_addr(ipaddr_t addr, char *buf)
6057 {
6058 	uint8_t *ap = (uint8_t *)&addr;
6059 
6060 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6061 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6062 	return (buf);
6063 }
6064 
6065 /*
6066  * Write the given MAC address as a printable string in the usual colon-
6067  * separated format.
6068  */
6069 const char *
6070 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6071 {
6072 	char *bp;
6073 
6074 	if (alen == 0 || buflen < 4)
6075 		return ("?");
6076 	bp = buf;
6077 	for (;;) {
6078 		/*
6079 		 * If there are more MAC address bytes available, but we won't
6080 		 * have any room to print them, then add "..." to the string
6081 		 * instead.  See below for the 'magic number' explanation.
6082 		 */
6083 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6084 			(void) strcpy(bp, "...");
6085 			break;
6086 		}
6087 		(void) sprintf(bp, "%02x", *addr++);
6088 		bp += 2;
6089 		if (--alen == 0)
6090 			break;
6091 		*bp++ = ':';
6092 		buflen -= 3;
6093 		/*
6094 		 * At this point, based on the first 'if' statement above,
6095 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6096 		 * buflen >= 4.  The first case leaves room for the final "xx"
6097 		 * number and trailing NUL byte.  The second leaves room for at
6098 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6099 		 * that statement.
6100 		 */
6101 	}
6102 	return (buf);
6103 }
6104 
6105 /*
6106  * Send an ICMP error after patching up the packet appropriately.  Returns
6107  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6108  */
6109 static boolean_t
6110 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6111     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6112     zoneid_t zoneid, ip_stack_t *ipst)
6113 {
6114 	ipha_t *ipha;
6115 	mblk_t *first_mp;
6116 	boolean_t secure;
6117 	unsigned char db_type;
6118 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6119 
6120 	first_mp = mp;
6121 	if (mctl_present) {
6122 		mp = mp->b_cont;
6123 		secure = ipsec_in_is_secure(first_mp);
6124 		ASSERT(mp != NULL);
6125 	} else {
6126 		/*
6127 		 * If this is an ICMP error being reported - which goes
6128 		 * up as M_CTLs, we need to convert them to M_DATA till
6129 		 * we finish checking with global policy because
6130 		 * ipsec_check_global_policy() assumes M_DATA as clear
6131 		 * and M_CTL as secure.
6132 		 */
6133 		db_type = DB_TYPE(mp);
6134 		DB_TYPE(mp) = M_DATA;
6135 		secure = B_FALSE;
6136 	}
6137 	/*
6138 	 * We are generating an icmp error for some inbound packet.
6139 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6140 	 * Before we generate an error, check with global policy
6141 	 * to see whether this is allowed to enter the system. As
6142 	 * there is no "conn", we are checking with global policy.
6143 	 */
6144 	ipha = (ipha_t *)mp->b_rptr;
6145 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6146 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6147 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6148 		if (first_mp == NULL)
6149 			return (B_FALSE);
6150 	}
6151 
6152 	if (!mctl_present)
6153 		DB_TYPE(mp) = db_type;
6154 
6155 	if (flags & IP_FF_SEND_ICMP) {
6156 		if (flags & IP_FF_HDR_COMPLETE) {
6157 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6158 				freemsg(first_mp);
6159 				return (B_TRUE);
6160 			}
6161 		}
6162 		if (flags & IP_FF_CKSUM) {
6163 			/*
6164 			 * Have to correct checksum since
6165 			 * the packet might have been
6166 			 * fragmented and the reassembly code in ip_rput
6167 			 * does not restore the IP checksum.
6168 			 */
6169 			ipha->ipha_hdr_checksum = 0;
6170 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6171 		}
6172 		switch (icmp_type) {
6173 		case ICMP_DEST_UNREACHABLE:
6174 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6175 			    ipst);
6176 			break;
6177 		default:
6178 			freemsg(first_mp);
6179 			break;
6180 		}
6181 	} else {
6182 		freemsg(first_mp);
6183 		return (B_FALSE);
6184 	}
6185 
6186 	return (B_TRUE);
6187 }
6188 
6189 /*
6190  * Used to send an ICMP error message when a packet is received for
6191  * a protocol that is not supported. The mblk passed as argument
6192  * is consumed by this function.
6193  */
6194 void
6195 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6196     ip_stack_t *ipst)
6197 {
6198 	mblk_t *mp;
6199 	ipha_t *ipha;
6200 	ill_t *ill;
6201 	ipsec_in_t *ii;
6202 
6203 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6204 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6205 
6206 	mp = ipsec_mp->b_cont;
6207 	ipsec_mp->b_cont = NULL;
6208 	ipha = (ipha_t *)mp->b_rptr;
6209 	/* Get ill from index in ipsec_in_t. */
6210 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6211 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6212 	    ipst);
6213 	if (ill != NULL) {
6214 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6215 			if (ip_fanout_send_icmp(q, mp, flags,
6216 			    ICMP_DEST_UNREACHABLE,
6217 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6218 				BUMP_MIB(ill->ill_ip_mib,
6219 				    ipIfStatsInUnknownProtos);
6220 			}
6221 		} else {
6222 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6223 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6224 			    0, B_FALSE, zoneid, ipst)) {
6225 				BUMP_MIB(ill->ill_ip_mib,
6226 				    ipIfStatsInUnknownProtos);
6227 			}
6228 		}
6229 		ill_refrele(ill);
6230 	} else { /* re-link for the freemsg() below. */
6231 		ipsec_mp->b_cont = mp;
6232 	}
6233 
6234 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6235 	freemsg(ipsec_mp);
6236 }
6237 
6238 /*
6239  * See if the inbound datagram has had IPsec processing applied to it.
6240  */
6241 boolean_t
6242 ipsec_in_is_secure(mblk_t *ipsec_mp)
6243 {
6244 	ipsec_in_t *ii;
6245 
6246 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6247 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6248 
6249 	if (ii->ipsec_in_loopback) {
6250 		return (ii->ipsec_in_secure);
6251 	} else {
6252 		return (ii->ipsec_in_ah_sa != NULL ||
6253 		    ii->ipsec_in_esp_sa != NULL ||
6254 		    ii->ipsec_in_decaps);
6255 	}
6256 }
6257 
6258 /*
6259  * Handle protocols with which IP is less intimate.  There
6260  * can be more than one stream bound to a particular
6261  * protocol.  When this is the case, normally each one gets a copy
6262  * of any incoming packets.
6263  *
6264  * IPsec NOTE :
6265  *
6266  * Don't allow a secure packet going up a non-secure connection.
6267  * We don't allow this because
6268  *
6269  * 1) Reply might go out in clear which will be dropped at
6270  *    the sending side.
6271  * 2) If the reply goes out in clear it will give the
6272  *    adversary enough information for getting the key in
6273  *    most of the cases.
6274  *
6275  * Moreover getting a secure packet when we expect clear
6276  * implies that SA's were added without checking for
6277  * policy on both ends. This should not happen once ISAKMP
6278  * is used to negotiate SAs as SAs will be added only after
6279  * verifying the policy.
6280  *
6281  * NOTE : If the packet was tunneled and not multicast we only send
6282  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6283  * back to delivering packets to AF_INET6 raw sockets.
6284  *
6285  * IPQoS Notes:
6286  * Once we have determined the client, invoke IPPF processing.
6287  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6288  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6289  * ip_policy will be false.
6290  *
6291  * Zones notes:
6292  * Currently only applications in the global zone can create raw sockets for
6293  * protocols other than ICMP. So unlike the broadcast / multicast case of
6294  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6295  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6296  */
6297 static void
6298 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6299     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6300     zoneid_t zoneid)
6301 {
6302 	queue_t	*rq;
6303 	mblk_t	*mp1, *first_mp1;
6304 	uint_t	protocol = ipha->ipha_protocol;
6305 	ipaddr_t dst;
6306 	boolean_t one_only;
6307 	mblk_t *first_mp = mp;
6308 	boolean_t secure;
6309 	uint32_t ill_index;
6310 	conn_t	*connp, *first_connp, *next_connp;
6311 	connf_t	*connfp;
6312 	boolean_t shared_addr;
6313 	mib2_ipIfStatsEntry_t *mibptr;
6314 	ip_stack_t *ipst = recv_ill->ill_ipst;
6315 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6316 
6317 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6318 	if (mctl_present) {
6319 		mp = first_mp->b_cont;
6320 		secure = ipsec_in_is_secure(first_mp);
6321 		ASSERT(mp != NULL);
6322 	} else {
6323 		secure = B_FALSE;
6324 	}
6325 	dst = ipha->ipha_dst;
6326 	/*
6327 	 * If the packet was tunneled and not multicast we only send to it
6328 	 * the first match.
6329 	 */
6330 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6331 	    !CLASSD(dst));
6332 
6333 	shared_addr = (zoneid == ALL_ZONES);
6334 	if (shared_addr) {
6335 		/*
6336 		 * We don't allow multilevel ports for raw IP, so no need to
6337 		 * check for that here.
6338 		 */
6339 		zoneid = tsol_packet_to_zoneid(mp);
6340 	}
6341 
6342 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6343 	mutex_enter(&connfp->connf_lock);
6344 	connp = connfp->connf_head;
6345 	for (connp = connfp->connf_head; connp != NULL;
6346 	    connp = connp->conn_next) {
6347 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6348 		    zoneid) &&
6349 		    (!is_system_labeled() ||
6350 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6351 		    connp))) {
6352 			break;
6353 		}
6354 	}
6355 
6356 	if (connp == NULL || connp->conn_upq == NULL) {
6357 		/*
6358 		 * No one bound to these addresses.  Is
6359 		 * there a client that wants all
6360 		 * unclaimed datagrams?
6361 		 */
6362 		mutex_exit(&connfp->connf_lock);
6363 		/*
6364 		 * Check for IPPROTO_ENCAP...
6365 		 */
6366 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6367 			/*
6368 			 * If an IPsec mblk is here on a multicast
6369 			 * tunnel (using ip_mroute stuff), check policy here,
6370 			 * THEN ship off to ip_mroute_decap().
6371 			 *
6372 			 * BTW,  If I match a configured IP-in-IP
6373 			 * tunnel, this path will not be reached, and
6374 			 * ip_mroute_decap will never be called.
6375 			 */
6376 			first_mp = ipsec_check_global_policy(first_mp, connp,
6377 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6378 			if (first_mp != NULL) {
6379 				if (mctl_present)
6380 					freeb(first_mp);
6381 				ip_mroute_decap(q, mp, ill);
6382 			} /* Else we already freed everything! */
6383 		} else {
6384 			/*
6385 			 * Otherwise send an ICMP protocol unreachable.
6386 			 */
6387 			if (ip_fanout_send_icmp(q, first_mp, flags,
6388 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6389 			    mctl_present, zoneid, ipst)) {
6390 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6391 			}
6392 		}
6393 		return;
6394 	}
6395 	CONN_INC_REF(connp);
6396 	first_connp = connp;
6397 
6398 	/*
6399 	 * Only send message to one tunnel driver by immediately
6400 	 * terminating the loop.
6401 	 */
6402 	connp = one_only ? NULL : connp->conn_next;
6403 
6404 	for (;;) {
6405 		while (connp != NULL) {
6406 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6407 			    flags, zoneid) &&
6408 			    (!is_system_labeled() ||
6409 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6410 			    shared_addr, connp)))
6411 				break;
6412 			connp = connp->conn_next;
6413 		}
6414 
6415 		/*
6416 		 * Copy the packet.
6417 		 */
6418 		if (connp == NULL || connp->conn_upq == NULL ||
6419 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6420 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6421 			/*
6422 			 * No more interested clients or memory
6423 			 * allocation failed
6424 			 */
6425 			connp = first_connp;
6426 			break;
6427 		}
6428 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6429 		CONN_INC_REF(connp);
6430 		mutex_exit(&connfp->connf_lock);
6431 		rq = connp->conn_rq;
6432 		if (!canputnext(rq)) {
6433 			if (flags & IP_FF_RAWIP) {
6434 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6435 			} else {
6436 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6437 			}
6438 
6439 			freemsg(first_mp1);
6440 		} else {
6441 			/*
6442 			 * Don't enforce here if we're an actual tunnel -
6443 			 * let "tun" do it instead.
6444 			 */
6445 			if (!IPCL_IS_IPTUN(connp) &&
6446 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6447 			    secure)) {
6448 				first_mp1 = ipsec_check_inbound_policy
6449 				    (first_mp1, connp, ipha, NULL,
6450 				    mctl_present);
6451 			}
6452 			if (first_mp1 != NULL) {
6453 				int in_flags = 0;
6454 				/*
6455 				 * ip_fanout_proto also gets called from
6456 				 * icmp_inbound_error_fanout, in which case
6457 				 * the msg type is M_CTL.  Don't add info
6458 				 * in this case for the time being. In future
6459 				 * when there is a need for knowing the
6460 				 * inbound iface index for ICMP error msgs,
6461 				 * then this can be changed.
6462 				 */
6463 				if (connp->conn_recvif)
6464 					in_flags = IPF_RECVIF;
6465 				/*
6466 				 * The ULP may support IP_RECVPKTINFO for both
6467 				 * IP v4 and v6 so pass the appropriate argument
6468 				 * based on conn IP version.
6469 				 */
6470 				if (connp->conn_ip_recvpktinfo) {
6471 					if (connp->conn_af_isv6) {
6472 						/*
6473 						 * V6 only needs index
6474 						 */
6475 						in_flags |= IPF_RECVIF;
6476 					} else {
6477 						/*
6478 						 * V4 needs index +
6479 						 * matching address.
6480 						 */
6481 						in_flags |= IPF_RECVADDR;
6482 					}
6483 				}
6484 				if ((in_flags != 0) &&
6485 				    (mp->b_datap->db_type != M_CTL)) {
6486 					/*
6487 					 * the actual data will be
6488 					 * contained in b_cont upon
6489 					 * successful return of the
6490 					 * following call else
6491 					 * original mblk is returned
6492 					 */
6493 					ASSERT(recv_ill != NULL);
6494 					mp1 = ip_add_info(mp1, recv_ill,
6495 					    in_flags, IPCL_ZONEID(connp), ipst);
6496 				}
6497 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6498 				if (mctl_present)
6499 					freeb(first_mp1);
6500 				(connp->conn_recv)(connp, mp1, NULL);
6501 			}
6502 		}
6503 		mutex_enter(&connfp->connf_lock);
6504 		/* Follow the next pointer before releasing the conn. */
6505 		next_connp = connp->conn_next;
6506 		CONN_DEC_REF(connp);
6507 		connp = next_connp;
6508 	}
6509 
6510 	/* Last one.  Send it upstream. */
6511 	mutex_exit(&connfp->connf_lock);
6512 
6513 	/*
6514 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6515 	 * will be set to false.
6516 	 */
6517 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6518 		ill_index = ill->ill_phyint->phyint_ifindex;
6519 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6520 		if (mp == NULL) {
6521 			CONN_DEC_REF(connp);
6522 			if (mctl_present) {
6523 				freeb(first_mp);
6524 			}
6525 			return;
6526 		}
6527 	}
6528 
6529 	rq = connp->conn_rq;
6530 	if (!canputnext(rq)) {
6531 		if (flags & IP_FF_RAWIP) {
6532 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6533 		} else {
6534 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6535 		}
6536 
6537 		freemsg(first_mp);
6538 	} else {
6539 		if (IPCL_IS_IPTUN(connp)) {
6540 			/*
6541 			 * Tunneled packet.  We enforce policy in the tunnel
6542 			 * module itself.
6543 			 *
6544 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6545 			 * a policy check.
6546 			 * FIXME to use conn_recv for tun later.
6547 			 */
6548 			putnext(rq, first_mp);
6549 			CONN_DEC_REF(connp);
6550 			return;
6551 		}
6552 
6553 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6554 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6555 			    ipha, NULL, mctl_present);
6556 		}
6557 
6558 		if (first_mp != NULL) {
6559 			int in_flags = 0;
6560 
6561 			/*
6562 			 * ip_fanout_proto also gets called
6563 			 * from icmp_inbound_error_fanout, in
6564 			 * which case the msg type is M_CTL.
6565 			 * Don't add info in this case for time
6566 			 * being. In future when there is a
6567 			 * need for knowing the inbound iface
6568 			 * index for ICMP error msgs, then this
6569 			 * can be changed
6570 			 */
6571 			if (connp->conn_recvif)
6572 				in_flags = IPF_RECVIF;
6573 			if (connp->conn_ip_recvpktinfo) {
6574 				if (connp->conn_af_isv6) {
6575 					/*
6576 					 * V6 only needs index
6577 					 */
6578 					in_flags |= IPF_RECVIF;
6579 				} else {
6580 					/*
6581 					 * V4 needs index +
6582 					 * matching address.
6583 					 */
6584 					in_flags |= IPF_RECVADDR;
6585 				}
6586 			}
6587 			if ((in_flags != 0) &&
6588 			    (mp->b_datap->db_type != M_CTL)) {
6589 
6590 				/*
6591 				 * the actual data will be contained in
6592 				 * b_cont upon successful return
6593 				 * of the following call else original
6594 				 * mblk is returned
6595 				 */
6596 				ASSERT(recv_ill != NULL);
6597 				mp = ip_add_info(mp, recv_ill,
6598 				    in_flags, IPCL_ZONEID(connp), ipst);
6599 			}
6600 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6601 			(connp->conn_recv)(connp, mp, NULL);
6602 			if (mctl_present)
6603 				freeb(first_mp);
6604 		}
6605 	}
6606 	CONN_DEC_REF(connp);
6607 }
6608 
6609 /*
6610  * Fanout for TCP packets
6611  * The caller puts <fport, lport> in the ports parameter.
6612  *
6613  * IPQoS Notes
6614  * Before sending it to the client, invoke IPPF processing.
6615  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6616  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6617  * ip_policy is false.
6618  */
6619 static void
6620 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6621     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6622 {
6623 	mblk_t  *first_mp;
6624 	boolean_t secure;
6625 	uint32_t ill_index;
6626 	int	ip_hdr_len;
6627 	tcph_t	*tcph;
6628 	boolean_t syn_present = B_FALSE;
6629 	conn_t	*connp;
6630 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6631 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6632 
6633 	ASSERT(recv_ill != NULL);
6634 
6635 	first_mp = mp;
6636 	if (mctl_present) {
6637 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6638 		mp = first_mp->b_cont;
6639 		secure = ipsec_in_is_secure(first_mp);
6640 		ASSERT(mp != NULL);
6641 	} else {
6642 		secure = B_FALSE;
6643 	}
6644 
6645 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6646 
6647 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6648 	    zoneid, ipst)) == NULL) {
6649 		/*
6650 		 * No connected connection or listener. Send a
6651 		 * TH_RST via tcp_xmit_listeners_reset.
6652 		 */
6653 
6654 		/* Initiate IPPf processing, if needed. */
6655 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6656 			uint32_t ill_index;
6657 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6658 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6659 			if (first_mp == NULL)
6660 				return;
6661 		}
6662 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6663 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6664 		    zoneid));
6665 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6666 		    ipst->ips_netstack->netstack_tcp, NULL);
6667 		return;
6668 	}
6669 
6670 	/*
6671 	 * Allocate the SYN for the TCP connection here itself
6672 	 */
6673 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6674 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6675 		if (IPCL_IS_TCP(connp)) {
6676 			squeue_t *sqp;
6677 
6678 			/*
6679 			 * For fused tcp loopback, assign the eager's
6680 			 * squeue to be that of the active connect's.
6681 			 * Note that we don't check for IP_FF_LOOPBACK
6682 			 * here since this routine gets called only
6683 			 * for loopback (unlike the IPv6 counterpart).
6684 			 */
6685 			ASSERT(Q_TO_CONN(q) != NULL);
6686 			if (do_tcp_fusion &&
6687 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6688 			    !secure &&
6689 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6690 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6691 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6692 				sqp = Q_TO_CONN(q)->conn_sqp;
6693 			} else {
6694 				sqp = IP_SQUEUE_GET(lbolt);
6695 			}
6696 
6697 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6698 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6699 			syn_present = B_TRUE;
6700 		}
6701 	}
6702 
6703 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6704 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6705 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6706 		if ((flags & TH_RST) || (flags & TH_URG)) {
6707 			CONN_DEC_REF(connp);
6708 			freemsg(first_mp);
6709 			return;
6710 		}
6711 		if (flags & TH_ACK) {
6712 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6713 			    ipst->ips_netstack->netstack_tcp, connp);
6714 			CONN_DEC_REF(connp);
6715 			return;
6716 		}
6717 
6718 		CONN_DEC_REF(connp);
6719 		freemsg(first_mp);
6720 		return;
6721 	}
6722 
6723 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6724 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6725 		    NULL, mctl_present);
6726 		if (first_mp == NULL) {
6727 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6728 			CONN_DEC_REF(connp);
6729 			return;
6730 		}
6731 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6732 			ASSERT(syn_present);
6733 			if (mctl_present) {
6734 				ASSERT(first_mp != mp);
6735 				first_mp->b_datap->db_struioflag |=
6736 				    STRUIO_POLICY;
6737 			} else {
6738 				ASSERT(first_mp == mp);
6739 				mp->b_datap->db_struioflag &=
6740 				    ~STRUIO_EAGER;
6741 				mp->b_datap->db_struioflag |=
6742 				    STRUIO_POLICY;
6743 			}
6744 		} else {
6745 			/*
6746 			 * Discard first_mp early since we're dealing with a
6747 			 * fully-connected conn_t and tcp doesn't do policy in
6748 			 * this case.
6749 			 */
6750 			if (mctl_present) {
6751 				freeb(first_mp);
6752 				mctl_present = B_FALSE;
6753 			}
6754 			first_mp = mp;
6755 		}
6756 	}
6757 
6758 	/*
6759 	 * Initiate policy processing here if needed. If we get here from
6760 	 * icmp_inbound_error_fanout, ip_policy is false.
6761 	 */
6762 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6763 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6764 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6765 		if (mp == NULL) {
6766 			CONN_DEC_REF(connp);
6767 			if (mctl_present)
6768 				freeb(first_mp);
6769 			return;
6770 		} else if (mctl_present) {
6771 			ASSERT(first_mp != mp);
6772 			first_mp->b_cont = mp;
6773 		} else {
6774 			first_mp = mp;
6775 		}
6776 	}
6777 
6778 
6779 
6780 	/* Handle socket options. */
6781 	if (!syn_present &&
6782 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6783 		/* Add header */
6784 		ASSERT(recv_ill != NULL);
6785 		/*
6786 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6787 		 * IPF_RECVIF.
6788 		 */
6789 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6790 		    ipst);
6791 		if (mp == NULL) {
6792 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6793 			CONN_DEC_REF(connp);
6794 			if (mctl_present)
6795 				freeb(first_mp);
6796 			return;
6797 		} else if (mctl_present) {
6798 			/*
6799 			 * ip_add_info might return a new mp.
6800 			 */
6801 			ASSERT(first_mp != mp);
6802 			first_mp->b_cont = mp;
6803 		} else {
6804 			first_mp = mp;
6805 		}
6806 	}
6807 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6808 	if (IPCL_IS_TCP(connp)) {
6809 		/* do not drain, certain use cases can blow the stack */
6810 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6811 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6812 	} else {
6813 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6814 		(connp->conn_recv)(connp, first_mp, NULL);
6815 		CONN_DEC_REF(connp);
6816 	}
6817 }
6818 
6819 /*
6820  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6821  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6822  * is not consumed.
6823  *
6824  * One of four things can happen, all of which affect the passed-in mblk:
6825  *
6826  * 1.) ICMP messages that go through here just get returned TRUE.
6827  *
6828  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6829  *
6830  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6831  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6832  *
6833  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6834  */
6835 static boolean_t
6836 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6837     ipsec_stack_t *ipss)
6838 {
6839 	int shift, plen, iph_len;
6840 	ipha_t *ipha;
6841 	udpha_t *udpha;
6842 	uint32_t *spi;
6843 	uint8_t *orptr;
6844 	boolean_t udp_pkt, free_ire;
6845 
6846 	if (DB_TYPE(mp) == M_CTL) {
6847 		/*
6848 		 * ICMP message with UDP inside.  Don't bother stripping, just
6849 		 * send it up.
6850 		 *
6851 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6852 		 * to ignore errors set by ICMP anyway ('cause they might be
6853 		 * forged), but that's the app's decision, not ours.
6854 		 */
6855 
6856 		/* Bunch of reality checks for DEBUG kernels... */
6857 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6858 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6859 
6860 		return (B_TRUE);
6861 	}
6862 
6863 	ipha = (ipha_t *)mp->b_rptr;
6864 	iph_len = IPH_HDR_LENGTH(ipha);
6865 	plen = ntohs(ipha->ipha_length);
6866 
6867 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6868 		/*
6869 		 * Most likely a keepalive for the benefit of an intervening
6870 		 * NAT.  These aren't for us, per se, so drop it.
6871 		 *
6872 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6873 		 * byte packets (keepalives are 1-byte), but we'll drop them
6874 		 * also.
6875 		 */
6876 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6877 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6878 		return (B_FALSE);
6879 	}
6880 
6881 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6882 		/* might as well pull it all up - it might be ESP. */
6883 		if (!pullupmsg(mp, -1)) {
6884 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6885 			    DROPPER(ipss, ipds_esp_nomem),
6886 			    &ipss->ipsec_dropper);
6887 			return (B_FALSE);
6888 		}
6889 
6890 		ipha = (ipha_t *)mp->b_rptr;
6891 	}
6892 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6893 	if (*spi == 0) {
6894 		/* UDP packet - remove 0-spi. */
6895 		shift = sizeof (uint32_t);
6896 	} else {
6897 		/* ESP-in-UDP packet - reduce to ESP. */
6898 		ipha->ipha_protocol = IPPROTO_ESP;
6899 		shift = sizeof (udpha_t);
6900 	}
6901 
6902 	/* Fix IP header */
6903 	ipha->ipha_length = htons(plen - shift);
6904 	ipha->ipha_hdr_checksum = 0;
6905 
6906 	orptr = mp->b_rptr;
6907 	mp->b_rptr += shift;
6908 
6909 	if (*spi == 0) {
6910 		ASSERT((uint8_t *)ipha == orptr);
6911 		udpha = (udpha_t *)(orptr + iph_len);
6912 		udpha->uha_length = htons(plen - shift - iph_len);
6913 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6914 		udp_pkt = B_TRUE;
6915 	} else {
6916 		udp_pkt = B_FALSE;
6917 	}
6918 	ovbcopy(orptr, orptr + shift, iph_len);
6919 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6920 		ipha = (ipha_t *)(orptr + shift);
6921 
6922 		free_ire = (ire == NULL);
6923 		if (free_ire) {
6924 			/* Re-acquire ire. */
6925 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6926 			    ipss->ipsec_netstack->netstack_ip);
6927 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6928 				if (ire != NULL)
6929 					ire_refrele(ire);
6930 				/*
6931 				 * Do a regular freemsg(), as this is an IP
6932 				 * error (no local route) not an IPsec one.
6933 				 */
6934 				freemsg(mp);
6935 			}
6936 		}
6937 
6938 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6939 		if (free_ire)
6940 			ire_refrele(ire);
6941 	}
6942 
6943 	return (udp_pkt);
6944 }
6945 
6946 /*
6947  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6948  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6949  * Caller is responsible for dropping references to the conn, and freeing
6950  * first_mp.
6951  *
6952  * IPQoS Notes
6953  * Before sending it to the client, invoke IPPF processing. Policy processing
6954  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6955  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6956  * ip_wput_local, ip_policy is false.
6957  */
6958 static void
6959 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6960     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6961     boolean_t ip_policy)
6962 {
6963 	boolean_t	mctl_present = (first_mp != NULL);
6964 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6965 	uint32_t	ill_index;
6966 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6967 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6968 
6969 	ASSERT(ill != NULL);
6970 
6971 	if (mctl_present)
6972 		first_mp->b_cont = mp;
6973 	else
6974 		first_mp = mp;
6975 
6976 	if (CONN_UDP_FLOWCTLD(connp)) {
6977 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6978 		freemsg(first_mp);
6979 		return;
6980 	}
6981 
6982 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6983 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6984 		    NULL, mctl_present);
6985 		if (first_mp == NULL) {
6986 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6987 			return;	/* Freed by ipsec_check_inbound_policy(). */
6988 		}
6989 	}
6990 	if (mctl_present)
6991 		freeb(first_mp);
6992 
6993 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6994 	if (connp->conn_udp->udp_nat_t_endpoint) {
6995 		if (mctl_present) {
6996 			/* mctl_present *shouldn't* happen. */
6997 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
6998 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
6999 			    &ipss->ipsec_dropper);
7000 			return;
7001 		}
7002 
7003 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7004 			return;
7005 	}
7006 
7007 	/* Handle options. */
7008 	if (connp->conn_recvif)
7009 		in_flags = IPF_RECVIF;
7010 	/*
7011 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7012 	 * passed to ip_add_info is based on IP version of connp.
7013 	 */
7014 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7015 		if (connp->conn_af_isv6) {
7016 			/*
7017 			 * V6 only needs index
7018 			 */
7019 			in_flags |= IPF_RECVIF;
7020 		} else {
7021 			/*
7022 			 * V4 needs index + matching address.
7023 			 */
7024 			in_flags |= IPF_RECVADDR;
7025 		}
7026 	}
7027 
7028 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7029 		in_flags |= IPF_RECVSLLA;
7030 
7031 	/*
7032 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7033 	 * freed if the packet is dropped. The caller will do so.
7034 	 */
7035 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7036 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7037 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7038 		if (mp == NULL) {
7039 			return;
7040 		}
7041 	}
7042 	if ((in_flags != 0) &&
7043 	    (mp->b_datap->db_type != M_CTL)) {
7044 		/*
7045 		 * The actual data will be contained in b_cont
7046 		 * upon successful return of the following call
7047 		 * else original mblk is returned
7048 		 */
7049 		ASSERT(recv_ill != NULL);
7050 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7051 		    ipst);
7052 	}
7053 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7054 	/* Send it upstream */
7055 	(connp->conn_recv)(connp, mp, NULL);
7056 }
7057 
7058 /*
7059  * Fanout for UDP packets.
7060  * The caller puts <fport, lport> in the ports parameter.
7061  *
7062  * If SO_REUSEADDR is set all multicast and broadcast packets
7063  * will be delivered to all streams bound to the same port.
7064  *
7065  * Zones notes:
7066  * Multicast and broadcast packets will be distributed to streams in all zones.
7067  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7068  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7069  * packets. To maintain this behavior with multiple zones, the conns are grouped
7070  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7071  * each zone. If unset, all the following conns in the same zone are skipped.
7072  */
7073 static void
7074 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7075     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7076     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7077 {
7078 	uint32_t	dstport, srcport;
7079 	ipaddr_t	dst;
7080 	mblk_t		*first_mp;
7081 	boolean_t	secure;
7082 	in6_addr_t	v6src;
7083 	conn_t		*connp;
7084 	connf_t		*connfp;
7085 	conn_t		*first_connp;
7086 	conn_t		*next_connp;
7087 	mblk_t		*mp1, *first_mp1;
7088 	ipaddr_t	src;
7089 	zoneid_t	last_zoneid;
7090 	boolean_t	reuseaddr;
7091 	boolean_t	shared_addr;
7092 	ip_stack_t	*ipst;
7093 
7094 	ASSERT(recv_ill != NULL);
7095 	ipst = recv_ill->ill_ipst;
7096 
7097 	first_mp = mp;
7098 	if (mctl_present) {
7099 		mp = first_mp->b_cont;
7100 		first_mp->b_cont = NULL;
7101 		secure = ipsec_in_is_secure(first_mp);
7102 		ASSERT(mp != NULL);
7103 	} else {
7104 		first_mp = NULL;
7105 		secure = B_FALSE;
7106 	}
7107 
7108 	/* Extract ports in net byte order */
7109 	dstport = htons(ntohl(ports) & 0xFFFF);
7110 	srcport = htons(ntohl(ports) >> 16);
7111 	dst = ipha->ipha_dst;
7112 	src = ipha->ipha_src;
7113 
7114 	shared_addr = (zoneid == ALL_ZONES);
7115 	if (shared_addr) {
7116 		/*
7117 		 * No need to handle exclusive-stack zones since ALL_ZONES
7118 		 * only applies to the shared stack.
7119 		 */
7120 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7121 		if (zoneid == ALL_ZONES)
7122 			zoneid = tsol_packet_to_zoneid(mp);
7123 	}
7124 
7125 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7126 	mutex_enter(&connfp->connf_lock);
7127 	connp = connfp->connf_head;
7128 	if (!broadcast && !CLASSD(dst)) {
7129 		/*
7130 		 * Not broadcast or multicast. Send to the one (first)
7131 		 * client we find. No need to check conn_wantpacket()
7132 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7133 		 * IPv4 unicast packets.
7134 		 */
7135 		while ((connp != NULL) &&
7136 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7137 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7138 			connp = connp->conn_next;
7139 		}
7140 
7141 		if (connp == NULL || connp->conn_upq == NULL)
7142 			goto notfound;
7143 
7144 		if (is_system_labeled() &&
7145 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7146 		    connp))
7147 			goto notfound;
7148 
7149 		CONN_INC_REF(connp);
7150 		mutex_exit(&connfp->connf_lock);
7151 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7152 		    flags, recv_ill, ip_policy);
7153 		IP_STAT(ipst, ip_udp_fannorm);
7154 		CONN_DEC_REF(connp);
7155 		return;
7156 	}
7157 
7158 	/*
7159 	 * Broadcast and multicast case
7160 	 *
7161 	 * Need to check conn_wantpacket().
7162 	 * If SO_REUSEADDR has been set on the first we send the
7163 	 * packet to all clients that have joined the group and
7164 	 * match the port.
7165 	 */
7166 
7167 	while (connp != NULL) {
7168 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7169 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7170 		    (!is_system_labeled() ||
7171 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7172 		    connp)))
7173 			break;
7174 		connp = connp->conn_next;
7175 	}
7176 
7177 	if (connp == NULL || connp->conn_upq == NULL)
7178 		goto notfound;
7179 
7180 	first_connp = connp;
7181 	/*
7182 	 * When SO_REUSEADDR is not set, send the packet only to the first
7183 	 * matching connection in its zone by keeping track of the zoneid.
7184 	 */
7185 	reuseaddr = first_connp->conn_reuseaddr;
7186 	last_zoneid = first_connp->conn_zoneid;
7187 
7188 	CONN_INC_REF(connp);
7189 	connp = connp->conn_next;
7190 	for (;;) {
7191 		while (connp != NULL) {
7192 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7193 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7194 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7195 			    (!is_system_labeled() ||
7196 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7197 			    shared_addr, connp)))
7198 				break;
7199 			connp = connp->conn_next;
7200 		}
7201 		/*
7202 		 * Just copy the data part alone. The mctl part is
7203 		 * needed just for verifying policy and it is never
7204 		 * sent up.
7205 		 */
7206 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7207 		    ((mp1 = copymsg(mp)) == NULL))) {
7208 			/*
7209 			 * No more interested clients or memory
7210 			 * allocation failed
7211 			 */
7212 			connp = first_connp;
7213 			break;
7214 		}
7215 		if (connp->conn_zoneid != last_zoneid) {
7216 			/*
7217 			 * Update the zoneid so that the packet isn't sent to
7218 			 * any more conns in the same zone unless SO_REUSEADDR
7219 			 * is set.
7220 			 */
7221 			reuseaddr = connp->conn_reuseaddr;
7222 			last_zoneid = connp->conn_zoneid;
7223 		}
7224 		if (first_mp != NULL) {
7225 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7226 			    ipsec_info_type == IPSEC_IN);
7227 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7228 			    ipst->ips_netstack);
7229 			if (first_mp1 == NULL) {
7230 				freemsg(mp1);
7231 				connp = first_connp;
7232 				break;
7233 			}
7234 		} else {
7235 			first_mp1 = NULL;
7236 		}
7237 		CONN_INC_REF(connp);
7238 		mutex_exit(&connfp->connf_lock);
7239 		/*
7240 		 * IPQoS notes: We don't send the packet for policy
7241 		 * processing here, will do it for the last one (below).
7242 		 * i.e. we do it per-packet now, but if we do policy
7243 		 * processing per-conn, then we would need to do it
7244 		 * here too.
7245 		 */
7246 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7247 		    ipha, flags, recv_ill, B_FALSE);
7248 		mutex_enter(&connfp->connf_lock);
7249 		/* Follow the next pointer before releasing the conn. */
7250 		next_connp = connp->conn_next;
7251 		IP_STAT(ipst, ip_udp_fanmb);
7252 		CONN_DEC_REF(connp);
7253 		connp = next_connp;
7254 	}
7255 
7256 	/* Last one.  Send it upstream. */
7257 	mutex_exit(&connfp->connf_lock);
7258 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7259 	    recv_ill, ip_policy);
7260 	IP_STAT(ipst, ip_udp_fanmb);
7261 	CONN_DEC_REF(connp);
7262 	return;
7263 
7264 notfound:
7265 
7266 	mutex_exit(&connfp->connf_lock);
7267 	IP_STAT(ipst, ip_udp_fanothers);
7268 	/*
7269 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7270 	 * have already been matched above, since they live in the IPv4
7271 	 * fanout tables. This implies we only need to
7272 	 * check for IPv6 in6addr_any endpoints here.
7273 	 * Thus we compare using ipv6_all_zeros instead of the destination
7274 	 * address, except for the multicast group membership lookup which
7275 	 * uses the IPv4 destination.
7276 	 */
7277 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7278 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7279 	mutex_enter(&connfp->connf_lock);
7280 	connp = connfp->connf_head;
7281 	if (!broadcast && !CLASSD(dst)) {
7282 		while (connp != NULL) {
7283 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7284 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7285 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7286 			    !connp->conn_ipv6_v6only)
7287 				break;
7288 			connp = connp->conn_next;
7289 		}
7290 
7291 		if (connp != NULL && is_system_labeled() &&
7292 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7293 		    connp))
7294 			connp = NULL;
7295 
7296 		if (connp == NULL || connp->conn_upq == NULL) {
7297 			/*
7298 			 * No one bound to this port.  Is
7299 			 * there a client that wants all
7300 			 * unclaimed datagrams?
7301 			 */
7302 			mutex_exit(&connfp->connf_lock);
7303 
7304 			if (mctl_present)
7305 				first_mp->b_cont = mp;
7306 			else
7307 				first_mp = mp;
7308 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7309 			    connf_head != NULL) {
7310 				ip_fanout_proto(q, first_mp, ill, ipha,
7311 				    flags | IP_FF_RAWIP, mctl_present,
7312 				    ip_policy, recv_ill, zoneid);
7313 			} else {
7314 				if (ip_fanout_send_icmp(q, first_mp, flags,
7315 				    ICMP_DEST_UNREACHABLE,
7316 				    ICMP_PORT_UNREACHABLE,
7317 				    mctl_present, zoneid, ipst)) {
7318 					BUMP_MIB(ill->ill_ip_mib,
7319 					    udpIfStatsNoPorts);
7320 				}
7321 			}
7322 			return;
7323 		}
7324 
7325 		CONN_INC_REF(connp);
7326 		mutex_exit(&connfp->connf_lock);
7327 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7328 		    flags, recv_ill, ip_policy);
7329 		CONN_DEC_REF(connp);
7330 		return;
7331 	}
7332 	/*
7333 	 * IPv4 multicast packet being delivered to an AF_INET6
7334 	 * in6addr_any endpoint.
7335 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7336 	 * and not conn_wantpacket_v6() since any multicast membership is
7337 	 * for an IPv4-mapped multicast address.
7338 	 * The packet is sent to all clients in all zones that have joined the
7339 	 * group and match the port.
7340 	 */
7341 	while (connp != NULL) {
7342 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7343 		    srcport, v6src) &&
7344 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7345 		    (!is_system_labeled() ||
7346 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7347 		    connp)))
7348 			break;
7349 		connp = connp->conn_next;
7350 	}
7351 
7352 	if (connp == NULL || connp->conn_upq == NULL) {
7353 		/*
7354 		 * No one bound to this port.  Is
7355 		 * there a client that wants all
7356 		 * unclaimed datagrams?
7357 		 */
7358 		mutex_exit(&connfp->connf_lock);
7359 
7360 		if (mctl_present)
7361 			first_mp->b_cont = mp;
7362 		else
7363 			first_mp = mp;
7364 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7365 		    NULL) {
7366 			ip_fanout_proto(q, first_mp, ill, ipha,
7367 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7368 			    recv_ill, zoneid);
7369 		} else {
7370 			/*
7371 			 * We used to attempt to send an icmp error here, but
7372 			 * since this is known to be a multicast packet
7373 			 * and we don't send icmp errors in response to
7374 			 * multicast, just drop the packet and give up sooner.
7375 			 */
7376 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7377 			freemsg(first_mp);
7378 		}
7379 		return;
7380 	}
7381 
7382 	first_connp = connp;
7383 
7384 	CONN_INC_REF(connp);
7385 	connp = connp->conn_next;
7386 	for (;;) {
7387 		while (connp != NULL) {
7388 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7389 			    ipv6_all_zeros, srcport, v6src) &&
7390 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7391 			    (!is_system_labeled() ||
7392 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7393 			    shared_addr, connp)))
7394 				break;
7395 			connp = connp->conn_next;
7396 		}
7397 		/*
7398 		 * Just copy the data part alone. The mctl part is
7399 		 * needed just for verifying policy and it is never
7400 		 * sent up.
7401 		 */
7402 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7403 		    ((mp1 = copymsg(mp)) == NULL))) {
7404 			/*
7405 			 * No more intested clients or memory
7406 			 * allocation failed
7407 			 */
7408 			connp = first_connp;
7409 			break;
7410 		}
7411 		if (first_mp != NULL) {
7412 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7413 			    ipsec_info_type == IPSEC_IN);
7414 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7415 			    ipst->ips_netstack);
7416 			if (first_mp1 == NULL) {
7417 				freemsg(mp1);
7418 				connp = first_connp;
7419 				break;
7420 			}
7421 		} else {
7422 			first_mp1 = NULL;
7423 		}
7424 		CONN_INC_REF(connp);
7425 		mutex_exit(&connfp->connf_lock);
7426 		/*
7427 		 * IPQoS notes: We don't send the packet for policy
7428 		 * processing here, will do it for the last one (below).
7429 		 * i.e. we do it per-packet now, but if we do policy
7430 		 * processing per-conn, then we would need to do it
7431 		 * here too.
7432 		 */
7433 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7434 		    ipha, flags, recv_ill, B_FALSE);
7435 		mutex_enter(&connfp->connf_lock);
7436 		/* Follow the next pointer before releasing the conn. */
7437 		next_connp = connp->conn_next;
7438 		CONN_DEC_REF(connp);
7439 		connp = next_connp;
7440 	}
7441 
7442 	/* Last one.  Send it upstream. */
7443 	mutex_exit(&connfp->connf_lock);
7444 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7445 	    recv_ill, ip_policy);
7446 	CONN_DEC_REF(connp);
7447 }
7448 
7449 /*
7450  * Complete the ip_wput header so that it
7451  * is possible to generate ICMP
7452  * errors.
7453  */
7454 int
7455 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7456 {
7457 	ire_t *ire;
7458 
7459 	if (ipha->ipha_src == INADDR_ANY) {
7460 		ire = ire_lookup_local(zoneid, ipst);
7461 		if (ire == NULL) {
7462 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7463 			return (1);
7464 		}
7465 		ipha->ipha_src = ire->ire_addr;
7466 		ire_refrele(ire);
7467 	}
7468 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7469 	ipha->ipha_hdr_checksum = 0;
7470 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7471 	return (0);
7472 }
7473 
7474 /*
7475  * Nobody should be sending
7476  * packets up this stream
7477  */
7478 static void
7479 ip_lrput(queue_t *q, mblk_t *mp)
7480 {
7481 	mblk_t *mp1;
7482 
7483 	switch (mp->b_datap->db_type) {
7484 	case M_FLUSH:
7485 		/* Turn around */
7486 		if (*mp->b_rptr & FLUSHW) {
7487 			*mp->b_rptr &= ~FLUSHR;
7488 			qreply(q, mp);
7489 			return;
7490 		}
7491 		break;
7492 	}
7493 	/* Could receive messages that passed through ar_rput */
7494 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7495 		mp1->b_prev = mp1->b_next = NULL;
7496 	freemsg(mp);
7497 }
7498 
7499 /* Nobody should be sending packets down this stream */
7500 /* ARGSUSED */
7501 void
7502 ip_lwput(queue_t *q, mblk_t *mp)
7503 {
7504 	freemsg(mp);
7505 }
7506 
7507 /*
7508  * Move the first hop in any source route to ipha_dst and remove that part of
7509  * the source route.  Called by other protocols.  Errors in option formatting
7510  * are ignored - will be handled by ip_wput_options Return the final
7511  * destination (either ipha_dst or the last entry in a source route.)
7512  */
7513 ipaddr_t
7514 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7515 {
7516 	ipoptp_t	opts;
7517 	uchar_t		*opt;
7518 	uint8_t		optval;
7519 	uint8_t		optlen;
7520 	ipaddr_t	dst;
7521 	int		i;
7522 	ire_t		*ire;
7523 	ip_stack_t	*ipst = ns->netstack_ip;
7524 
7525 	ip2dbg(("ip_massage_options\n"));
7526 	dst = ipha->ipha_dst;
7527 	for (optval = ipoptp_first(&opts, ipha);
7528 	    optval != IPOPT_EOL;
7529 	    optval = ipoptp_next(&opts)) {
7530 		opt = opts.ipoptp_cur;
7531 		switch (optval) {
7532 			uint8_t off;
7533 		case IPOPT_SSRR:
7534 		case IPOPT_LSRR:
7535 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7536 				ip1dbg(("ip_massage_options: bad src route\n"));
7537 				break;
7538 			}
7539 			optlen = opts.ipoptp_len;
7540 			off = opt[IPOPT_OFFSET];
7541 			off--;
7542 		redo_srr:
7543 			if (optlen < IP_ADDR_LEN ||
7544 			    off > optlen - IP_ADDR_LEN) {
7545 				/* End of source route */
7546 				ip1dbg(("ip_massage_options: end of SR\n"));
7547 				break;
7548 			}
7549 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7550 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7551 			    ntohl(dst)));
7552 			/*
7553 			 * Check if our address is present more than
7554 			 * once as consecutive hops in source route.
7555 			 * XXX verify per-interface ip_forwarding
7556 			 * for source route?
7557 			 */
7558 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7559 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7560 			if (ire != NULL) {
7561 				ire_refrele(ire);
7562 				off += IP_ADDR_LEN;
7563 				goto redo_srr;
7564 			}
7565 			if (dst == htonl(INADDR_LOOPBACK)) {
7566 				ip1dbg(("ip_massage_options: loopback addr in "
7567 				    "source route!\n"));
7568 				break;
7569 			}
7570 			/*
7571 			 * Update ipha_dst to be the first hop and remove the
7572 			 * first hop from the source route (by overwriting
7573 			 * part of the option with NOP options).
7574 			 */
7575 			ipha->ipha_dst = dst;
7576 			/* Put the last entry in dst */
7577 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7578 			    3;
7579 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7580 
7581 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7582 			    ntohl(dst)));
7583 			/* Move down and overwrite */
7584 			opt[IP_ADDR_LEN] = opt[0];
7585 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7586 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7587 			for (i = 0; i < IP_ADDR_LEN; i++)
7588 				opt[i] = IPOPT_NOP;
7589 			break;
7590 		}
7591 	}
7592 	return (dst);
7593 }
7594 
7595 /*
7596  * Return the network mask
7597  * associated with the specified address.
7598  */
7599 ipaddr_t
7600 ip_net_mask(ipaddr_t addr)
7601 {
7602 	uchar_t	*up = (uchar_t *)&addr;
7603 	ipaddr_t mask = 0;
7604 	uchar_t	*maskp = (uchar_t *)&mask;
7605 
7606 #if defined(__i386) || defined(__amd64)
7607 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7608 #endif
7609 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7610 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7611 #endif
7612 	if (CLASSD(addr)) {
7613 		maskp[0] = 0xF0;
7614 		return (mask);
7615 	}
7616 
7617 	/* We assume Class E default netmask to be 32 */
7618 	if (CLASSE(addr))
7619 		return (0xffffffffU);
7620 
7621 	if (addr == 0)
7622 		return (0);
7623 	maskp[0] = 0xFF;
7624 	if ((up[0] & 0x80) == 0)
7625 		return (mask);
7626 
7627 	maskp[1] = 0xFF;
7628 	if ((up[0] & 0xC0) == 0x80)
7629 		return (mask);
7630 
7631 	maskp[2] = 0xFF;
7632 	if ((up[0] & 0xE0) == 0xC0)
7633 		return (mask);
7634 
7635 	/* Otherwise return no mask */
7636 	return ((ipaddr_t)0);
7637 }
7638 
7639 /*
7640  * Select an ill for the packet by considering load spreading across
7641  * a different ill in the group if dst_ill is part of some group.
7642  */
7643 ill_t *
7644 ip_newroute_get_dst_ill(ill_t *dst_ill)
7645 {
7646 	ill_t *ill;
7647 
7648 	/*
7649 	 * We schedule irrespective of whether the source address is
7650 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7651 	 */
7652 	ill = illgrp_scheduler(dst_ill);
7653 	if (ill == NULL)
7654 		return (NULL);
7655 
7656 	/*
7657 	 * For groups with names ip_sioctl_groupname ensures that all
7658 	 * ills are of same type. For groups without names, ifgrp_insert
7659 	 * ensures this.
7660 	 */
7661 	ASSERT(dst_ill->ill_type == ill->ill_type);
7662 
7663 	return (ill);
7664 }
7665 
7666 /*
7667  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7668  */
7669 ill_t *
7670 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7671     ip_stack_t *ipst)
7672 {
7673 	ill_t *ret_ill;
7674 
7675 	ASSERT(ifindex != 0);
7676 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7677 	    ipst);
7678 	if (ret_ill == NULL ||
7679 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7680 		if (isv6) {
7681 			if (ill != NULL) {
7682 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7683 			} else {
7684 				BUMP_MIB(&ipst->ips_ip6_mib,
7685 				    ipIfStatsOutDiscards);
7686 			}
7687 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7688 			    "bad ifindex %d.\n", ifindex));
7689 		} else {
7690 			if (ill != NULL) {
7691 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7692 			} else {
7693 				BUMP_MIB(&ipst->ips_ip_mib,
7694 				    ipIfStatsOutDiscards);
7695 			}
7696 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7697 			    "bad ifindex %d.\n", ifindex));
7698 		}
7699 		if (ret_ill != NULL)
7700 			ill_refrele(ret_ill);
7701 		freemsg(first_mp);
7702 		return (NULL);
7703 	}
7704 
7705 	return (ret_ill);
7706 }
7707 
7708 /*
7709  * IPv4 -
7710  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7711  * out a packet to a destination address for which we do not have specific
7712  * (or sufficient) routing information.
7713  *
7714  * NOTE : These are the scopes of some of the variables that point at IRE,
7715  *	  which needs to be followed while making any future modifications
7716  *	  to avoid memory leaks.
7717  *
7718  *	- ire and sire are the entries looked up initially by
7719  *	  ire_ftable_lookup.
7720  *	- ipif_ire is used to hold the interface ire associated with
7721  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7722  *	  it before branching out to error paths.
7723  *	- save_ire is initialized before ire_create, so that ire returned
7724  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7725  *	  before breaking out of the switch.
7726  *
7727  *	Thus on failures, we have to REFRELE only ire and sire, if they
7728  *	are not NULL.
7729  */
7730 void
7731 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7732     zoneid_t zoneid, ip_stack_t *ipst)
7733 {
7734 	areq_t	*areq;
7735 	ipaddr_t gw = 0;
7736 	ire_t	*ire = NULL;
7737 	mblk_t	*res_mp;
7738 	ipaddr_t *addrp;
7739 	ipaddr_t nexthop_addr;
7740 	ipif_t  *src_ipif = NULL;
7741 	ill_t	*dst_ill = NULL;
7742 	ipha_t  *ipha;
7743 	ire_t	*sire = NULL;
7744 	mblk_t	*first_mp;
7745 	ire_t	*save_ire;
7746 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7747 	ushort_t ire_marks = 0;
7748 	boolean_t mctl_present;
7749 	ipsec_out_t *io;
7750 	mblk_t	*saved_mp;
7751 	ire_t	*first_sire = NULL;
7752 	mblk_t	*copy_mp = NULL;
7753 	mblk_t	*xmit_mp = NULL;
7754 	ipaddr_t save_dst;
7755 	uint32_t multirt_flags =
7756 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7757 	boolean_t multirt_is_resolvable;
7758 	boolean_t multirt_resolve_next;
7759 	boolean_t unspec_src;
7760 	boolean_t do_attach_ill = B_FALSE;
7761 	boolean_t ip_nexthop = B_FALSE;
7762 	tsol_ire_gw_secattr_t *attrp = NULL;
7763 	tsol_gcgrp_t *gcgrp = NULL;
7764 	tsol_gcgrp_addr_t ga;
7765 
7766 	if (ip_debug > 2) {
7767 		/* ip1dbg */
7768 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7769 	}
7770 
7771 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7772 	if (mctl_present) {
7773 		io = (ipsec_out_t *)first_mp->b_rptr;
7774 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7775 		ASSERT(zoneid == io->ipsec_out_zoneid);
7776 		ASSERT(zoneid != ALL_ZONES);
7777 	}
7778 
7779 	ipha = (ipha_t *)mp->b_rptr;
7780 
7781 	/* All multicast lookups come through ip_newroute_ipif() */
7782 	if (CLASSD(dst)) {
7783 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7784 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7785 		freemsg(first_mp);
7786 		return;
7787 	}
7788 
7789 	if (mctl_present && io->ipsec_out_attach_if) {
7790 		/* ip_grab_attach_ill returns a held ill */
7791 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7792 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7793 
7794 		/* Failure case frees things for us. */
7795 		if (attach_ill == NULL)
7796 			return;
7797 
7798 		/*
7799 		 * Check if we need an ire that will not be
7800 		 * looked up by anybody else i.e. HIDDEN.
7801 		 */
7802 		if (ill_is_probeonly(attach_ill))
7803 			ire_marks = IRE_MARK_HIDDEN;
7804 	}
7805 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7806 		ip_nexthop = B_TRUE;
7807 		nexthop_addr = io->ipsec_out_nexthop_addr;
7808 	}
7809 	/*
7810 	 * If this IRE is created for forwarding or it is not for
7811 	 * traffic for congestion controlled protocols, mark it as temporary.
7812 	 */
7813 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7814 		ire_marks |= IRE_MARK_TEMPORARY;
7815 
7816 	/*
7817 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7818 	 * chain until it gets the most specific information available.
7819 	 * For example, we know that there is no IRE_CACHE for this dest,
7820 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7821 	 * ire_ftable_lookup will look up the gateway, etc.
7822 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7823 	 * to the destination, of equal netmask length in the forward table,
7824 	 * will be recursively explored. If no information is available
7825 	 * for the final gateway of that route, we force the returned ire
7826 	 * to be equal to sire using MATCH_IRE_PARENT.
7827 	 * At least, in this case we have a starting point (in the buckets)
7828 	 * to look for other routes to the destination in the forward table.
7829 	 * This is actually used only for multirouting, where a list
7830 	 * of routes has to be processed in sequence.
7831 	 *
7832 	 * In the process of coming up with the most specific information,
7833 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7834 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7835 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7836 	 * Two caveats when handling incomplete ire's in ip_newroute:
7837 	 * - we should be careful when accessing its ire_nce (specifically
7838 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7839 	 * - not all legacy code path callers are prepared to handle
7840 	 *   incomplete ire's, so we should not create/add incomplete
7841 	 *   ire_cache entries here. (See discussion about temporary solution
7842 	 *   further below).
7843 	 *
7844 	 * In order to minimize packet dropping, and to preserve existing
7845 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7846 	 * gateway, and instead use the IF_RESOLVER ire to send out
7847 	 * another request to ARP (this is achieved by passing the
7848 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7849 	 * arp response comes back in ip_wput_nondata, we will create
7850 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7851 	 *
7852 	 * Note that this is a temporary solution; the correct solution is
7853 	 * to create an incomplete  per-dst ire_cache entry, and send the
7854 	 * packet out when the gw's nce is resolved. In order to achieve this,
7855 	 * all packet processing must have been completed prior to calling
7856 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7857 	 * to be modified to accomodate this solution.
7858 	 */
7859 	if (ip_nexthop) {
7860 		/*
7861 		 * The first time we come here, we look for an IRE_INTERFACE
7862 		 * entry for the specified nexthop, set the dst to be the
7863 		 * nexthop address and create an IRE_CACHE entry for the
7864 		 * nexthop. The next time around, we are able to find an
7865 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7866 		 * nexthop address and create an IRE_CACHE entry for the
7867 		 * destination address via the specified nexthop.
7868 		 */
7869 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7870 		    MBLK_GETLABEL(mp), ipst);
7871 		if (ire != NULL) {
7872 			gw = nexthop_addr;
7873 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7874 		} else {
7875 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7876 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7877 			    MBLK_GETLABEL(mp),
7878 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7879 			    ipst);
7880 			if (ire != NULL) {
7881 				dst = nexthop_addr;
7882 			}
7883 		}
7884 	} else if (attach_ill == NULL) {
7885 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7886 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7887 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7888 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7889 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7890 		    ipst);
7891 	} else {
7892 		/*
7893 		 * attach_ill is set only for communicating with
7894 		 * on-link hosts. So, don't look for DEFAULT.
7895 		 */
7896 		ipif_t	*attach_ipif;
7897 
7898 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7899 		if (attach_ipif == NULL) {
7900 			ill_refrele(attach_ill);
7901 			goto icmp_err_ret;
7902 		}
7903 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7904 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7905 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7906 		    MATCH_IRE_SECATTR, ipst);
7907 		ipif_refrele(attach_ipif);
7908 	}
7909 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7910 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7911 
7912 	/*
7913 	 * This loop is run only once in most cases.
7914 	 * We loop to resolve further routes only when the destination
7915 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7916 	 */
7917 	do {
7918 		/* Clear the previous iteration's values */
7919 		if (src_ipif != NULL) {
7920 			ipif_refrele(src_ipif);
7921 			src_ipif = NULL;
7922 		}
7923 		if (dst_ill != NULL) {
7924 			ill_refrele(dst_ill);
7925 			dst_ill = NULL;
7926 		}
7927 
7928 		multirt_resolve_next = B_FALSE;
7929 		/*
7930 		 * We check if packets have to be multirouted.
7931 		 * In this case, given the current <ire, sire> couple,
7932 		 * we look for the next suitable <ire, sire>.
7933 		 * This check is done in ire_multirt_lookup(),
7934 		 * which applies various criteria to find the next route
7935 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7936 		 * unchanged if it detects it has not been tried yet.
7937 		 */
7938 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7939 			ip3dbg(("ip_newroute: starting next_resolution "
7940 			    "with first_mp %p, tag %d\n",
7941 			    (void *)first_mp,
7942 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7943 
7944 			ASSERT(sire != NULL);
7945 			multirt_is_resolvable =
7946 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7947 			    MBLK_GETLABEL(mp), ipst);
7948 
7949 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7950 			    "ire %p, sire %p\n",
7951 			    multirt_is_resolvable,
7952 			    (void *)ire, (void *)sire));
7953 
7954 			if (!multirt_is_resolvable) {
7955 				/*
7956 				 * No more multirt route to resolve; give up
7957 				 * (all routes resolved or no more
7958 				 * resolvable routes).
7959 				 */
7960 				if (ire != NULL) {
7961 					ire_refrele(ire);
7962 					ire = NULL;
7963 				}
7964 			} else {
7965 				ASSERT(sire != NULL);
7966 				ASSERT(ire != NULL);
7967 				/*
7968 				 * We simply use first_sire as a flag that
7969 				 * indicates if a resolvable multirt route
7970 				 * has already been found.
7971 				 * If it is not the case, we may have to send
7972 				 * an ICMP error to report that the
7973 				 * destination is unreachable.
7974 				 * We do not IRE_REFHOLD first_sire.
7975 				 */
7976 				if (first_sire == NULL) {
7977 					first_sire = sire;
7978 				}
7979 			}
7980 		}
7981 		if (ire == NULL) {
7982 			if (ip_debug > 3) {
7983 				/* ip2dbg */
7984 				pr_addr_dbg("ip_newroute: "
7985 				    "can't resolve %s\n", AF_INET, &dst);
7986 			}
7987 			ip3dbg(("ip_newroute: "
7988 			    "ire %p, sire %p, first_sire %p\n",
7989 			    (void *)ire, (void *)sire, (void *)first_sire));
7990 
7991 			if (sire != NULL) {
7992 				ire_refrele(sire);
7993 				sire = NULL;
7994 			}
7995 
7996 			if (first_sire != NULL) {
7997 				/*
7998 				 * At least one multirt route has been found
7999 				 * in the same call to ip_newroute();
8000 				 * there is no need to report an ICMP error.
8001 				 * first_sire was not IRE_REFHOLDed.
8002 				 */
8003 				MULTIRT_DEBUG_UNTAG(first_mp);
8004 				freemsg(first_mp);
8005 				return;
8006 			}
8007 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8008 			    RTA_DST, ipst);
8009 			if (attach_ill != NULL)
8010 				ill_refrele(attach_ill);
8011 			goto icmp_err_ret;
8012 		}
8013 
8014 		/*
8015 		 * Verify that the returned IRE does not have either
8016 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8017 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8018 		 */
8019 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8020 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8021 			if (attach_ill != NULL)
8022 				ill_refrele(attach_ill);
8023 			goto icmp_err_ret;
8024 		}
8025 		/*
8026 		 * Increment the ire_ob_pkt_count field for ire if it is an
8027 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8028 		 * increment the same for the parent IRE, sire, if it is some
8029 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8030 		 */
8031 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8032 			UPDATE_OB_PKT_COUNT(ire);
8033 			ire->ire_last_used_time = lbolt;
8034 		}
8035 
8036 		if (sire != NULL) {
8037 			gw = sire->ire_gateway_addr;
8038 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8039 			    IRE_INTERFACE)) == 0);
8040 			UPDATE_OB_PKT_COUNT(sire);
8041 			sire->ire_last_used_time = lbolt;
8042 		}
8043 		/*
8044 		 * We have a route to reach the destination.
8045 		 *
8046 		 * 1) If the interface is part of ill group, try to get a new
8047 		 *    ill taking load spreading into account.
8048 		 *
8049 		 * 2) After selecting the ill, get a source address that
8050 		 *    might create good inbound load spreading.
8051 		 *    ipif_select_source does this for us.
8052 		 *
8053 		 * If the application specified the ill (ifindex), we still
8054 		 * load spread. Only if the packets needs to go out
8055 		 * specifically on a given ill e.g. binding to
8056 		 * IPIF_NOFAILOVER address, then we don't try to use a
8057 		 * different ill for load spreading.
8058 		 */
8059 		if (attach_ill == NULL) {
8060 			/*
8061 			 * Don't perform outbound load spreading in the
8062 			 * case of an RTF_MULTIRT route, as we actually
8063 			 * typically want to replicate outgoing packets
8064 			 * through particular interfaces.
8065 			 */
8066 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8067 				dst_ill = ire->ire_ipif->ipif_ill;
8068 				/* for uniformity */
8069 				ill_refhold(dst_ill);
8070 			} else {
8071 				/*
8072 				 * If we are here trying to create an IRE_CACHE
8073 				 * for an offlink destination and have the
8074 				 * IRE_CACHE for the next hop and the latter is
8075 				 * using virtual IP source address selection i.e
8076 				 * it's ire->ire_ipif is pointing to a virtual
8077 				 * network interface (vni) then
8078 				 * ip_newroute_get_dst_ll() will return the vni
8079 				 * interface as the dst_ill. Since the vni is
8080 				 * virtual i.e not associated with any physical
8081 				 * interface, it cannot be the dst_ill, hence
8082 				 * in such a case call ip_newroute_get_dst_ll()
8083 				 * with the stq_ill instead of the ire_ipif ILL.
8084 				 * The function returns a refheld ill.
8085 				 */
8086 				if ((ire->ire_type == IRE_CACHE) &&
8087 				    IS_VNI(ire->ire_ipif->ipif_ill))
8088 					dst_ill = ip_newroute_get_dst_ill(
8089 					    ire->ire_stq->q_ptr);
8090 				else
8091 					dst_ill = ip_newroute_get_dst_ill(
8092 					    ire->ire_ipif->ipif_ill);
8093 			}
8094 			if (dst_ill == NULL) {
8095 				if (ip_debug > 2) {
8096 					pr_addr_dbg("ip_newroute: "
8097 					    "no dst ill for dst"
8098 					    " %s\n", AF_INET, &dst);
8099 				}
8100 				goto icmp_err_ret;
8101 			}
8102 		} else {
8103 			dst_ill = ire->ire_ipif->ipif_ill;
8104 			/* for uniformity */
8105 			ill_refhold(dst_ill);
8106 			/*
8107 			 * We should have found a route matching ill as we
8108 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8109 			 * Rather than asserting, when there is a mismatch,
8110 			 * we just drop the packet.
8111 			 */
8112 			if (dst_ill != attach_ill) {
8113 				ip0dbg(("ip_newroute: Packet dropped as "
8114 				    "IPIF_NOFAILOVER ill is %s, "
8115 				    "ire->ire_ipif->ipif_ill is %s\n",
8116 				    attach_ill->ill_name,
8117 				    dst_ill->ill_name));
8118 				ill_refrele(attach_ill);
8119 				goto icmp_err_ret;
8120 			}
8121 		}
8122 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8123 		if (attach_ill != NULL) {
8124 			ill_refrele(attach_ill);
8125 			attach_ill = NULL;
8126 			do_attach_ill = B_TRUE;
8127 		}
8128 		ASSERT(dst_ill != NULL);
8129 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8130 
8131 		/*
8132 		 * Pick the best source address from dst_ill.
8133 		 *
8134 		 * 1) If it is part of a multipathing group, we would
8135 		 *    like to spread the inbound packets across different
8136 		 *    interfaces. ipif_select_source picks a random source
8137 		 *    across the different ills in the group.
8138 		 *
8139 		 * 2) If it is not part of a multipathing group, we try
8140 		 *    to pick the source address from the destination
8141 		 *    route. Clustering assumes that when we have multiple
8142 		 *    prefixes hosted on an interface, the prefix of the
8143 		 *    source address matches the prefix of the destination
8144 		 *    route. We do this only if the address is not
8145 		 *    DEPRECATED.
8146 		 *
8147 		 * 3) If the conn is in a different zone than the ire, we
8148 		 *    need to pick a source address from the right zone.
8149 		 *
8150 		 * NOTE : If we hit case (1) above, the prefix of the source
8151 		 *	  address picked may not match the prefix of the
8152 		 *	  destination routes prefix as ipif_select_source
8153 		 *	  does not look at "dst" while picking a source
8154 		 *	  address.
8155 		 *	  If we want the same behavior as (2), we will need
8156 		 *	  to change the behavior of ipif_select_source.
8157 		 */
8158 		ASSERT(src_ipif == NULL);
8159 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8160 			/*
8161 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8162 			 * Check that the ipif matching the requested source
8163 			 * address still exists.
8164 			 */
8165 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8166 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8167 		}
8168 
8169 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8170 
8171 		if (src_ipif == NULL &&
8172 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8173 			ire_marks |= IRE_MARK_USESRC_CHECK;
8174 			if ((dst_ill->ill_group != NULL) ||
8175 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8176 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8177 			    ire->ire_zoneid != ALL_ZONES) ||
8178 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8179 				/*
8180 				 * If the destination is reachable via a
8181 				 * given gateway, the selected source address
8182 				 * should be in the same subnet as the gateway.
8183 				 * Otherwise, the destination is not reachable.
8184 				 *
8185 				 * If there are no interfaces on the same subnet
8186 				 * as the destination, ipif_select_source gives
8187 				 * first non-deprecated interface which might be
8188 				 * on a different subnet than the gateway.
8189 				 * This is not desirable. Hence pass the dst_ire
8190 				 * source address to ipif_select_source.
8191 				 * It is sure that the destination is reachable
8192 				 * with the dst_ire source address subnet.
8193 				 * So passing dst_ire source address to
8194 				 * ipif_select_source will make sure that the
8195 				 * selected source will be on the same subnet
8196 				 * as dst_ire source address.
8197 				 */
8198 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8199 				src_ipif = ipif_select_source(dst_ill, saddr,
8200 				    zoneid);
8201 				if (src_ipif == NULL) {
8202 					if (ip_debug > 2) {
8203 						pr_addr_dbg("ip_newroute: "
8204 						    "no src for dst %s ",
8205 						    AF_INET, &dst);
8206 						printf("through interface %s\n",
8207 						    dst_ill->ill_name);
8208 					}
8209 					goto icmp_err_ret;
8210 				}
8211 			} else {
8212 				src_ipif = ire->ire_ipif;
8213 				ASSERT(src_ipif != NULL);
8214 				/* hold src_ipif for uniformity */
8215 				ipif_refhold(src_ipif);
8216 			}
8217 		}
8218 
8219 		/*
8220 		 * Assign a source address while we have the conn.
8221 		 * We can't have ip_wput_ire pick a source address when the
8222 		 * packet returns from arp since we need to look at
8223 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8224 		 * going through arp.
8225 		 *
8226 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8227 		 *	  it uses ip6i to store this information.
8228 		 */
8229 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8230 			ipha->ipha_src = src_ipif->ipif_src_addr;
8231 
8232 		if (ip_debug > 3) {
8233 			/* ip2dbg */
8234 			pr_addr_dbg("ip_newroute: first hop %s\n",
8235 			    AF_INET, &gw);
8236 		}
8237 		ip2dbg(("\tire type %s (%d)\n",
8238 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8239 
8240 		/*
8241 		 * The TTL of multirouted packets is bounded by the
8242 		 * ip_multirt_ttl ndd variable.
8243 		 */
8244 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8245 			/* Force TTL of multirouted packets */
8246 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8247 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8248 				ip2dbg(("ip_newroute: forcing multirt TTL "
8249 				    "to %d (was %d), dst 0x%08x\n",
8250 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8251 				    ntohl(sire->ire_addr)));
8252 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8253 			}
8254 		}
8255 		/*
8256 		 * At this point in ip_newroute(), ire is either the
8257 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8258 		 * destination or an IRE_INTERFACE type that should be used
8259 		 * to resolve an on-subnet destination or an on-subnet
8260 		 * next-hop gateway.
8261 		 *
8262 		 * In the IRE_CACHE case, we have the following :
8263 		 *
8264 		 * 1) src_ipif - used for getting a source address.
8265 		 *
8266 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8267 		 *    means packets using this IRE_CACHE will go out on
8268 		 *    dst_ill.
8269 		 *
8270 		 * 3) The IRE sire will point to the prefix that is the
8271 		 *    longest  matching route for the destination. These
8272 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8273 		 *
8274 		 *    The newly created IRE_CACHE entry for the off-subnet
8275 		 *    destination is tied to both the prefix route and the
8276 		 *    interface route used to resolve the next-hop gateway
8277 		 *    via the ire_phandle and ire_ihandle fields,
8278 		 *    respectively.
8279 		 *
8280 		 * In the IRE_INTERFACE case, we have the following :
8281 		 *
8282 		 * 1) src_ipif - used for getting a source address.
8283 		 *
8284 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8285 		 *    means packets using the IRE_CACHE that we will build
8286 		 *    here will go out on dst_ill.
8287 		 *
8288 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8289 		 *    to be created will only be tied to the IRE_INTERFACE
8290 		 *    that was derived from the ire_ihandle field.
8291 		 *
8292 		 *    If sire is non-NULL, it means the destination is
8293 		 *    off-link and we will first create the IRE_CACHE for the
8294 		 *    gateway. Next time through ip_newroute, we will create
8295 		 *    the IRE_CACHE for the final destination as described
8296 		 *    above.
8297 		 *
8298 		 * In both cases, after the current resolution has been
8299 		 * completed (or possibly initialised, in the IRE_INTERFACE
8300 		 * case), the loop may be re-entered to attempt the resolution
8301 		 * of another RTF_MULTIRT route.
8302 		 *
8303 		 * When an IRE_CACHE entry for the off-subnet destination is
8304 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8305 		 * for further processing in emission loops.
8306 		 */
8307 		save_ire = ire;
8308 		switch (ire->ire_type) {
8309 		case IRE_CACHE: {
8310 			ire_t	*ipif_ire;
8311 
8312 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8313 			if (gw == 0)
8314 				gw = ire->ire_gateway_addr;
8315 			/*
8316 			 * We need 3 ire's to create a new cache ire for an
8317 			 * off-link destination from the cache ire of the
8318 			 * gateway.
8319 			 *
8320 			 *	1. The prefix ire 'sire' (Note that this does
8321 			 *	   not apply to the conn_nexthop_set case)
8322 			 *	2. The cache ire of the gateway 'ire'
8323 			 *	3. The interface ire 'ipif_ire'
8324 			 *
8325 			 * We have (1) and (2). We lookup (3) below.
8326 			 *
8327 			 * If there is no interface route to the gateway,
8328 			 * it is a race condition, where we found the cache
8329 			 * but the interface route has been deleted.
8330 			 */
8331 			if (ip_nexthop) {
8332 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8333 			} else {
8334 				ipif_ire =
8335 				    ire_ihandle_lookup_offlink(ire, sire);
8336 			}
8337 			if (ipif_ire == NULL) {
8338 				ip1dbg(("ip_newroute: "
8339 				    "ire_ihandle_lookup_offlink failed\n"));
8340 				goto icmp_err_ret;
8341 			}
8342 
8343 			/*
8344 			 * Check cached gateway IRE for any security
8345 			 * attributes; if found, associate the gateway
8346 			 * credentials group to the destination IRE.
8347 			 */
8348 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8349 				mutex_enter(&attrp->igsa_lock);
8350 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8351 					GCGRP_REFHOLD(gcgrp);
8352 				mutex_exit(&attrp->igsa_lock);
8353 			}
8354 
8355 			/*
8356 			 * XXX For the source of the resolver mp,
8357 			 * we are using the same DL_UNITDATA_REQ
8358 			 * (from save_ire->ire_nce->nce_res_mp)
8359 			 * though the save_ire is not pointing at the same ill.
8360 			 * This is incorrect. We need to send it up to the
8361 			 * resolver to get the right res_mp. For ethernets
8362 			 * this may be okay (ill_type == DL_ETHER).
8363 			 */
8364 
8365 			ire = ire_create(
8366 			    (uchar_t *)&dst,		/* dest address */
8367 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8368 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8369 			    (uchar_t *)&gw,		/* gateway address */
8370 			    &save_ire->ire_max_frag,
8371 			    save_ire->ire_nce,		/* src nce */
8372 			    dst_ill->ill_rq,		/* recv-from queue */
8373 			    dst_ill->ill_wq,		/* send-to queue */
8374 			    IRE_CACHE,			/* IRE type */
8375 			    src_ipif,
8376 			    (sire != NULL) ?
8377 			    sire->ire_mask : 0, 	/* Parent mask */
8378 			    (sire != NULL) ?
8379 			    sire->ire_phandle : 0,	/* Parent handle */
8380 			    ipif_ire->ire_ihandle,	/* Interface handle */
8381 			    (sire != NULL) ? (sire->ire_flags &
8382 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8383 			    (sire != NULL) ?
8384 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8385 			    NULL,
8386 			    gcgrp,
8387 			    ipst);
8388 
8389 			if (ire == NULL) {
8390 				if (gcgrp != NULL) {
8391 					GCGRP_REFRELE(gcgrp);
8392 					gcgrp = NULL;
8393 				}
8394 				ire_refrele(ipif_ire);
8395 				ire_refrele(save_ire);
8396 				break;
8397 			}
8398 
8399 			/* reference now held by IRE */
8400 			gcgrp = NULL;
8401 
8402 			ire->ire_marks |= ire_marks;
8403 
8404 			/*
8405 			 * Prevent sire and ipif_ire from getting deleted.
8406 			 * The newly created ire is tied to both of them via
8407 			 * the phandle and ihandle respectively.
8408 			 */
8409 			if (sire != NULL) {
8410 				IRB_REFHOLD(sire->ire_bucket);
8411 				/* Has it been removed already ? */
8412 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8413 					IRB_REFRELE(sire->ire_bucket);
8414 					ire_refrele(ipif_ire);
8415 					ire_refrele(save_ire);
8416 					break;
8417 				}
8418 			}
8419 
8420 			IRB_REFHOLD(ipif_ire->ire_bucket);
8421 			/* Has it been removed already ? */
8422 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8423 				IRB_REFRELE(ipif_ire->ire_bucket);
8424 				if (sire != NULL)
8425 					IRB_REFRELE(sire->ire_bucket);
8426 				ire_refrele(ipif_ire);
8427 				ire_refrele(save_ire);
8428 				break;
8429 			}
8430 
8431 			xmit_mp = first_mp;
8432 			/*
8433 			 * In the case of multirouting, a copy
8434 			 * of the packet is done before its sending.
8435 			 * The copy is used to attempt another
8436 			 * route resolution, in a next loop.
8437 			 */
8438 			if (ire->ire_flags & RTF_MULTIRT) {
8439 				copy_mp = copymsg(first_mp);
8440 				if (copy_mp != NULL) {
8441 					xmit_mp = copy_mp;
8442 					MULTIRT_DEBUG_TAG(first_mp);
8443 				}
8444 			}
8445 			ire_add_then_send(q, ire, xmit_mp);
8446 			ire_refrele(save_ire);
8447 
8448 			/* Assert that sire is not deleted yet. */
8449 			if (sire != NULL) {
8450 				ASSERT(sire->ire_ptpn != NULL);
8451 				IRB_REFRELE(sire->ire_bucket);
8452 			}
8453 
8454 			/* Assert that ipif_ire is not deleted yet. */
8455 			ASSERT(ipif_ire->ire_ptpn != NULL);
8456 			IRB_REFRELE(ipif_ire->ire_bucket);
8457 			ire_refrele(ipif_ire);
8458 
8459 			/*
8460 			 * If copy_mp is not NULL, multirouting was
8461 			 * requested. We loop to initiate a next
8462 			 * route resolution attempt, starting from sire.
8463 			 */
8464 			if (copy_mp != NULL) {
8465 				/*
8466 				 * Search for the next unresolved
8467 				 * multirt route.
8468 				 */
8469 				copy_mp = NULL;
8470 				ipif_ire = NULL;
8471 				ire = NULL;
8472 				multirt_resolve_next = B_TRUE;
8473 				continue;
8474 			}
8475 			if (sire != NULL)
8476 				ire_refrele(sire);
8477 			ipif_refrele(src_ipif);
8478 			ill_refrele(dst_ill);
8479 			return;
8480 		}
8481 		case IRE_IF_NORESOLVER: {
8482 
8483 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8484 			    dst_ill->ill_resolver_mp == NULL) {
8485 				ip1dbg(("ip_newroute: dst_ill %p "
8486 				    "for IRE_IF_NORESOLVER ire %p has "
8487 				    "no ill_resolver_mp\n",
8488 				    (void *)dst_ill, (void *)ire));
8489 				break;
8490 			}
8491 
8492 			/*
8493 			 * TSol note: We are creating the ire cache for the
8494 			 * destination 'dst'. If 'dst' is offlink, going
8495 			 * through the first hop 'gw', the security attributes
8496 			 * of 'dst' must be set to point to the gateway
8497 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8498 			 * is possible that 'dst' is a potential gateway that is
8499 			 * referenced by some route that has some security
8500 			 * attributes. Thus in the former case, we need to do a
8501 			 * gcgrp_lookup of 'gw' while in the latter case we
8502 			 * need to do gcgrp_lookup of 'dst' itself.
8503 			 */
8504 			ga.ga_af = AF_INET;
8505 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8506 			    &ga.ga_addr);
8507 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8508 
8509 			ire = ire_create(
8510 			    (uchar_t *)&dst,		/* dest address */
8511 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8512 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8513 			    (uchar_t *)&gw,		/* gateway address */
8514 			    &save_ire->ire_max_frag,
8515 			    NULL,			/* no src nce */
8516 			    dst_ill->ill_rq,		/* recv-from queue */
8517 			    dst_ill->ill_wq,		/* send-to queue */
8518 			    IRE_CACHE,
8519 			    src_ipif,
8520 			    save_ire->ire_mask,		/* Parent mask */
8521 			    (sire != NULL) ?		/* Parent handle */
8522 			    sire->ire_phandle : 0,
8523 			    save_ire->ire_ihandle,	/* Interface handle */
8524 			    (sire != NULL) ? sire->ire_flags &
8525 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8526 			    &(save_ire->ire_uinfo),
8527 			    NULL,
8528 			    gcgrp,
8529 			    ipst);
8530 
8531 			if (ire == NULL) {
8532 				if (gcgrp != NULL) {
8533 					GCGRP_REFRELE(gcgrp);
8534 					gcgrp = NULL;
8535 				}
8536 				ire_refrele(save_ire);
8537 				break;
8538 			}
8539 
8540 			/* reference now held by IRE */
8541 			gcgrp = NULL;
8542 
8543 			ire->ire_marks |= ire_marks;
8544 
8545 			/* Prevent save_ire from getting deleted */
8546 			IRB_REFHOLD(save_ire->ire_bucket);
8547 			/* Has it been removed already ? */
8548 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8549 				IRB_REFRELE(save_ire->ire_bucket);
8550 				ire_refrele(save_ire);
8551 				break;
8552 			}
8553 
8554 			/*
8555 			 * In the case of multirouting, a copy
8556 			 * of the packet is made before it is sent.
8557 			 * The copy is used in the next
8558 			 * loop to attempt another resolution.
8559 			 */
8560 			xmit_mp = first_mp;
8561 			if ((sire != NULL) &&
8562 			    (sire->ire_flags & RTF_MULTIRT)) {
8563 				copy_mp = copymsg(first_mp);
8564 				if (copy_mp != NULL) {
8565 					xmit_mp = copy_mp;
8566 					MULTIRT_DEBUG_TAG(first_mp);
8567 				}
8568 			}
8569 			ire_add_then_send(q, ire, xmit_mp);
8570 
8571 			/* Assert that it is not deleted yet. */
8572 			ASSERT(save_ire->ire_ptpn != NULL);
8573 			IRB_REFRELE(save_ire->ire_bucket);
8574 			ire_refrele(save_ire);
8575 
8576 			if (copy_mp != NULL) {
8577 				/*
8578 				 * If we found a (no)resolver, we ignore any
8579 				 * trailing top priority IRE_CACHE in further
8580 				 * loops. This ensures that we do not omit any
8581 				 * (no)resolver.
8582 				 * This IRE_CACHE, if any, will be processed
8583 				 * by another thread entering ip_newroute().
8584 				 * IRE_CACHE entries, if any, will be processed
8585 				 * by another thread entering ip_newroute(),
8586 				 * (upon resolver response, for instance).
8587 				 * This aims to force parallel multirt
8588 				 * resolutions as soon as a packet must be sent.
8589 				 * In the best case, after the tx of only one
8590 				 * packet, all reachable routes are resolved.
8591 				 * Otherwise, the resolution of all RTF_MULTIRT
8592 				 * routes would require several emissions.
8593 				 */
8594 				multirt_flags &= ~MULTIRT_CACHEGW;
8595 
8596 				/*
8597 				 * Search for the next unresolved multirt
8598 				 * route.
8599 				 */
8600 				copy_mp = NULL;
8601 				save_ire = NULL;
8602 				ire = NULL;
8603 				multirt_resolve_next = B_TRUE;
8604 				continue;
8605 			}
8606 
8607 			/*
8608 			 * Don't need sire anymore
8609 			 */
8610 			if (sire != NULL)
8611 				ire_refrele(sire);
8612 
8613 			ipif_refrele(src_ipif);
8614 			ill_refrele(dst_ill);
8615 			return;
8616 		}
8617 		case IRE_IF_RESOLVER:
8618 			/*
8619 			 * We can't build an IRE_CACHE yet, but at least we
8620 			 * found a resolver that can help.
8621 			 */
8622 			res_mp = dst_ill->ill_resolver_mp;
8623 			if (!OK_RESOLVER_MP(res_mp))
8624 				break;
8625 
8626 			/*
8627 			 * To be at this point in the code with a non-zero gw
8628 			 * means that dst is reachable through a gateway that
8629 			 * we have never resolved.  By changing dst to the gw
8630 			 * addr we resolve the gateway first.
8631 			 * When ire_add_then_send() tries to put the IP dg
8632 			 * to dst, it will reenter ip_newroute() at which
8633 			 * time we will find the IRE_CACHE for the gw and
8634 			 * create another IRE_CACHE in case IRE_CACHE above.
8635 			 */
8636 			if (gw != INADDR_ANY) {
8637 				/*
8638 				 * The source ipif that was determined above was
8639 				 * relative to the destination address, not the
8640 				 * gateway's. If src_ipif was not taken out of
8641 				 * the IRE_IF_RESOLVER entry, we'll need to call
8642 				 * ipif_select_source() again.
8643 				 */
8644 				if (src_ipif != ire->ire_ipif) {
8645 					ipif_refrele(src_ipif);
8646 					src_ipif = ipif_select_source(dst_ill,
8647 					    gw, zoneid);
8648 					if (src_ipif == NULL) {
8649 						if (ip_debug > 2) {
8650 							pr_addr_dbg(
8651 							    "ip_newroute: no "
8652 							    "src for gw %s ",
8653 							    AF_INET, &gw);
8654 							printf("through "
8655 							    "interface %s\n",
8656 							    dst_ill->ill_name);
8657 						}
8658 						goto icmp_err_ret;
8659 					}
8660 				}
8661 				save_dst = dst;
8662 				dst = gw;
8663 				gw = INADDR_ANY;
8664 			}
8665 
8666 			/*
8667 			 * We obtain a partial IRE_CACHE which we will pass
8668 			 * along with the resolver query.  When the response
8669 			 * comes back it will be there ready for us to add.
8670 			 * The ire_max_frag is atomically set under the
8671 			 * irebucket lock in ire_add_v[46].
8672 			 */
8673 
8674 			ire = ire_create_mp(
8675 			    (uchar_t *)&dst,		/* dest address */
8676 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8677 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8678 			    (uchar_t *)&gw,		/* gateway address */
8679 			    NULL,			/* ire_max_frag */
8680 			    NULL,			/* no src nce */
8681 			    dst_ill->ill_rq,		/* recv-from queue */
8682 			    dst_ill->ill_wq,		/* send-to queue */
8683 			    IRE_CACHE,
8684 			    src_ipif,			/* Interface ipif */
8685 			    save_ire->ire_mask,		/* Parent mask */
8686 			    0,
8687 			    save_ire->ire_ihandle,	/* Interface handle */
8688 			    0,				/* flags if any */
8689 			    &(save_ire->ire_uinfo),
8690 			    NULL,
8691 			    NULL,
8692 			    ipst);
8693 
8694 			if (ire == NULL) {
8695 				ire_refrele(save_ire);
8696 				break;
8697 			}
8698 
8699 			if ((sire != NULL) &&
8700 			    (sire->ire_flags & RTF_MULTIRT)) {
8701 				copy_mp = copymsg(first_mp);
8702 				if (copy_mp != NULL)
8703 					MULTIRT_DEBUG_TAG(copy_mp);
8704 			}
8705 
8706 			ire->ire_marks |= ire_marks;
8707 
8708 			/*
8709 			 * Construct message chain for the resolver
8710 			 * of the form:
8711 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8712 			 * Packet could contain a IPSEC_OUT mp.
8713 			 *
8714 			 * NOTE : ire will be added later when the response
8715 			 * comes back from ARP. If the response does not
8716 			 * come back, ARP frees the packet. For this reason,
8717 			 * we can't REFHOLD the bucket of save_ire to prevent
8718 			 * deletions. We may not be able to REFRELE the bucket
8719 			 * if the response never comes back. Thus, before
8720 			 * adding the ire, ire_add_v4 will make sure that the
8721 			 * interface route does not get deleted. This is the
8722 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8723 			 * where we can always prevent deletions because of
8724 			 * the synchronous nature of adding IRES i.e
8725 			 * ire_add_then_send is called after creating the IRE.
8726 			 */
8727 			ASSERT(ire->ire_mp != NULL);
8728 			ire->ire_mp->b_cont = first_mp;
8729 			/* Have saved_mp handy, for cleanup if canput fails */
8730 			saved_mp = mp;
8731 			mp = copyb(res_mp);
8732 			if (mp == NULL) {
8733 				/* Prepare for cleanup */
8734 				mp = saved_mp; /* pkt */
8735 				ire_delete(ire); /* ire_mp */
8736 				ire = NULL;
8737 				ire_refrele(save_ire);
8738 				if (copy_mp != NULL) {
8739 					MULTIRT_DEBUG_UNTAG(copy_mp);
8740 					freemsg(copy_mp);
8741 					copy_mp = NULL;
8742 				}
8743 				break;
8744 			}
8745 			linkb(mp, ire->ire_mp);
8746 
8747 			/*
8748 			 * Fill in the source and dest addrs for the resolver.
8749 			 * NOTE: this depends on memory layouts imposed by
8750 			 * ill_init().
8751 			 */
8752 			areq = (areq_t *)mp->b_rptr;
8753 			addrp = (ipaddr_t *)((char *)areq +
8754 			    areq->areq_sender_addr_offset);
8755 			if (do_attach_ill) {
8756 				/*
8757 				 * This is bind to no failover case.
8758 				 * arp packet also must go out on attach_ill.
8759 				 */
8760 				ASSERT(ipha->ipha_src != NULL);
8761 				*addrp = ipha->ipha_src;
8762 			} else {
8763 				*addrp = save_ire->ire_src_addr;
8764 			}
8765 
8766 			ire_refrele(save_ire);
8767 			addrp = (ipaddr_t *)((char *)areq +
8768 			    areq->areq_target_addr_offset);
8769 			*addrp = dst;
8770 			/* Up to the resolver. */
8771 			if (canputnext(dst_ill->ill_rq) &&
8772 			    !(dst_ill->ill_arp_closing)) {
8773 				putnext(dst_ill->ill_rq, mp);
8774 				ire = NULL;
8775 				if (copy_mp != NULL) {
8776 					/*
8777 					 * If we found a resolver, we ignore
8778 					 * any trailing top priority IRE_CACHE
8779 					 * in the further loops. This ensures
8780 					 * that we do not omit any resolver.
8781 					 * IRE_CACHE entries, if any, will be
8782 					 * processed next time we enter
8783 					 * ip_newroute().
8784 					 */
8785 					multirt_flags &= ~MULTIRT_CACHEGW;
8786 					/*
8787 					 * Search for the next unresolved
8788 					 * multirt route.
8789 					 */
8790 					first_mp = copy_mp;
8791 					copy_mp = NULL;
8792 					/* Prepare the next resolution loop. */
8793 					mp = first_mp;
8794 					EXTRACT_PKT_MP(mp, first_mp,
8795 					    mctl_present);
8796 					if (mctl_present)
8797 						io = (ipsec_out_t *)
8798 						    first_mp->b_rptr;
8799 					ipha = (ipha_t *)mp->b_rptr;
8800 
8801 					ASSERT(sire != NULL);
8802 
8803 					dst = save_dst;
8804 					multirt_resolve_next = B_TRUE;
8805 					continue;
8806 				}
8807 
8808 				if (sire != NULL)
8809 					ire_refrele(sire);
8810 
8811 				/*
8812 				 * The response will come back in ip_wput
8813 				 * with db_type IRE_DB_TYPE.
8814 				 */
8815 				ipif_refrele(src_ipif);
8816 				ill_refrele(dst_ill);
8817 				return;
8818 			} else {
8819 				/* Prepare for cleanup */
8820 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8821 				    mp);
8822 				mp->b_cont = NULL;
8823 				freeb(mp); /* areq */
8824 				/*
8825 				 * this is an ire that is not added to the
8826 				 * cache. ire_freemblk will handle the release
8827 				 * of any resources associated with the ire.
8828 				 */
8829 				ire_delete(ire); /* ire_mp */
8830 				mp = saved_mp; /* pkt */
8831 				ire = NULL;
8832 				if (copy_mp != NULL) {
8833 					MULTIRT_DEBUG_UNTAG(copy_mp);
8834 					freemsg(copy_mp);
8835 					copy_mp = NULL;
8836 				}
8837 				break;
8838 			}
8839 		default:
8840 			break;
8841 		}
8842 	} while (multirt_resolve_next);
8843 
8844 	ip1dbg(("ip_newroute: dropped\n"));
8845 	/* Did this packet originate externally? */
8846 	if (mp->b_prev) {
8847 		mp->b_next = NULL;
8848 		mp->b_prev = NULL;
8849 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8850 	} else {
8851 		if (dst_ill != NULL) {
8852 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8853 		} else {
8854 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8855 		}
8856 	}
8857 	ASSERT(copy_mp == NULL);
8858 	MULTIRT_DEBUG_UNTAG(first_mp);
8859 	freemsg(first_mp);
8860 	if (ire != NULL)
8861 		ire_refrele(ire);
8862 	if (sire != NULL)
8863 		ire_refrele(sire);
8864 	if (src_ipif != NULL)
8865 		ipif_refrele(src_ipif);
8866 	if (dst_ill != NULL)
8867 		ill_refrele(dst_ill);
8868 	return;
8869 
8870 icmp_err_ret:
8871 	ip1dbg(("ip_newroute: no route\n"));
8872 	if (src_ipif != NULL)
8873 		ipif_refrele(src_ipif);
8874 	if (dst_ill != NULL)
8875 		ill_refrele(dst_ill);
8876 	if (sire != NULL)
8877 		ire_refrele(sire);
8878 	/* Did this packet originate externally? */
8879 	if (mp->b_prev) {
8880 		mp->b_next = NULL;
8881 		mp->b_prev = NULL;
8882 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8883 		q = WR(q);
8884 	} else {
8885 		/*
8886 		 * There is no outgoing ill, so just increment the
8887 		 * system MIB.
8888 		 */
8889 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8890 		/*
8891 		 * Since ip_wput() isn't close to finished, we fill
8892 		 * in enough of the header for credible error reporting.
8893 		 */
8894 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8895 			/* Failed */
8896 			MULTIRT_DEBUG_UNTAG(first_mp);
8897 			freemsg(first_mp);
8898 			if (ire != NULL)
8899 				ire_refrele(ire);
8900 			return;
8901 		}
8902 	}
8903 
8904 	/*
8905 	 * At this point we will have ire only if RTF_BLACKHOLE
8906 	 * or RTF_REJECT flags are set on the IRE. It will not
8907 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8908 	 */
8909 	if (ire != NULL) {
8910 		if (ire->ire_flags & RTF_BLACKHOLE) {
8911 			ire_refrele(ire);
8912 			MULTIRT_DEBUG_UNTAG(first_mp);
8913 			freemsg(first_mp);
8914 			return;
8915 		}
8916 		ire_refrele(ire);
8917 	}
8918 	if (ip_source_routed(ipha, ipst)) {
8919 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8920 		    zoneid, ipst);
8921 		return;
8922 	}
8923 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8924 }
8925 
8926 ip_opt_info_t zero_info;
8927 
8928 /*
8929  * IPv4 -
8930  * ip_newroute_ipif is called by ip_wput_multicast and
8931  * ip_rput_forward_multicast whenever we need to send
8932  * out a packet to a destination address for which we do not have specific
8933  * routing information. It is used when the packet will be sent out
8934  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8935  * socket option is set or icmp error message wants to go out on a particular
8936  * interface for a unicast packet.
8937  *
8938  * In most cases, the destination address is resolved thanks to the ipif
8939  * intrinsic resolver. However, there are some cases where the call to
8940  * ip_newroute_ipif must take into account the potential presence of
8941  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8942  * that uses the interface. This is specified through flags,
8943  * which can be a combination of:
8944  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8945  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8946  *   and flags. Additionally, the packet source address has to be set to
8947  *   the specified address. The caller is thus expected to set this flag
8948  *   if the packet has no specific source address yet.
8949  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8950  *   flag, the resulting ire will inherit the flag. All unresolved routes
8951  *   to the destination must be explored in the same call to
8952  *   ip_newroute_ipif().
8953  */
8954 static void
8955 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8956     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8957 {
8958 	areq_t	*areq;
8959 	ire_t	*ire = NULL;
8960 	mblk_t	*res_mp;
8961 	ipaddr_t *addrp;
8962 	mblk_t *first_mp;
8963 	ire_t	*save_ire = NULL;
8964 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8965 	ipif_t	*src_ipif = NULL;
8966 	ushort_t ire_marks = 0;
8967 	ill_t	*dst_ill = NULL;
8968 	boolean_t mctl_present;
8969 	ipsec_out_t *io;
8970 	ipha_t *ipha;
8971 	int	ihandle = 0;
8972 	mblk_t	*saved_mp;
8973 	ire_t   *fire = NULL;
8974 	mblk_t  *copy_mp = NULL;
8975 	boolean_t multirt_resolve_next;
8976 	boolean_t unspec_src;
8977 	ipaddr_t ipha_dst;
8978 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8979 
8980 	/*
8981 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8982 	 * here for uniformity
8983 	 */
8984 	ipif_refhold(ipif);
8985 
8986 	/*
8987 	 * This loop is run only once in most cases.
8988 	 * We loop to resolve further routes only when the destination
8989 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8990 	 */
8991 	do {
8992 		if (dst_ill != NULL) {
8993 			ill_refrele(dst_ill);
8994 			dst_ill = NULL;
8995 		}
8996 		if (src_ipif != NULL) {
8997 			ipif_refrele(src_ipif);
8998 			src_ipif = NULL;
8999 		}
9000 		multirt_resolve_next = B_FALSE;
9001 
9002 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9003 		    ipif->ipif_ill->ill_name));
9004 
9005 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9006 		if (mctl_present)
9007 			io = (ipsec_out_t *)first_mp->b_rptr;
9008 
9009 		ipha = (ipha_t *)mp->b_rptr;
9010 
9011 		/*
9012 		 * Save the packet destination address, we may need it after
9013 		 * the packet has been consumed.
9014 		 */
9015 		ipha_dst = ipha->ipha_dst;
9016 
9017 		/*
9018 		 * If the interface is a pt-pt interface we look for an
9019 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9020 		 * local_address and the pt-pt destination address. Otherwise
9021 		 * we just match the local address.
9022 		 * NOTE: dst could be different than ipha->ipha_dst in case
9023 		 * of sending igmp multicast packets over a point-to-point
9024 		 * connection.
9025 		 * Thus we must be careful enough to check ipha_dst to be a
9026 		 * multicast address, otherwise it will take xmit_if path for
9027 		 * multicast packets resulting into kernel stack overflow by
9028 		 * repeated calls to ip_newroute_ipif from ire_send().
9029 		 */
9030 		if (CLASSD(ipha_dst) &&
9031 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9032 			goto err_ret;
9033 		}
9034 
9035 		/*
9036 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9037 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9038 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9039 		 * propagate its flags to the new ire.
9040 		 */
9041 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9042 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9043 			ip2dbg(("ip_newroute_ipif: "
9044 			    "ipif_lookup_multi_ire("
9045 			    "ipif %p, dst %08x) = fire %p\n",
9046 			    (void *)ipif, ntohl(dst), (void *)fire));
9047 		}
9048 
9049 		if (mctl_present && io->ipsec_out_attach_if) {
9050 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9051 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9052 
9053 			/* Failure case frees things for us. */
9054 			if (attach_ill == NULL) {
9055 				ipif_refrele(ipif);
9056 				if (fire != NULL)
9057 					ire_refrele(fire);
9058 				return;
9059 			}
9060 
9061 			/*
9062 			 * Check if we need an ire that will not be
9063 			 * looked up by anybody else i.e. HIDDEN.
9064 			 */
9065 			if (ill_is_probeonly(attach_ill)) {
9066 				ire_marks = IRE_MARK_HIDDEN;
9067 			}
9068 			/*
9069 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9070 			 * case.
9071 			 */
9072 			dst_ill = ipif->ipif_ill;
9073 			/* attach_ill has been refheld by ip_grab_attach_ill */
9074 			ASSERT(dst_ill == attach_ill);
9075 		} else {
9076 			/*
9077 			 * If the interface belongs to an interface group,
9078 			 * make sure the next possible interface in the group
9079 			 * is used.  This encourages load spreading among
9080 			 * peers in an interface group.
9081 			 * Note: load spreading is disabled for RTF_MULTIRT
9082 			 * routes.
9083 			 */
9084 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9085 			    (fire->ire_flags & RTF_MULTIRT)) {
9086 				/*
9087 				 * Don't perform outbound load spreading
9088 				 * in the case of an RTF_MULTIRT issued route,
9089 				 * we actually typically want to replicate
9090 				 * outgoing packets through particular
9091 				 * interfaces.
9092 				 */
9093 				dst_ill = ipif->ipif_ill;
9094 				ill_refhold(dst_ill);
9095 			} else {
9096 				dst_ill = ip_newroute_get_dst_ill(
9097 				    ipif->ipif_ill);
9098 			}
9099 			if (dst_ill == NULL) {
9100 				if (ip_debug > 2) {
9101 					pr_addr_dbg("ip_newroute_ipif: "
9102 					    "no dst ill for dst %s\n",
9103 					    AF_INET, &dst);
9104 				}
9105 				goto err_ret;
9106 			}
9107 		}
9108 
9109 		/*
9110 		 * Pick a source address preferring non-deprecated ones.
9111 		 * Unlike ip_newroute, we don't do any source address
9112 		 * selection here since for multicast it really does not help
9113 		 * in inbound load spreading as in the unicast case.
9114 		 */
9115 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9116 		    (fire->ire_flags & RTF_SETSRC)) {
9117 			/*
9118 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9119 			 * on that interface. This ire has RTF_SETSRC flag, so
9120 			 * the source address of the packet must be changed.
9121 			 * Check that the ipif matching the requested source
9122 			 * address still exists.
9123 			 */
9124 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9125 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9126 		}
9127 
9128 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9129 
9130 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9131 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9132 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9133 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9134 		    (src_ipif == NULL) &&
9135 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9136 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9137 			if (src_ipif == NULL) {
9138 				if (ip_debug > 2) {
9139 					/* ip1dbg */
9140 					pr_addr_dbg("ip_newroute_ipif: "
9141 					    "no src for dst %s",
9142 					    AF_INET, &dst);
9143 				}
9144 				ip1dbg((" through interface %s\n",
9145 				    dst_ill->ill_name));
9146 				goto err_ret;
9147 			}
9148 			ipif_refrele(ipif);
9149 			ipif = src_ipif;
9150 			ipif_refhold(ipif);
9151 		}
9152 		if (src_ipif == NULL) {
9153 			src_ipif = ipif;
9154 			ipif_refhold(src_ipif);
9155 		}
9156 
9157 		/*
9158 		 * Assign a source address while we have the conn.
9159 		 * We can't have ip_wput_ire pick a source address when the
9160 		 * packet returns from arp since conn_unspec_src might be set
9161 		 * and we lose the conn when going through arp.
9162 		 */
9163 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9164 			ipha->ipha_src = src_ipif->ipif_src_addr;
9165 
9166 		/*
9167 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9168 		 * that the outgoing interface does not have an interface ire.
9169 		 */
9170 		if (CLASSD(ipha_dst) && (connp == NULL ||
9171 		    connp->conn_outgoing_ill == NULL) &&
9172 		    infop->ip_opt_ill_index == 0) {
9173 			/* ipif_to_ire returns an held ire */
9174 			ire = ipif_to_ire(ipif);
9175 			if (ire == NULL)
9176 				goto err_ret;
9177 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9178 				goto err_ret;
9179 			/*
9180 			 * ihandle is needed when the ire is added to
9181 			 * cache table.
9182 			 */
9183 			save_ire = ire;
9184 			ihandle = save_ire->ire_ihandle;
9185 
9186 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9187 			    "flags %04x\n",
9188 			    (void *)ire, (void *)ipif, flags));
9189 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9190 			    (fire->ire_flags & RTF_MULTIRT)) {
9191 				/*
9192 				 * As requested by flags, an IRE_OFFSUBNET was
9193 				 * looked up on that interface. This ire has
9194 				 * RTF_MULTIRT flag, so the resolution loop will
9195 				 * be re-entered to resolve additional routes on
9196 				 * other interfaces. For that purpose, a copy of
9197 				 * the packet is performed at this point.
9198 				 */
9199 				fire->ire_last_used_time = lbolt;
9200 				copy_mp = copymsg(first_mp);
9201 				if (copy_mp) {
9202 					MULTIRT_DEBUG_TAG(copy_mp);
9203 				}
9204 			}
9205 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9206 			    (fire->ire_flags & RTF_SETSRC)) {
9207 				/*
9208 				 * As requested by flags, an IRE_OFFSUBET was
9209 				 * looked up on that interface. This ire has
9210 				 * RTF_SETSRC flag, so the source address of the
9211 				 * packet must be changed.
9212 				 */
9213 				ipha->ipha_src = fire->ire_src_addr;
9214 			}
9215 		} else {
9216 			ASSERT((connp == NULL) ||
9217 			    (connp->conn_outgoing_ill != NULL) ||
9218 			    (connp->conn_dontroute) ||
9219 			    infop->ip_opt_ill_index != 0);
9220 			/*
9221 			 * The only ways we can come here are:
9222 			 * 1) IP_BOUND_IF socket option is set
9223 			 * 2) SO_DONTROUTE socket option is set
9224 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9225 			 * In all cases, the new ire will not be added
9226 			 * into cache table.
9227 			 */
9228 			ire_marks |= IRE_MARK_NOADD;
9229 		}
9230 
9231 		switch (ipif->ipif_net_type) {
9232 		case IRE_IF_NORESOLVER: {
9233 			/* We have what we need to build an IRE_CACHE. */
9234 
9235 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9236 			    (dst_ill->ill_resolver_mp == NULL)) {
9237 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9238 				    "for IRE_IF_NORESOLVER ire %p has "
9239 				    "no ill_resolver_mp\n",
9240 				    (void *)dst_ill, (void *)ire));
9241 				break;
9242 			}
9243 
9244 			/*
9245 			 * The new ire inherits the IRE_OFFSUBNET flags
9246 			 * and source address, if this was requested.
9247 			 */
9248 			ire = ire_create(
9249 			    (uchar_t *)&dst,		/* dest address */
9250 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9251 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9252 			    NULL,			/* gateway address */
9253 			    &ipif->ipif_mtu,
9254 			    NULL,			/* no src nce */
9255 			    dst_ill->ill_rq,		/* recv-from queue */
9256 			    dst_ill->ill_wq,		/* send-to queue */
9257 			    IRE_CACHE,
9258 			    src_ipif,
9259 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9260 			    (fire != NULL) ?		/* Parent handle */
9261 			    fire->ire_phandle : 0,
9262 			    ihandle,			/* Interface handle */
9263 			    (fire != NULL) ?
9264 			    (fire->ire_flags &
9265 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9266 			    (save_ire == NULL ? &ire_uinfo_null :
9267 			    &save_ire->ire_uinfo),
9268 			    NULL,
9269 			    NULL,
9270 			    ipst);
9271 
9272 			if (ire == NULL) {
9273 				if (save_ire != NULL)
9274 					ire_refrele(save_ire);
9275 				break;
9276 			}
9277 
9278 			ire->ire_marks |= ire_marks;
9279 
9280 			/*
9281 			 * If IRE_MARK_NOADD is set then we need to convert
9282 			 * the max_fragp to a useable value now. This is
9283 			 * normally done in ire_add_v[46]. We also need to
9284 			 * associate the ire with an nce (normally would be
9285 			 * done in ip_wput_nondata()).
9286 			 *
9287 			 * Note that IRE_MARK_NOADD packets created here
9288 			 * do not have a non-null ire_mp pointer. The null
9289 			 * value of ire_bucket indicates that they were
9290 			 * never added.
9291 			 */
9292 			if (ire->ire_marks & IRE_MARK_NOADD) {
9293 				uint_t  max_frag;
9294 
9295 				max_frag = *ire->ire_max_fragp;
9296 				ire->ire_max_fragp = NULL;
9297 				ire->ire_max_frag = max_frag;
9298 
9299 				if ((ire->ire_nce = ndp_lookup_v4(
9300 				    ire_to_ill(ire),
9301 				    (ire->ire_gateway_addr != INADDR_ANY ?
9302 				    &ire->ire_gateway_addr : &ire->ire_addr),
9303 				    B_FALSE)) == NULL) {
9304 					if (save_ire != NULL)
9305 						ire_refrele(save_ire);
9306 					break;
9307 				}
9308 				ASSERT(ire->ire_nce->nce_state ==
9309 				    ND_REACHABLE);
9310 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9311 			}
9312 
9313 			/* Prevent save_ire from getting deleted */
9314 			if (save_ire != NULL) {
9315 				IRB_REFHOLD(save_ire->ire_bucket);
9316 				/* Has it been removed already ? */
9317 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9318 					IRB_REFRELE(save_ire->ire_bucket);
9319 					ire_refrele(save_ire);
9320 					break;
9321 				}
9322 			}
9323 
9324 			ire_add_then_send(q, ire, first_mp);
9325 
9326 			/* Assert that save_ire is not deleted yet. */
9327 			if (save_ire != NULL) {
9328 				ASSERT(save_ire->ire_ptpn != NULL);
9329 				IRB_REFRELE(save_ire->ire_bucket);
9330 				ire_refrele(save_ire);
9331 				save_ire = NULL;
9332 			}
9333 			if (fire != NULL) {
9334 				ire_refrele(fire);
9335 				fire = NULL;
9336 			}
9337 
9338 			/*
9339 			 * the resolution loop is re-entered if this
9340 			 * was requested through flags and if we
9341 			 * actually are in a multirouting case.
9342 			 */
9343 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9344 				boolean_t need_resolve =
9345 				    ire_multirt_need_resolve(ipha_dst,
9346 				    MBLK_GETLABEL(copy_mp), ipst);
9347 				if (!need_resolve) {
9348 					MULTIRT_DEBUG_UNTAG(copy_mp);
9349 					freemsg(copy_mp);
9350 					copy_mp = NULL;
9351 				} else {
9352 					/*
9353 					 * ipif_lookup_group() calls
9354 					 * ire_lookup_multi() that uses
9355 					 * ire_ftable_lookup() to find
9356 					 * an IRE_INTERFACE for the group.
9357 					 * In the multirt case,
9358 					 * ire_lookup_multi() then invokes
9359 					 * ire_multirt_lookup() to find
9360 					 * the next resolvable ire.
9361 					 * As a result, we obtain an new
9362 					 * interface, derived from the
9363 					 * next ire.
9364 					 */
9365 					ipif_refrele(ipif);
9366 					ipif = ipif_lookup_group(ipha_dst,
9367 					    zoneid, ipst);
9368 					ip2dbg(("ip_newroute_ipif: "
9369 					    "multirt dst %08x, ipif %p\n",
9370 					    htonl(dst), (void *)ipif));
9371 					if (ipif != NULL) {
9372 						mp = copy_mp;
9373 						copy_mp = NULL;
9374 						multirt_resolve_next = B_TRUE;
9375 						continue;
9376 					} else {
9377 						freemsg(copy_mp);
9378 					}
9379 				}
9380 			}
9381 			if (ipif != NULL)
9382 				ipif_refrele(ipif);
9383 			ill_refrele(dst_ill);
9384 			ipif_refrele(src_ipif);
9385 			return;
9386 		}
9387 		case IRE_IF_RESOLVER:
9388 			/*
9389 			 * We can't build an IRE_CACHE yet, but at least
9390 			 * we found a resolver that can help.
9391 			 */
9392 			res_mp = dst_ill->ill_resolver_mp;
9393 			if (!OK_RESOLVER_MP(res_mp))
9394 				break;
9395 
9396 			/*
9397 			 * We obtain a partial IRE_CACHE which we will pass
9398 			 * along with the resolver query.  When the response
9399 			 * comes back it will be there ready for us to add.
9400 			 * The new ire inherits the IRE_OFFSUBNET flags
9401 			 * and source address, if this was requested.
9402 			 * The ire_max_frag is atomically set under the
9403 			 * irebucket lock in ire_add_v[46]. Only in the
9404 			 * case of IRE_MARK_NOADD, we set it here itself.
9405 			 */
9406 			ire = ire_create_mp(
9407 			    (uchar_t *)&dst,		/* dest address */
9408 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9409 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9410 			    NULL,			/* gateway address */
9411 			    (ire_marks & IRE_MARK_NOADD) ?
9412 			    ipif->ipif_mtu : 0,		/* max_frag */
9413 			    NULL,			/* no src nce */
9414 			    dst_ill->ill_rq,		/* recv-from queue */
9415 			    dst_ill->ill_wq,		/* send-to queue */
9416 			    IRE_CACHE,
9417 			    src_ipif,
9418 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9419 			    (fire != NULL) ?		/* Parent handle */
9420 			    fire->ire_phandle : 0,
9421 			    ihandle,			/* Interface handle */
9422 			    (fire != NULL) ?		/* flags if any */
9423 			    (fire->ire_flags &
9424 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9425 			    (save_ire == NULL ? &ire_uinfo_null :
9426 			    &save_ire->ire_uinfo),
9427 			    NULL,
9428 			    NULL,
9429 			    ipst);
9430 
9431 			if (save_ire != NULL) {
9432 				ire_refrele(save_ire);
9433 				save_ire = NULL;
9434 			}
9435 			if (ire == NULL)
9436 				break;
9437 
9438 			ire->ire_marks |= ire_marks;
9439 			/*
9440 			 * Construct message chain for the resolver of the
9441 			 * form:
9442 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9443 			 *
9444 			 * NOTE : ire will be added later when the response
9445 			 * comes back from ARP. If the response does not
9446 			 * come back, ARP frees the packet. For this reason,
9447 			 * we can't REFHOLD the bucket of save_ire to prevent
9448 			 * deletions. We may not be able to REFRELE the
9449 			 * bucket if the response never comes back.
9450 			 * Thus, before adding the ire, ire_add_v4 will make
9451 			 * sure that the interface route does not get deleted.
9452 			 * This is the only case unlike ip_newroute_v6,
9453 			 * ip_newroute_ipif_v6 where we can always prevent
9454 			 * deletions because ire_add_then_send is called after
9455 			 * creating the IRE.
9456 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9457 			 * does not add this IRE into the IRE CACHE.
9458 			 */
9459 			ASSERT(ire->ire_mp != NULL);
9460 			ire->ire_mp->b_cont = first_mp;
9461 			/* Have saved_mp handy, for cleanup if canput fails */
9462 			saved_mp = mp;
9463 			mp = copyb(res_mp);
9464 			if (mp == NULL) {
9465 				/* Prepare for cleanup */
9466 				mp = saved_mp; /* pkt */
9467 				ire_delete(ire); /* ire_mp */
9468 				ire = NULL;
9469 				if (copy_mp != NULL) {
9470 					MULTIRT_DEBUG_UNTAG(copy_mp);
9471 					freemsg(copy_mp);
9472 					copy_mp = NULL;
9473 				}
9474 				break;
9475 			}
9476 			linkb(mp, ire->ire_mp);
9477 
9478 			/*
9479 			 * Fill in the source and dest addrs for the resolver.
9480 			 * NOTE: this depends on memory layouts imposed by
9481 			 * ill_init().
9482 			 */
9483 			areq = (areq_t *)mp->b_rptr;
9484 			addrp = (ipaddr_t *)((char *)areq +
9485 			    areq->areq_sender_addr_offset);
9486 			*addrp = ire->ire_src_addr;
9487 			addrp = (ipaddr_t *)((char *)areq +
9488 			    areq->areq_target_addr_offset);
9489 			*addrp = dst;
9490 			/* Up to the resolver. */
9491 			if (canputnext(dst_ill->ill_rq) &&
9492 			    !(dst_ill->ill_arp_closing)) {
9493 				putnext(dst_ill->ill_rq, mp);
9494 				/*
9495 				 * The response will come back in ip_wput
9496 				 * with db_type IRE_DB_TYPE.
9497 				 */
9498 			} else {
9499 				mp->b_cont = NULL;
9500 				freeb(mp); /* areq */
9501 				ire_delete(ire); /* ire_mp */
9502 				saved_mp->b_next = NULL;
9503 				saved_mp->b_prev = NULL;
9504 				freemsg(first_mp); /* pkt */
9505 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9506 			}
9507 
9508 			if (fire != NULL) {
9509 				ire_refrele(fire);
9510 				fire = NULL;
9511 			}
9512 
9513 
9514 			/*
9515 			 * The resolution loop is re-entered if this was
9516 			 * requested through flags and we actually are
9517 			 * in a multirouting case.
9518 			 */
9519 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9520 				boolean_t need_resolve =
9521 				    ire_multirt_need_resolve(ipha_dst,
9522 				    MBLK_GETLABEL(copy_mp), ipst);
9523 				if (!need_resolve) {
9524 					MULTIRT_DEBUG_UNTAG(copy_mp);
9525 					freemsg(copy_mp);
9526 					copy_mp = NULL;
9527 				} else {
9528 					/*
9529 					 * ipif_lookup_group() calls
9530 					 * ire_lookup_multi() that uses
9531 					 * ire_ftable_lookup() to find
9532 					 * an IRE_INTERFACE for the group.
9533 					 * In the multirt case,
9534 					 * ire_lookup_multi() then invokes
9535 					 * ire_multirt_lookup() to find
9536 					 * the next resolvable ire.
9537 					 * As a result, we obtain an new
9538 					 * interface, derived from the
9539 					 * next ire.
9540 					 */
9541 					ipif_refrele(ipif);
9542 					ipif = ipif_lookup_group(ipha_dst,
9543 					    zoneid, ipst);
9544 					if (ipif != NULL) {
9545 						mp = copy_mp;
9546 						copy_mp = NULL;
9547 						multirt_resolve_next = B_TRUE;
9548 						continue;
9549 					} else {
9550 						freemsg(copy_mp);
9551 					}
9552 				}
9553 			}
9554 			if (ipif != NULL)
9555 				ipif_refrele(ipif);
9556 			ill_refrele(dst_ill);
9557 			ipif_refrele(src_ipif);
9558 			return;
9559 		default:
9560 			break;
9561 		}
9562 	} while (multirt_resolve_next);
9563 
9564 err_ret:
9565 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9566 	if (fire != NULL)
9567 		ire_refrele(fire);
9568 	ipif_refrele(ipif);
9569 	/* Did this packet originate externally? */
9570 	if (dst_ill != NULL)
9571 		ill_refrele(dst_ill);
9572 	if (src_ipif != NULL)
9573 		ipif_refrele(src_ipif);
9574 	if (mp->b_prev || mp->b_next) {
9575 		mp->b_next = NULL;
9576 		mp->b_prev = NULL;
9577 	} else {
9578 		/*
9579 		 * Since ip_wput() isn't close to finished, we fill
9580 		 * in enough of the header for credible error reporting.
9581 		 */
9582 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9583 			/* Failed */
9584 			freemsg(first_mp);
9585 			if (ire != NULL)
9586 				ire_refrele(ire);
9587 			return;
9588 		}
9589 	}
9590 	/*
9591 	 * At this point we will have ire only if RTF_BLACKHOLE
9592 	 * or RTF_REJECT flags are set on the IRE. It will not
9593 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9594 	 */
9595 	if (ire != NULL) {
9596 		if (ire->ire_flags & RTF_BLACKHOLE) {
9597 			ire_refrele(ire);
9598 			freemsg(first_mp);
9599 			return;
9600 		}
9601 		ire_refrele(ire);
9602 	}
9603 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9604 }
9605 
9606 /* Name/Value Table Lookup Routine */
9607 char *
9608 ip_nv_lookup(nv_t *nv, int value)
9609 {
9610 	if (!nv)
9611 		return (NULL);
9612 	for (; nv->nv_name; nv++) {
9613 		if (nv->nv_value == value)
9614 			return (nv->nv_name);
9615 	}
9616 	return ("unknown");
9617 }
9618 
9619 /*
9620  * This is a module open, i.e. this is a control stream for access
9621  * to a DLPI device.  We allocate an ill_t as the instance data in
9622  * this case.
9623  */
9624 int
9625 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9626 {
9627 	ill_t	*ill;
9628 	int	err;
9629 	zoneid_t zoneid;
9630 	netstack_t *ns;
9631 	ip_stack_t *ipst;
9632 
9633 	/*
9634 	 * Prevent unprivileged processes from pushing IP so that
9635 	 * they can't send raw IP.
9636 	 */
9637 	if (secpolicy_net_rawaccess(credp) != 0)
9638 		return (EPERM);
9639 
9640 	ns = netstack_find_by_cred(credp);
9641 	ASSERT(ns != NULL);
9642 	ipst = ns->netstack_ip;
9643 	ASSERT(ipst != NULL);
9644 
9645 	/*
9646 	 * For exclusive stacks we set the zoneid to zero
9647 	 * to make IP operate as if in the global zone.
9648 	 */
9649 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9650 		zoneid = GLOBAL_ZONEID;
9651 	else
9652 		zoneid = crgetzoneid(credp);
9653 
9654 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9655 	q->q_ptr = WR(q)->q_ptr = ill;
9656 	ill->ill_ipst = ipst;
9657 	ill->ill_zoneid = zoneid;
9658 
9659 	/*
9660 	 * ill_init initializes the ill fields and then sends down
9661 	 * down a DL_INFO_REQ after calling qprocson.
9662 	 */
9663 	err = ill_init(q, ill);
9664 	if (err != 0) {
9665 		mi_free(ill);
9666 		netstack_rele(ipst->ips_netstack);
9667 		q->q_ptr = NULL;
9668 		WR(q)->q_ptr = NULL;
9669 		return (err);
9670 	}
9671 
9672 	/* ill_init initializes the ipsq marking this thread as writer */
9673 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9674 	/* Wait for the DL_INFO_ACK */
9675 	mutex_enter(&ill->ill_lock);
9676 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9677 		/*
9678 		 * Return value of 0 indicates a pending signal.
9679 		 */
9680 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9681 		if (err == 0) {
9682 			mutex_exit(&ill->ill_lock);
9683 			(void) ip_close(q, 0);
9684 			return (EINTR);
9685 		}
9686 	}
9687 	mutex_exit(&ill->ill_lock);
9688 
9689 	/*
9690 	 * ip_rput_other could have set an error  in ill_error on
9691 	 * receipt of M_ERROR.
9692 	 */
9693 
9694 	err = ill->ill_error;
9695 	if (err != 0) {
9696 		(void) ip_close(q, 0);
9697 		return (err);
9698 	}
9699 
9700 	ill->ill_credp = credp;
9701 	crhold(credp);
9702 
9703 	mutex_enter(&ipst->ips_ip_mi_lock);
9704 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9705 	    credp);
9706 	mutex_exit(&ipst->ips_ip_mi_lock);
9707 	if (err) {
9708 		(void) ip_close(q, 0);
9709 		return (err);
9710 	}
9711 	return (0);
9712 }
9713 
9714 /* For /dev/ip aka AF_INET open */
9715 int
9716 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9717 {
9718 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9719 }
9720 
9721 /* For /dev/ip6 aka AF_INET6 open */
9722 int
9723 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9724 {
9725 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9726 }
9727 
9728 /* IP open routine. */
9729 int
9730 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9731     boolean_t isv6)
9732 {
9733 	conn_t 		*connp;
9734 	major_t		maj;
9735 	zoneid_t	zoneid;
9736 	netstack_t	*ns;
9737 	ip_stack_t	*ipst;
9738 
9739 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9740 
9741 	/* Allow reopen. */
9742 	if (q->q_ptr != NULL)
9743 		return (0);
9744 
9745 	if (sflag & MODOPEN) {
9746 		/* This is a module open */
9747 		return (ip_modopen(q, devp, flag, sflag, credp));
9748 	}
9749 
9750 	ns = netstack_find_by_cred(credp);
9751 	ASSERT(ns != NULL);
9752 	ipst = ns->netstack_ip;
9753 	ASSERT(ipst != NULL);
9754 
9755 	/*
9756 	 * For exclusive stacks we set the zoneid to zero
9757 	 * to make IP operate as if in the global zone.
9758 	 */
9759 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9760 		zoneid = GLOBAL_ZONEID;
9761 	else
9762 		zoneid = crgetzoneid(credp);
9763 
9764 	/*
9765 	 * We are opening as a device. This is an IP client stream, and we
9766 	 * allocate an conn_t as the instance data.
9767 	 */
9768 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9769 
9770 	/*
9771 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9772 	 * done by netstack_find_by_cred()
9773 	 */
9774 	netstack_rele(ipst->ips_netstack);
9775 
9776 	connp->conn_zoneid = zoneid;
9777 
9778 	connp->conn_upq = q;
9779 	q->q_ptr = WR(q)->q_ptr = connp;
9780 
9781 	if (flag & SO_SOCKSTR)
9782 		connp->conn_flags |= IPCL_SOCKET;
9783 
9784 	/* Minor tells us which /dev entry was opened */
9785 	if (isv6) {
9786 		connp->conn_flags |= IPCL_ISV6;
9787 		connp->conn_af_isv6 = B_TRUE;
9788 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9789 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9790 	} else {
9791 		connp->conn_af_isv6 = B_FALSE;
9792 		connp->conn_pkt_isv6 = B_FALSE;
9793 	}
9794 
9795 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9796 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9797 		connp->conn_minor_arena = ip_minor_arena_la;
9798 	} else {
9799 		/*
9800 		 * Either minor numbers in the large arena were exhausted
9801 		 * or a non socket application is doing the open.
9802 		 * Try to allocate from the small arena.
9803 		 */
9804 		if ((connp->conn_dev =
9805 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9806 			/* CONN_DEC_REF takes care of netstack_rele() */
9807 			q->q_ptr = WR(q)->q_ptr = NULL;
9808 			CONN_DEC_REF(connp);
9809 			return (EBUSY);
9810 		}
9811 		connp->conn_minor_arena = ip_minor_arena_sa;
9812 	}
9813 
9814 	maj = getemajor(*devp);
9815 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9816 
9817 	/*
9818 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9819 	 */
9820 	connp->conn_cred = credp;
9821 
9822 	/*
9823 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9824 	 */
9825 	connp->conn_recv = ip_conn_input;
9826 
9827 	crhold(connp->conn_cred);
9828 
9829 	/*
9830 	 * If the caller has the process-wide flag set, then default to MAC
9831 	 * exempt mode.  This allows read-down to unlabeled hosts.
9832 	 */
9833 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9834 		connp->conn_mac_exempt = B_TRUE;
9835 
9836 	connp->conn_rq = q;
9837 	connp->conn_wq = WR(q);
9838 
9839 	/* Non-zero default values */
9840 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9841 
9842 	/*
9843 	 * Make the conn globally visible to walkers
9844 	 */
9845 	ASSERT(connp->conn_ref == 1);
9846 	mutex_enter(&connp->conn_lock);
9847 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9848 	mutex_exit(&connp->conn_lock);
9849 
9850 	qprocson(q);
9851 
9852 	return (0);
9853 }
9854 
9855 /*
9856  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9857  * Note that there is no race since either ip_output function works - it
9858  * is just an optimization to enter the best ip_output routine directly.
9859  */
9860 void
9861 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9862     ip_stack_t *ipst)
9863 {
9864 	if (isv6)  {
9865 		if (bump_mib) {
9866 			BUMP_MIB(&ipst->ips_ip6_mib,
9867 			    ipIfStatsOutSwitchIPVersion);
9868 		}
9869 		connp->conn_send = ip_output_v6;
9870 		connp->conn_pkt_isv6 = B_TRUE;
9871 	} else {
9872 		if (bump_mib) {
9873 			BUMP_MIB(&ipst->ips_ip_mib,
9874 			    ipIfStatsOutSwitchIPVersion);
9875 		}
9876 		connp->conn_send = ip_output;
9877 		connp->conn_pkt_isv6 = B_FALSE;
9878 	}
9879 
9880 }
9881 
9882 /*
9883  * See if IPsec needs loading because of the options in mp.
9884  */
9885 static boolean_t
9886 ipsec_opt_present(mblk_t *mp)
9887 {
9888 	uint8_t *optcp, *next_optcp, *opt_endcp;
9889 	struct opthdr *opt;
9890 	struct T_opthdr *topt;
9891 	int opthdr_len;
9892 	t_uscalar_t optname, optlevel;
9893 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9894 	ipsec_req_t *ipsr;
9895 
9896 	/*
9897 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9898 	 * return TRUE.
9899 	 */
9900 
9901 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9902 	opt_endcp = optcp + tor->OPT_length;
9903 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9904 		opthdr_len = sizeof (struct T_opthdr);
9905 	} else {		/* O_OPTMGMT_REQ */
9906 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9907 		opthdr_len = sizeof (struct opthdr);
9908 	}
9909 	for (; optcp < opt_endcp; optcp = next_optcp) {
9910 		if (optcp + opthdr_len > opt_endcp)
9911 			return (B_FALSE);	/* Not enough option header. */
9912 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9913 			topt = (struct T_opthdr *)optcp;
9914 			optlevel = topt->level;
9915 			optname = topt->name;
9916 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9917 		} else {
9918 			opt = (struct opthdr *)optcp;
9919 			optlevel = opt->level;
9920 			optname = opt->name;
9921 			next_optcp = optcp + opthdr_len +
9922 			    _TPI_ALIGN_OPT(opt->len);
9923 		}
9924 		if ((next_optcp < optcp) || /* wraparound pointer space */
9925 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9926 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9927 			return (B_FALSE); /* bad option buffer */
9928 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9929 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9930 			/*
9931 			 * Check to see if it's an all-bypass or all-zeroes
9932 			 * IPsec request.  Don't bother loading IPsec if
9933 			 * the socket doesn't want to use it.  (A good example
9934 			 * is a bypass request.)
9935 			 *
9936 			 * Basically, if any of the non-NEVER bits are set,
9937 			 * load IPsec.
9938 			 */
9939 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9940 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9941 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9942 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9943 			    != 0)
9944 				return (B_TRUE);
9945 		}
9946 	}
9947 	return (B_FALSE);
9948 }
9949 
9950 /*
9951  * If conn is is waiting for ipsec to finish loading, kick it.
9952  */
9953 /* ARGSUSED */
9954 static void
9955 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9956 {
9957 	t_scalar_t	optreq_prim;
9958 	mblk_t		*mp;
9959 	cred_t		*cr;
9960 	int		err = 0;
9961 
9962 	/*
9963 	 * This function is called, after ipsec loading is complete.
9964 	 * Since IP checks exclusively and atomically (i.e it prevents
9965 	 * ipsec load from completing until ip_optcom_req completes)
9966 	 * whether ipsec load is complete, there cannot be a race with IP
9967 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9968 	 */
9969 	mutex_enter(&connp->conn_lock);
9970 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9971 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9972 		mp = connp->conn_ipsec_opt_mp;
9973 		connp->conn_ipsec_opt_mp = NULL;
9974 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9975 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9976 		mutex_exit(&connp->conn_lock);
9977 
9978 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9979 
9980 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9981 		if (optreq_prim == T_OPTMGMT_REQ) {
9982 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9983 			    &ip_opt_obj, B_FALSE);
9984 		} else {
9985 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9986 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9987 			    &ip_opt_obj, B_FALSE);
9988 		}
9989 		if (err != EINPROGRESS)
9990 			CONN_OPER_PENDING_DONE(connp);
9991 		return;
9992 	}
9993 	mutex_exit(&connp->conn_lock);
9994 }
9995 
9996 /*
9997  * Called from the ipsec_loader thread, outside any perimeter, to tell
9998  * ip qenable any of the queues waiting for the ipsec loader to
9999  * complete.
10000  */
10001 void
10002 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10003 {
10004 	netstack_t *ns = ipss->ipsec_netstack;
10005 
10006 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10007 }
10008 
10009 /*
10010  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10011  * determines the grp on which it has to become exclusive, queues the mp
10012  * and sq draining restarts the optmgmt
10013  */
10014 static boolean_t
10015 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10016 {
10017 	conn_t *connp = Q_TO_CONN(q);
10018 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10019 
10020 	/*
10021 	 * Take IPsec requests and treat them special.
10022 	 */
10023 	if (ipsec_opt_present(mp)) {
10024 		/* First check if IPsec is loaded. */
10025 		mutex_enter(&ipss->ipsec_loader_lock);
10026 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10027 			mutex_exit(&ipss->ipsec_loader_lock);
10028 			return (B_FALSE);
10029 		}
10030 		mutex_enter(&connp->conn_lock);
10031 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10032 
10033 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10034 		connp->conn_ipsec_opt_mp = mp;
10035 		mutex_exit(&connp->conn_lock);
10036 		mutex_exit(&ipss->ipsec_loader_lock);
10037 
10038 		ipsec_loader_loadnow(ipss);
10039 		return (B_TRUE);
10040 	}
10041 	return (B_FALSE);
10042 }
10043 
10044 /*
10045  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10046  * all of them are copied to the conn_t. If the req is "zero", the policy is
10047  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10048  * fields.
10049  * We keep only the latest setting of the policy and thus policy setting
10050  * is not incremental/cumulative.
10051  *
10052  * Requests to set policies with multiple alternative actions will
10053  * go through a different API.
10054  */
10055 int
10056 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10057 {
10058 	uint_t ah_req = 0;
10059 	uint_t esp_req = 0;
10060 	uint_t se_req = 0;
10061 	ipsec_selkey_t sel;
10062 	ipsec_act_t *actp = NULL;
10063 	uint_t nact;
10064 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10065 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10066 	ipsec_policy_root_t *pr;
10067 	ipsec_policy_head_t *ph;
10068 	int fam;
10069 	boolean_t is_pol_reset;
10070 	int error = 0;
10071 	netstack_t	*ns = connp->conn_netstack;
10072 	ip_stack_t	*ipst = ns->netstack_ip;
10073 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10074 
10075 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10076 
10077 	/*
10078 	 * The IP_SEC_OPT option does not allow variable length parameters,
10079 	 * hence a request cannot be NULL.
10080 	 */
10081 	if (req == NULL)
10082 		return (EINVAL);
10083 
10084 	ah_req = req->ipsr_ah_req;
10085 	esp_req = req->ipsr_esp_req;
10086 	se_req = req->ipsr_self_encap_req;
10087 
10088 	/*
10089 	 * Are we dealing with a request to reset the policy (i.e.
10090 	 * zero requests).
10091 	 */
10092 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10093 	    (esp_req & REQ_MASK) == 0 &&
10094 	    (se_req & REQ_MASK) == 0);
10095 
10096 	if (!is_pol_reset) {
10097 		/*
10098 		 * If we couldn't load IPsec, fail with "protocol
10099 		 * not supported".
10100 		 * IPsec may not have been loaded for a request with zero
10101 		 * policies, so we don't fail in this case.
10102 		 */
10103 		mutex_enter(&ipss->ipsec_loader_lock);
10104 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10105 			mutex_exit(&ipss->ipsec_loader_lock);
10106 			return (EPROTONOSUPPORT);
10107 		}
10108 		mutex_exit(&ipss->ipsec_loader_lock);
10109 
10110 		/*
10111 		 * Test for valid requests. Invalid algorithms
10112 		 * need to be tested by IPsec code because new
10113 		 * algorithms can be added dynamically.
10114 		 */
10115 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10116 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10117 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10118 			return (EINVAL);
10119 		}
10120 
10121 		/*
10122 		 * Only privileged users can issue these
10123 		 * requests.
10124 		 */
10125 		if (((ah_req & IPSEC_PREF_NEVER) ||
10126 		    (esp_req & IPSEC_PREF_NEVER) ||
10127 		    (se_req & IPSEC_PREF_NEVER)) &&
10128 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10129 			return (EPERM);
10130 		}
10131 
10132 		/*
10133 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10134 		 * are mutually exclusive.
10135 		 */
10136 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10137 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10138 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10139 			/* Both of them are set */
10140 			return (EINVAL);
10141 		}
10142 	}
10143 
10144 	mutex_enter(&connp->conn_lock);
10145 
10146 	/*
10147 	 * If we have already cached policies in ip_bind_connected*(), don't
10148 	 * let them change now. We cache policies for connections
10149 	 * whose src,dst [addr, port] is known.
10150 	 */
10151 	if (connp->conn_policy_cached) {
10152 		mutex_exit(&connp->conn_lock);
10153 		return (EINVAL);
10154 	}
10155 
10156 	/*
10157 	 * We have a zero policies, reset the connection policy if already
10158 	 * set. This will cause the connection to inherit the
10159 	 * global policy, if any.
10160 	 */
10161 	if (is_pol_reset) {
10162 		if (connp->conn_policy != NULL) {
10163 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10164 			connp->conn_policy = NULL;
10165 		}
10166 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10167 		connp->conn_in_enforce_policy = B_FALSE;
10168 		connp->conn_out_enforce_policy = B_FALSE;
10169 		mutex_exit(&connp->conn_lock);
10170 		return (0);
10171 	}
10172 
10173 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10174 	    ipst->ips_netstack);
10175 	if (ph == NULL)
10176 		goto enomem;
10177 
10178 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10179 	if (actp == NULL)
10180 		goto enomem;
10181 
10182 	/*
10183 	 * Always allocate IPv4 policy entries, since they can also
10184 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10185 	 */
10186 	bzero(&sel, sizeof (sel));
10187 	sel.ipsl_valid = IPSL_IPV4;
10188 
10189 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10190 	    ipst->ips_netstack);
10191 	if (pin4 == NULL)
10192 		goto enomem;
10193 
10194 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10195 	    ipst->ips_netstack);
10196 	if (pout4 == NULL)
10197 		goto enomem;
10198 
10199 	if (connp->conn_af_isv6) {
10200 		/*
10201 		 * We're looking at a v6 socket, also allocate the
10202 		 * v6-specific entries...
10203 		 */
10204 		sel.ipsl_valid = IPSL_IPV6;
10205 		pin6 = ipsec_policy_create(&sel, actp, nact,
10206 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10207 		if (pin6 == NULL)
10208 			goto enomem;
10209 
10210 		pout6 = ipsec_policy_create(&sel, actp, nact,
10211 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10212 		if (pout6 == NULL)
10213 			goto enomem;
10214 
10215 		/*
10216 		 * .. and file them away in the right place.
10217 		 */
10218 		fam = IPSEC_AF_V6;
10219 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10220 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10221 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10222 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10223 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10224 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10225 	}
10226 
10227 	ipsec_actvec_free(actp, nact);
10228 
10229 	/*
10230 	 * File the v4 policies.
10231 	 */
10232 	fam = IPSEC_AF_V4;
10233 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10234 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10235 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10236 
10237 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10238 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10239 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10240 
10241 	/*
10242 	 * If the requests need security, set enforce_policy.
10243 	 * If the requests are IPSEC_PREF_NEVER, one should
10244 	 * still set conn_out_enforce_policy so that an ipsec_out
10245 	 * gets attached in ip_wput. This is needed so that
10246 	 * for connections that we don't cache policy in ip_bind,
10247 	 * if global policy matches in ip_wput_attach_policy, we
10248 	 * don't wrongly inherit global policy. Similarly, we need
10249 	 * to set conn_in_enforce_policy also so that we don't verify
10250 	 * policy wrongly.
10251 	 */
10252 	if ((ah_req & REQ_MASK) != 0 ||
10253 	    (esp_req & REQ_MASK) != 0 ||
10254 	    (se_req & REQ_MASK) != 0) {
10255 		connp->conn_in_enforce_policy = B_TRUE;
10256 		connp->conn_out_enforce_policy = B_TRUE;
10257 		connp->conn_flags |= IPCL_CHECK_POLICY;
10258 	}
10259 
10260 	mutex_exit(&connp->conn_lock);
10261 	return (error);
10262 #undef REQ_MASK
10263 
10264 	/*
10265 	 * Common memory-allocation-failure exit path.
10266 	 */
10267 enomem:
10268 	mutex_exit(&connp->conn_lock);
10269 	if (actp != NULL)
10270 		ipsec_actvec_free(actp, nact);
10271 	if (pin4 != NULL)
10272 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10273 	if (pout4 != NULL)
10274 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10275 	if (pin6 != NULL)
10276 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10277 	if (pout6 != NULL)
10278 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10279 	return (ENOMEM);
10280 }
10281 
10282 /*
10283  * Only for options that pass in an IP addr. Currently only V4 options
10284  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10285  * So this function assumes level is IPPROTO_IP
10286  */
10287 int
10288 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10289     mblk_t *first_mp)
10290 {
10291 	ipif_t *ipif = NULL;
10292 	int error;
10293 	ill_t *ill;
10294 	int zoneid;
10295 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10296 
10297 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10298 
10299 	if (addr != INADDR_ANY || checkonly) {
10300 		ASSERT(connp != NULL);
10301 		zoneid = IPCL_ZONEID(connp);
10302 		if (option == IP_NEXTHOP) {
10303 			ipif = ipif_lookup_onlink_addr(addr,
10304 			    connp->conn_zoneid, ipst);
10305 		} else {
10306 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10307 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10308 			    &error, ipst);
10309 		}
10310 		if (ipif == NULL) {
10311 			if (error == EINPROGRESS)
10312 				return (error);
10313 			else if ((option == IP_MULTICAST_IF) ||
10314 			    (option == IP_NEXTHOP))
10315 				return (EHOSTUNREACH);
10316 			else
10317 				return (EINVAL);
10318 		} else if (checkonly) {
10319 			if (option == IP_MULTICAST_IF) {
10320 				ill = ipif->ipif_ill;
10321 				/* not supported by the virtual network iface */
10322 				if (IS_VNI(ill)) {
10323 					ipif_refrele(ipif);
10324 					return (EINVAL);
10325 				}
10326 			}
10327 			ipif_refrele(ipif);
10328 			return (0);
10329 		}
10330 		ill = ipif->ipif_ill;
10331 		mutex_enter(&connp->conn_lock);
10332 		mutex_enter(&ill->ill_lock);
10333 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10334 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10335 			mutex_exit(&ill->ill_lock);
10336 			mutex_exit(&connp->conn_lock);
10337 			ipif_refrele(ipif);
10338 			return (option == IP_MULTICAST_IF ?
10339 			    EHOSTUNREACH : EINVAL);
10340 		}
10341 	} else {
10342 		mutex_enter(&connp->conn_lock);
10343 	}
10344 
10345 	/* None of the options below are supported on the VNI */
10346 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10347 		mutex_exit(&ill->ill_lock);
10348 		mutex_exit(&connp->conn_lock);
10349 		ipif_refrele(ipif);
10350 		return (EINVAL);
10351 	}
10352 
10353 	switch (option) {
10354 	case IP_DONTFAILOVER_IF:
10355 		/*
10356 		 * This option is used by in.mpathd to ensure
10357 		 * that IPMP probe packets only go out on the
10358 		 * test interfaces. in.mpathd sets this option
10359 		 * on the non-failover interfaces.
10360 		 * For backward compatibility, this option
10361 		 * implicitly sets IP_MULTICAST_IF, as used
10362 		 * be done in bind(), so that ip_wput gets
10363 		 * this ipif to send mcast packets.
10364 		 */
10365 		if (ipif != NULL) {
10366 			ASSERT(addr != INADDR_ANY);
10367 			connp->conn_nofailover_ill = ipif->ipif_ill;
10368 			connp->conn_multicast_ipif = ipif;
10369 		} else {
10370 			ASSERT(addr == INADDR_ANY);
10371 			connp->conn_nofailover_ill = NULL;
10372 			connp->conn_multicast_ipif = NULL;
10373 		}
10374 		break;
10375 
10376 	case IP_MULTICAST_IF:
10377 		connp->conn_multicast_ipif = ipif;
10378 		break;
10379 	case IP_NEXTHOP:
10380 		connp->conn_nexthop_v4 = addr;
10381 		connp->conn_nexthop_set = B_TRUE;
10382 		break;
10383 	}
10384 
10385 	if (ipif != NULL) {
10386 		mutex_exit(&ill->ill_lock);
10387 		mutex_exit(&connp->conn_lock);
10388 		ipif_refrele(ipif);
10389 		return (0);
10390 	}
10391 	mutex_exit(&connp->conn_lock);
10392 	/* We succeded in cleared the option */
10393 	return (0);
10394 }
10395 
10396 /*
10397  * For options that pass in an ifindex specifying the ill. V6 options always
10398  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10399  */
10400 int
10401 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10402     int level, int option, mblk_t *first_mp)
10403 {
10404 	ill_t *ill = NULL;
10405 	int error = 0;
10406 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10407 
10408 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10409 	if (ifindex != 0) {
10410 		ASSERT(connp != NULL);
10411 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10412 		    first_mp, ip_restart_optmgmt, &error, ipst);
10413 		if (ill != NULL) {
10414 			if (checkonly) {
10415 				/* not supported by the virtual network iface */
10416 				if (IS_VNI(ill)) {
10417 					ill_refrele(ill);
10418 					return (EINVAL);
10419 				}
10420 				ill_refrele(ill);
10421 				return (0);
10422 			}
10423 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10424 			    0, NULL)) {
10425 				ill_refrele(ill);
10426 				ill = NULL;
10427 				mutex_enter(&connp->conn_lock);
10428 				goto setit;
10429 			}
10430 			mutex_enter(&connp->conn_lock);
10431 			mutex_enter(&ill->ill_lock);
10432 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10433 				mutex_exit(&ill->ill_lock);
10434 				mutex_exit(&connp->conn_lock);
10435 				ill_refrele(ill);
10436 				ill = NULL;
10437 				mutex_enter(&connp->conn_lock);
10438 			}
10439 			goto setit;
10440 		} else if (error == EINPROGRESS) {
10441 			return (error);
10442 		} else {
10443 			error = 0;
10444 		}
10445 	}
10446 	mutex_enter(&connp->conn_lock);
10447 setit:
10448 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10449 
10450 	/*
10451 	 * The options below assume that the ILL (if any) transmits and/or
10452 	 * receives traffic. Neither of which is true for the virtual network
10453 	 * interface, so fail setting these on a VNI.
10454 	 */
10455 	if (IS_VNI(ill)) {
10456 		ASSERT(ill != NULL);
10457 		mutex_exit(&ill->ill_lock);
10458 		mutex_exit(&connp->conn_lock);
10459 		ill_refrele(ill);
10460 		return (EINVAL);
10461 	}
10462 
10463 	if (level == IPPROTO_IP) {
10464 		switch (option) {
10465 		case IP_BOUND_IF:
10466 			connp->conn_incoming_ill = ill;
10467 			connp->conn_outgoing_ill = ill;
10468 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10469 			    0 : ifindex;
10470 			break;
10471 
10472 		case IP_MULTICAST_IF:
10473 			/*
10474 			 * This option is an internal special. The socket
10475 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10476 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10477 			 * specifies an ifindex and we try first on V6 ill's.
10478 			 * If we don't find one, we they try using on v4 ill's
10479 			 * intenally and we come here.
10480 			 */
10481 			if (!checkonly && ill != NULL) {
10482 				ipif_t	*ipif;
10483 				ipif = ill->ill_ipif;
10484 
10485 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10486 					mutex_exit(&ill->ill_lock);
10487 					mutex_exit(&connp->conn_lock);
10488 					ill_refrele(ill);
10489 					ill = NULL;
10490 					mutex_enter(&connp->conn_lock);
10491 				} else {
10492 					connp->conn_multicast_ipif = ipif;
10493 				}
10494 			}
10495 			break;
10496 
10497 		case IP_DHCPINIT_IF:
10498 			if (connp->conn_dhcpinit_ill != NULL) {
10499 				/*
10500 				 * We've locked the conn so conn_cleanup_ill()
10501 				 * cannot clear conn_dhcpinit_ill -- so it's
10502 				 * safe to access the ill.
10503 				 */
10504 				ill_t *oill = connp->conn_dhcpinit_ill;
10505 
10506 				ASSERT(oill->ill_dhcpinit != 0);
10507 				atomic_dec_32(&oill->ill_dhcpinit);
10508 				connp->conn_dhcpinit_ill = NULL;
10509 			}
10510 
10511 			if (ill != NULL) {
10512 				connp->conn_dhcpinit_ill = ill;
10513 				atomic_inc_32(&ill->ill_dhcpinit);
10514 			}
10515 			break;
10516 		}
10517 	} else {
10518 		switch (option) {
10519 		case IPV6_BOUND_IF:
10520 			connp->conn_incoming_ill = ill;
10521 			connp->conn_outgoing_ill = ill;
10522 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10523 			    0 : ifindex;
10524 			break;
10525 
10526 		case IPV6_BOUND_PIF:
10527 			/*
10528 			 * Limit all transmit to this ill.
10529 			 * Unlike IPV6_BOUND_IF, using this option
10530 			 * prevents load spreading and failover from
10531 			 * happening when the interface is part of the
10532 			 * group. That's why we don't need to remember
10533 			 * the ifindex in orig_bound_ifindex as in
10534 			 * IPV6_BOUND_IF.
10535 			 */
10536 			connp->conn_outgoing_pill = ill;
10537 			break;
10538 
10539 		case IPV6_DONTFAILOVER_IF:
10540 			/*
10541 			 * This option is used by in.mpathd to ensure
10542 			 * that IPMP probe packets only go out on the
10543 			 * test interfaces. in.mpathd sets this option
10544 			 * on the non-failover interfaces.
10545 			 */
10546 			connp->conn_nofailover_ill = ill;
10547 			/*
10548 			 * For backward compatibility, this option
10549 			 * implicitly sets ip_multicast_ill as used in
10550 			 * IPV6_MULTICAST_IF so that ip_wput gets
10551 			 * this ill to send mcast packets.
10552 			 */
10553 			connp->conn_multicast_ill = ill;
10554 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10555 			    0 : ifindex;
10556 			break;
10557 
10558 		case IPV6_MULTICAST_IF:
10559 			/*
10560 			 * Set conn_multicast_ill to be the IPv6 ill.
10561 			 * Set conn_multicast_ipif to be an IPv4 ipif
10562 			 * for ifindex to make IPv4 mapped addresses
10563 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10564 			 * Even if no IPv6 ill exists for the ifindex
10565 			 * we need to check for an IPv4 ifindex in order
10566 			 * for this to work with mapped addresses. In that
10567 			 * case only set conn_multicast_ipif.
10568 			 */
10569 			if (!checkonly) {
10570 				if (ifindex == 0) {
10571 					connp->conn_multicast_ill = NULL;
10572 					connp->conn_orig_multicast_ifindex = 0;
10573 					connp->conn_multicast_ipif = NULL;
10574 				} else if (ill != NULL) {
10575 					connp->conn_multicast_ill = ill;
10576 					connp->conn_orig_multicast_ifindex =
10577 					    ifindex;
10578 				}
10579 			}
10580 			break;
10581 		}
10582 	}
10583 
10584 	if (ill != NULL) {
10585 		mutex_exit(&ill->ill_lock);
10586 		mutex_exit(&connp->conn_lock);
10587 		ill_refrele(ill);
10588 		return (0);
10589 	}
10590 	mutex_exit(&connp->conn_lock);
10591 	/*
10592 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10593 	 * locate the ill and could not set the option (ifindex != 0)
10594 	 */
10595 	return (ifindex == 0 ? 0 : EINVAL);
10596 }
10597 
10598 /* This routine sets socket options. */
10599 /* ARGSUSED */
10600 int
10601 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10602     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10603     void *dummy, cred_t *cr, mblk_t *first_mp)
10604 {
10605 	int		*i1 = (int *)invalp;
10606 	conn_t		*connp = Q_TO_CONN(q);
10607 	int		error = 0;
10608 	boolean_t	checkonly;
10609 	ire_t		*ire;
10610 	boolean_t	found;
10611 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10612 
10613 	switch (optset_context) {
10614 
10615 	case SETFN_OPTCOM_CHECKONLY:
10616 		checkonly = B_TRUE;
10617 		/*
10618 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10619 		 * inlen != 0 implies value supplied and
10620 		 * 	we have to "pretend" to set it.
10621 		 * inlen == 0 implies that there is no
10622 		 * 	value part in T_CHECK request and just validation
10623 		 * done elsewhere should be enough, we just return here.
10624 		 */
10625 		if (inlen == 0) {
10626 			*outlenp = 0;
10627 			return (0);
10628 		}
10629 		break;
10630 	case SETFN_OPTCOM_NEGOTIATE:
10631 	case SETFN_UD_NEGOTIATE:
10632 	case SETFN_CONN_NEGOTIATE:
10633 		checkonly = B_FALSE;
10634 		break;
10635 	default:
10636 		/*
10637 		 * We should never get here
10638 		 */
10639 		*outlenp = 0;
10640 		return (EINVAL);
10641 	}
10642 
10643 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10644 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10645 
10646 	/*
10647 	 * For fixed length options, no sanity check
10648 	 * of passed in length is done. It is assumed *_optcom_req()
10649 	 * routines do the right thing.
10650 	 */
10651 
10652 	switch (level) {
10653 	case SOL_SOCKET:
10654 		/*
10655 		 * conn_lock protects the bitfields, and is used to
10656 		 * set the fields atomically.
10657 		 */
10658 		switch (name) {
10659 		case SO_BROADCAST:
10660 			if (!checkonly) {
10661 				/* TODO: use value someplace? */
10662 				mutex_enter(&connp->conn_lock);
10663 				connp->conn_broadcast = *i1 ? 1 : 0;
10664 				mutex_exit(&connp->conn_lock);
10665 			}
10666 			break;	/* goto sizeof (int) option return */
10667 		case SO_USELOOPBACK:
10668 			if (!checkonly) {
10669 				/* TODO: use value someplace? */
10670 				mutex_enter(&connp->conn_lock);
10671 				connp->conn_loopback = *i1 ? 1 : 0;
10672 				mutex_exit(&connp->conn_lock);
10673 			}
10674 			break;	/* goto sizeof (int) option return */
10675 		case SO_DONTROUTE:
10676 			if (!checkonly) {
10677 				mutex_enter(&connp->conn_lock);
10678 				connp->conn_dontroute = *i1 ? 1 : 0;
10679 				mutex_exit(&connp->conn_lock);
10680 			}
10681 			break;	/* goto sizeof (int) option return */
10682 		case SO_REUSEADDR:
10683 			if (!checkonly) {
10684 				mutex_enter(&connp->conn_lock);
10685 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10686 				mutex_exit(&connp->conn_lock);
10687 			}
10688 			break;	/* goto sizeof (int) option return */
10689 		case SO_PROTOTYPE:
10690 			if (!checkonly) {
10691 				mutex_enter(&connp->conn_lock);
10692 				connp->conn_proto = *i1;
10693 				mutex_exit(&connp->conn_lock);
10694 			}
10695 			break;	/* goto sizeof (int) option return */
10696 		case SO_ALLZONES:
10697 			if (!checkonly) {
10698 				mutex_enter(&connp->conn_lock);
10699 				if (IPCL_IS_BOUND(connp)) {
10700 					mutex_exit(&connp->conn_lock);
10701 					return (EINVAL);
10702 				}
10703 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10704 				mutex_exit(&connp->conn_lock);
10705 			}
10706 			break;	/* goto sizeof (int) option return */
10707 		case SO_ANON_MLP:
10708 			if (!checkonly) {
10709 				mutex_enter(&connp->conn_lock);
10710 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10711 				mutex_exit(&connp->conn_lock);
10712 			}
10713 			break;	/* goto sizeof (int) option return */
10714 		case SO_MAC_EXEMPT:
10715 			if (secpolicy_net_mac_aware(cr) != 0 ||
10716 			    IPCL_IS_BOUND(connp))
10717 				return (EACCES);
10718 			if (!checkonly) {
10719 				mutex_enter(&connp->conn_lock);
10720 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10721 				mutex_exit(&connp->conn_lock);
10722 			}
10723 			break;	/* goto sizeof (int) option return */
10724 		default:
10725 			/*
10726 			 * "soft" error (negative)
10727 			 * option not handled at this level
10728 			 * Note: Do not modify *outlenp
10729 			 */
10730 			return (-EINVAL);
10731 		}
10732 		break;
10733 	case IPPROTO_IP:
10734 		switch (name) {
10735 		case IP_NEXTHOP:
10736 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10737 				return (EPERM);
10738 			/* FALLTHRU */
10739 		case IP_MULTICAST_IF:
10740 		case IP_DONTFAILOVER_IF: {
10741 			ipaddr_t addr = *i1;
10742 
10743 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10744 			    first_mp);
10745 			if (error != 0)
10746 				return (error);
10747 			break;	/* goto sizeof (int) option return */
10748 		}
10749 
10750 		case IP_MULTICAST_TTL:
10751 			/* Recorded in transport above IP */
10752 			*outvalp = *invalp;
10753 			*outlenp = sizeof (uchar_t);
10754 			return (0);
10755 		case IP_MULTICAST_LOOP:
10756 			if (!checkonly) {
10757 				mutex_enter(&connp->conn_lock);
10758 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10759 				mutex_exit(&connp->conn_lock);
10760 			}
10761 			*outvalp = *invalp;
10762 			*outlenp = sizeof (uchar_t);
10763 			return (0);
10764 		case IP_ADD_MEMBERSHIP:
10765 		case MCAST_JOIN_GROUP:
10766 		case IP_DROP_MEMBERSHIP:
10767 		case MCAST_LEAVE_GROUP: {
10768 			struct ip_mreq *mreqp;
10769 			struct group_req *greqp;
10770 			ire_t *ire;
10771 			boolean_t done = B_FALSE;
10772 			ipaddr_t group, ifaddr;
10773 			struct sockaddr_in *sin;
10774 			uint32_t *ifindexp;
10775 			boolean_t mcast_opt = B_TRUE;
10776 			mcast_record_t fmode;
10777 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10778 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10779 
10780 			switch (name) {
10781 			case IP_ADD_MEMBERSHIP:
10782 				mcast_opt = B_FALSE;
10783 				/* FALLTHRU */
10784 			case MCAST_JOIN_GROUP:
10785 				fmode = MODE_IS_EXCLUDE;
10786 				optfn = ip_opt_add_group;
10787 				break;
10788 
10789 			case IP_DROP_MEMBERSHIP:
10790 				mcast_opt = B_FALSE;
10791 				/* FALLTHRU */
10792 			case MCAST_LEAVE_GROUP:
10793 				fmode = MODE_IS_INCLUDE;
10794 				optfn = ip_opt_delete_group;
10795 				break;
10796 			}
10797 
10798 			if (mcast_opt) {
10799 				greqp = (struct group_req *)i1;
10800 				sin = (struct sockaddr_in *)&greqp->gr_group;
10801 				if (sin->sin_family != AF_INET) {
10802 					*outlenp = 0;
10803 					return (ENOPROTOOPT);
10804 				}
10805 				group = (ipaddr_t)sin->sin_addr.s_addr;
10806 				ifaddr = INADDR_ANY;
10807 				ifindexp = &greqp->gr_interface;
10808 			} else {
10809 				mreqp = (struct ip_mreq *)i1;
10810 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10811 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10812 				ifindexp = NULL;
10813 			}
10814 
10815 			/*
10816 			 * In the multirouting case, we need to replicate
10817 			 * the request on all interfaces that will take part
10818 			 * in replication.  We do so because multirouting is
10819 			 * reflective, thus we will probably receive multi-
10820 			 * casts on those interfaces.
10821 			 * The ip_multirt_apply_membership() succeeds if the
10822 			 * operation succeeds on at least one interface.
10823 			 */
10824 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10825 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10826 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10827 			if (ire != NULL) {
10828 				if (ire->ire_flags & RTF_MULTIRT) {
10829 					error = ip_multirt_apply_membership(
10830 					    optfn, ire, connp, checkonly, group,
10831 					    fmode, INADDR_ANY, first_mp);
10832 					done = B_TRUE;
10833 				}
10834 				ire_refrele(ire);
10835 			}
10836 			if (!done) {
10837 				error = optfn(connp, checkonly, group, ifaddr,
10838 				    ifindexp, fmode, INADDR_ANY, first_mp);
10839 			}
10840 			if (error) {
10841 				/*
10842 				 * EINPROGRESS is a soft error, needs retry
10843 				 * so don't make *outlenp zero.
10844 				 */
10845 				if (error != EINPROGRESS)
10846 					*outlenp = 0;
10847 				return (error);
10848 			}
10849 			/* OK return - copy input buffer into output buffer */
10850 			if (invalp != outvalp) {
10851 				/* don't trust bcopy for identical src/dst */
10852 				bcopy(invalp, outvalp, inlen);
10853 			}
10854 			*outlenp = inlen;
10855 			return (0);
10856 		}
10857 		case IP_BLOCK_SOURCE:
10858 		case IP_UNBLOCK_SOURCE:
10859 		case IP_ADD_SOURCE_MEMBERSHIP:
10860 		case IP_DROP_SOURCE_MEMBERSHIP:
10861 		case MCAST_BLOCK_SOURCE:
10862 		case MCAST_UNBLOCK_SOURCE:
10863 		case MCAST_JOIN_SOURCE_GROUP:
10864 		case MCAST_LEAVE_SOURCE_GROUP: {
10865 			struct ip_mreq_source *imreqp;
10866 			struct group_source_req *gsreqp;
10867 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10868 			uint32_t ifindex = 0;
10869 			mcast_record_t fmode;
10870 			struct sockaddr_in *sin;
10871 			ire_t *ire;
10872 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10873 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10874 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10875 
10876 			switch (name) {
10877 			case IP_BLOCK_SOURCE:
10878 				mcast_opt = B_FALSE;
10879 				/* FALLTHRU */
10880 			case MCAST_BLOCK_SOURCE:
10881 				fmode = MODE_IS_EXCLUDE;
10882 				optfn = ip_opt_add_group;
10883 				break;
10884 
10885 			case IP_UNBLOCK_SOURCE:
10886 				mcast_opt = B_FALSE;
10887 				/* FALLTHRU */
10888 			case MCAST_UNBLOCK_SOURCE:
10889 				fmode = MODE_IS_EXCLUDE;
10890 				optfn = ip_opt_delete_group;
10891 				break;
10892 
10893 			case IP_ADD_SOURCE_MEMBERSHIP:
10894 				mcast_opt = B_FALSE;
10895 				/* FALLTHRU */
10896 			case MCAST_JOIN_SOURCE_GROUP:
10897 				fmode = MODE_IS_INCLUDE;
10898 				optfn = ip_opt_add_group;
10899 				break;
10900 
10901 			case IP_DROP_SOURCE_MEMBERSHIP:
10902 				mcast_opt = B_FALSE;
10903 				/* FALLTHRU */
10904 			case MCAST_LEAVE_SOURCE_GROUP:
10905 				fmode = MODE_IS_INCLUDE;
10906 				optfn = ip_opt_delete_group;
10907 				break;
10908 			}
10909 
10910 			if (mcast_opt) {
10911 				gsreqp = (struct group_source_req *)i1;
10912 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10913 					*outlenp = 0;
10914 					return (ENOPROTOOPT);
10915 				}
10916 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10917 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10918 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10919 				src = (ipaddr_t)sin->sin_addr.s_addr;
10920 				ifindex = gsreqp->gsr_interface;
10921 			} else {
10922 				imreqp = (struct ip_mreq_source *)i1;
10923 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10924 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10925 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10926 			}
10927 
10928 			/*
10929 			 * In the multirouting case, we need to replicate
10930 			 * the request as noted in the mcast cases above.
10931 			 */
10932 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10933 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10934 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10935 			if (ire != NULL) {
10936 				if (ire->ire_flags & RTF_MULTIRT) {
10937 					error = ip_multirt_apply_membership(
10938 					    optfn, ire, connp, checkonly, grp,
10939 					    fmode, src, first_mp);
10940 					done = B_TRUE;
10941 				}
10942 				ire_refrele(ire);
10943 			}
10944 			if (!done) {
10945 				error = optfn(connp, checkonly, grp, ifaddr,
10946 				    &ifindex, fmode, src, first_mp);
10947 			}
10948 			if (error != 0) {
10949 				/*
10950 				 * EINPROGRESS is a soft error, needs retry
10951 				 * so don't make *outlenp zero.
10952 				 */
10953 				if (error != EINPROGRESS)
10954 					*outlenp = 0;
10955 				return (error);
10956 			}
10957 			/* OK return - copy input buffer into output buffer */
10958 			if (invalp != outvalp) {
10959 				bcopy(invalp, outvalp, inlen);
10960 			}
10961 			*outlenp = inlen;
10962 			return (0);
10963 		}
10964 		case IP_SEC_OPT:
10965 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10966 			if (error != 0) {
10967 				*outlenp = 0;
10968 				return (error);
10969 			}
10970 			break;
10971 		case IP_HDRINCL:
10972 		case IP_OPTIONS:
10973 		case T_IP_OPTIONS:
10974 		case IP_TOS:
10975 		case T_IP_TOS:
10976 		case IP_TTL:
10977 		case IP_RECVDSTADDR:
10978 		case IP_RECVOPTS:
10979 			/* OK return - copy input buffer into output buffer */
10980 			if (invalp != outvalp) {
10981 				/* don't trust bcopy for identical src/dst */
10982 				bcopy(invalp, outvalp, inlen);
10983 			}
10984 			*outlenp = inlen;
10985 			return (0);
10986 		case IP_RECVIF:
10987 			/* Retrieve the inbound interface index */
10988 			if (!checkonly) {
10989 				mutex_enter(&connp->conn_lock);
10990 				connp->conn_recvif = *i1 ? 1 : 0;
10991 				mutex_exit(&connp->conn_lock);
10992 			}
10993 			break;	/* goto sizeof (int) option return */
10994 		case IP_RECVPKTINFO:
10995 			if (!checkonly) {
10996 				mutex_enter(&connp->conn_lock);
10997 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
10998 				mutex_exit(&connp->conn_lock);
10999 			}
11000 			break;	/* goto sizeof (int) option return */
11001 		case IP_RECVSLLA:
11002 			/* Retrieve the source link layer address */
11003 			if (!checkonly) {
11004 				mutex_enter(&connp->conn_lock);
11005 				connp->conn_recvslla = *i1 ? 1 : 0;
11006 				mutex_exit(&connp->conn_lock);
11007 			}
11008 			break;	/* goto sizeof (int) option return */
11009 		case MRT_INIT:
11010 		case MRT_DONE:
11011 		case MRT_ADD_VIF:
11012 		case MRT_DEL_VIF:
11013 		case MRT_ADD_MFC:
11014 		case MRT_DEL_MFC:
11015 		case MRT_ASSERT:
11016 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11017 				*outlenp = 0;
11018 				return (error);
11019 			}
11020 			error = ip_mrouter_set((int)name, q, checkonly,
11021 			    (uchar_t *)invalp, inlen, first_mp);
11022 			if (error) {
11023 				*outlenp = 0;
11024 				return (error);
11025 			}
11026 			/* OK return - copy input buffer into output buffer */
11027 			if (invalp != outvalp) {
11028 				/* don't trust bcopy for identical src/dst */
11029 				bcopy(invalp, outvalp, inlen);
11030 			}
11031 			*outlenp = inlen;
11032 			return (0);
11033 		case IP_BOUND_IF:
11034 		case IP_DHCPINIT_IF:
11035 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11036 			    level, name, first_mp);
11037 			if (error != 0)
11038 				return (error);
11039 			break; 		/* goto sizeof (int) option return */
11040 
11041 		case IP_UNSPEC_SRC:
11042 			/* Allow sending with a zero source address */
11043 			if (!checkonly) {
11044 				mutex_enter(&connp->conn_lock);
11045 				connp->conn_unspec_src = *i1 ? 1 : 0;
11046 				mutex_exit(&connp->conn_lock);
11047 			}
11048 			break;	/* goto sizeof (int) option return */
11049 		default:
11050 			/*
11051 			 * "soft" error (negative)
11052 			 * option not handled at this level
11053 			 * Note: Do not modify *outlenp
11054 			 */
11055 			return (-EINVAL);
11056 		}
11057 		break;
11058 	case IPPROTO_IPV6:
11059 		switch (name) {
11060 		case IPV6_BOUND_IF:
11061 		case IPV6_BOUND_PIF:
11062 		case IPV6_DONTFAILOVER_IF:
11063 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11064 			    level, name, first_mp);
11065 			if (error != 0)
11066 				return (error);
11067 			break; 		/* goto sizeof (int) option return */
11068 
11069 		case IPV6_MULTICAST_IF:
11070 			/*
11071 			 * The only possible errors are EINPROGRESS and
11072 			 * EINVAL. EINPROGRESS will be restarted and is not
11073 			 * a hard error. We call this option on both V4 and V6
11074 			 * If both return EINVAL, then this call returns
11075 			 * EINVAL. If at least one of them succeeds we
11076 			 * return success.
11077 			 */
11078 			found = B_FALSE;
11079 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11080 			    level, name, first_mp);
11081 			if (error == EINPROGRESS)
11082 				return (error);
11083 			if (error == 0)
11084 				found = B_TRUE;
11085 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11086 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11087 			if (error == 0)
11088 				found = B_TRUE;
11089 			if (!found)
11090 				return (error);
11091 			break; 		/* goto sizeof (int) option return */
11092 
11093 		case IPV6_MULTICAST_HOPS:
11094 			/* Recorded in transport above IP */
11095 			break;	/* goto sizeof (int) option return */
11096 		case IPV6_MULTICAST_LOOP:
11097 			if (!checkonly) {
11098 				mutex_enter(&connp->conn_lock);
11099 				connp->conn_multicast_loop = *i1;
11100 				mutex_exit(&connp->conn_lock);
11101 			}
11102 			break;	/* goto sizeof (int) option return */
11103 		case IPV6_JOIN_GROUP:
11104 		case MCAST_JOIN_GROUP:
11105 		case IPV6_LEAVE_GROUP:
11106 		case MCAST_LEAVE_GROUP: {
11107 			struct ipv6_mreq *ip_mreqp;
11108 			struct group_req *greqp;
11109 			ire_t *ire;
11110 			boolean_t done = B_FALSE;
11111 			in6_addr_t groupv6;
11112 			uint32_t ifindex;
11113 			boolean_t mcast_opt = B_TRUE;
11114 			mcast_record_t fmode;
11115 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11116 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11117 
11118 			switch (name) {
11119 			case IPV6_JOIN_GROUP:
11120 				mcast_opt = B_FALSE;
11121 				/* FALLTHRU */
11122 			case MCAST_JOIN_GROUP:
11123 				fmode = MODE_IS_EXCLUDE;
11124 				optfn = ip_opt_add_group_v6;
11125 				break;
11126 
11127 			case IPV6_LEAVE_GROUP:
11128 				mcast_opt = B_FALSE;
11129 				/* FALLTHRU */
11130 			case MCAST_LEAVE_GROUP:
11131 				fmode = MODE_IS_INCLUDE;
11132 				optfn = ip_opt_delete_group_v6;
11133 				break;
11134 			}
11135 
11136 			if (mcast_opt) {
11137 				struct sockaddr_in *sin;
11138 				struct sockaddr_in6 *sin6;
11139 				greqp = (struct group_req *)i1;
11140 				if (greqp->gr_group.ss_family == AF_INET) {
11141 					sin = (struct sockaddr_in *)
11142 					    &(greqp->gr_group);
11143 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11144 					    &groupv6);
11145 				} else {
11146 					sin6 = (struct sockaddr_in6 *)
11147 					    &(greqp->gr_group);
11148 					groupv6 = sin6->sin6_addr;
11149 				}
11150 				ifindex = greqp->gr_interface;
11151 			} else {
11152 				ip_mreqp = (struct ipv6_mreq *)i1;
11153 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11154 				ifindex = ip_mreqp->ipv6mr_interface;
11155 			}
11156 			/*
11157 			 * In the multirouting case, we need to replicate
11158 			 * the request on all interfaces that will take part
11159 			 * in replication.  We do so because multirouting is
11160 			 * reflective, thus we will probably receive multi-
11161 			 * casts on those interfaces.
11162 			 * The ip_multirt_apply_membership_v6() succeeds if
11163 			 * the operation succeeds on at least one interface.
11164 			 */
11165 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11166 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11167 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11168 			if (ire != NULL) {
11169 				if (ire->ire_flags & RTF_MULTIRT) {
11170 					error = ip_multirt_apply_membership_v6(
11171 					    optfn, ire, connp, checkonly,
11172 					    &groupv6, fmode, &ipv6_all_zeros,
11173 					    first_mp);
11174 					done = B_TRUE;
11175 				}
11176 				ire_refrele(ire);
11177 			}
11178 			if (!done) {
11179 				error = optfn(connp, checkonly, &groupv6,
11180 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11181 			}
11182 			if (error) {
11183 				/*
11184 				 * EINPROGRESS is a soft error, needs retry
11185 				 * so don't make *outlenp zero.
11186 				 */
11187 				if (error != EINPROGRESS)
11188 					*outlenp = 0;
11189 				return (error);
11190 			}
11191 			/* OK return - copy input buffer into output buffer */
11192 			if (invalp != outvalp) {
11193 				/* don't trust bcopy for identical src/dst */
11194 				bcopy(invalp, outvalp, inlen);
11195 			}
11196 			*outlenp = inlen;
11197 			return (0);
11198 		}
11199 		case MCAST_BLOCK_SOURCE:
11200 		case MCAST_UNBLOCK_SOURCE:
11201 		case MCAST_JOIN_SOURCE_GROUP:
11202 		case MCAST_LEAVE_SOURCE_GROUP: {
11203 			struct group_source_req *gsreqp;
11204 			in6_addr_t v6grp, v6src;
11205 			uint32_t ifindex;
11206 			mcast_record_t fmode;
11207 			ire_t *ire;
11208 			boolean_t done = B_FALSE;
11209 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11210 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11211 
11212 			switch (name) {
11213 			case MCAST_BLOCK_SOURCE:
11214 				fmode = MODE_IS_EXCLUDE;
11215 				optfn = ip_opt_add_group_v6;
11216 				break;
11217 			case MCAST_UNBLOCK_SOURCE:
11218 				fmode = MODE_IS_EXCLUDE;
11219 				optfn = ip_opt_delete_group_v6;
11220 				break;
11221 			case MCAST_JOIN_SOURCE_GROUP:
11222 				fmode = MODE_IS_INCLUDE;
11223 				optfn = ip_opt_add_group_v6;
11224 				break;
11225 			case MCAST_LEAVE_SOURCE_GROUP:
11226 				fmode = MODE_IS_INCLUDE;
11227 				optfn = ip_opt_delete_group_v6;
11228 				break;
11229 			}
11230 
11231 			gsreqp = (struct group_source_req *)i1;
11232 			ifindex = gsreqp->gsr_interface;
11233 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11234 				struct sockaddr_in *s;
11235 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11236 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11237 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11238 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11239 			} else {
11240 				struct sockaddr_in6 *s6;
11241 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11242 				v6grp = s6->sin6_addr;
11243 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11244 				v6src = s6->sin6_addr;
11245 			}
11246 
11247 			/*
11248 			 * In the multirouting case, we need to replicate
11249 			 * the request as noted in the mcast cases above.
11250 			 */
11251 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11252 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11253 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11254 			if (ire != NULL) {
11255 				if (ire->ire_flags & RTF_MULTIRT) {
11256 					error = ip_multirt_apply_membership_v6(
11257 					    optfn, ire, connp, checkonly,
11258 					    &v6grp, fmode, &v6src, first_mp);
11259 					done = B_TRUE;
11260 				}
11261 				ire_refrele(ire);
11262 			}
11263 			if (!done) {
11264 				error = optfn(connp, checkonly, &v6grp,
11265 				    ifindex, fmode, &v6src, first_mp);
11266 			}
11267 			if (error != 0) {
11268 				/*
11269 				 * EINPROGRESS is a soft error, needs retry
11270 				 * so don't make *outlenp zero.
11271 				 */
11272 				if (error != EINPROGRESS)
11273 					*outlenp = 0;
11274 				return (error);
11275 			}
11276 			/* OK return - copy input buffer into output buffer */
11277 			if (invalp != outvalp) {
11278 				bcopy(invalp, outvalp, inlen);
11279 			}
11280 			*outlenp = inlen;
11281 			return (0);
11282 		}
11283 		case IPV6_UNICAST_HOPS:
11284 			/* Recorded in transport above IP */
11285 			break;	/* goto sizeof (int) option return */
11286 		case IPV6_UNSPEC_SRC:
11287 			/* Allow sending with a zero source address */
11288 			if (!checkonly) {
11289 				mutex_enter(&connp->conn_lock);
11290 				connp->conn_unspec_src = *i1 ? 1 : 0;
11291 				mutex_exit(&connp->conn_lock);
11292 			}
11293 			break;	/* goto sizeof (int) option return */
11294 		case IPV6_RECVPKTINFO:
11295 			if (!checkonly) {
11296 				mutex_enter(&connp->conn_lock);
11297 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11298 				mutex_exit(&connp->conn_lock);
11299 			}
11300 			break;	/* goto sizeof (int) option return */
11301 		case IPV6_RECVTCLASS:
11302 			if (!checkonly) {
11303 				if (*i1 < 0 || *i1 > 1) {
11304 					return (EINVAL);
11305 				}
11306 				mutex_enter(&connp->conn_lock);
11307 				connp->conn_ipv6_recvtclass = *i1;
11308 				mutex_exit(&connp->conn_lock);
11309 			}
11310 			break;
11311 		case IPV6_RECVPATHMTU:
11312 			if (!checkonly) {
11313 				if (*i1 < 0 || *i1 > 1) {
11314 					return (EINVAL);
11315 				}
11316 				mutex_enter(&connp->conn_lock);
11317 				connp->conn_ipv6_recvpathmtu = *i1;
11318 				mutex_exit(&connp->conn_lock);
11319 			}
11320 			break;
11321 		case IPV6_RECVHOPLIMIT:
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVHOPOPTS:
11329 			if (!checkonly) {
11330 				mutex_enter(&connp->conn_lock);
11331 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11332 				mutex_exit(&connp->conn_lock);
11333 			}
11334 			break;	/* goto sizeof (int) option return */
11335 		case IPV6_RECVDSTOPTS:
11336 			if (!checkonly) {
11337 				mutex_enter(&connp->conn_lock);
11338 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11339 				mutex_exit(&connp->conn_lock);
11340 			}
11341 			break;	/* goto sizeof (int) option return */
11342 		case IPV6_RECVRTHDR:
11343 			if (!checkonly) {
11344 				mutex_enter(&connp->conn_lock);
11345 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11346 				mutex_exit(&connp->conn_lock);
11347 			}
11348 			break;	/* goto sizeof (int) option return */
11349 		case IPV6_RECVRTHDRDSTOPTS:
11350 			if (!checkonly) {
11351 				mutex_enter(&connp->conn_lock);
11352 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11353 				mutex_exit(&connp->conn_lock);
11354 			}
11355 			break;	/* goto sizeof (int) option return */
11356 		case IPV6_PKTINFO:
11357 			if (inlen == 0)
11358 				return (-EINVAL);	/* clearing option */
11359 			error = ip6_set_pktinfo(cr, connp,
11360 			    (struct in6_pktinfo *)invalp, first_mp);
11361 			if (error != 0)
11362 				*outlenp = 0;
11363 			else
11364 				*outlenp = inlen;
11365 			return (error);
11366 		case IPV6_NEXTHOP: {
11367 			struct sockaddr_in6 *sin6;
11368 
11369 			/* Verify that the nexthop is reachable */
11370 			if (inlen == 0)
11371 				return (-EINVAL);	/* clearing option */
11372 
11373 			sin6 = (struct sockaddr_in6 *)invalp;
11374 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11375 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11376 			    NULL, MATCH_IRE_DEFAULT, ipst);
11377 
11378 			if (ire == NULL) {
11379 				*outlenp = 0;
11380 				return (EHOSTUNREACH);
11381 			}
11382 			ire_refrele(ire);
11383 			return (-EINVAL);
11384 		}
11385 		case IPV6_SEC_OPT:
11386 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11387 			if (error != 0) {
11388 				*outlenp = 0;
11389 				return (error);
11390 			}
11391 			break;
11392 		case IPV6_SRC_PREFERENCES: {
11393 			/*
11394 			 * This is implemented strictly in the ip module
11395 			 * (here and in tcp_opt_*() to accomodate tcp
11396 			 * sockets).  Modules above ip pass this option
11397 			 * down here since ip is the only one that needs to
11398 			 * be aware of source address preferences.
11399 			 *
11400 			 * This socket option only affects connected
11401 			 * sockets that haven't already bound to a specific
11402 			 * IPv6 address.  In other words, sockets that
11403 			 * don't call bind() with an address other than the
11404 			 * unspecified address and that call connect().
11405 			 * ip_bind_connected_v6() passes these preferences
11406 			 * to the ipif_select_source_v6() function.
11407 			 */
11408 			if (inlen != sizeof (uint32_t))
11409 				return (EINVAL);
11410 			error = ip6_set_src_preferences(connp,
11411 			    *(uint32_t *)invalp);
11412 			if (error != 0) {
11413 				*outlenp = 0;
11414 				return (error);
11415 			} else {
11416 				*outlenp = sizeof (uint32_t);
11417 			}
11418 			break;
11419 		}
11420 		case IPV6_V6ONLY:
11421 			if (*i1 < 0 || *i1 > 1) {
11422 				return (EINVAL);
11423 			}
11424 			mutex_enter(&connp->conn_lock);
11425 			connp->conn_ipv6_v6only = *i1;
11426 			mutex_exit(&connp->conn_lock);
11427 			break;
11428 		default:
11429 			return (-EINVAL);
11430 		}
11431 		break;
11432 	default:
11433 		/*
11434 		 * "soft" error (negative)
11435 		 * option not handled at this level
11436 		 * Note: Do not modify *outlenp
11437 		 */
11438 		return (-EINVAL);
11439 	}
11440 	/*
11441 	 * Common case of return from an option that is sizeof (int)
11442 	 */
11443 	*(int *)outvalp = *i1;
11444 	*outlenp = sizeof (int);
11445 	return (0);
11446 }
11447 
11448 /*
11449  * This routine gets default values of certain options whose default
11450  * values are maintained by protocol specific code
11451  */
11452 /* ARGSUSED */
11453 int
11454 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11455 {
11456 	int *i1 = (int *)ptr;
11457 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11458 
11459 	switch (level) {
11460 	case IPPROTO_IP:
11461 		switch (name) {
11462 		case IP_MULTICAST_TTL:
11463 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11464 			return (sizeof (uchar_t));
11465 		case IP_MULTICAST_LOOP:
11466 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11467 			return (sizeof (uchar_t));
11468 		default:
11469 			return (-1);
11470 		}
11471 	case IPPROTO_IPV6:
11472 		switch (name) {
11473 		case IPV6_UNICAST_HOPS:
11474 			*i1 = ipst->ips_ipv6_def_hops;
11475 			return (sizeof (int));
11476 		case IPV6_MULTICAST_HOPS:
11477 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11478 			return (sizeof (int));
11479 		case IPV6_MULTICAST_LOOP:
11480 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11481 			return (sizeof (int));
11482 		case IPV6_V6ONLY:
11483 			*i1 = 1;
11484 			return (sizeof (int));
11485 		default:
11486 			return (-1);
11487 		}
11488 	default:
11489 		return (-1);
11490 	}
11491 	/* NOTREACHED */
11492 }
11493 
11494 /*
11495  * Given a destination address and a pointer to where to put the information
11496  * this routine fills in the mtuinfo.
11497  */
11498 int
11499 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11500     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11501 {
11502 	ire_t *ire;
11503 	ip_stack_t	*ipst = ns->netstack_ip;
11504 
11505 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11506 		return (-1);
11507 
11508 	bzero(mtuinfo, sizeof (*mtuinfo));
11509 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11510 	mtuinfo->ip6m_addr.sin6_port = port;
11511 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11512 
11513 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11514 	if (ire != NULL) {
11515 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11516 		ire_refrele(ire);
11517 	} else {
11518 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11519 	}
11520 	return (sizeof (struct ip6_mtuinfo));
11521 }
11522 
11523 /*
11524  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11525  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11526  * isn't.  This doesn't matter as the error checking is done properly for the
11527  * other MRT options coming in through ip_opt_set.
11528  */
11529 int
11530 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11531 {
11532 	conn_t		*connp = Q_TO_CONN(q);
11533 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11534 
11535 	switch (level) {
11536 	case IPPROTO_IP:
11537 		switch (name) {
11538 		case MRT_VERSION:
11539 		case MRT_ASSERT:
11540 			(void) ip_mrouter_get(name, q, ptr);
11541 			return (sizeof (int));
11542 		case IP_SEC_OPT:
11543 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11544 		case IP_NEXTHOP:
11545 			if (connp->conn_nexthop_set) {
11546 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11547 				return (sizeof (ipaddr_t));
11548 			} else
11549 				return (0);
11550 		case IP_RECVPKTINFO:
11551 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11552 			return (sizeof (int));
11553 		default:
11554 			break;
11555 		}
11556 		break;
11557 	case IPPROTO_IPV6:
11558 		switch (name) {
11559 		case IPV6_SEC_OPT:
11560 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11561 		case IPV6_SRC_PREFERENCES: {
11562 			return (ip6_get_src_preferences(connp,
11563 			    (uint32_t *)ptr));
11564 		}
11565 		case IPV6_V6ONLY:
11566 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11567 			return (sizeof (int));
11568 		case IPV6_PATHMTU:
11569 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11570 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11571 		default:
11572 			break;
11573 		}
11574 		break;
11575 	default:
11576 		break;
11577 	}
11578 	return (-1);
11579 }
11580 
11581 /* Named Dispatch routine to get a current value out of our parameter table. */
11582 /* ARGSUSED */
11583 static int
11584 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11585 {
11586 	ipparam_t *ippa = (ipparam_t *)cp;
11587 
11588 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11589 	return (0);
11590 }
11591 
11592 /* ARGSUSED */
11593 static int
11594 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11595 {
11596 
11597 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11598 	return (0);
11599 }
11600 
11601 /*
11602  * Set ip{,6}_forwarding values.  This means walking through all of the
11603  * ill's and toggling their forwarding values.
11604  */
11605 /* ARGSUSED */
11606 static int
11607 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11608 {
11609 	long new_value;
11610 	int *forwarding_value = (int *)cp;
11611 	ill_t *ill;
11612 	boolean_t isv6;
11613 	ill_walk_context_t ctx;
11614 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11615 
11616 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11617 
11618 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11619 	    new_value < 0 || new_value > 1) {
11620 		return (EINVAL);
11621 	}
11622 
11623 	*forwarding_value = new_value;
11624 
11625 	/*
11626 	 * Regardless of the current value of ip_forwarding, set all per-ill
11627 	 * values of ip_forwarding to the value being set.
11628 	 *
11629 	 * Bring all the ill's up to date with the new global value.
11630 	 */
11631 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11632 
11633 	if (isv6)
11634 		ill = ILL_START_WALK_V6(&ctx, ipst);
11635 	else
11636 		ill = ILL_START_WALK_V4(&ctx, ipst);
11637 
11638 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11639 		(void) ill_forward_set(ill, new_value != 0);
11640 
11641 	rw_exit(&ipst->ips_ill_g_lock);
11642 	return (0);
11643 }
11644 
11645 /*
11646  * Walk through the param array specified registering each element with the
11647  * Named Dispatch handler. This is called only during init. So it is ok
11648  * not to acquire any locks
11649  */
11650 static boolean_t
11651 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11652     ipndp_t *ipnd, size_t ipnd_cnt)
11653 {
11654 	for (; ippa_cnt-- > 0; ippa++) {
11655 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11656 			if (!nd_load(ndp, ippa->ip_param_name,
11657 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11658 				nd_free(ndp);
11659 				return (B_FALSE);
11660 			}
11661 		}
11662 	}
11663 
11664 	for (; ipnd_cnt-- > 0; ipnd++) {
11665 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11666 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11667 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11668 			    ipnd->ip_ndp_data)) {
11669 				nd_free(ndp);
11670 				return (B_FALSE);
11671 			}
11672 		}
11673 	}
11674 
11675 	return (B_TRUE);
11676 }
11677 
11678 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11679 /* ARGSUSED */
11680 static int
11681 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11682 {
11683 	long		new_value;
11684 	ipparam_t	*ippa = (ipparam_t *)cp;
11685 
11686 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11687 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11688 		return (EINVAL);
11689 	}
11690 	ippa->ip_param_value = new_value;
11691 	return (0);
11692 }
11693 
11694 /*
11695  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11696  * When an ipf is passed here for the first time, if
11697  * we already have in-order fragments on the queue, we convert from the fast-
11698  * path reassembly scheme to the hard-case scheme.  From then on, additional
11699  * fragments are reassembled here.  We keep track of the start and end offsets
11700  * of each piece, and the number of holes in the chain.  When the hole count
11701  * goes to zero, we are done!
11702  *
11703  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11704  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11705  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11706  * after the call to ip_reassemble().
11707  */
11708 int
11709 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11710     size_t msg_len)
11711 {
11712 	uint_t	end;
11713 	mblk_t	*next_mp;
11714 	mblk_t	*mp1;
11715 	uint_t	offset;
11716 	boolean_t incr_dups = B_TRUE;
11717 	boolean_t offset_zero_seen = B_FALSE;
11718 	boolean_t pkt_boundary_checked = B_FALSE;
11719 
11720 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11721 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11722 
11723 	/* Add in byte count */
11724 	ipf->ipf_count += msg_len;
11725 	if (ipf->ipf_end) {
11726 		/*
11727 		 * We were part way through in-order reassembly, but now there
11728 		 * is a hole.  We walk through messages already queued, and
11729 		 * mark them for hard case reassembly.  We know that up till
11730 		 * now they were in order starting from offset zero.
11731 		 */
11732 		offset = 0;
11733 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11734 			IP_REASS_SET_START(mp1, offset);
11735 			if (offset == 0) {
11736 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11737 				offset = -ipf->ipf_nf_hdr_len;
11738 			}
11739 			offset += mp1->b_wptr - mp1->b_rptr;
11740 			IP_REASS_SET_END(mp1, offset);
11741 		}
11742 		/* One hole at the end. */
11743 		ipf->ipf_hole_cnt = 1;
11744 		/* Brand it as a hard case, forever. */
11745 		ipf->ipf_end = 0;
11746 	}
11747 	/* Walk through all the new pieces. */
11748 	do {
11749 		end = start + (mp->b_wptr - mp->b_rptr);
11750 		/*
11751 		 * If start is 0, decrease 'end' only for the first mblk of
11752 		 * the fragment. Otherwise 'end' can get wrong value in the
11753 		 * second pass of the loop if first mblk is exactly the
11754 		 * size of ipf_nf_hdr_len.
11755 		 */
11756 		if (start == 0 && !offset_zero_seen) {
11757 			/* First segment */
11758 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11759 			end -= ipf->ipf_nf_hdr_len;
11760 			offset_zero_seen = B_TRUE;
11761 		}
11762 		next_mp = mp->b_cont;
11763 		/*
11764 		 * We are checking to see if there is any interesing data
11765 		 * to process.  If there isn't and the mblk isn't the
11766 		 * one which carries the unfragmentable header then we
11767 		 * drop it.  It's possible to have just the unfragmentable
11768 		 * header come through without any data.  That needs to be
11769 		 * saved.
11770 		 *
11771 		 * If the assert at the top of this function holds then the
11772 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11773 		 * is infrequently traveled enough that the test is left in
11774 		 * to protect against future code changes which break that
11775 		 * invariant.
11776 		 */
11777 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11778 			/* Empty.  Blast it. */
11779 			IP_REASS_SET_START(mp, 0);
11780 			IP_REASS_SET_END(mp, 0);
11781 			/*
11782 			 * If the ipf points to the mblk we are about to free,
11783 			 * update ipf to point to the next mblk (or NULL
11784 			 * if none).
11785 			 */
11786 			if (ipf->ipf_mp->b_cont == mp)
11787 				ipf->ipf_mp->b_cont = next_mp;
11788 			freeb(mp);
11789 			continue;
11790 		}
11791 		mp->b_cont = NULL;
11792 		IP_REASS_SET_START(mp, start);
11793 		IP_REASS_SET_END(mp, end);
11794 		if (!ipf->ipf_tail_mp) {
11795 			ipf->ipf_tail_mp = mp;
11796 			ipf->ipf_mp->b_cont = mp;
11797 			if (start == 0 || !more) {
11798 				ipf->ipf_hole_cnt = 1;
11799 				/*
11800 				 * if the first fragment comes in more than one
11801 				 * mblk, this loop will be executed for each
11802 				 * mblk. Need to adjust hole count so exiting
11803 				 * this routine will leave hole count at 1.
11804 				 */
11805 				if (next_mp)
11806 					ipf->ipf_hole_cnt++;
11807 			} else
11808 				ipf->ipf_hole_cnt = 2;
11809 			continue;
11810 		} else if (ipf->ipf_last_frag_seen && !more &&
11811 		    !pkt_boundary_checked) {
11812 			/*
11813 			 * We check datagram boundary only if this fragment
11814 			 * claims to be the last fragment and we have seen a
11815 			 * last fragment in the past too. We do this only
11816 			 * once for a given fragment.
11817 			 *
11818 			 * start cannot be 0 here as fragments with start=0
11819 			 * and MF=0 gets handled as a complete packet. These
11820 			 * fragments should not reach here.
11821 			 */
11822 
11823 			if (start + msgdsize(mp) !=
11824 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11825 				/*
11826 				 * We have two fragments both of which claim
11827 				 * to be the last fragment but gives conflicting
11828 				 * information about the whole datagram size.
11829 				 * Something fishy is going on. Drop the
11830 				 * fragment and free up the reassembly list.
11831 				 */
11832 				return (IP_REASS_FAILED);
11833 			}
11834 
11835 			/*
11836 			 * We shouldn't come to this code block again for this
11837 			 * particular fragment.
11838 			 */
11839 			pkt_boundary_checked = B_TRUE;
11840 		}
11841 
11842 		/* New stuff at or beyond tail? */
11843 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11844 		if (start >= offset) {
11845 			if (ipf->ipf_last_frag_seen) {
11846 				/* current fragment is beyond last fragment */
11847 				return (IP_REASS_FAILED);
11848 			}
11849 			/* Link it on end. */
11850 			ipf->ipf_tail_mp->b_cont = mp;
11851 			ipf->ipf_tail_mp = mp;
11852 			if (more) {
11853 				if (start != offset)
11854 					ipf->ipf_hole_cnt++;
11855 			} else if (start == offset && next_mp == NULL)
11856 					ipf->ipf_hole_cnt--;
11857 			continue;
11858 		}
11859 		mp1 = ipf->ipf_mp->b_cont;
11860 		offset = IP_REASS_START(mp1);
11861 		/* New stuff at the front? */
11862 		if (start < offset) {
11863 			if (start == 0) {
11864 				if (end >= offset) {
11865 					/* Nailed the hole at the begining. */
11866 					ipf->ipf_hole_cnt--;
11867 				}
11868 			} else if (end < offset) {
11869 				/*
11870 				 * A hole, stuff, and a hole where there used
11871 				 * to be just a hole.
11872 				 */
11873 				ipf->ipf_hole_cnt++;
11874 			}
11875 			mp->b_cont = mp1;
11876 			/* Check for overlap. */
11877 			while (end > offset) {
11878 				if (end < IP_REASS_END(mp1)) {
11879 					mp->b_wptr -= end - offset;
11880 					IP_REASS_SET_END(mp, offset);
11881 					BUMP_MIB(ill->ill_ip_mib,
11882 					    ipIfStatsReasmPartDups);
11883 					break;
11884 				}
11885 				/* Did we cover another hole? */
11886 				if ((mp1->b_cont &&
11887 				    IP_REASS_END(mp1) !=
11888 				    IP_REASS_START(mp1->b_cont) &&
11889 				    end >= IP_REASS_START(mp1->b_cont)) ||
11890 				    (!ipf->ipf_last_frag_seen && !more)) {
11891 					ipf->ipf_hole_cnt--;
11892 				}
11893 				/* Clip out mp1. */
11894 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11895 					/*
11896 					 * After clipping out mp1, this guy
11897 					 * is now hanging off the end.
11898 					 */
11899 					ipf->ipf_tail_mp = mp;
11900 				}
11901 				IP_REASS_SET_START(mp1, 0);
11902 				IP_REASS_SET_END(mp1, 0);
11903 				/* Subtract byte count */
11904 				ipf->ipf_count -= mp1->b_datap->db_lim -
11905 				    mp1->b_datap->db_base;
11906 				freeb(mp1);
11907 				BUMP_MIB(ill->ill_ip_mib,
11908 				    ipIfStatsReasmPartDups);
11909 				mp1 = mp->b_cont;
11910 				if (!mp1)
11911 					break;
11912 				offset = IP_REASS_START(mp1);
11913 			}
11914 			ipf->ipf_mp->b_cont = mp;
11915 			continue;
11916 		}
11917 		/*
11918 		 * The new piece starts somewhere between the start of the head
11919 		 * and before the end of the tail.
11920 		 */
11921 		for (; mp1; mp1 = mp1->b_cont) {
11922 			offset = IP_REASS_END(mp1);
11923 			if (start < offset) {
11924 				if (end <= offset) {
11925 					/* Nothing new. */
11926 					IP_REASS_SET_START(mp, 0);
11927 					IP_REASS_SET_END(mp, 0);
11928 					/* Subtract byte count */
11929 					ipf->ipf_count -= mp->b_datap->db_lim -
11930 					    mp->b_datap->db_base;
11931 					if (incr_dups) {
11932 						ipf->ipf_num_dups++;
11933 						incr_dups = B_FALSE;
11934 					}
11935 					freeb(mp);
11936 					BUMP_MIB(ill->ill_ip_mib,
11937 					    ipIfStatsReasmDuplicates);
11938 					break;
11939 				}
11940 				/*
11941 				 * Trim redundant stuff off beginning of new
11942 				 * piece.
11943 				 */
11944 				IP_REASS_SET_START(mp, offset);
11945 				mp->b_rptr += offset - start;
11946 				BUMP_MIB(ill->ill_ip_mib,
11947 				    ipIfStatsReasmPartDups);
11948 				start = offset;
11949 				if (!mp1->b_cont) {
11950 					/*
11951 					 * After trimming, this guy is now
11952 					 * hanging off the end.
11953 					 */
11954 					mp1->b_cont = mp;
11955 					ipf->ipf_tail_mp = mp;
11956 					if (!more) {
11957 						ipf->ipf_hole_cnt--;
11958 					}
11959 					break;
11960 				}
11961 			}
11962 			if (start >= IP_REASS_START(mp1->b_cont))
11963 				continue;
11964 			/* Fill a hole */
11965 			if (start > offset)
11966 				ipf->ipf_hole_cnt++;
11967 			mp->b_cont = mp1->b_cont;
11968 			mp1->b_cont = mp;
11969 			mp1 = mp->b_cont;
11970 			offset = IP_REASS_START(mp1);
11971 			if (end >= offset) {
11972 				ipf->ipf_hole_cnt--;
11973 				/* Check for overlap. */
11974 				while (end > offset) {
11975 					if (end < IP_REASS_END(mp1)) {
11976 						mp->b_wptr -= end - offset;
11977 						IP_REASS_SET_END(mp, offset);
11978 						/*
11979 						 * TODO we might bump
11980 						 * this up twice if there is
11981 						 * overlap at both ends.
11982 						 */
11983 						BUMP_MIB(ill->ill_ip_mib,
11984 						    ipIfStatsReasmPartDups);
11985 						break;
11986 					}
11987 					/* Did we cover another hole? */
11988 					if ((mp1->b_cont &&
11989 					    IP_REASS_END(mp1)
11990 					    != IP_REASS_START(mp1->b_cont) &&
11991 					    end >=
11992 					    IP_REASS_START(mp1->b_cont)) ||
11993 					    (!ipf->ipf_last_frag_seen &&
11994 					    !more)) {
11995 						ipf->ipf_hole_cnt--;
11996 					}
11997 					/* Clip out mp1. */
11998 					if ((mp->b_cont = mp1->b_cont) ==
11999 					    NULL) {
12000 						/*
12001 						 * After clipping out mp1,
12002 						 * this guy is now hanging
12003 						 * off the end.
12004 						 */
12005 						ipf->ipf_tail_mp = mp;
12006 					}
12007 					IP_REASS_SET_START(mp1, 0);
12008 					IP_REASS_SET_END(mp1, 0);
12009 					/* Subtract byte count */
12010 					ipf->ipf_count -=
12011 					    mp1->b_datap->db_lim -
12012 					    mp1->b_datap->db_base;
12013 					freeb(mp1);
12014 					BUMP_MIB(ill->ill_ip_mib,
12015 					    ipIfStatsReasmPartDups);
12016 					mp1 = mp->b_cont;
12017 					if (!mp1)
12018 						break;
12019 					offset = IP_REASS_START(mp1);
12020 				}
12021 			}
12022 			break;
12023 		}
12024 	} while (start = end, mp = next_mp);
12025 
12026 	/* Fragment just processed could be the last one. Remember this fact */
12027 	if (!more)
12028 		ipf->ipf_last_frag_seen = B_TRUE;
12029 
12030 	/* Still got holes? */
12031 	if (ipf->ipf_hole_cnt)
12032 		return (IP_REASS_PARTIAL);
12033 	/* Clean up overloaded fields to avoid upstream disasters. */
12034 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12035 		IP_REASS_SET_START(mp1, 0);
12036 		IP_REASS_SET_END(mp1, 0);
12037 	}
12038 	return (IP_REASS_COMPLETE);
12039 }
12040 
12041 /*
12042  * ipsec processing for the fast path, used for input UDP Packets
12043  * Returns true if ready for passup to UDP.
12044  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12045  * was an ESP-in-UDP packet, etc.).
12046  */
12047 static boolean_t
12048 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12049     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12050 {
12051 	uint32_t	ill_index;
12052 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12053 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12054 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12055 	udp_t		*udp = connp->conn_udp;
12056 
12057 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12058 	/* The ill_index of the incoming ILL */
12059 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12060 
12061 	/* pass packet up to the transport */
12062 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12063 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12064 		    NULL, mctl_present);
12065 		if (*first_mpp == NULL) {
12066 			return (B_FALSE);
12067 		}
12068 	}
12069 
12070 	/* Initiate IPPF processing for fastpath UDP */
12071 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12072 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12073 		if (*mpp == NULL) {
12074 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12075 			    "deferred/dropped during IPPF processing\n"));
12076 			return (B_FALSE);
12077 		}
12078 	}
12079 	/*
12080 	 * Remove 0-spi if it's 0, or move everything behind
12081 	 * the UDP header over it and forward to ESP via
12082 	 * ip_proto_input().
12083 	 */
12084 	if (udp->udp_nat_t_endpoint) {
12085 		if (mctl_present) {
12086 			/* mctl_present *shouldn't* happen. */
12087 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12088 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12089 			    &ipss->ipsec_dropper);
12090 			*first_mpp = NULL;
12091 			return (B_FALSE);
12092 		}
12093 
12094 		/* "ill" is "recv_ill" in actuality. */
12095 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12096 			return (B_FALSE);
12097 
12098 		/* Else continue like a normal UDP packet. */
12099 	}
12100 
12101 	/*
12102 	 * We make the checks as below since we are in the fast path
12103 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12104 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12105 	 */
12106 	if (connp->conn_recvif || connp->conn_recvslla ||
12107 	    connp->conn_ip_recvpktinfo) {
12108 		if (connp->conn_recvif) {
12109 			in_flags = IPF_RECVIF;
12110 		}
12111 		/*
12112 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12113 		 * so the flag passed to ip_add_info is based on IP version
12114 		 * of connp.
12115 		 */
12116 		if (connp->conn_ip_recvpktinfo) {
12117 			if (connp->conn_af_isv6) {
12118 				/*
12119 				 * V6 only needs index
12120 				 */
12121 				in_flags |= IPF_RECVIF;
12122 			} else {
12123 				/*
12124 				 * V4 needs index + matching address.
12125 				 */
12126 				in_flags |= IPF_RECVADDR;
12127 			}
12128 		}
12129 		if (connp->conn_recvslla) {
12130 			in_flags |= IPF_RECVSLLA;
12131 		}
12132 		/*
12133 		 * since in_flags are being set ill will be
12134 		 * referenced in ip_add_info, so it better not
12135 		 * be NULL.
12136 		 */
12137 		/*
12138 		 * the actual data will be contained in b_cont
12139 		 * upon successful return of the following call.
12140 		 * If the call fails then the original mblk is
12141 		 * returned.
12142 		 */
12143 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12144 		    ipst);
12145 	}
12146 
12147 	return (B_TRUE);
12148 }
12149 
12150 /*
12151  * Fragmentation reassembly.  Each ILL has a hash table for
12152  * queuing packets undergoing reassembly for all IPIFs
12153  * associated with the ILL.  The hash is based on the packet
12154  * IP ident field.  The ILL frag hash table was allocated
12155  * as a timer block at the time the ILL was created.  Whenever
12156  * there is anything on the reassembly queue, the timer will
12157  * be running.  Returns B_TRUE if successful else B_FALSE;
12158  * frees mp on failure.
12159  */
12160 static boolean_t
12161 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12162     uint32_t *cksum_val, uint16_t *cksum_flags)
12163 {
12164 	uint32_t	frag_offset_flags;
12165 	ill_t		*ill = (ill_t *)q->q_ptr;
12166 	mblk_t		*mp = *mpp;
12167 	mblk_t		*t_mp;
12168 	ipaddr_t	dst;
12169 	uint8_t		proto = ipha->ipha_protocol;
12170 	uint32_t	sum_val;
12171 	uint16_t	sum_flags;
12172 	ipf_t		*ipf;
12173 	ipf_t		**ipfp;
12174 	ipfb_t		*ipfb;
12175 	uint16_t	ident;
12176 	uint32_t	offset;
12177 	ipaddr_t	src;
12178 	uint_t		hdr_length;
12179 	uint32_t	end;
12180 	mblk_t		*mp1;
12181 	mblk_t		*tail_mp;
12182 	size_t		count;
12183 	size_t		msg_len;
12184 	uint8_t		ecn_info = 0;
12185 	uint32_t	packet_size;
12186 	boolean_t	pruned = B_FALSE;
12187 	ip_stack_t *ipst = ill->ill_ipst;
12188 
12189 	if (cksum_val != NULL)
12190 		*cksum_val = 0;
12191 	if (cksum_flags != NULL)
12192 		*cksum_flags = 0;
12193 
12194 	/*
12195 	 * Drop the fragmented as early as possible, if
12196 	 * we don't have resource(s) to re-assemble.
12197 	 */
12198 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12199 		freemsg(mp);
12200 		return (B_FALSE);
12201 	}
12202 
12203 	/* Check for fragmentation offset; return if there's none */
12204 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12205 	    (IPH_MF | IPH_OFFSET)) == 0)
12206 		return (B_TRUE);
12207 
12208 	/*
12209 	 * We utilize hardware computed checksum info only for UDP since
12210 	 * IP fragmentation is a normal occurence for the protocol.  In
12211 	 * addition, checksum offload support for IP fragments carrying
12212 	 * UDP payload is commonly implemented across network adapters.
12213 	 */
12214 	ASSERT(ill != NULL);
12215 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12216 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12217 		mblk_t *mp1 = mp->b_cont;
12218 		int32_t len;
12219 
12220 		/* Record checksum information from the packet */
12221 		sum_val = (uint32_t)DB_CKSUM16(mp);
12222 		sum_flags = DB_CKSUMFLAGS(mp);
12223 
12224 		/* IP payload offset from beginning of mblk */
12225 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12226 
12227 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12228 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12229 		    offset >= DB_CKSUMSTART(mp) &&
12230 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12231 			uint32_t adj;
12232 			/*
12233 			 * Partial checksum has been calculated by hardware
12234 			 * and attached to the packet; in addition, any
12235 			 * prepended extraneous data is even byte aligned.
12236 			 * If any such data exists, we adjust the checksum;
12237 			 * this would also handle any postpended data.
12238 			 */
12239 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12240 			    mp, mp1, len, adj);
12241 
12242 			/* One's complement subtract extraneous checksum */
12243 			if (adj >= sum_val)
12244 				sum_val = ~(adj - sum_val) & 0xFFFF;
12245 			else
12246 				sum_val -= adj;
12247 		}
12248 	} else {
12249 		sum_val = 0;
12250 		sum_flags = 0;
12251 	}
12252 
12253 	/* Clear hardware checksumming flag */
12254 	DB_CKSUMFLAGS(mp) = 0;
12255 
12256 	ident = ipha->ipha_ident;
12257 	offset = (frag_offset_flags << 3) & 0xFFFF;
12258 	src = ipha->ipha_src;
12259 	dst = ipha->ipha_dst;
12260 	hdr_length = IPH_HDR_LENGTH(ipha);
12261 	end = ntohs(ipha->ipha_length) - hdr_length;
12262 
12263 	/* If end == 0 then we have a packet with no data, so just free it */
12264 	if (end == 0) {
12265 		freemsg(mp);
12266 		return (B_FALSE);
12267 	}
12268 
12269 	/* Record the ECN field info. */
12270 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12271 	if (offset != 0) {
12272 		/*
12273 		 * If this isn't the first piece, strip the header, and
12274 		 * add the offset to the end value.
12275 		 */
12276 		mp->b_rptr += hdr_length;
12277 		end += offset;
12278 	}
12279 
12280 	msg_len = MBLKSIZE(mp);
12281 	tail_mp = mp;
12282 	while (tail_mp->b_cont != NULL) {
12283 		tail_mp = tail_mp->b_cont;
12284 		msg_len += MBLKSIZE(tail_mp);
12285 	}
12286 
12287 	/* If the reassembly list for this ILL will get too big, prune it */
12288 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12289 	    ipst->ips_ip_reass_queue_bytes) {
12290 		ill_frag_prune(ill,
12291 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12292 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12293 		pruned = B_TRUE;
12294 	}
12295 
12296 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12297 	mutex_enter(&ipfb->ipfb_lock);
12298 
12299 	ipfp = &ipfb->ipfb_ipf;
12300 	/* Try to find an existing fragment queue for this packet. */
12301 	for (;;) {
12302 		ipf = ipfp[0];
12303 		if (ipf != NULL) {
12304 			/*
12305 			 * It has to match on ident and src/dst address.
12306 			 */
12307 			if (ipf->ipf_ident == ident &&
12308 			    ipf->ipf_src == src &&
12309 			    ipf->ipf_dst == dst &&
12310 			    ipf->ipf_protocol == proto) {
12311 				/*
12312 				 * If we have received too many
12313 				 * duplicate fragments for this packet
12314 				 * free it.
12315 				 */
12316 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12317 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12318 					freemsg(mp);
12319 					mutex_exit(&ipfb->ipfb_lock);
12320 					return (B_FALSE);
12321 				}
12322 				/* Found it. */
12323 				break;
12324 			}
12325 			ipfp = &ipf->ipf_hash_next;
12326 			continue;
12327 		}
12328 
12329 		/*
12330 		 * If we pruned the list, do we want to store this new
12331 		 * fragment?. We apply an optimization here based on the
12332 		 * fact that most fragments will be received in order.
12333 		 * So if the offset of this incoming fragment is zero,
12334 		 * it is the first fragment of a new packet. We will
12335 		 * keep it.  Otherwise drop the fragment, as we have
12336 		 * probably pruned the packet already (since the
12337 		 * packet cannot be found).
12338 		 */
12339 		if (pruned && offset != 0) {
12340 			mutex_exit(&ipfb->ipfb_lock);
12341 			freemsg(mp);
12342 			return (B_FALSE);
12343 		}
12344 
12345 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12346 			/*
12347 			 * Too many fragmented packets in this hash
12348 			 * bucket. Free the oldest.
12349 			 */
12350 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12351 		}
12352 
12353 		/* New guy.  Allocate a frag message. */
12354 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12355 		if (mp1 == NULL) {
12356 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12357 			freemsg(mp);
12358 reass_done:
12359 			mutex_exit(&ipfb->ipfb_lock);
12360 			return (B_FALSE);
12361 		}
12362 
12363 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12364 		mp1->b_cont = mp;
12365 
12366 		/* Initialize the fragment header. */
12367 		ipf = (ipf_t *)mp1->b_rptr;
12368 		ipf->ipf_mp = mp1;
12369 		ipf->ipf_ptphn = ipfp;
12370 		ipfp[0] = ipf;
12371 		ipf->ipf_hash_next = NULL;
12372 		ipf->ipf_ident = ident;
12373 		ipf->ipf_protocol = proto;
12374 		ipf->ipf_src = src;
12375 		ipf->ipf_dst = dst;
12376 		ipf->ipf_nf_hdr_len = 0;
12377 		/* Record reassembly start time. */
12378 		ipf->ipf_timestamp = gethrestime_sec();
12379 		/* Record ipf generation and account for frag header */
12380 		ipf->ipf_gen = ill->ill_ipf_gen++;
12381 		ipf->ipf_count = MBLKSIZE(mp1);
12382 		ipf->ipf_last_frag_seen = B_FALSE;
12383 		ipf->ipf_ecn = ecn_info;
12384 		ipf->ipf_num_dups = 0;
12385 		ipfb->ipfb_frag_pkts++;
12386 		ipf->ipf_checksum = 0;
12387 		ipf->ipf_checksum_flags = 0;
12388 
12389 		/* Store checksum value in fragment header */
12390 		if (sum_flags != 0) {
12391 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12392 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12393 			ipf->ipf_checksum = sum_val;
12394 			ipf->ipf_checksum_flags = sum_flags;
12395 		}
12396 
12397 		/*
12398 		 * We handle reassembly two ways.  In the easy case,
12399 		 * where all the fragments show up in order, we do
12400 		 * minimal bookkeeping, and just clip new pieces on
12401 		 * the end.  If we ever see a hole, then we go off
12402 		 * to ip_reassemble which has to mark the pieces and
12403 		 * keep track of the number of holes, etc.  Obviously,
12404 		 * the point of having both mechanisms is so we can
12405 		 * handle the easy case as efficiently as possible.
12406 		 */
12407 		if (offset == 0) {
12408 			/* Easy case, in-order reassembly so far. */
12409 			ipf->ipf_count += msg_len;
12410 			ipf->ipf_tail_mp = tail_mp;
12411 			/*
12412 			 * Keep track of next expected offset in
12413 			 * ipf_end.
12414 			 */
12415 			ipf->ipf_end = end;
12416 			ipf->ipf_nf_hdr_len = hdr_length;
12417 		} else {
12418 			/* Hard case, hole at the beginning. */
12419 			ipf->ipf_tail_mp = NULL;
12420 			/*
12421 			 * ipf_end == 0 means that we have given up
12422 			 * on easy reassembly.
12423 			 */
12424 			ipf->ipf_end = 0;
12425 
12426 			/* Forget checksum offload from now on */
12427 			ipf->ipf_checksum_flags = 0;
12428 
12429 			/*
12430 			 * ipf_hole_cnt is set by ip_reassemble.
12431 			 * ipf_count is updated by ip_reassemble.
12432 			 * No need to check for return value here
12433 			 * as we don't expect reassembly to complete
12434 			 * or fail for the first fragment itself.
12435 			 */
12436 			(void) ip_reassemble(mp, ipf,
12437 			    (frag_offset_flags & IPH_OFFSET) << 3,
12438 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12439 		}
12440 		/* Update per ipfb and ill byte counts */
12441 		ipfb->ipfb_count += ipf->ipf_count;
12442 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12443 		ill->ill_frag_count += ipf->ipf_count;
12444 		/* If the frag timer wasn't already going, start it. */
12445 		mutex_enter(&ill->ill_lock);
12446 		ill_frag_timer_start(ill);
12447 		mutex_exit(&ill->ill_lock);
12448 		goto reass_done;
12449 	}
12450 
12451 	/*
12452 	 * If the packet's flag has changed (it could be coming up
12453 	 * from an interface different than the previous, therefore
12454 	 * possibly different checksum capability), then forget about
12455 	 * any stored checksum states.  Otherwise add the value to
12456 	 * the existing one stored in the fragment header.
12457 	 */
12458 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12459 		sum_val += ipf->ipf_checksum;
12460 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12461 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12462 		ipf->ipf_checksum = sum_val;
12463 	} else if (ipf->ipf_checksum_flags != 0) {
12464 		/* Forget checksum offload from now on */
12465 		ipf->ipf_checksum_flags = 0;
12466 	}
12467 
12468 	/*
12469 	 * We have a new piece of a datagram which is already being
12470 	 * reassembled.  Update the ECN info if all IP fragments
12471 	 * are ECN capable.  If there is one which is not, clear
12472 	 * all the info.  If there is at least one which has CE
12473 	 * code point, IP needs to report that up to transport.
12474 	 */
12475 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12476 		if (ecn_info == IPH_ECN_CE)
12477 			ipf->ipf_ecn = IPH_ECN_CE;
12478 	} else {
12479 		ipf->ipf_ecn = IPH_ECN_NECT;
12480 	}
12481 	if (offset && ipf->ipf_end == offset) {
12482 		/* The new fragment fits at the end */
12483 		ipf->ipf_tail_mp->b_cont = mp;
12484 		/* Update the byte count */
12485 		ipf->ipf_count += msg_len;
12486 		/* Update per ipfb and ill byte counts */
12487 		ipfb->ipfb_count += msg_len;
12488 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12489 		ill->ill_frag_count += msg_len;
12490 		if (frag_offset_flags & IPH_MF) {
12491 			/* More to come. */
12492 			ipf->ipf_end = end;
12493 			ipf->ipf_tail_mp = tail_mp;
12494 			goto reass_done;
12495 		}
12496 	} else {
12497 		/* Go do the hard cases. */
12498 		int ret;
12499 
12500 		if (offset == 0)
12501 			ipf->ipf_nf_hdr_len = hdr_length;
12502 
12503 		/* Save current byte count */
12504 		count = ipf->ipf_count;
12505 		ret = ip_reassemble(mp, ipf,
12506 		    (frag_offset_flags & IPH_OFFSET) << 3,
12507 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12508 		/* Count of bytes added and subtracted (freeb()ed) */
12509 		count = ipf->ipf_count - count;
12510 		if (count) {
12511 			/* Update per ipfb and ill byte counts */
12512 			ipfb->ipfb_count += count;
12513 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12514 			ill->ill_frag_count += count;
12515 		}
12516 		if (ret == IP_REASS_PARTIAL) {
12517 			goto reass_done;
12518 		} else if (ret == IP_REASS_FAILED) {
12519 			/* Reassembly failed. Free up all resources */
12520 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12521 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12522 				IP_REASS_SET_START(t_mp, 0);
12523 				IP_REASS_SET_END(t_mp, 0);
12524 			}
12525 			freemsg(mp);
12526 			goto reass_done;
12527 		}
12528 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12529 	}
12530 	/*
12531 	 * We have completed reassembly.  Unhook the frag header from
12532 	 * the reassembly list.
12533 	 *
12534 	 * Before we free the frag header, record the ECN info
12535 	 * to report back to the transport.
12536 	 */
12537 	ecn_info = ipf->ipf_ecn;
12538 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12539 	ipfp = ipf->ipf_ptphn;
12540 
12541 	/* We need to supply these to caller */
12542 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12543 		sum_val = ipf->ipf_checksum;
12544 	else
12545 		sum_val = 0;
12546 
12547 	mp1 = ipf->ipf_mp;
12548 	count = ipf->ipf_count;
12549 	ipf = ipf->ipf_hash_next;
12550 	if (ipf != NULL)
12551 		ipf->ipf_ptphn = ipfp;
12552 	ipfp[0] = ipf;
12553 	ill->ill_frag_count -= count;
12554 	ASSERT(ipfb->ipfb_count >= count);
12555 	ipfb->ipfb_count -= count;
12556 	ipfb->ipfb_frag_pkts--;
12557 	mutex_exit(&ipfb->ipfb_lock);
12558 	/* Ditch the frag header. */
12559 	mp = mp1->b_cont;
12560 
12561 	freeb(mp1);
12562 
12563 	/* Restore original IP length in header. */
12564 	packet_size = (uint32_t)msgdsize(mp);
12565 	if (packet_size > IP_MAXPACKET) {
12566 		freemsg(mp);
12567 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12568 		return (B_FALSE);
12569 	}
12570 
12571 	if (DB_REF(mp) > 1) {
12572 		mblk_t *mp2 = copymsg(mp);
12573 
12574 		freemsg(mp);
12575 		if (mp2 == NULL) {
12576 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12577 			return (B_FALSE);
12578 		}
12579 		mp = mp2;
12580 	}
12581 	ipha = (ipha_t *)mp->b_rptr;
12582 
12583 	ipha->ipha_length = htons((uint16_t)packet_size);
12584 	/* We're now complete, zip the frag state */
12585 	ipha->ipha_fragment_offset_and_flags = 0;
12586 	/* Record the ECN info. */
12587 	ipha->ipha_type_of_service &= 0xFC;
12588 	ipha->ipha_type_of_service |= ecn_info;
12589 	*mpp = mp;
12590 
12591 	/* Reassembly is successful; return checksum information if needed */
12592 	if (cksum_val != NULL)
12593 		*cksum_val = sum_val;
12594 	if (cksum_flags != NULL)
12595 		*cksum_flags = sum_flags;
12596 
12597 	return (B_TRUE);
12598 }
12599 
12600 /*
12601  * Perform ip header check sum update local options.
12602  * return B_TRUE if all is well, else return B_FALSE and release
12603  * the mp. caller is responsible for decrementing ire ref cnt.
12604  */
12605 static boolean_t
12606 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12607     ip_stack_t *ipst)
12608 {
12609 	mblk_t		*first_mp;
12610 	boolean_t	mctl_present;
12611 	uint16_t	sum;
12612 
12613 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12614 	/*
12615 	 * Don't do the checksum if it has gone through AH/ESP
12616 	 * processing.
12617 	 */
12618 	if (!mctl_present) {
12619 		sum = ip_csum_hdr(ipha);
12620 		if (sum != 0) {
12621 			if (ill != NULL) {
12622 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12623 			} else {
12624 				BUMP_MIB(&ipst->ips_ip_mib,
12625 				    ipIfStatsInCksumErrs);
12626 			}
12627 			freemsg(first_mp);
12628 			return (B_FALSE);
12629 		}
12630 	}
12631 
12632 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12633 		if (mctl_present)
12634 			freeb(first_mp);
12635 		return (B_FALSE);
12636 	}
12637 
12638 	return (B_TRUE);
12639 }
12640 
12641 /*
12642  * All udp packet are delivered to the local host via this routine.
12643  */
12644 void
12645 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12646     ill_t *recv_ill)
12647 {
12648 	uint32_t	sum;
12649 	uint32_t	u1;
12650 	boolean_t	mctl_present;
12651 	conn_t		*connp;
12652 	mblk_t		*first_mp;
12653 	uint16_t	*up;
12654 	ill_t		*ill = (ill_t *)q->q_ptr;
12655 	uint16_t	reass_hck_flags = 0;
12656 	ip_stack_t	*ipst;
12657 
12658 	ASSERT(recv_ill != NULL);
12659 	ipst = recv_ill->ill_ipst;
12660 
12661 #define	rptr    ((uchar_t *)ipha)
12662 
12663 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12664 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12665 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12666 	ASSERT(ill != NULL);
12667 
12668 	/*
12669 	 * FAST PATH for udp packets
12670 	 */
12671 
12672 	/* u1 is # words of IP options */
12673 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12674 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12675 
12676 	/* IP options present */
12677 	if (u1 != 0)
12678 		goto ipoptions;
12679 
12680 	/* Check the IP header checksum.  */
12681 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12682 		/* Clear the IP header h/w cksum flag */
12683 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12684 	} else if (!mctl_present) {
12685 		/*
12686 		 * Don't verify header checksum if this packet is coming
12687 		 * back from AH/ESP as we already did it.
12688 		 */
12689 #define	uph	((uint16_t *)ipha)
12690 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12691 		    uph[6] + uph[7] + uph[8] + uph[9];
12692 #undef	uph
12693 		/* finish doing IP checksum */
12694 		sum = (sum & 0xFFFF) + (sum >> 16);
12695 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12696 		if (sum != 0 && sum != 0xFFFF) {
12697 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12698 			freemsg(first_mp);
12699 			return;
12700 		}
12701 	}
12702 
12703 	/*
12704 	 * Count for SNMP of inbound packets for ire.
12705 	 * if mctl is present this might be a secure packet and
12706 	 * has already been counted for in ip_proto_input().
12707 	 */
12708 	if (!mctl_present) {
12709 		UPDATE_IB_PKT_COUNT(ire);
12710 		ire->ire_last_used_time = lbolt;
12711 	}
12712 
12713 	/* packet part of fragmented IP packet? */
12714 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12715 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12716 		goto fragmented;
12717 	}
12718 
12719 	/* u1 = IP header length (20 bytes) */
12720 	u1 = IP_SIMPLE_HDR_LENGTH;
12721 
12722 	/* packet does not contain complete IP & UDP headers */
12723 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12724 		goto udppullup;
12725 
12726 	/* up points to UDP header */
12727 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12728 #define	iphs    ((uint16_t *)ipha)
12729 
12730 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12731 	if (up[3] != 0) {
12732 		mblk_t *mp1 = mp->b_cont;
12733 		boolean_t cksum_err;
12734 		uint16_t hck_flags = 0;
12735 
12736 		/* Pseudo-header checksum */
12737 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12738 		    iphs[9] + up[2];
12739 
12740 		/*
12741 		 * Revert to software checksum calculation if the interface
12742 		 * isn't capable of checksum offload or if IPsec is present.
12743 		 */
12744 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12745 			hck_flags = DB_CKSUMFLAGS(mp);
12746 
12747 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12748 			IP_STAT(ipst, ip_in_sw_cksum);
12749 
12750 		IP_CKSUM_RECV(hck_flags, u1,
12751 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12752 		    (int32_t)((uchar_t *)up - rptr),
12753 		    mp, mp1, cksum_err);
12754 
12755 		if (cksum_err) {
12756 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12757 			if (hck_flags & HCK_FULLCKSUM)
12758 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12759 			else if (hck_flags & HCK_PARTIALCKSUM)
12760 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12761 			else
12762 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12763 
12764 			freemsg(first_mp);
12765 			return;
12766 		}
12767 	}
12768 
12769 	/* Non-fragmented broadcast or multicast packet? */
12770 	if (ire->ire_type == IRE_BROADCAST)
12771 		goto udpslowpath;
12772 
12773 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12774 	    ire->ire_zoneid, ipst)) != NULL) {
12775 		ASSERT(connp->conn_upq != NULL);
12776 		IP_STAT(ipst, ip_udp_fast_path);
12777 
12778 		if (CONN_UDP_FLOWCTLD(connp)) {
12779 			freemsg(mp);
12780 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12781 		} else {
12782 			if (!mctl_present) {
12783 				BUMP_MIB(ill->ill_ip_mib,
12784 				    ipIfStatsHCInDelivers);
12785 			}
12786 			/*
12787 			 * mp and first_mp can change.
12788 			 */
12789 			if (ip_udp_check(q, connp, recv_ill,
12790 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12791 				/* Send it upstream */
12792 				(connp->conn_recv)(connp, mp, NULL);
12793 			}
12794 		}
12795 		/*
12796 		 * freeb() cannot deal with null mblk being passed
12797 		 * in and first_mp can be set to null in the call
12798 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12799 		 */
12800 		if (mctl_present && first_mp != NULL) {
12801 			freeb(first_mp);
12802 		}
12803 		CONN_DEC_REF(connp);
12804 		return;
12805 	}
12806 
12807 	/*
12808 	 * if we got here we know the packet is not fragmented and
12809 	 * has no options. The classifier could not find a conn_t and
12810 	 * most likely its an icmp packet so send it through slow path.
12811 	 */
12812 
12813 	goto udpslowpath;
12814 
12815 ipoptions:
12816 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12817 		goto slow_done;
12818 	}
12819 
12820 	UPDATE_IB_PKT_COUNT(ire);
12821 	ire->ire_last_used_time = lbolt;
12822 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12823 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12824 fragmented:
12825 		/*
12826 		 * "sum" and "reass_hck_flags" are non-zero if the
12827 		 * reassembled packet has a valid hardware computed
12828 		 * checksum information associated with it.
12829 		 */
12830 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12831 			goto slow_done;
12832 		/*
12833 		 * Make sure that first_mp points back to mp as
12834 		 * the mp we came in with could have changed in
12835 		 * ip_rput_fragment().
12836 		 */
12837 		ASSERT(!mctl_present);
12838 		ipha = (ipha_t *)mp->b_rptr;
12839 		first_mp = mp;
12840 	}
12841 
12842 	/* Now we have a complete datagram, destined for this machine. */
12843 	u1 = IPH_HDR_LENGTH(ipha);
12844 	/* Pull up the UDP header, if necessary. */
12845 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12846 udppullup:
12847 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12848 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12849 			freemsg(first_mp);
12850 			goto slow_done;
12851 		}
12852 		ipha = (ipha_t *)mp->b_rptr;
12853 	}
12854 
12855 	/*
12856 	 * Validate the checksum for the reassembled packet; for the
12857 	 * pullup case we calculate the payload checksum in software.
12858 	 */
12859 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12860 	if (up[3] != 0) {
12861 		boolean_t cksum_err;
12862 
12863 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12864 			IP_STAT(ipst, ip_in_sw_cksum);
12865 
12866 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12867 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12868 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12869 		    iphs[9] + up[2], sum, cksum_err);
12870 
12871 		if (cksum_err) {
12872 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12873 
12874 			if (reass_hck_flags & HCK_FULLCKSUM)
12875 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12876 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12877 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12878 			else
12879 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12880 
12881 			freemsg(first_mp);
12882 			goto slow_done;
12883 		}
12884 	}
12885 udpslowpath:
12886 
12887 	/* Clear hardware checksum flag to be safe */
12888 	DB_CKSUMFLAGS(mp) = 0;
12889 
12890 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12891 	    (ire->ire_type == IRE_BROADCAST),
12892 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12893 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12894 
12895 slow_done:
12896 	IP_STAT(ipst, ip_udp_slow_path);
12897 	return;
12898 
12899 #undef  iphs
12900 #undef  rptr
12901 }
12902 
12903 /* ARGSUSED */
12904 static mblk_t *
12905 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12906     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12907     ill_rx_ring_t *ill_ring)
12908 {
12909 	conn_t		*connp;
12910 	uint32_t	sum;
12911 	uint32_t	u1;
12912 	uint16_t	*up;
12913 	int		offset;
12914 	ssize_t		len;
12915 	mblk_t		*mp1;
12916 	boolean_t	syn_present = B_FALSE;
12917 	tcph_t		*tcph;
12918 	uint_t		ip_hdr_len;
12919 	ill_t		*ill = (ill_t *)q->q_ptr;
12920 	zoneid_t	zoneid = ire->ire_zoneid;
12921 	boolean_t	cksum_err;
12922 	uint16_t	hck_flags = 0;
12923 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12924 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12925 
12926 #define	rptr	((uchar_t *)ipha)
12927 
12928 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12929 	ASSERT(ill != NULL);
12930 
12931 	/*
12932 	 * FAST PATH for tcp packets
12933 	 */
12934 
12935 	/* u1 is # words of IP options */
12936 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12937 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12938 
12939 	/* IP options present */
12940 	if (u1) {
12941 		goto ipoptions;
12942 	} else if (!mctl_present) {
12943 		/* Check the IP header checksum.  */
12944 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12945 			/* Clear the IP header h/w cksum flag */
12946 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12947 		} else if (!mctl_present) {
12948 			/*
12949 			 * Don't verify header checksum if this packet
12950 			 * is coming back from AH/ESP as we already did it.
12951 			 */
12952 #define	uph	((uint16_t *)ipha)
12953 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12954 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12955 #undef	uph
12956 			/* finish doing IP checksum */
12957 			sum = (sum & 0xFFFF) + (sum >> 16);
12958 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12959 			if (sum != 0 && sum != 0xFFFF) {
12960 				BUMP_MIB(ill->ill_ip_mib,
12961 				    ipIfStatsInCksumErrs);
12962 				goto error;
12963 			}
12964 		}
12965 	}
12966 
12967 	if (!mctl_present) {
12968 		UPDATE_IB_PKT_COUNT(ire);
12969 		ire->ire_last_used_time = lbolt;
12970 	}
12971 
12972 	/* packet part of fragmented IP packet? */
12973 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12974 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12975 		goto fragmented;
12976 	}
12977 
12978 	/* u1 = IP header length (20 bytes) */
12979 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12980 
12981 	/* does packet contain IP+TCP headers? */
12982 	len = mp->b_wptr - rptr;
12983 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12984 		IP_STAT(ipst, ip_tcppullup);
12985 		goto tcppullup;
12986 	}
12987 
12988 	/* TCP options present? */
12989 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12990 
12991 	/*
12992 	 * If options need to be pulled up, then goto tcpoptions.
12993 	 * otherwise we are still in the fast path
12994 	 */
12995 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
12996 		IP_STAT(ipst, ip_tcpoptions);
12997 		goto tcpoptions;
12998 	}
12999 
13000 	/* multiple mblks of tcp data? */
13001 	if ((mp1 = mp->b_cont) != NULL) {
13002 		/* more then two? */
13003 		if (mp1->b_cont != NULL) {
13004 			IP_STAT(ipst, ip_multipkttcp);
13005 			goto multipkttcp;
13006 		}
13007 		len += mp1->b_wptr - mp1->b_rptr;
13008 	}
13009 
13010 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13011 
13012 	/* part of pseudo checksum */
13013 
13014 	/* TCP datagram length */
13015 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13016 
13017 #define	iphs    ((uint16_t *)ipha)
13018 
13019 #ifdef	_BIG_ENDIAN
13020 	u1 += IPPROTO_TCP;
13021 #else
13022 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13023 #endif
13024 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13025 
13026 	/*
13027 	 * Revert to software checksum calculation if the interface
13028 	 * isn't capable of checksum offload or if IPsec is present.
13029 	 */
13030 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13031 		hck_flags = DB_CKSUMFLAGS(mp);
13032 
13033 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13034 		IP_STAT(ipst, ip_in_sw_cksum);
13035 
13036 	IP_CKSUM_RECV(hck_flags, u1,
13037 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13038 	    (int32_t)((uchar_t *)up - rptr),
13039 	    mp, mp1, cksum_err);
13040 
13041 	if (cksum_err) {
13042 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13043 
13044 		if (hck_flags & HCK_FULLCKSUM)
13045 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13046 		else if (hck_flags & HCK_PARTIALCKSUM)
13047 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13048 		else
13049 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13050 
13051 		goto error;
13052 	}
13053 
13054 try_again:
13055 
13056 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13057 	    zoneid, ipst)) == NULL) {
13058 		/* Send the TH_RST */
13059 		goto no_conn;
13060 	}
13061 
13062 	/*
13063 	 * TCP FAST PATH for AF_INET socket.
13064 	 *
13065 	 * TCP fast path to avoid extra work. An AF_INET socket type
13066 	 * does not have facility to receive extra information via
13067 	 * ip_process or ip_add_info. Also, when the connection was
13068 	 * established, we made a check if this connection is impacted
13069 	 * by any global IPsec policy or per connection policy (a
13070 	 * policy that comes in effect later will not apply to this
13071 	 * connection). Since all this can be determined at the
13072 	 * connection establishment time, a quick check of flags
13073 	 * can avoid extra work.
13074 	 */
13075 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13076 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13077 		ASSERT(first_mp == mp);
13078 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13079 		SET_SQUEUE(mp, tcp_rput_data, connp);
13080 		return (mp);
13081 	}
13082 
13083 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13084 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13085 		if (IPCL_IS_TCP(connp)) {
13086 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13087 			DB_CKSUMSTART(mp) =
13088 			    (intptr_t)ip_squeue_get(ill_ring);
13089 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13090 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13091 				BUMP_MIB(ill->ill_ip_mib,
13092 				    ipIfStatsHCInDelivers);
13093 				SET_SQUEUE(mp, connp->conn_recv, connp);
13094 				return (mp);
13095 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13096 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13097 				BUMP_MIB(ill->ill_ip_mib,
13098 				    ipIfStatsHCInDelivers);
13099 				ip_squeue_enter_unbound++;
13100 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13101 				    connp);
13102 				return (mp);
13103 			}
13104 			syn_present = B_TRUE;
13105 		}
13106 
13107 	}
13108 
13109 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13110 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13111 
13112 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13113 		/* No need to send this packet to TCP */
13114 		if ((flags & TH_RST) || (flags & TH_URG)) {
13115 			CONN_DEC_REF(connp);
13116 			freemsg(first_mp);
13117 			return (NULL);
13118 		}
13119 		if (flags & TH_ACK) {
13120 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13121 			    ipst->ips_netstack->netstack_tcp, connp);
13122 			CONN_DEC_REF(connp);
13123 			return (NULL);
13124 		}
13125 
13126 		CONN_DEC_REF(connp);
13127 		freemsg(first_mp);
13128 		return (NULL);
13129 	}
13130 
13131 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13132 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13133 		    ipha, NULL, mctl_present);
13134 		if (first_mp == NULL) {
13135 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13136 			CONN_DEC_REF(connp);
13137 			return (NULL);
13138 		}
13139 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13140 			ASSERT(syn_present);
13141 			if (mctl_present) {
13142 				ASSERT(first_mp != mp);
13143 				first_mp->b_datap->db_struioflag |=
13144 				    STRUIO_POLICY;
13145 			} else {
13146 				ASSERT(first_mp == mp);
13147 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13148 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13149 			}
13150 		} else {
13151 			/*
13152 			 * Discard first_mp early since we're dealing with a
13153 			 * fully-connected conn_t and tcp doesn't do policy in
13154 			 * this case.
13155 			 */
13156 			if (mctl_present) {
13157 				freeb(first_mp);
13158 				mctl_present = B_FALSE;
13159 			}
13160 			first_mp = mp;
13161 		}
13162 	}
13163 
13164 	/* Initiate IPPF processing for fastpath */
13165 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13166 		uint32_t	ill_index;
13167 
13168 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13169 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13170 		if (mp == NULL) {
13171 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13172 			    "deferred/dropped during IPPF processing\n"));
13173 			CONN_DEC_REF(connp);
13174 			if (mctl_present)
13175 				freeb(first_mp);
13176 			return (NULL);
13177 		} else if (mctl_present) {
13178 			/*
13179 			 * ip_process might return a new mp.
13180 			 */
13181 			ASSERT(first_mp != mp);
13182 			first_mp->b_cont = mp;
13183 		} else {
13184 			first_mp = mp;
13185 		}
13186 
13187 	}
13188 
13189 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13190 		/*
13191 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13192 		 * make sure IPF_RECVIF is passed to ip_add_info.
13193 		 */
13194 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13195 		    IPCL_ZONEID(connp), ipst);
13196 		if (mp == NULL) {
13197 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13198 			CONN_DEC_REF(connp);
13199 			if (mctl_present)
13200 				freeb(first_mp);
13201 			return (NULL);
13202 		} else if (mctl_present) {
13203 			/*
13204 			 * ip_add_info might return a new mp.
13205 			 */
13206 			ASSERT(first_mp != mp);
13207 			first_mp->b_cont = mp;
13208 		} else {
13209 			first_mp = mp;
13210 		}
13211 	}
13212 
13213 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13214 	if (IPCL_IS_TCP(connp)) {
13215 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13216 		return (first_mp);
13217 	} else {
13218 		/* SOCK_RAW, IPPROTO_TCP case */
13219 		(connp->conn_recv)(connp, first_mp, NULL);
13220 		CONN_DEC_REF(connp);
13221 		return (NULL);
13222 	}
13223 
13224 no_conn:
13225 	/* Initiate IPPf processing, if needed. */
13226 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13227 		uint32_t ill_index;
13228 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13229 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13230 		if (first_mp == NULL) {
13231 			return (NULL);
13232 		}
13233 	}
13234 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13235 
13236 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13237 	    ipst->ips_netstack->netstack_tcp, NULL);
13238 	return (NULL);
13239 ipoptions:
13240 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13241 		goto slow_done;
13242 	}
13243 
13244 	UPDATE_IB_PKT_COUNT(ire);
13245 	ire->ire_last_used_time = lbolt;
13246 
13247 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13248 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13249 fragmented:
13250 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13251 			if (mctl_present)
13252 				freeb(first_mp);
13253 			goto slow_done;
13254 		}
13255 		/*
13256 		 * Make sure that first_mp points back to mp as
13257 		 * the mp we came in with could have changed in
13258 		 * ip_rput_fragment().
13259 		 */
13260 		ASSERT(!mctl_present);
13261 		ipha = (ipha_t *)mp->b_rptr;
13262 		first_mp = mp;
13263 	}
13264 
13265 	/* Now we have a complete datagram, destined for this machine. */
13266 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13267 
13268 	len = mp->b_wptr - mp->b_rptr;
13269 	/* Pull up a minimal TCP header, if necessary. */
13270 	if (len < (u1 + 20)) {
13271 tcppullup:
13272 		if (!pullupmsg(mp, u1 + 20)) {
13273 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13274 			goto error;
13275 		}
13276 		ipha = (ipha_t *)mp->b_rptr;
13277 		len = mp->b_wptr - mp->b_rptr;
13278 	}
13279 
13280 	/*
13281 	 * Extract the offset field from the TCP header.  As usual, we
13282 	 * try to help the compiler more than the reader.
13283 	 */
13284 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13285 	if (offset != 5) {
13286 tcpoptions:
13287 		if (offset < 5) {
13288 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13289 			goto error;
13290 		}
13291 		/*
13292 		 * There must be TCP options.
13293 		 * Make sure we can grab them.
13294 		 */
13295 		offset <<= 2;
13296 		offset += u1;
13297 		if (len < offset) {
13298 			if (!pullupmsg(mp, offset)) {
13299 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13300 				goto error;
13301 			}
13302 			ipha = (ipha_t *)mp->b_rptr;
13303 			len = mp->b_wptr - rptr;
13304 		}
13305 	}
13306 
13307 	/* Get the total packet length in len, including headers. */
13308 	if (mp->b_cont) {
13309 multipkttcp:
13310 		len = msgdsize(mp);
13311 	}
13312 
13313 	/*
13314 	 * Check the TCP checksum by pulling together the pseudo-
13315 	 * header checksum, and passing it to ip_csum to be added in
13316 	 * with the TCP datagram.
13317 	 *
13318 	 * Since we are not using the hwcksum if available we must
13319 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13320 	 * If either of these fails along the way the mblk is freed.
13321 	 * If this logic ever changes and mblk is reused to say send
13322 	 * ICMP's back, then this flag may need to be cleared in
13323 	 * other places as well.
13324 	 */
13325 	DB_CKSUMFLAGS(mp) = 0;
13326 
13327 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13328 
13329 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13330 #ifdef	_BIG_ENDIAN
13331 	u1 += IPPROTO_TCP;
13332 #else
13333 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13334 #endif
13335 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13336 	/*
13337 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13338 	 */
13339 	IP_STAT(ipst, ip_in_sw_cksum);
13340 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13341 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13342 		goto error;
13343 	}
13344 
13345 	IP_STAT(ipst, ip_tcp_slow_path);
13346 	goto try_again;
13347 #undef  iphs
13348 #undef  rptr
13349 
13350 error:
13351 	freemsg(first_mp);
13352 slow_done:
13353 	return (NULL);
13354 }
13355 
13356 /* ARGSUSED */
13357 static void
13358 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13359     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13360 {
13361 	conn_t		*connp;
13362 	uint32_t	sum;
13363 	uint32_t	u1;
13364 	ssize_t		len;
13365 	sctp_hdr_t	*sctph;
13366 	zoneid_t	zoneid = ire->ire_zoneid;
13367 	uint32_t	pktsum;
13368 	uint32_t	calcsum;
13369 	uint32_t	ports;
13370 	in6_addr_t	map_src, map_dst;
13371 	ill_t		*ill = (ill_t *)q->q_ptr;
13372 	ip_stack_t	*ipst;
13373 	sctp_stack_t	*sctps;
13374 	boolean_t	sctp_csum_err = B_FALSE;
13375 
13376 	ASSERT(recv_ill != NULL);
13377 	ipst = recv_ill->ill_ipst;
13378 	sctps = ipst->ips_netstack->netstack_sctp;
13379 
13380 #define	rptr	((uchar_t *)ipha)
13381 
13382 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13383 	ASSERT(ill != NULL);
13384 
13385 	/* u1 is # words of IP options */
13386 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13387 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13388 
13389 	/* IP options present */
13390 	if (u1 > 0) {
13391 		goto ipoptions;
13392 	} else {
13393 		/* Check the IP header checksum.  */
13394 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13395 		    !mctl_present) {
13396 #define	uph	((uint16_t *)ipha)
13397 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13398 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13399 #undef	uph
13400 			/* finish doing IP checksum */
13401 			sum = (sum & 0xFFFF) + (sum >> 16);
13402 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13403 			/*
13404 			 * Don't verify header checksum if this packet
13405 			 * is coming back from AH/ESP as we already did it.
13406 			 */
13407 			if (sum != 0 && sum != 0xFFFF) {
13408 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13409 				goto error;
13410 			}
13411 		}
13412 		/*
13413 		 * Since there is no SCTP h/w cksum support yet, just
13414 		 * clear the flag.
13415 		 */
13416 		DB_CKSUMFLAGS(mp) = 0;
13417 	}
13418 
13419 	/*
13420 	 * Don't verify header checksum if this packet is coming
13421 	 * back from AH/ESP as we already did it.
13422 	 */
13423 	if (!mctl_present) {
13424 		UPDATE_IB_PKT_COUNT(ire);
13425 		ire->ire_last_used_time = lbolt;
13426 	}
13427 
13428 	/* packet part of fragmented IP packet? */
13429 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13430 	if (u1 & (IPH_MF | IPH_OFFSET))
13431 		goto fragmented;
13432 
13433 	/* u1 = IP header length (20 bytes) */
13434 	u1 = IP_SIMPLE_HDR_LENGTH;
13435 
13436 find_sctp_client:
13437 	/* Pullup if we don't have the sctp common header. */
13438 	len = MBLKL(mp);
13439 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13440 		if (mp->b_cont == NULL ||
13441 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13442 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13443 			goto error;
13444 		}
13445 		ipha = (ipha_t *)mp->b_rptr;
13446 		len = MBLKL(mp);
13447 	}
13448 
13449 	sctph = (sctp_hdr_t *)(rptr + u1);
13450 #ifdef	DEBUG
13451 	if (!skip_sctp_cksum) {
13452 #endif
13453 		pktsum = sctph->sh_chksum;
13454 		sctph->sh_chksum = 0;
13455 		calcsum = sctp_cksum(mp, u1);
13456 		sctph->sh_chksum = pktsum;
13457 		if (calcsum != pktsum)
13458 			sctp_csum_err = B_TRUE;
13459 #ifdef	DEBUG	/* skip_sctp_cksum */
13460 	}
13461 #endif
13462 	/* get the ports */
13463 	ports = *(uint32_t *)&sctph->sh_sport;
13464 
13465 	IRE_REFRELE(ire);
13466 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13467 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13468 	if (sctp_csum_err) {
13469 		/*
13470 		 * No potential sctp checksum errors go to the Sun
13471 		 * sctp stack however they might be Adler-32 summed
13472 		 * packets a userland stack bound to a raw IP socket
13473 		 * could reasonably use. Note though that Adler-32 is
13474 		 * a long deprecated algorithm and customer sctp
13475 		 * networks should eventually migrate to CRC-32 at
13476 		 * which time this facility should be removed.
13477 		 */
13478 		flags |= IP_FF_SCTP_CSUM_ERR;
13479 		goto no_conn;
13480 	}
13481 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13482 	    sctps)) == NULL) {
13483 		/* Check for raw socket or OOTB handling */
13484 		goto no_conn;
13485 	}
13486 
13487 	/* Found a client; up it goes */
13488 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13489 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13490 	return;
13491 
13492 no_conn:
13493 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13494 	    ports, mctl_present, flags, B_TRUE, zoneid);
13495 	return;
13496 
13497 ipoptions:
13498 	DB_CKSUMFLAGS(mp) = 0;
13499 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13500 		goto slow_done;
13501 
13502 	UPDATE_IB_PKT_COUNT(ire);
13503 	ire->ire_last_used_time = lbolt;
13504 
13505 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13506 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13507 fragmented:
13508 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13509 			goto slow_done;
13510 		/*
13511 		 * Make sure that first_mp points back to mp as
13512 		 * the mp we came in with could have changed in
13513 		 * ip_rput_fragment().
13514 		 */
13515 		ASSERT(!mctl_present);
13516 		ipha = (ipha_t *)mp->b_rptr;
13517 		first_mp = mp;
13518 	}
13519 
13520 	/* Now we have a complete datagram, destined for this machine. */
13521 	u1 = IPH_HDR_LENGTH(ipha);
13522 	goto find_sctp_client;
13523 #undef  iphs
13524 #undef  rptr
13525 
13526 error:
13527 	freemsg(first_mp);
13528 slow_done:
13529 	IRE_REFRELE(ire);
13530 }
13531 
13532 #define	VER_BITS	0xF0
13533 #define	VERSION_6	0x60
13534 
13535 static boolean_t
13536 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13537     ipaddr_t *dstp, ip_stack_t *ipst)
13538 {
13539 	uint_t	opt_len;
13540 	ipha_t *ipha;
13541 	ssize_t len;
13542 	uint_t	pkt_len;
13543 
13544 	ASSERT(ill != NULL);
13545 	IP_STAT(ipst, ip_ipoptions);
13546 	ipha = *iphapp;
13547 
13548 #define	rptr    ((uchar_t *)ipha)
13549 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13550 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13551 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13552 		freemsg(mp);
13553 		return (B_FALSE);
13554 	}
13555 
13556 	/* multiple mblk or too short */
13557 	pkt_len = ntohs(ipha->ipha_length);
13558 
13559 	/* Get the number of words of IP options in the IP header. */
13560 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13561 	if (opt_len) {
13562 		/* IP Options present!  Validate and process. */
13563 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13564 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13565 			goto done;
13566 		}
13567 		/*
13568 		 * Recompute complete header length and make sure we
13569 		 * have access to all of it.
13570 		 */
13571 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13572 		if (len > (mp->b_wptr - rptr)) {
13573 			if (len > pkt_len) {
13574 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13575 				goto done;
13576 			}
13577 			if (!pullupmsg(mp, len)) {
13578 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13579 				goto done;
13580 			}
13581 			ipha = (ipha_t *)mp->b_rptr;
13582 		}
13583 		/*
13584 		 * Go off to ip_rput_options which returns the next hop
13585 		 * destination address, which may have been affected
13586 		 * by source routing.
13587 		 */
13588 		IP_STAT(ipst, ip_opt);
13589 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13590 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13591 			return (B_FALSE);
13592 		}
13593 	}
13594 	*iphapp = ipha;
13595 	return (B_TRUE);
13596 done:
13597 	/* clear b_prev - used by ip_mroute_decap */
13598 	mp->b_prev = NULL;
13599 	freemsg(mp);
13600 	return (B_FALSE);
13601 #undef  rptr
13602 }
13603 
13604 /*
13605  * Deal with the fact that there is no ire for the destination.
13606  */
13607 static ire_t *
13608 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13609 {
13610 	ipha_t	*ipha;
13611 	ill_t	*ill;
13612 	ire_t	*ire;
13613 	ip_stack_t *ipst;
13614 	enum	ire_forward_action ret_action;
13615 
13616 	ipha = (ipha_t *)mp->b_rptr;
13617 	ill = (ill_t *)q->q_ptr;
13618 
13619 	ASSERT(ill != NULL);
13620 	ipst = ill->ill_ipst;
13621 
13622 	/*
13623 	 * No IRE for this destination, so it can't be for us.
13624 	 * Unless we are forwarding, drop the packet.
13625 	 * We have to let source routed packets through
13626 	 * since we don't yet know if they are 'ping -l'
13627 	 * packets i.e. if they will go out over the
13628 	 * same interface as they came in on.
13629 	 */
13630 	if (ll_multicast) {
13631 		freemsg(mp);
13632 		return (NULL);
13633 	}
13634 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13635 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13636 		freemsg(mp);
13637 		return (NULL);
13638 	}
13639 
13640 	/*
13641 	 * Mark this packet as having originated externally.
13642 	 *
13643 	 * For non-forwarding code path, ire_send later double
13644 	 * checks this interface to see if it is still exists
13645 	 * post-ARP resolution.
13646 	 *
13647 	 * Also, IPQOS uses this to differentiate between
13648 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13649 	 * QOS packet processing in ip_wput_attach_llhdr().
13650 	 * The QoS module can mark the b_band for a fastpath message
13651 	 * or the dl_priority field in a unitdata_req header for
13652 	 * CoS marking. This info can only be found in
13653 	 * ip_wput_attach_llhdr().
13654 	 */
13655 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13656 	/*
13657 	 * Clear the indication that this may have a hardware checksum
13658 	 * as we are not using it
13659 	 */
13660 	DB_CKSUMFLAGS(mp) = 0;
13661 
13662 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13663 	    MBLK_GETLABEL(mp), ipst);
13664 
13665 	if (ire == NULL && ret_action == Forward_check_multirt) {
13666 		/* Let ip_newroute handle CGTP  */
13667 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13668 		return (NULL);
13669 	}
13670 
13671 	if (ire != NULL)
13672 		return (ire);
13673 
13674 	mp->b_prev = mp->b_next = 0;
13675 
13676 	if (ret_action == Forward_blackhole) {
13677 		freemsg(mp);
13678 		return (NULL);
13679 	}
13680 	/* send icmp unreachable */
13681 	q = WR(q);
13682 	/* Sent by forwarding path, and router is global zone */
13683 	if (ip_source_routed(ipha, ipst)) {
13684 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13685 		    GLOBAL_ZONEID, ipst);
13686 	} else {
13687 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13688 		    ipst);
13689 	}
13690 
13691 	return (NULL);
13692 
13693 }
13694 
13695 /*
13696  * check ip header length and align it.
13697  */
13698 static boolean_t
13699 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13700 {
13701 	ssize_t len;
13702 	ill_t *ill;
13703 	ipha_t	*ipha;
13704 
13705 	len = MBLKL(mp);
13706 
13707 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13708 		ill = (ill_t *)q->q_ptr;
13709 
13710 		if (!OK_32PTR(mp->b_rptr))
13711 			IP_STAT(ipst, ip_notaligned1);
13712 		else
13713 			IP_STAT(ipst, ip_notaligned2);
13714 		/* Guard against bogus device drivers */
13715 		if (len < 0) {
13716 			/* clear b_prev - used by ip_mroute_decap */
13717 			mp->b_prev = NULL;
13718 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13719 			freemsg(mp);
13720 			return (B_FALSE);
13721 		}
13722 
13723 		if (ip_rput_pullups++ == 0) {
13724 			ipha = (ipha_t *)mp->b_rptr;
13725 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13726 			    "ip_check_and_align_header: %s forced us to "
13727 			    " pullup pkt, hdr len %ld, hdr addr %p",
13728 			    ill->ill_name, len, ipha);
13729 		}
13730 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13731 			/* clear b_prev - used by ip_mroute_decap */
13732 			mp->b_prev = NULL;
13733 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13734 			freemsg(mp);
13735 			return (B_FALSE);
13736 		}
13737 	}
13738 	return (B_TRUE);
13739 }
13740 
13741 ire_t *
13742 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13743 {
13744 	ire_t		*new_ire;
13745 	ill_t		*ire_ill;
13746 	uint_t		ifindex;
13747 	ip_stack_t	*ipst = ill->ill_ipst;
13748 	boolean_t	strict_check = B_FALSE;
13749 
13750 	/*
13751 	 * This packet came in on an interface other than the one associated
13752 	 * with the first ire we found for the destination address. We do
13753 	 * another ire lookup here, using the ingress ill, to see if the
13754 	 * interface is in an interface group.
13755 	 * As long as the ills belong to the same group, we don't consider
13756 	 * them to be arriving on the wrong interface. Thus, if the switch
13757 	 * is doing inbound load spreading, we won't drop packets when the
13758 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13759 	 * for 'usesrc groups' where the destination address may belong to
13760 	 * another interface to allow multipathing to happen.
13761 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13762 	 * where the local address may not be unique. In this case we were
13763 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13764 	 * actually returned. The new lookup, which is more specific, should
13765 	 * only find the IRE_LOCAL associated with the ingress ill if one
13766 	 * exists.
13767 	 */
13768 
13769 	if (ire->ire_ipversion == IPV4_VERSION) {
13770 		if (ipst->ips_ip_strict_dst_multihoming)
13771 			strict_check = B_TRUE;
13772 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13773 		    ill->ill_ipif, ALL_ZONES, NULL,
13774 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13775 	} else {
13776 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13777 		if (ipst->ips_ipv6_strict_dst_multihoming)
13778 			strict_check = B_TRUE;
13779 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13780 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13781 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13782 	}
13783 	/*
13784 	 * If the same ire that was returned in ip_input() is found then this
13785 	 * is an indication that interface groups are in use. The packet
13786 	 * arrived on a different ill in the group than the one associated with
13787 	 * the destination address.  If a different ire was found then the same
13788 	 * IP address must be hosted on multiple ills. This is possible with
13789 	 * unnumbered point2point interfaces. We switch to use this new ire in
13790 	 * order to have accurate interface statistics.
13791 	 */
13792 	if (new_ire != NULL) {
13793 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13794 			ire_refrele(ire);
13795 			ire = new_ire;
13796 		} else {
13797 			ire_refrele(new_ire);
13798 		}
13799 		return (ire);
13800 	} else if ((ire->ire_rfq == NULL) &&
13801 	    (ire->ire_ipversion == IPV4_VERSION)) {
13802 		/*
13803 		 * The best match could have been the original ire which
13804 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13805 		 * the strict multihoming checks are irrelevant as we consider
13806 		 * local addresses hosted on lo0 to be interface agnostic. We
13807 		 * only expect a null ire_rfq on IREs which are associated with
13808 		 * lo0 hence we can return now.
13809 		 */
13810 		return (ire);
13811 	}
13812 
13813 	/*
13814 	 * Chase pointers once and store locally.
13815 	 */
13816 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13817 	    (ill_t *)(ire->ire_rfq->q_ptr);
13818 	ifindex = ill->ill_usesrc_ifindex;
13819 
13820 	/*
13821 	 * Check if it's a legal address on the 'usesrc' interface.
13822 	 */
13823 	if ((ifindex != 0) && (ire_ill != NULL) &&
13824 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13825 		return (ire);
13826 	}
13827 
13828 	/*
13829 	 * If the ip*_strict_dst_multihoming switch is on then we can
13830 	 * only accept this packet if the interface is marked as routing.
13831 	 */
13832 	if (!(strict_check))
13833 		return (ire);
13834 
13835 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13836 	    ILLF_ROUTER) != 0) {
13837 		return (ire);
13838 	}
13839 
13840 	ire_refrele(ire);
13841 	return (NULL);
13842 }
13843 
13844 ire_t *
13845 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13846 {
13847 	ipha_t	*ipha;
13848 	ire_t	*src_ire;
13849 	ill_t	*stq_ill;
13850 	uint_t	hlen;
13851 	uint_t	pkt_len;
13852 	uint32_t sum;
13853 	queue_t	*dev_q;
13854 	ip_stack_t *ipst = ill->ill_ipst;
13855 	mblk_t *fpmp;
13856 	enum	ire_forward_action ret_action;
13857 
13858 	ipha = (ipha_t *)mp->b_rptr;
13859 
13860 	/*
13861 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13862 	 * The loopback address check for both src and dst has already
13863 	 * been checked in ip_input
13864 	 */
13865 
13866 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13867 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13868 		goto drop;
13869 	}
13870 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13871 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13872 
13873 	if (src_ire != NULL) {
13874 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13875 		ire_refrele(src_ire);
13876 		goto drop;
13877 	}
13878 
13879 
13880 	/* No ire cache of nexthop. So first create one  */
13881 	if (ire == NULL) {
13882 
13883 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13884 		    NULL, ipst);
13885 		/*
13886 		 * We only come to ip_fast_forward if ip_cgtp_filter
13887 		 * is not set. So ire_forward() should not return with
13888 		 * Forward_check_multirt as the next action.
13889 		 */
13890 		ASSERT(ret_action != Forward_check_multirt);
13891 		if (ire == NULL) {
13892 			/* An attempt was made to forward the packet */
13893 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13894 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13895 			mp->b_prev = mp->b_next = 0;
13896 			/* send icmp unreachable */
13897 			/* Sent by forwarding path, and router is global zone */
13898 			if (ret_action == Forward_ret_icmp_err) {
13899 				if (ip_source_routed(ipha, ipst)) {
13900 					icmp_unreachable(ill->ill_wq, mp,
13901 					    ICMP_SOURCE_ROUTE_FAILED,
13902 					    GLOBAL_ZONEID, ipst);
13903 				} else {
13904 					icmp_unreachable(ill->ill_wq, mp,
13905 					    ICMP_HOST_UNREACHABLE,
13906 					    GLOBAL_ZONEID, ipst);
13907 				}
13908 			} else {
13909 				freemsg(mp);
13910 			}
13911 			return (NULL);
13912 		}
13913 	}
13914 
13915 	/*
13916 	 * Forwarding fastpath exception case:
13917 	 * If either of the follwoing case is true, we take
13918 	 * the slowpath
13919 	 *	o forwarding is not enabled
13920 	 *	o incoming and outgoing interface are the same, or the same
13921 	 *	  IPMP group
13922 	 *	o corresponding ire is in incomplete state
13923 	 *	o packet needs fragmentation
13924 	 *	o ARP cache is not resolved
13925 	 *
13926 	 * The codeflow from here on is thus:
13927 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13928 	 */
13929 	pkt_len = ntohs(ipha->ipha_length);
13930 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13931 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13932 	    !(ill->ill_flags & ILLF_ROUTER) ||
13933 	    (ill == stq_ill) ||
13934 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13935 	    (ire->ire_nce == NULL) ||
13936 	    (pkt_len > ire->ire_max_frag) ||
13937 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13938 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13939 	    ipha->ipha_ttl <= 1) {
13940 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13941 		    ipha, ill, B_FALSE);
13942 		return (ire);
13943 	}
13944 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13945 
13946 	DTRACE_PROBE4(ip4__forwarding__start,
13947 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13948 
13949 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13950 	    ipst->ips_ipv4firewall_forwarding,
13951 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13952 
13953 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13954 
13955 	if (mp == NULL)
13956 		goto drop;
13957 
13958 	mp->b_datap->db_struioun.cksum.flags = 0;
13959 	/* Adjust the checksum to reflect the ttl decrement. */
13960 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13961 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13962 	ipha->ipha_ttl--;
13963 
13964 	/*
13965 	 * Write the link layer header.  We can do this safely here,
13966 	 * because we have already tested to make sure that the IP
13967 	 * policy is not set, and that we have a fast path destination
13968 	 * header.
13969 	 */
13970 	mp->b_rptr -= hlen;
13971 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13972 
13973 	UPDATE_IB_PKT_COUNT(ire);
13974 	ire->ire_last_used_time = lbolt;
13975 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13976 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13977 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13978 
13979 	dev_q = ire->ire_stq->q_next;
13980 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
13981 	    !canputnext(ire->ire_stq)) {
13982 		goto indiscard;
13983 	}
13984 	if (ILL_DLS_CAPABLE(stq_ill)) {
13985 		/*
13986 		 * Send the packet directly to DLD, where it
13987 		 * may be queued depending on the availability
13988 		 * of transmit resources at the media layer.
13989 		 */
13990 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
13991 	} else {
13992 		DTRACE_PROBE4(ip4__physical__out__start,
13993 		    ill_t *, NULL, ill_t *, stq_ill,
13994 		    ipha_t *, ipha, mblk_t *, mp);
13995 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
13996 		    ipst->ips_ipv4firewall_physical_out,
13997 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
13998 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
13999 		if (mp == NULL)
14000 			goto drop;
14001 		putnext(ire->ire_stq, mp);
14002 	}
14003 	return (ire);
14004 
14005 indiscard:
14006 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14007 drop:
14008 	if (mp != NULL)
14009 		freemsg(mp);
14010 	return (ire);
14011 
14012 }
14013 
14014 /*
14015  * This function is called in the forwarding slowpath, when
14016  * either the ire lacks the link-layer address, or the packet needs
14017  * further processing(eg. fragmentation), before transmission.
14018  */
14019 
14020 static void
14021 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14022     ill_t *ill, boolean_t ll_multicast)
14023 {
14024 	ill_group_t	*ill_group;
14025 	ill_group_t	*ire_group;
14026 	queue_t		*dev_q;
14027 	ire_t		*src_ire;
14028 	ip_stack_t	*ipst = ill->ill_ipst;
14029 
14030 	ASSERT(ire->ire_stq != NULL);
14031 
14032 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14033 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14034 
14035 	if (ll_multicast != 0) {
14036 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14037 		goto drop_pkt;
14038 	}
14039 
14040 	/*
14041 	 * check if ipha_src is a broadcast address. Note that this
14042 	 * check is redundant when we get here from ip_fast_forward()
14043 	 * which has already done this check. However, since we can
14044 	 * also get here from ip_rput_process_broadcast() or, for
14045 	 * for the slow path through ip_fast_forward(), we perform
14046 	 * the check again for code-reusability
14047 	 */
14048 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14049 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14050 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14051 		if (src_ire != NULL)
14052 			ire_refrele(src_ire);
14053 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14054 		ip2dbg(("ip_rput_process_forward: Received packet with"
14055 		    " bad src/dst address on %s\n", ill->ill_name));
14056 		goto drop_pkt;
14057 	}
14058 
14059 	ill_group = ill->ill_group;
14060 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14061 	/*
14062 	 * Check if we want to forward this one at this time.
14063 	 * We allow source routed packets on a host provided that
14064 	 * they go out the same interface or same interface group
14065 	 * as they came in on.
14066 	 *
14067 	 * XXX To be quicker, we may wish to not chase pointers to
14068 	 * get the ILLF_ROUTER flag and instead store the
14069 	 * forwarding policy in the ire.  An unfortunate
14070 	 * side-effect of that would be requiring an ire flush
14071 	 * whenever the ILLF_ROUTER flag changes.
14072 	 */
14073 	if (((ill->ill_flags &
14074 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14075 	    ILLF_ROUTER) == 0) &&
14076 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14077 	    (ill_group != NULL && ill_group == ire_group)))) {
14078 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14079 		if (ip_source_routed(ipha, ipst)) {
14080 			q = WR(q);
14081 			/*
14082 			 * Clear the indication that this may have
14083 			 * hardware checksum as we are not using it.
14084 			 */
14085 			DB_CKSUMFLAGS(mp) = 0;
14086 			/* Sent by forwarding path, and router is global zone */
14087 			icmp_unreachable(q, mp,
14088 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14089 			return;
14090 		}
14091 		goto drop_pkt;
14092 	}
14093 
14094 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14095 
14096 	/* Packet is being forwarded. Turning off hwcksum flag. */
14097 	DB_CKSUMFLAGS(mp) = 0;
14098 	if (ipst->ips_ip_g_send_redirects) {
14099 		/*
14100 		 * Check whether the incoming interface and outgoing
14101 		 * interface is part of the same group. If so,
14102 		 * send redirects.
14103 		 *
14104 		 * Check the source address to see if it originated
14105 		 * on the same logical subnet it is going back out on.
14106 		 * If so, we should be able to send it a redirect.
14107 		 * Avoid sending a redirect if the destination
14108 		 * is directly connected (i.e., ipha_dst is the same
14109 		 * as ire_gateway_addr or the ire_addr of the
14110 		 * nexthop IRE_CACHE ), or if the packet was source
14111 		 * routed out this interface.
14112 		 */
14113 		ipaddr_t src, nhop;
14114 		mblk_t	*mp1;
14115 		ire_t	*nhop_ire = NULL;
14116 
14117 		/*
14118 		 * Check whether ire_rfq and q are from the same ill
14119 		 * or if they are not same, they at least belong
14120 		 * to the same group. If so, send redirects.
14121 		 */
14122 		if ((ire->ire_rfq == q ||
14123 		    (ill_group != NULL && ill_group == ire_group)) &&
14124 		    !ip_source_routed(ipha, ipst)) {
14125 
14126 			nhop = (ire->ire_gateway_addr != 0 ?
14127 			    ire->ire_gateway_addr : ire->ire_addr);
14128 
14129 			if (ipha->ipha_dst == nhop) {
14130 				/*
14131 				 * We avoid sending a redirect if the
14132 				 * destination is directly connected
14133 				 * because it is possible that multiple
14134 				 * IP subnets may have been configured on
14135 				 * the link, and the source may not
14136 				 * be on the same subnet as ip destination,
14137 				 * even though they are on the same
14138 				 * physical link.
14139 				 */
14140 				goto sendit;
14141 			}
14142 
14143 			src = ipha->ipha_src;
14144 
14145 			/*
14146 			 * We look up the interface ire for the nexthop,
14147 			 * to see if ipha_src is in the same subnet
14148 			 * as the nexthop.
14149 			 *
14150 			 * Note that, if, in the future, IRE_CACHE entries
14151 			 * are obsoleted,  this lookup will not be needed,
14152 			 * as the ire passed to this function will be the
14153 			 * same as the nhop_ire computed below.
14154 			 */
14155 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14156 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14157 			    0, NULL, MATCH_IRE_TYPE, ipst);
14158 
14159 			if (nhop_ire != NULL) {
14160 				if ((src & nhop_ire->ire_mask) ==
14161 				    (nhop & nhop_ire->ire_mask)) {
14162 					/*
14163 					 * The source is directly connected.
14164 					 * Just copy the ip header (which is
14165 					 * in the first mblk)
14166 					 */
14167 					mp1 = copyb(mp);
14168 					if (mp1 != NULL) {
14169 						icmp_send_redirect(WR(q), mp1,
14170 						    nhop, ipst);
14171 					}
14172 				}
14173 				ire_refrele(nhop_ire);
14174 			}
14175 		}
14176 	}
14177 sendit:
14178 	dev_q = ire->ire_stq->q_next;
14179 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14180 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14181 		freemsg(mp);
14182 		return;
14183 	}
14184 
14185 	ip_rput_forward(ire, ipha, mp, ill);
14186 	return;
14187 
14188 drop_pkt:
14189 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14190 	freemsg(mp);
14191 }
14192 
14193 ire_t *
14194 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14195     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14196 {
14197 	queue_t		*q;
14198 	uint16_t	hcksumflags;
14199 	ip_stack_t	*ipst = ill->ill_ipst;
14200 
14201 	q = *qp;
14202 
14203 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14204 
14205 	/*
14206 	 * Clear the indication that this may have hardware
14207 	 * checksum as we are not using it for forwarding.
14208 	 */
14209 	hcksumflags = DB_CKSUMFLAGS(mp);
14210 	DB_CKSUMFLAGS(mp) = 0;
14211 
14212 	/*
14213 	 * Directed broadcast forwarding: if the packet came in over a
14214 	 * different interface then it is routed out over we can forward it.
14215 	 */
14216 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14217 		ire_refrele(ire);
14218 		freemsg(mp);
14219 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14220 		return (NULL);
14221 	}
14222 	/*
14223 	 * For multicast we have set dst to be INADDR_BROADCAST
14224 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14225 	 * only for broadcast packets.
14226 	 */
14227 	if (!CLASSD(ipha->ipha_dst)) {
14228 		ire_t *new_ire;
14229 		ipif_t *ipif;
14230 		/*
14231 		 * For ill groups, as the switch duplicates broadcasts
14232 		 * across all the ports, we need to filter out and
14233 		 * send up only one copy. There is one copy for every
14234 		 * broadcast address on each ill. Thus, we look for a
14235 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14236 		 * later to see whether this ill is eligible to receive
14237 		 * them or not. ill_nominate_bcast_rcv() nominates only
14238 		 * one set of IREs for receiving.
14239 		 */
14240 
14241 		ipif = ipif_get_next_ipif(NULL, ill);
14242 		if (ipif == NULL) {
14243 			ire_refrele(ire);
14244 			freemsg(mp);
14245 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14246 			return (NULL);
14247 		}
14248 		new_ire = ire_ctable_lookup(dst, 0, 0,
14249 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14250 		ipif_refrele(ipif);
14251 
14252 		if (new_ire != NULL) {
14253 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14254 				ire_refrele(ire);
14255 				ire_refrele(new_ire);
14256 				freemsg(mp);
14257 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14258 				return (NULL);
14259 			}
14260 			/*
14261 			 * In the special case of multirouted broadcast
14262 			 * packets, we unconditionally need to "gateway"
14263 			 * them to the appropriate interface here.
14264 			 * In the normal case, this cannot happen, because
14265 			 * there is no broadcast IRE tagged with the
14266 			 * RTF_MULTIRT flag.
14267 			 */
14268 			if (new_ire->ire_flags & RTF_MULTIRT) {
14269 				ire_refrele(new_ire);
14270 				if (ire->ire_rfq != NULL) {
14271 					q = ire->ire_rfq;
14272 					*qp = q;
14273 				}
14274 			} else {
14275 				ire_refrele(ire);
14276 				ire = new_ire;
14277 			}
14278 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14279 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14280 				/*
14281 				 * Free the message if
14282 				 * ip_g_forward_directed_bcast is turned
14283 				 * off for non-local broadcast.
14284 				 */
14285 				ire_refrele(ire);
14286 				freemsg(mp);
14287 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14288 				return (NULL);
14289 			}
14290 		} else {
14291 			/*
14292 			 * This CGTP packet successfully passed the
14293 			 * CGTP filter, but the related CGTP
14294 			 * broadcast IRE has not been found,
14295 			 * meaning that the redundant ipif is
14296 			 * probably down. However, if we discarded
14297 			 * this packet, its duplicate would be
14298 			 * filtered out by the CGTP filter so none
14299 			 * of them would get through. So we keep
14300 			 * going with this one.
14301 			 */
14302 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14303 			if (ire->ire_rfq != NULL) {
14304 				q = ire->ire_rfq;
14305 				*qp = q;
14306 			}
14307 		}
14308 	}
14309 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14310 		/*
14311 		 * Verify that there are not more then one
14312 		 * IRE_BROADCAST with this broadcast address which
14313 		 * has ire_stq set.
14314 		 * TODO: simplify, loop over all IRE's
14315 		 */
14316 		ire_t	*ire1;
14317 		int	num_stq = 0;
14318 		mblk_t	*mp1;
14319 
14320 		/* Find the first one with ire_stq set */
14321 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14322 		for (ire1 = ire; ire1 &&
14323 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14324 		    ire1 = ire1->ire_next)
14325 			;
14326 		if (ire1) {
14327 			ire_refrele(ire);
14328 			ire = ire1;
14329 			IRE_REFHOLD(ire);
14330 		}
14331 
14332 		/* Check if there are additional ones with stq set */
14333 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14334 			if (ire->ire_addr != ire1->ire_addr)
14335 				break;
14336 			if (ire1->ire_stq) {
14337 				num_stq++;
14338 				break;
14339 			}
14340 		}
14341 		rw_exit(&ire->ire_bucket->irb_lock);
14342 		if (num_stq == 1 && ire->ire_stq != NULL) {
14343 			ip1dbg(("ip_rput_process_broadcast: directed "
14344 			    "broadcast to 0x%x\n",
14345 			    ntohl(ire->ire_addr)));
14346 			mp1 = copymsg(mp);
14347 			if (mp1) {
14348 				switch (ipha->ipha_protocol) {
14349 				case IPPROTO_UDP:
14350 					ip_udp_input(q, mp1, ipha, ire, ill);
14351 					break;
14352 				default:
14353 					ip_proto_input(q, mp1, ipha, ire, ill,
14354 					    B_FALSE);
14355 					break;
14356 				}
14357 			}
14358 			/*
14359 			 * Adjust ttl to 2 (1+1 - the forward engine
14360 			 * will decrement it by one.
14361 			 */
14362 			if (ip_csum_hdr(ipha)) {
14363 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14364 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14365 				freemsg(mp);
14366 				ire_refrele(ire);
14367 				return (NULL);
14368 			}
14369 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14370 			ipha->ipha_hdr_checksum = 0;
14371 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14372 			ip_rput_process_forward(q, mp, ire, ipha,
14373 			    ill, ll_multicast);
14374 			ire_refrele(ire);
14375 			return (NULL);
14376 		}
14377 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14378 		    ntohl(ire->ire_addr)));
14379 	}
14380 
14381 
14382 	/* Restore any hardware checksum flags */
14383 	DB_CKSUMFLAGS(mp) = hcksumflags;
14384 	return (ire);
14385 }
14386 
14387 /* ARGSUSED */
14388 static boolean_t
14389 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14390     int *ll_multicast, ipaddr_t *dstp)
14391 {
14392 	ip_stack_t	*ipst = ill->ill_ipst;
14393 
14394 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14395 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14396 	    ntohs(ipha->ipha_length));
14397 
14398 	/*
14399 	 * Forward packets only if we have joined the allmulti
14400 	 * group on this interface.
14401 	 */
14402 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14403 		int retval;
14404 
14405 		/*
14406 		 * Clear the indication that this may have hardware
14407 		 * checksum as we are not using it.
14408 		 */
14409 		DB_CKSUMFLAGS(mp) = 0;
14410 		retval = ip_mforward(ill, ipha, mp);
14411 		/* ip_mforward updates mib variables if needed */
14412 		/* clear b_prev - used by ip_mroute_decap */
14413 		mp->b_prev = NULL;
14414 
14415 		switch (retval) {
14416 		case 0:
14417 			/*
14418 			 * pkt is okay and arrived on phyint.
14419 			 *
14420 			 * If we are running as a multicast router
14421 			 * we need to see all IGMP and/or PIM packets.
14422 			 */
14423 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14424 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14425 				goto done;
14426 			}
14427 			break;
14428 		case -1:
14429 			/* pkt is mal-formed, toss it */
14430 			goto drop_pkt;
14431 		case 1:
14432 			/* pkt is okay and arrived on a tunnel */
14433 			/*
14434 			 * If we are running a multicast router
14435 			 *  we need to see all igmp packets.
14436 			 */
14437 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14438 				*dstp = INADDR_BROADCAST;
14439 				*ll_multicast = 1;
14440 				return (B_FALSE);
14441 			}
14442 
14443 			goto drop_pkt;
14444 		}
14445 	}
14446 
14447 	ILM_WALKER_HOLD(ill);
14448 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14449 		/*
14450 		 * This might just be caused by the fact that
14451 		 * multiple IP Multicast addresses map to the same
14452 		 * link layer multicast - no need to increment counter!
14453 		 */
14454 		ILM_WALKER_RELE(ill);
14455 		freemsg(mp);
14456 		return (B_TRUE);
14457 	}
14458 	ILM_WALKER_RELE(ill);
14459 done:
14460 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14461 	/*
14462 	 * This assumes the we deliver to all streams for multicast
14463 	 * and broadcast packets.
14464 	 */
14465 	*dstp = INADDR_BROADCAST;
14466 	*ll_multicast = 1;
14467 	return (B_FALSE);
14468 drop_pkt:
14469 	ip2dbg(("ip_rput: drop pkt\n"));
14470 	freemsg(mp);
14471 	return (B_TRUE);
14472 }
14473 
14474 /*
14475  * This function is used to both return an indication of whether or not
14476  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14477  * and in doing so, determine whether or not it is broadcast vs multicast.
14478  * For it to be a broadcast packet, we must have the appropriate mblk_t
14479  * hanging off the ill_t.  If this is either not present or doesn't match
14480  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14481  * to be multicast.  Thus NICs that have no broadcast address (or no
14482  * capability for one, such as point to point links) cannot return as
14483  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14484  * the return values simplifies the current use of the return value of this
14485  * function, which is to pass through the multicast/broadcast characteristic
14486  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14487  * changing the return value to some other symbol demands the appropriate
14488  * "translation" when hpe_flags is set prior to calling hook_run() for
14489  * packet events.
14490  */
14491 int
14492 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14493 {
14494 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14495 	mblk_t *bmp;
14496 
14497 	if (ind->dl_group_address) {
14498 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14499 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14500 		    MBLKL(mb) &&
14501 		    (bmp = ill->ill_bcast_mp) != NULL) {
14502 			dl_unitdata_req_t *dlur;
14503 			uint8_t *bphys_addr;
14504 
14505 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14506 			if (ill->ill_sap_length < 0)
14507 				bphys_addr = (uchar_t *)dlur +
14508 				    dlur->dl_dest_addr_offset;
14509 			else
14510 				bphys_addr = (uchar_t *)dlur +
14511 				    dlur->dl_dest_addr_offset +
14512 				    ill->ill_sap_length;
14513 
14514 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14515 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14516 				return (HPE_BROADCAST);
14517 			}
14518 			return (HPE_MULTICAST);
14519 		}
14520 		return (HPE_MULTICAST);
14521 	}
14522 	return (0);
14523 }
14524 
14525 static boolean_t
14526 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14527     int *ll_multicast, mblk_t **mpp)
14528 {
14529 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14530 	boolean_t must_copy = B_FALSE;
14531 	struct iocblk   *iocp;
14532 	ipha_t		*ipha;
14533 	ip_stack_t	*ipst = ill->ill_ipst;
14534 
14535 #define	rptr    ((uchar_t *)ipha)
14536 
14537 	first_mp = *first_mpp;
14538 	mp = *mpp;
14539 
14540 	ASSERT(first_mp == mp);
14541 
14542 	/*
14543 	 * if db_ref > 1 then copymsg and free original. Packet may be
14544 	 * changed and do not want other entity who has a reference to this
14545 	 * message to trip over the changes. This is a blind change because
14546 	 * trying to catch all places that might change packet is too
14547 	 * difficult (since it may be a module above this one)
14548 	 *
14549 	 * This corresponds to the non-fast path case. We walk down the full
14550 	 * chain in this case, and check the db_ref count of all the dblks,
14551 	 * and do a copymsg if required. It is possible that the db_ref counts
14552 	 * of the data blocks in the mblk chain can be different.
14553 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14554 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14555 	 * 'snoop' is running.
14556 	 */
14557 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14558 		if (mp1->b_datap->db_ref > 1) {
14559 			must_copy = B_TRUE;
14560 			break;
14561 		}
14562 	}
14563 
14564 	if (must_copy) {
14565 		mp1 = copymsg(mp);
14566 		if (mp1 == NULL) {
14567 			for (mp1 = mp; mp1 != NULL;
14568 			    mp1 = mp1->b_cont) {
14569 				mp1->b_next = NULL;
14570 				mp1->b_prev = NULL;
14571 			}
14572 			freemsg(mp);
14573 			if (ill != NULL) {
14574 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14575 			} else {
14576 				BUMP_MIB(&ipst->ips_ip_mib,
14577 				    ipIfStatsInDiscards);
14578 			}
14579 			return (B_TRUE);
14580 		}
14581 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14582 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14583 			/* Copy b_prev - used by ip_mroute_decap */
14584 			to_mp->b_prev = from_mp->b_prev;
14585 			from_mp->b_prev = NULL;
14586 		}
14587 		*first_mpp = first_mp = mp1;
14588 		freemsg(mp);
14589 		mp = mp1;
14590 		*mpp = mp1;
14591 	}
14592 
14593 	ipha = (ipha_t *)mp->b_rptr;
14594 
14595 	/*
14596 	 * previous code has a case for M_DATA.
14597 	 * We want to check how that happens.
14598 	 */
14599 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14600 	switch (first_mp->b_datap->db_type) {
14601 	case M_PROTO:
14602 	case M_PCPROTO:
14603 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14604 		    DL_UNITDATA_IND) {
14605 			/* Go handle anything other than data elsewhere. */
14606 			ip_rput_dlpi(q, mp);
14607 			return (B_TRUE);
14608 		}
14609 
14610 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14611 		/* Ditch the DLPI header. */
14612 		mp1 = mp->b_cont;
14613 		ASSERT(first_mp == mp);
14614 		*first_mpp = mp1;
14615 		freeb(mp);
14616 		*mpp = mp1;
14617 		return (B_FALSE);
14618 	case M_IOCACK:
14619 		ip1dbg(("got iocack "));
14620 		iocp = (struct iocblk *)mp->b_rptr;
14621 		switch (iocp->ioc_cmd) {
14622 		case DL_IOC_HDR_INFO:
14623 			ill = (ill_t *)q->q_ptr;
14624 			ill_fastpath_ack(ill, mp);
14625 			return (B_TRUE);
14626 		case SIOCSTUNPARAM:
14627 		case OSIOCSTUNPARAM:
14628 			/* Go through qwriter_ip */
14629 			break;
14630 		case SIOCGTUNPARAM:
14631 		case OSIOCGTUNPARAM:
14632 			ip_rput_other(NULL, q, mp, NULL);
14633 			return (B_TRUE);
14634 		default:
14635 			putnext(q, mp);
14636 			return (B_TRUE);
14637 		}
14638 		/* FALLTHRU */
14639 	case M_ERROR:
14640 	case M_HANGUP:
14641 		/*
14642 		 * Since this is on the ill stream we unconditionally
14643 		 * bump up the refcount
14644 		 */
14645 		ill_refhold(ill);
14646 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14647 		return (B_TRUE);
14648 	case M_CTL:
14649 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14650 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14651 		    IPHADA_M_CTL)) {
14652 			/*
14653 			 * It's an IPsec accelerated packet.
14654 			 * Make sure that the ill from which we received the
14655 			 * packet has enabled IPsec hardware acceleration.
14656 			 */
14657 			if (!(ill->ill_capabilities &
14658 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14659 				/* IPsec kstats: bean counter */
14660 				freemsg(mp);
14661 				return (B_TRUE);
14662 			}
14663 
14664 			/*
14665 			 * Make mp point to the mblk following the M_CTL,
14666 			 * then process according to type of mp.
14667 			 * After this processing, first_mp will point to
14668 			 * the data-attributes and mp to the pkt following
14669 			 * the M_CTL.
14670 			 */
14671 			mp = first_mp->b_cont;
14672 			if (mp == NULL) {
14673 				freemsg(first_mp);
14674 				return (B_TRUE);
14675 			}
14676 			/*
14677 			 * A Hardware Accelerated packet can only be M_DATA
14678 			 * ESP or AH packet.
14679 			 */
14680 			if (mp->b_datap->db_type != M_DATA) {
14681 				/* non-M_DATA IPsec accelerated packet */
14682 				IPSECHW_DEBUG(IPSECHW_PKT,
14683 				    ("non-M_DATA IPsec accelerated pkt\n"));
14684 				freemsg(first_mp);
14685 				return (B_TRUE);
14686 			}
14687 			ipha = (ipha_t *)mp->b_rptr;
14688 			if (ipha->ipha_protocol != IPPROTO_AH &&
14689 			    ipha->ipha_protocol != IPPROTO_ESP) {
14690 				IPSECHW_DEBUG(IPSECHW_PKT,
14691 				    ("non-M_DATA IPsec accelerated pkt\n"));
14692 				freemsg(first_mp);
14693 				return (B_TRUE);
14694 			}
14695 			*mpp = mp;
14696 			return (B_FALSE);
14697 		}
14698 		putnext(q, mp);
14699 		return (B_TRUE);
14700 	case M_IOCNAK:
14701 		ip1dbg(("got iocnak "));
14702 		iocp = (struct iocblk *)mp->b_rptr;
14703 		switch (iocp->ioc_cmd) {
14704 		case SIOCSTUNPARAM:
14705 		case OSIOCSTUNPARAM:
14706 			/*
14707 			 * Since this is on the ill stream we unconditionally
14708 			 * bump up the refcount
14709 			 */
14710 			ill_refhold(ill);
14711 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14712 			return (B_TRUE);
14713 		case DL_IOC_HDR_INFO:
14714 		case SIOCGTUNPARAM:
14715 		case OSIOCGTUNPARAM:
14716 			ip_rput_other(NULL, q, mp, NULL);
14717 			return (B_TRUE);
14718 		default:
14719 			break;
14720 		}
14721 		/* FALLTHRU */
14722 	default:
14723 		putnext(q, mp);
14724 		return (B_TRUE);
14725 	}
14726 }
14727 
14728 /* Read side put procedure.  Packets coming from the wire arrive here. */
14729 void
14730 ip_rput(queue_t *q, mblk_t *mp)
14731 {
14732 	ill_t	*ill;
14733 	union DL_primitives *dl;
14734 
14735 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14736 
14737 	ill = (ill_t *)q->q_ptr;
14738 
14739 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14740 		/*
14741 		 * If things are opening or closing, only accept high-priority
14742 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14743 		 * created; on close, things hanging off the ill may have been
14744 		 * freed already.)
14745 		 */
14746 		dl = (union DL_primitives *)mp->b_rptr;
14747 		if (DB_TYPE(mp) != M_PCPROTO ||
14748 		    dl->dl_primitive == DL_UNITDATA_IND) {
14749 			/*
14750 			 * SIOC[GS]TUNPARAM ioctls can come here.
14751 			 */
14752 			inet_freemsg(mp);
14753 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14754 			    "ip_rput_end: q %p (%S)", q, "uninit");
14755 			return;
14756 		}
14757 	}
14758 
14759 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14760 	    "ip_rput_end: q %p (%S)", q, "end");
14761 
14762 	ip_input(ill, NULL, mp, NULL);
14763 }
14764 
14765 static mblk_t *
14766 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14767 {
14768 	mblk_t *mp1;
14769 	boolean_t adjusted = B_FALSE;
14770 	ip_stack_t *ipst = ill->ill_ipst;
14771 
14772 	IP_STAT(ipst, ip_db_ref);
14773 	/*
14774 	 * The IP_RECVSLLA option depends on having the
14775 	 * link layer header. First check that:
14776 	 * a> the underlying device is of type ether,
14777 	 * since this option is currently supported only
14778 	 * over ethernet.
14779 	 * b> there is enough room to copy over the link
14780 	 * layer header.
14781 	 *
14782 	 * Once the checks are done, adjust rptr so that
14783 	 * the link layer header will be copied via
14784 	 * copymsg. Note that, IFT_ETHER may be returned
14785 	 * by some non-ethernet drivers but in this case
14786 	 * the second check will fail.
14787 	 */
14788 	if (ill->ill_type == IFT_ETHER &&
14789 	    (mp->b_rptr - mp->b_datap->db_base) >=
14790 	    sizeof (struct ether_header)) {
14791 		mp->b_rptr -= sizeof (struct ether_header);
14792 		adjusted = B_TRUE;
14793 	}
14794 	mp1 = copymsg(mp);
14795 
14796 	if (mp1 == NULL) {
14797 		mp->b_next = NULL;
14798 		/* clear b_prev - used by ip_mroute_decap */
14799 		mp->b_prev = NULL;
14800 		freemsg(mp);
14801 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14802 		return (NULL);
14803 	}
14804 
14805 	if (adjusted) {
14806 		/*
14807 		 * Copy is done. Restore the pointer in
14808 		 * the _new_ mblk
14809 		 */
14810 		mp1->b_rptr += sizeof (struct ether_header);
14811 	}
14812 
14813 	/* Copy b_prev - used by ip_mroute_decap */
14814 	mp1->b_prev = mp->b_prev;
14815 	mp->b_prev = NULL;
14816 
14817 	/* preserve the hardware checksum flags and data, if present */
14818 	if (DB_CKSUMFLAGS(mp) != 0) {
14819 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14820 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14821 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14822 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14823 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14824 	}
14825 
14826 	freemsg(mp);
14827 	return (mp1);
14828 }
14829 
14830 /*
14831  * Direct read side procedure capable of dealing with chains. GLDv3 based
14832  * drivers call this function directly with mblk chains while STREAMS
14833  * read side procedure ip_rput() calls this for single packet with ip_ring
14834  * set to NULL to process one packet at a time.
14835  *
14836  * The ill will always be valid if this function is called directly from
14837  * the driver.
14838  *
14839  * If ip_input() is called from GLDv3:
14840  *
14841  *   - This must be a non-VLAN IP stream.
14842  *   - 'mp' is either an untagged or a special priority-tagged packet.
14843  *   - Any VLAN tag that was in the MAC header has been stripped.
14844  *
14845  * If the IP header in packet is not 32-bit aligned, every message in the
14846  * chain will be aligned before further operations. This is required on SPARC
14847  * platform.
14848  */
14849 /* ARGSUSED */
14850 void
14851 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14852     struct mac_header_info_s *mhip)
14853 {
14854 	ipaddr_t		dst = NULL;
14855 	ipaddr_t		prev_dst;
14856 	ire_t			*ire = NULL;
14857 	ipha_t			*ipha;
14858 	uint_t			pkt_len;
14859 	ssize_t			len;
14860 	uint_t			opt_len;
14861 	int			ll_multicast;
14862 	int			cgtp_flt_pkt;
14863 	queue_t			*q = ill->ill_rq;
14864 	squeue_t		*curr_sqp = NULL;
14865 	mblk_t 			*head = NULL;
14866 	mblk_t			*tail = NULL;
14867 	mblk_t			*first_mp;
14868 	mblk_t 			*mp;
14869 	mblk_t			*dmp;
14870 	int			cnt = 0;
14871 	ip_stack_t		*ipst = ill->ill_ipst;
14872 
14873 	ASSERT(mp_chain != NULL);
14874 	ASSERT(ill != NULL);
14875 
14876 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14877 
14878 #define	rptr	((uchar_t *)ipha)
14879 
14880 	while (mp_chain != NULL) {
14881 		first_mp = mp = mp_chain;
14882 		mp_chain = mp_chain->b_next;
14883 		mp->b_next = NULL;
14884 		ll_multicast = 0;
14885 
14886 		/*
14887 		 * We do ire caching from one iteration to
14888 		 * another. In the event the packet chain contains
14889 		 * all packets from the same dst, this caching saves
14890 		 * an ire_cache_lookup for each of the succeeding
14891 		 * packets in a packet chain.
14892 		 */
14893 		prev_dst = dst;
14894 
14895 		/*
14896 		 * if db_ref > 1 then copymsg and free original. Packet
14897 		 * may be changed and we do not want the other entity
14898 		 * who has a reference to this message to trip over the
14899 		 * changes. This is a blind change because trying to
14900 		 * catch all places that might change the packet is too
14901 		 * difficult.
14902 		 *
14903 		 * This corresponds to the fast path case, where we have
14904 		 * a chain of M_DATA mblks.  We check the db_ref count
14905 		 * of only the 1st data block in the mblk chain. There
14906 		 * doesn't seem to be a reason why a device driver would
14907 		 * send up data with varying db_ref counts in the mblk
14908 		 * chain. In any case the Fast path is a private
14909 		 * interface, and our drivers don't do such a thing.
14910 		 * Given the above assumption, there is no need to walk
14911 		 * down the entire mblk chain (which could have a
14912 		 * potential performance problem)
14913 		 */
14914 
14915 		if (DB_REF(mp) > 1) {
14916 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14917 				continue;
14918 		}
14919 
14920 		/*
14921 		 * Check and align the IP header.
14922 		 */
14923 		first_mp = mp;
14924 		if (DB_TYPE(mp) == M_DATA) {
14925 			dmp = mp;
14926 		} else if (DB_TYPE(mp) == M_PROTO &&
14927 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14928 			dmp = mp->b_cont;
14929 		} else {
14930 			dmp = NULL;
14931 		}
14932 		if (dmp != NULL) {
14933 			/*
14934 			 * IP header ptr not aligned?
14935 			 * OR IP header not complete in first mblk
14936 			 */
14937 			if (!OK_32PTR(dmp->b_rptr) ||
14938 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14939 				if (!ip_check_and_align_header(q, dmp, ipst))
14940 					continue;
14941 			}
14942 		}
14943 
14944 		/*
14945 		 * ip_input fast path
14946 		 */
14947 
14948 		/* mblk type is not M_DATA */
14949 		if (DB_TYPE(mp) != M_DATA) {
14950 			if (ip_rput_process_notdata(q, &first_mp, ill,
14951 			    &ll_multicast, &mp))
14952 				continue;
14953 
14954 			/*
14955 			 * The only way we can get here is if we had a
14956 			 * packet that was either a DL_UNITDATA_IND or
14957 			 * an M_CTL for an IPsec accelerated packet.
14958 			 *
14959 			 * In either case, the first_mp will point to
14960 			 * the leading M_PROTO or M_CTL.
14961 			 */
14962 			ASSERT(first_mp != NULL);
14963 		} else if (mhip != NULL) {
14964 			/*
14965 			 * ll_multicast is set here so that it is ready
14966 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14967 			 * manipulates ll_multicast in the same fashion when
14968 			 * called from ip_rput_process_notdata.
14969 			 */
14970 			switch (mhip->mhi_dsttype) {
14971 			case MAC_ADDRTYPE_MULTICAST :
14972 				ll_multicast = HPE_MULTICAST;
14973 				break;
14974 			case MAC_ADDRTYPE_BROADCAST :
14975 				ll_multicast = HPE_BROADCAST;
14976 				break;
14977 			default :
14978 				break;
14979 			}
14980 		}
14981 
14982 		/* Make sure its an M_DATA and that its aligned */
14983 		ASSERT(DB_TYPE(mp) == M_DATA);
14984 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14985 
14986 		ipha = (ipha_t *)mp->b_rptr;
14987 		len = mp->b_wptr - rptr;
14988 		pkt_len = ntohs(ipha->ipha_length);
14989 
14990 		/*
14991 		 * We must count all incoming packets, even if they end
14992 		 * up being dropped later on.
14993 		 */
14994 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
14995 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
14996 
14997 		/* multiple mblk or too short */
14998 		len -= pkt_len;
14999 		if (len != 0) {
15000 			/*
15001 			 * Make sure we have data length consistent
15002 			 * with the IP header.
15003 			 */
15004 			if (mp->b_cont == NULL) {
15005 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15006 					BUMP_MIB(ill->ill_ip_mib,
15007 					    ipIfStatsInHdrErrors);
15008 					ip2dbg(("ip_input: drop pkt\n"));
15009 					freemsg(mp);
15010 					continue;
15011 				}
15012 				mp->b_wptr = rptr + pkt_len;
15013 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15014 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15015 					BUMP_MIB(ill->ill_ip_mib,
15016 					    ipIfStatsInHdrErrors);
15017 					ip2dbg(("ip_input: drop pkt\n"));
15018 					freemsg(mp);
15019 					continue;
15020 				}
15021 				(void) adjmsg(mp, -len);
15022 				IP_STAT(ipst, ip_multimblk3);
15023 			}
15024 		}
15025 
15026 		/* Obtain the dst of the current packet */
15027 		dst = ipha->ipha_dst;
15028 
15029 		/*
15030 		 * The following test for loopback is faster than
15031 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15032 		 * operations.
15033 		 * Note that these addresses are always in network byte order
15034 		 */
15035 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15036 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15037 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15038 			freemsg(mp);
15039 			continue;
15040 		}
15041 
15042 		/*
15043 		 * The event for packets being received from a 'physical'
15044 		 * interface is placed after validation of the source and/or
15045 		 * destination address as being local so that packets can be
15046 		 * redirected to loopback addresses using ipnat.
15047 		 */
15048 		DTRACE_PROBE4(ip4__physical__in__start,
15049 		    ill_t *, ill, ill_t *, NULL,
15050 		    ipha_t *, ipha, mblk_t *, first_mp);
15051 
15052 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15053 		    ipst->ips_ipv4firewall_physical_in,
15054 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15055 
15056 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15057 
15058 		if (first_mp == NULL) {
15059 			continue;
15060 		}
15061 		dst = ipha->ipha_dst;
15062 
15063 		/*
15064 		 * Attach any necessary label information to
15065 		 * this packet
15066 		 */
15067 		if (is_system_labeled() &&
15068 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15069 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15070 			freemsg(mp);
15071 			continue;
15072 		}
15073 
15074 		/*
15075 		 * Reuse the cached ire only if the ipha_dst of the previous
15076 		 * packet is the same as the current packet AND it is not
15077 		 * INADDR_ANY.
15078 		 */
15079 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15080 		    (ire != NULL)) {
15081 			ire_refrele(ire);
15082 			ire = NULL;
15083 		}
15084 		opt_len = ipha->ipha_version_and_hdr_length -
15085 		    IP_SIMPLE_HDR_VERSION;
15086 
15087 		/*
15088 		 * Check to see if we can take the fastpath.
15089 		 * That is possible if the following conditions are met
15090 		 *	o Tsol disabled
15091 		 *	o CGTP disabled
15092 		 *	o ipp_action_count is 0
15093 		 *	o no options in the packet
15094 		 *	o not a RSVP packet
15095 		 * 	o not a multicast packet
15096 		 *	o ill not in IP_DHCPINIT_IF mode
15097 		 */
15098 		if (!is_system_labeled() &&
15099 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15100 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15101 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15102 			if (ire == NULL)
15103 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15104 				    ipst);
15105 
15106 			/* incoming packet is for forwarding */
15107 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15108 				ire = ip_fast_forward(ire, dst, ill, mp);
15109 				continue;
15110 			}
15111 			/* incoming packet is for local consumption */
15112 			if (ire->ire_type & IRE_LOCAL)
15113 				goto local;
15114 		}
15115 
15116 		/*
15117 		 * Disable ire caching for anything more complex
15118 		 * than the simple fast path case we checked for above.
15119 		 */
15120 		if (ire != NULL) {
15121 			ire_refrele(ire);
15122 			ire = NULL;
15123 		}
15124 
15125 		/*
15126 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15127 		 * server to unicast DHCP packets to a DHCP client using the
15128 		 * IP address it is offering to the client.  This can be
15129 		 * disabled through the "broadcast bit", but not all DHCP
15130 		 * servers honor that bit.  Therefore, to interoperate with as
15131 		 * many DHCP servers as possible, the DHCP client allows the
15132 		 * server to unicast, but we treat those packets as broadcast
15133 		 * here.  Note that we don't rewrite the packet itself since
15134 		 * (a) that would mess up the checksums and (b) the DHCP
15135 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15136 		 * hand it the packet regardless.
15137 		 */
15138 		if (ill->ill_dhcpinit != 0 &&
15139 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15140 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15141 			udpha_t *udpha;
15142 
15143 			/*
15144 			 * Reload ipha since pullupmsg() can change b_rptr.
15145 			 */
15146 			ipha = (ipha_t *)mp->b_rptr;
15147 			udpha = (udpha_t *)&ipha[1];
15148 
15149 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15150 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15151 				    mblk_t *, mp);
15152 				dst = INADDR_BROADCAST;
15153 			}
15154 		}
15155 
15156 		/* Full-blown slow path */
15157 		if (opt_len != 0) {
15158 			if (len != 0)
15159 				IP_STAT(ipst, ip_multimblk4);
15160 			else
15161 				IP_STAT(ipst, ip_ipoptions);
15162 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15163 			    &dst, ipst))
15164 				continue;
15165 		}
15166 
15167 		/*
15168 		 * Invoke the CGTP (multirouting) filtering module to process
15169 		 * the incoming packet. Packets identified as duplicates
15170 		 * must be discarded. Filtering is active only if the
15171 		 * the ip_cgtp_filter ndd variable is non-zero.
15172 		 */
15173 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15174 		if (ipst->ips_ip_cgtp_filter &&
15175 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15176 			netstackid_t stackid;
15177 
15178 			stackid = ipst->ips_netstack->netstack_stackid;
15179 			cgtp_flt_pkt =
15180 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15181 			    ill->ill_phyint->phyint_ifindex, mp);
15182 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15183 				freemsg(first_mp);
15184 				continue;
15185 			}
15186 		}
15187 
15188 		/*
15189 		 * If rsvpd is running, let RSVP daemon handle its processing
15190 		 * and forwarding of RSVP multicast/unicast packets.
15191 		 * If rsvpd is not running but mrouted is running, RSVP
15192 		 * multicast packets are forwarded as multicast traffic
15193 		 * and RSVP unicast packets are forwarded by unicast router.
15194 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15195 		 * packets are not forwarded, but the unicast packets are
15196 		 * forwarded like unicast traffic.
15197 		 */
15198 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15199 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15200 		    NULL) {
15201 			/* RSVP packet and rsvpd running. Treat as ours */
15202 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15203 			/*
15204 			 * This assumes that we deliver to all streams for
15205 			 * multicast and broadcast packets.
15206 			 * We have to force ll_multicast to 1 to handle the
15207 			 * M_DATA messages passed in from ip_mroute_decap.
15208 			 */
15209 			dst = INADDR_BROADCAST;
15210 			ll_multicast = 1;
15211 		} else if (CLASSD(dst)) {
15212 			/* packet is multicast */
15213 			mp->b_next = NULL;
15214 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15215 			    &ll_multicast, &dst))
15216 				continue;
15217 		}
15218 
15219 		if (ire == NULL) {
15220 			ire = ire_cache_lookup(dst, ALL_ZONES,
15221 			    MBLK_GETLABEL(mp), ipst);
15222 		}
15223 
15224 		if (ire == NULL) {
15225 			/*
15226 			 * No IRE for this destination, so it can't be for us.
15227 			 * Unless we are forwarding, drop the packet.
15228 			 * We have to let source routed packets through
15229 			 * since we don't yet know if they are 'ping -l'
15230 			 * packets i.e. if they will go out over the
15231 			 * same interface as they came in on.
15232 			 */
15233 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15234 			if (ire == NULL)
15235 				continue;
15236 		}
15237 
15238 		/*
15239 		 * Broadcast IRE may indicate either broadcast or
15240 		 * multicast packet
15241 		 */
15242 		if (ire->ire_type == IRE_BROADCAST) {
15243 			/*
15244 			 * Skip broadcast checks if packet is UDP multicast;
15245 			 * we'd rather not enter ip_rput_process_broadcast()
15246 			 * unless the packet is broadcast for real, since
15247 			 * that routine is a no-op for multicast.
15248 			 */
15249 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15250 			    !CLASSD(ipha->ipha_dst)) {
15251 				ire = ip_rput_process_broadcast(&q, mp,
15252 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15253 				    ll_multicast);
15254 				if (ire == NULL)
15255 					continue;
15256 			}
15257 		} else if (ire->ire_stq != NULL) {
15258 			/* fowarding? */
15259 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15260 			    ll_multicast);
15261 			/* ip_rput_process_forward consumed the packet */
15262 			continue;
15263 		}
15264 
15265 local:
15266 		/*
15267 		 * If the queue in the ire is different to the ingress queue
15268 		 * then we need to check to see if we can accept the packet.
15269 		 * Note that for multicast packets and broadcast packets sent
15270 		 * to a broadcast address which is shared between multiple
15271 		 * interfaces we should not do this since we just got a random
15272 		 * broadcast ire.
15273 		 */
15274 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15275 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15276 			    ill)) == NULL) {
15277 				/* Drop packet */
15278 				BUMP_MIB(ill->ill_ip_mib,
15279 				    ipIfStatsForwProhibits);
15280 				freemsg(mp);
15281 				continue;
15282 			}
15283 			if (ire->ire_rfq != NULL)
15284 				q = ire->ire_rfq;
15285 		}
15286 
15287 		switch (ipha->ipha_protocol) {
15288 		case IPPROTO_TCP:
15289 			ASSERT(first_mp == mp);
15290 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15291 			    mp, 0, q, ip_ring)) != NULL) {
15292 				if (curr_sqp == NULL) {
15293 					curr_sqp = GET_SQUEUE(mp);
15294 					ASSERT(cnt == 0);
15295 					cnt++;
15296 					head = tail = mp;
15297 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15298 					ASSERT(tail != NULL);
15299 					cnt++;
15300 					tail->b_next = mp;
15301 					tail = mp;
15302 				} else {
15303 					/*
15304 					 * A different squeue. Send the
15305 					 * chain for the previous squeue on
15306 					 * its way. This shouldn't happen
15307 					 * often unless interrupt binding
15308 					 * changes.
15309 					 */
15310 					IP_STAT(ipst, ip_input_multi_squeue);
15311 					squeue_enter_chain(curr_sqp, head,
15312 					    tail, cnt, SQTAG_IP_INPUT);
15313 					curr_sqp = GET_SQUEUE(mp);
15314 					head = mp;
15315 					tail = mp;
15316 					cnt = 1;
15317 				}
15318 			}
15319 			continue;
15320 		case IPPROTO_UDP:
15321 			ASSERT(first_mp == mp);
15322 			ip_udp_input(q, mp, ipha, ire, ill);
15323 			continue;
15324 		case IPPROTO_SCTP:
15325 			ASSERT(first_mp == mp);
15326 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15327 			    q, dst);
15328 			/* ire has been released by ip_sctp_input */
15329 			ire = NULL;
15330 			continue;
15331 		default:
15332 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15333 			continue;
15334 		}
15335 	}
15336 
15337 	if (ire != NULL)
15338 		ire_refrele(ire);
15339 
15340 	if (head != NULL)
15341 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15342 
15343 	/*
15344 	 * This code is there just to make netperf/ttcp look good.
15345 	 *
15346 	 * Its possible that after being in polling mode (and having cleared
15347 	 * the backlog), squeues have turned the interrupt frequency higher
15348 	 * to improve latency at the expense of more CPU utilization (less
15349 	 * packets per interrupts or more number of interrupts). Workloads
15350 	 * like ttcp/netperf do manage to tickle polling once in a while
15351 	 * but for the remaining time, stay in higher interrupt mode since
15352 	 * their packet arrival rate is pretty uniform and this shows up
15353 	 * as higher CPU utilization. Since people care about CPU utilization
15354 	 * while running netperf/ttcp, turn the interrupt frequency back to
15355 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15356 	 */
15357 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15358 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15359 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15360 			ip_ring->rr_blank(ip_ring->rr_handle,
15361 			    ip_ring->rr_normal_blank_time,
15362 			    ip_ring->rr_normal_pkt_cnt);
15363 		}
15364 		}
15365 
15366 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15367 	    "ip_input_end: q %p (%S)", q, "end");
15368 #undef  rptr
15369 }
15370 
15371 static void
15372 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15373     t_uscalar_t err)
15374 {
15375 	if (dl_err == DL_SYSERR) {
15376 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15377 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15378 		    ill->ill_name, dl_primstr(prim), err);
15379 		return;
15380 	}
15381 
15382 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15383 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15384 	    dl_errstr(dl_err));
15385 }
15386 
15387 /*
15388  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15389  * than DL_UNITDATA_IND messages. If we need to process this message
15390  * exclusively, we call qwriter_ip, in which case we also need to call
15391  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15392  */
15393 void
15394 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15395 {
15396 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15397 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15398 	ill_t		*ill = (ill_t *)q->q_ptr;
15399 	boolean_t	pending;
15400 
15401 	ip1dbg(("ip_rput_dlpi"));
15402 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15403 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15404 		    "%s (0x%x), unix %u\n", ill->ill_name,
15405 		    dl_primstr(dlea->dl_error_primitive),
15406 		    dlea->dl_error_primitive,
15407 		    dl_errstr(dlea->dl_errno),
15408 		    dlea->dl_errno,
15409 		    dlea->dl_unix_errno));
15410 	}
15411 
15412 	/*
15413 	 * If we received an ACK but didn't send a request for it, then it
15414 	 * can't be part of any pending operation; discard up-front.
15415 	 */
15416 	switch (dloa->dl_primitive) {
15417 	case DL_NOTIFY_IND:
15418 		pending = B_TRUE;
15419 		break;
15420 	case DL_ERROR_ACK:
15421 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15422 		break;
15423 	case DL_OK_ACK:
15424 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15425 		break;
15426 	case DL_INFO_ACK:
15427 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15428 		break;
15429 	case DL_BIND_ACK:
15430 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15431 		break;
15432 	case DL_PHYS_ADDR_ACK:
15433 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15434 		break;
15435 	case DL_NOTIFY_ACK:
15436 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15437 		break;
15438 	case DL_CONTROL_ACK:
15439 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15440 		break;
15441 	case DL_CAPABILITY_ACK:
15442 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15443 		break;
15444 	default:
15445 		/* Not a DLPI message we support or were expecting */
15446 		freemsg(mp);
15447 		return;
15448 	}
15449 
15450 	if (!pending) {
15451 		freemsg(mp);
15452 		return;
15453 	}
15454 
15455 	switch (dloa->dl_primitive) {
15456 	case DL_ERROR_ACK:
15457 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15458 			mutex_enter(&ill->ill_lock);
15459 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15460 			cv_signal(&ill->ill_cv);
15461 			mutex_exit(&ill->ill_lock);
15462 		}
15463 		break;
15464 
15465 	case DL_OK_ACK:
15466 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15467 		    dl_primstr((int)dloa->dl_correct_primitive)));
15468 		switch (dloa->dl_correct_primitive) {
15469 		case DL_UNBIND_REQ:
15470 			mutex_enter(&ill->ill_lock);
15471 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15472 			cv_signal(&ill->ill_cv);
15473 			mutex_exit(&ill->ill_lock);
15474 			break;
15475 
15476 		case DL_ENABMULTI_REQ:
15477 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15478 				ill->ill_dlpi_multicast_state = IDS_OK;
15479 			break;
15480 		}
15481 		break;
15482 	default:
15483 		break;
15484 	}
15485 
15486 	/*
15487 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15488 	 * and we need to become writer to continue to process it. If it's not
15489 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15490 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15491 	 * some work as part of the current exclusive operation that actually
15492 	 * is not part of it -- which is wrong, but better than the
15493 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15494 	 * should track which DLPI requests have ACKs that we wait on
15495 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15496 	 *
15497 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15498 	 * Since this is on the ill stream we unconditionally bump up the
15499 	 * refcount without doing ILL_CAN_LOOKUP().
15500 	 */
15501 	ill_refhold(ill);
15502 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15503 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15504 	else
15505 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15506 }
15507 
15508 /*
15509  * Handling of DLPI messages that require exclusive access to the ipsq.
15510  *
15511  * Need to do ill_pending_mp_release on ioctl completion, which could
15512  * happen here. (along with mi_copy_done)
15513  */
15514 /* ARGSUSED */
15515 static void
15516 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15517 {
15518 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15519 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15520 	int		err = 0;
15521 	ill_t		*ill;
15522 	ipif_t		*ipif = NULL;
15523 	mblk_t		*mp1 = NULL;
15524 	conn_t		*connp = NULL;
15525 	t_uscalar_t	paddrreq;
15526 	mblk_t		*mp_hw;
15527 	boolean_t	success;
15528 	boolean_t	ioctl_aborted = B_FALSE;
15529 	boolean_t	log = B_TRUE;
15530 	ip_stack_t		*ipst;
15531 
15532 	ip1dbg(("ip_rput_dlpi_writer .."));
15533 	ill = (ill_t *)q->q_ptr;
15534 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15535 
15536 	ASSERT(IAM_WRITER_ILL(ill));
15537 
15538 	ipst = ill->ill_ipst;
15539 
15540 	/*
15541 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15542 	 * both are null or non-null. However we can assert that only
15543 	 * after grabbing the ipsq_lock. So we don't make any assertion
15544 	 * here and in other places in the code.
15545 	 */
15546 	ipif = ipsq->ipsq_pending_ipif;
15547 	/*
15548 	 * The current ioctl could have been aborted by the user and a new
15549 	 * ioctl to bring up another ill could have started. We could still
15550 	 * get a response from the driver later.
15551 	 */
15552 	if (ipif != NULL && ipif->ipif_ill != ill)
15553 		ioctl_aborted = B_TRUE;
15554 
15555 	switch (dloa->dl_primitive) {
15556 	case DL_ERROR_ACK:
15557 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15558 		    dl_primstr(dlea->dl_error_primitive)));
15559 
15560 		switch (dlea->dl_error_primitive) {
15561 		case DL_PROMISCON_REQ:
15562 		case DL_PROMISCOFF_REQ:
15563 		case DL_DISABMULTI_REQ:
15564 		case DL_UNBIND_REQ:
15565 		case DL_ATTACH_REQ:
15566 		case DL_INFO_REQ:
15567 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15568 			break;
15569 		case DL_NOTIFY_REQ:
15570 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15571 			log = B_FALSE;
15572 			break;
15573 		case DL_PHYS_ADDR_REQ:
15574 			/*
15575 			 * For IPv6 only, there are two additional
15576 			 * phys_addr_req's sent to the driver to get the
15577 			 * IPv6 token and lla. This allows IP to acquire
15578 			 * the hardware address format for a given interface
15579 			 * without having built in knowledge of the hardware
15580 			 * address. ill_phys_addr_pend keeps track of the last
15581 			 * DL_PAR sent so we know which response we are
15582 			 * dealing with. ill_dlpi_done will update
15583 			 * ill_phys_addr_pend when it sends the next req.
15584 			 * We don't complete the IOCTL until all three DL_PARs
15585 			 * have been attempted, so set *_len to 0 and break.
15586 			 */
15587 			paddrreq = ill->ill_phys_addr_pend;
15588 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15589 			if (paddrreq == DL_IPV6_TOKEN) {
15590 				ill->ill_token_length = 0;
15591 				log = B_FALSE;
15592 				break;
15593 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15594 				ill->ill_nd_lla_len = 0;
15595 				log = B_FALSE;
15596 				break;
15597 			}
15598 			/*
15599 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15600 			 * We presumably have an IOCTL hanging out waiting
15601 			 * for completion. Find it and complete the IOCTL
15602 			 * with the error noted.
15603 			 * However, ill_dl_phys was called on an ill queue
15604 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15605 			 * set. But the ioctl is known to be pending on ill_wq.
15606 			 */
15607 			if (!ill->ill_ifname_pending)
15608 				break;
15609 			ill->ill_ifname_pending = 0;
15610 			if (!ioctl_aborted)
15611 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15612 			if (mp1 != NULL) {
15613 				/*
15614 				 * This operation (SIOCSLIFNAME) must have
15615 				 * happened on the ill. Assert there is no conn
15616 				 */
15617 				ASSERT(connp == NULL);
15618 				q = ill->ill_wq;
15619 			}
15620 			break;
15621 		case DL_BIND_REQ:
15622 			ill_dlpi_done(ill, DL_BIND_REQ);
15623 			if (ill->ill_ifname_pending)
15624 				break;
15625 			/*
15626 			 * Something went wrong with the bind.  We presumably
15627 			 * have an IOCTL hanging out waiting for completion.
15628 			 * Find it, take down the interface that was coming
15629 			 * up, and complete the IOCTL with the error noted.
15630 			 */
15631 			if (!ioctl_aborted)
15632 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15633 			if (mp1 != NULL) {
15634 				/*
15635 				 * This operation (SIOCSLIFFLAGS) must have
15636 				 * happened from a conn.
15637 				 */
15638 				ASSERT(connp != NULL);
15639 				q = CONNP_TO_WQ(connp);
15640 				if (ill->ill_move_in_progress) {
15641 					ILL_CLEAR_MOVE(ill);
15642 				}
15643 				(void) ipif_down(ipif, NULL, NULL);
15644 				/* error is set below the switch */
15645 			}
15646 			break;
15647 		case DL_ENABMULTI_REQ:
15648 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15649 
15650 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15651 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15652 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15653 				ipif_t *ipif;
15654 
15655 				printf("ip: joining multicasts failed (%d)"
15656 				    " on %s - will use link layer "
15657 				    "broadcasts for multicast\n",
15658 				    dlea->dl_errno, ill->ill_name);
15659 
15660 				/*
15661 				 * Set up the multicast mapping alone.
15662 				 * writer, so ok to access ill->ill_ipif
15663 				 * without any lock.
15664 				 */
15665 				ipif = ill->ill_ipif;
15666 				mutex_enter(&ill->ill_phyint->phyint_lock);
15667 				ill->ill_phyint->phyint_flags |=
15668 				    PHYI_MULTI_BCAST;
15669 				mutex_exit(&ill->ill_phyint->phyint_lock);
15670 
15671 				if (!ill->ill_isv6) {
15672 					(void) ipif_arp_setup_multicast(ipif,
15673 					    NULL);
15674 				} else {
15675 					(void) ipif_ndp_setup_multicast(ipif,
15676 					    NULL);
15677 				}
15678 			}
15679 			freemsg(mp);	/* Don't want to pass this up */
15680 			return;
15681 
15682 		case DL_CAPABILITY_REQ:
15683 		case DL_CONTROL_REQ:
15684 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15685 			ill->ill_dlpi_capab_state = IDS_FAILED;
15686 			freemsg(mp);
15687 			return;
15688 		}
15689 		/*
15690 		 * Note the error for IOCTL completion (mp1 is set when
15691 		 * ready to complete ioctl). If ill_ifname_pending_err is
15692 		 * set, an error occured during plumbing (ill_ifname_pending),
15693 		 * so we want to report that error.
15694 		 *
15695 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15696 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15697 		 * expected to get errack'd if the driver doesn't support
15698 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15699 		 * if these error conditions are encountered.
15700 		 */
15701 		if (mp1 != NULL) {
15702 			if (ill->ill_ifname_pending_err != 0)  {
15703 				err = ill->ill_ifname_pending_err;
15704 				ill->ill_ifname_pending_err = 0;
15705 			} else {
15706 				err = dlea->dl_unix_errno ?
15707 				    dlea->dl_unix_errno : ENXIO;
15708 			}
15709 		/*
15710 		 * If we're plumbing an interface and an error hasn't already
15711 		 * been saved, set ill_ifname_pending_err to the error passed
15712 		 * up. Ignore the error if log is B_FALSE (see comment above).
15713 		 */
15714 		} else if (log && ill->ill_ifname_pending &&
15715 		    ill->ill_ifname_pending_err == 0) {
15716 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15717 			    dlea->dl_unix_errno : ENXIO;
15718 		}
15719 
15720 		if (log)
15721 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15722 			    dlea->dl_errno, dlea->dl_unix_errno);
15723 		break;
15724 	case DL_CAPABILITY_ACK:
15725 		/* Call a routine to handle this one. */
15726 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15727 		ill_capability_ack(ill, mp);
15728 
15729 		/*
15730 		 * If the ack is due to renegotiation, we will need to send
15731 		 * a new CAPABILITY_REQ to start the renegotiation.
15732 		 */
15733 		if (ill->ill_capab_reneg) {
15734 			ill->ill_capab_reneg = B_FALSE;
15735 			ill_capability_probe(ill);
15736 		}
15737 		break;
15738 	case DL_CONTROL_ACK:
15739 		/* We treat all of these as "fire and forget" */
15740 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15741 		break;
15742 	case DL_INFO_ACK:
15743 		/* Call a routine to handle this one. */
15744 		ill_dlpi_done(ill, DL_INFO_REQ);
15745 		ip_ll_subnet_defaults(ill, mp);
15746 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15747 		return;
15748 	case DL_BIND_ACK:
15749 		/*
15750 		 * We should have an IOCTL waiting on this unless
15751 		 * sent by ill_dl_phys, in which case just return
15752 		 */
15753 		ill_dlpi_done(ill, DL_BIND_REQ);
15754 		if (ill->ill_ifname_pending)
15755 			break;
15756 
15757 		if (!ioctl_aborted)
15758 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15759 		if (mp1 == NULL)
15760 			break;
15761 		/*
15762 		 * Because mp1 was added by ill_dl_up(), and it always
15763 		 * passes a valid connp, connp must be valid here.
15764 		 */
15765 		ASSERT(connp != NULL);
15766 		q = CONNP_TO_WQ(connp);
15767 
15768 		/*
15769 		 * We are exclusive. So nothing can change even after
15770 		 * we get the pending mp. If need be we can put it back
15771 		 * and restart, as in calling ipif_arp_up()  below.
15772 		 */
15773 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15774 
15775 		mutex_enter(&ill->ill_lock);
15776 		ill->ill_dl_up = 1;
15777 		(void) ill_hook_event_create(ill, 0, NE_UP, NULL, 0);
15778 		mutex_exit(&ill->ill_lock);
15779 
15780 		/*
15781 		 * Now bring up the resolver; when that is complete, we'll
15782 		 * create IREs.  Note that we intentionally mirror what
15783 		 * ipif_up() would have done, because we got here by way of
15784 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15785 		 */
15786 		if (ill->ill_isv6) {
15787 			/*
15788 			 * v6 interfaces.
15789 			 * Unlike ARP which has to do another bind
15790 			 * and attach, once we get here we are
15791 			 * done with NDP. Except in the case of
15792 			 * ILLF_XRESOLV, in which case we send an
15793 			 * AR_INTERFACE_UP to the external resolver.
15794 			 * If all goes well, the ioctl will complete
15795 			 * in ip_rput(). If there's an error, we
15796 			 * complete it here.
15797 			 */
15798 			if ((err = ipif_ndp_up(ipif)) == 0) {
15799 				if (ill->ill_flags & ILLF_XRESOLV) {
15800 					mutex_enter(&connp->conn_lock);
15801 					mutex_enter(&ill->ill_lock);
15802 					success = ipsq_pending_mp_add(
15803 					    connp, ipif, q, mp1, 0);
15804 					mutex_exit(&ill->ill_lock);
15805 					mutex_exit(&connp->conn_lock);
15806 					if (success) {
15807 						err = ipif_resolver_up(ipif,
15808 						    Res_act_initial);
15809 						if (err == EINPROGRESS) {
15810 							freemsg(mp);
15811 							return;
15812 						}
15813 						ASSERT(err != 0);
15814 						mp1 = ipsq_pending_mp_get(ipsq,
15815 						    &connp);
15816 						ASSERT(mp1 != NULL);
15817 					} else {
15818 						/* conn has started closing */
15819 						err = EINTR;
15820 					}
15821 				} else { /* Non XRESOLV interface */
15822 					(void) ipif_resolver_up(ipif,
15823 					    Res_act_initial);
15824 					err = ipif_up_done_v6(ipif);
15825 				}
15826 			}
15827 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15828 			/*
15829 			 * ARP and other v4 external resolvers.
15830 			 * Leave the pending mblk intact so that
15831 			 * the ioctl completes in ip_rput().
15832 			 */
15833 			mutex_enter(&connp->conn_lock);
15834 			mutex_enter(&ill->ill_lock);
15835 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15836 			mutex_exit(&ill->ill_lock);
15837 			mutex_exit(&connp->conn_lock);
15838 			if (success) {
15839 				err = ipif_resolver_up(ipif, Res_act_initial);
15840 				if (err == EINPROGRESS) {
15841 					freemsg(mp);
15842 					return;
15843 				}
15844 				ASSERT(err != 0);
15845 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15846 			} else {
15847 				/* The conn has started closing */
15848 				err = EINTR;
15849 			}
15850 		} else {
15851 			/*
15852 			 * This one is complete. Reply to pending ioctl.
15853 			 */
15854 			(void) ipif_resolver_up(ipif, Res_act_initial);
15855 			err = ipif_up_done(ipif);
15856 		}
15857 
15858 		if ((err == 0) && (ill->ill_up_ipifs)) {
15859 			err = ill_up_ipifs(ill, q, mp1);
15860 			if (err == EINPROGRESS) {
15861 				freemsg(mp);
15862 				return;
15863 			}
15864 		}
15865 
15866 		if (ill->ill_up_ipifs) {
15867 			ill_group_cleanup(ill);
15868 		}
15869 
15870 		break;
15871 	case DL_NOTIFY_IND: {
15872 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15873 		ire_t *ire;
15874 		boolean_t need_ire_walk_v4 = B_FALSE;
15875 		boolean_t need_ire_walk_v6 = B_FALSE;
15876 
15877 		switch (notify->dl_notification) {
15878 		case DL_NOTE_PHYS_ADDR:
15879 			err = ill_set_phys_addr(ill, mp);
15880 			break;
15881 
15882 		case DL_NOTE_FASTPATH_FLUSH:
15883 			ill_fastpath_flush(ill);
15884 			break;
15885 
15886 		case DL_NOTE_SDU_SIZE:
15887 			/*
15888 			 * Change the MTU size of the interface, of all
15889 			 * attached ipif's, and of all relevant ire's.  The
15890 			 * new value's a uint32_t at notify->dl_data.
15891 			 * Mtu change Vs. new ire creation - protocol below.
15892 			 *
15893 			 * a Mark the ipif as IPIF_CHANGING.
15894 			 * b Set the new mtu in the ipif.
15895 			 * c Change the ire_max_frag on all affected ires
15896 			 * d Unmark the IPIF_CHANGING
15897 			 *
15898 			 * To see how the protocol works, assume an interface
15899 			 * route is also being added simultaneously by
15900 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15901 			 * the ire. If the ire is created before step a,
15902 			 * it will be cleaned up by step c. If the ire is
15903 			 * created after step d, it will see the new value of
15904 			 * ipif_mtu. Any attempt to create the ire between
15905 			 * steps a to d will fail because of the IPIF_CHANGING
15906 			 * flag. Note that ire_create() is passed a pointer to
15907 			 * the ipif_mtu, and not the value. During ire_add
15908 			 * under the bucket lock, the ire_max_frag of the
15909 			 * new ire being created is set from the ipif/ire from
15910 			 * which it is being derived.
15911 			 */
15912 			mutex_enter(&ill->ill_lock);
15913 			ill->ill_max_frag = (uint_t)notify->dl_data;
15914 
15915 			/*
15916 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15917 			 * leave it alone
15918 			 */
15919 			if (ill->ill_mtu_userspecified) {
15920 				mutex_exit(&ill->ill_lock);
15921 				break;
15922 			}
15923 			ill->ill_max_mtu = ill->ill_max_frag;
15924 			if (ill->ill_isv6) {
15925 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15926 					ill->ill_max_mtu = IPV6_MIN_MTU;
15927 			} else {
15928 				if (ill->ill_max_mtu < IP_MIN_MTU)
15929 					ill->ill_max_mtu = IP_MIN_MTU;
15930 			}
15931 			for (ipif = ill->ill_ipif; ipif != NULL;
15932 			    ipif = ipif->ipif_next) {
15933 				/*
15934 				 * Don't override the mtu if the user
15935 				 * has explicitly set it.
15936 				 */
15937 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15938 					continue;
15939 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15940 				if (ipif->ipif_isv6)
15941 					ire = ipif_to_ire_v6(ipif);
15942 				else
15943 					ire = ipif_to_ire(ipif);
15944 				if (ire != NULL) {
15945 					ire->ire_max_frag = ipif->ipif_mtu;
15946 					ire_refrele(ire);
15947 				}
15948 				if (ipif->ipif_flags & IPIF_UP) {
15949 					if (ill->ill_isv6)
15950 						need_ire_walk_v6 = B_TRUE;
15951 					else
15952 						need_ire_walk_v4 = B_TRUE;
15953 				}
15954 			}
15955 			mutex_exit(&ill->ill_lock);
15956 			if (need_ire_walk_v4)
15957 				ire_walk_v4(ill_mtu_change, (char *)ill,
15958 				    ALL_ZONES, ipst);
15959 			if (need_ire_walk_v6)
15960 				ire_walk_v6(ill_mtu_change, (char *)ill,
15961 				    ALL_ZONES, ipst);
15962 			break;
15963 		case DL_NOTE_LINK_UP:
15964 		case DL_NOTE_LINK_DOWN: {
15965 			/*
15966 			 * We are writer. ill / phyint / ipsq assocs stable.
15967 			 * The RUNNING flag reflects the state of the link.
15968 			 */
15969 			phyint_t *phyint = ill->ill_phyint;
15970 			uint64_t new_phyint_flags;
15971 			boolean_t changed = B_FALSE;
15972 			boolean_t went_up;
15973 
15974 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15975 			mutex_enter(&phyint->phyint_lock);
15976 			new_phyint_flags = went_up ?
15977 			    phyint->phyint_flags | PHYI_RUNNING :
15978 			    phyint->phyint_flags & ~PHYI_RUNNING;
15979 			if (new_phyint_flags != phyint->phyint_flags) {
15980 				phyint->phyint_flags = new_phyint_flags;
15981 				changed = B_TRUE;
15982 			}
15983 			mutex_exit(&phyint->phyint_lock);
15984 			/*
15985 			 * ill_restart_dad handles the DAD restart and routing
15986 			 * socket notification logic.
15987 			 */
15988 			if (changed) {
15989 				ill_restart_dad(phyint->phyint_illv4, went_up);
15990 				ill_restart_dad(phyint->phyint_illv6, went_up);
15991 			}
15992 			break;
15993 		}
15994 		case DL_NOTE_PROMISC_ON_PHYS:
15995 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
15996 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
15997 			mutex_enter(&ill->ill_lock);
15998 			ill->ill_promisc_on_phys = B_TRUE;
15999 			mutex_exit(&ill->ill_lock);
16000 			break;
16001 		case DL_NOTE_PROMISC_OFF_PHYS:
16002 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16003 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16004 			mutex_enter(&ill->ill_lock);
16005 			ill->ill_promisc_on_phys = B_FALSE;
16006 			mutex_exit(&ill->ill_lock);
16007 			break;
16008 		case DL_NOTE_CAPAB_RENEG:
16009 			/*
16010 			 * Something changed on the driver side.
16011 			 * It wants us to renegotiate the capabilities
16012 			 * on this ill. One possible cause is the aggregation
16013 			 * interface under us where a port got added or
16014 			 * went away.
16015 			 *
16016 			 * If the capability negotiation is already done
16017 			 * or is in progress, reset the capabilities and
16018 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16019 			 * so that when the ack comes back, we can start
16020 			 * the renegotiation process.
16021 			 *
16022 			 * Note that if ill_capab_reneg is already B_TRUE
16023 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16024 			 * the capability resetting request has been sent
16025 			 * and the renegotiation has not been started yet;
16026 			 * nothing needs to be done in this case.
16027 			 */
16028 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16029 				ill_capability_reset(ill);
16030 				ill->ill_capab_reneg = B_TRUE;
16031 			}
16032 			break;
16033 		default:
16034 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16035 			    "type 0x%x for DL_NOTIFY_IND\n",
16036 			    notify->dl_notification));
16037 			break;
16038 		}
16039 
16040 		/*
16041 		 * As this is an asynchronous operation, we
16042 		 * should not call ill_dlpi_done
16043 		 */
16044 		break;
16045 	}
16046 	case DL_NOTIFY_ACK: {
16047 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16048 
16049 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16050 			ill->ill_note_link = 1;
16051 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16052 		break;
16053 	}
16054 	case DL_PHYS_ADDR_ACK: {
16055 		/*
16056 		 * As part of plumbing the interface via SIOCSLIFNAME,
16057 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16058 		 * whose answers we receive here.  As each answer is received,
16059 		 * we call ill_dlpi_done() to dispatch the next request as
16060 		 * we're processing the current one.  Once all answers have
16061 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16062 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16063 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16064 		 * available, but we know the ioctl is pending on ill_wq.)
16065 		 */
16066 		uint_t paddrlen, paddroff;
16067 
16068 		paddrreq = ill->ill_phys_addr_pend;
16069 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16070 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16071 
16072 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16073 		if (paddrreq == DL_IPV6_TOKEN) {
16074 			/*
16075 			 * bcopy to low-order bits of ill_token
16076 			 *
16077 			 * XXX Temporary hack - currently, all known tokens
16078 			 * are 64 bits, so I'll cheat for the moment.
16079 			 */
16080 			bcopy(mp->b_rptr + paddroff,
16081 			    &ill->ill_token.s6_addr32[2], paddrlen);
16082 			ill->ill_token_length = paddrlen;
16083 			break;
16084 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16085 			ASSERT(ill->ill_nd_lla_mp == NULL);
16086 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16087 			mp = NULL;
16088 			break;
16089 		}
16090 
16091 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16092 		ASSERT(ill->ill_phys_addr_mp == NULL);
16093 		if (!ill->ill_ifname_pending)
16094 			break;
16095 		ill->ill_ifname_pending = 0;
16096 		if (!ioctl_aborted)
16097 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16098 		if (mp1 != NULL) {
16099 			ASSERT(connp == NULL);
16100 			q = ill->ill_wq;
16101 		}
16102 		/*
16103 		 * If any error acks received during the plumbing sequence,
16104 		 * ill_ifname_pending_err will be set. Break out and send up
16105 		 * the error to the pending ioctl.
16106 		 */
16107 		if (ill->ill_ifname_pending_err != 0) {
16108 			err = ill->ill_ifname_pending_err;
16109 			ill->ill_ifname_pending_err = 0;
16110 			break;
16111 		}
16112 
16113 		ill->ill_phys_addr_mp = mp;
16114 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16115 		mp = NULL;
16116 
16117 		/*
16118 		 * If paddrlen is zero, the DLPI provider doesn't support
16119 		 * physical addresses.  The other two tests were historical
16120 		 * workarounds for bugs in our former PPP implementation, but
16121 		 * now other things have grown dependencies on them -- e.g.,
16122 		 * the tun module specifies a dl_addr_length of zero in its
16123 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16124 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16125 		 * but only after careful testing ensures that all dependent
16126 		 * broken DLPI providers have been fixed.
16127 		 */
16128 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16129 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16130 			ill->ill_phys_addr = NULL;
16131 		} else if (paddrlen != ill->ill_phys_addr_length) {
16132 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16133 			    paddrlen, ill->ill_phys_addr_length));
16134 			err = EINVAL;
16135 			break;
16136 		}
16137 
16138 		if (ill->ill_nd_lla_mp == NULL) {
16139 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16140 				err = ENOMEM;
16141 				break;
16142 			}
16143 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16144 		}
16145 
16146 		/*
16147 		 * Set the interface token.  If the zeroth interface address
16148 		 * is unspecified, then set it to the link local address.
16149 		 */
16150 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16151 			(void) ill_setdefaulttoken(ill);
16152 
16153 		ASSERT(ill->ill_ipif->ipif_id == 0);
16154 		if (ipif != NULL &&
16155 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16156 			(void) ipif_setlinklocal(ipif);
16157 		}
16158 		break;
16159 	}
16160 	case DL_OK_ACK:
16161 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16162 		    dl_primstr((int)dloa->dl_correct_primitive),
16163 		    dloa->dl_correct_primitive));
16164 		switch (dloa->dl_correct_primitive) {
16165 		case DL_PROMISCON_REQ:
16166 		case DL_PROMISCOFF_REQ:
16167 		case DL_ENABMULTI_REQ:
16168 		case DL_DISABMULTI_REQ:
16169 		case DL_UNBIND_REQ:
16170 		case DL_ATTACH_REQ:
16171 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16172 			break;
16173 		}
16174 		break;
16175 	default:
16176 		break;
16177 	}
16178 
16179 	freemsg(mp);
16180 	if (mp1 != NULL) {
16181 		/*
16182 		 * The operation must complete without EINPROGRESS
16183 		 * since ipsq_pending_mp_get() has removed the mblk
16184 		 * from ipsq_pending_mp.  Otherwise, the operation
16185 		 * will be stuck forever in the ipsq.
16186 		 */
16187 		ASSERT(err != EINPROGRESS);
16188 
16189 		switch (ipsq->ipsq_current_ioctl) {
16190 		case 0:
16191 			ipsq_current_finish(ipsq);
16192 			break;
16193 
16194 		case SIOCLIFADDIF:
16195 		case SIOCSLIFNAME:
16196 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16197 			break;
16198 
16199 		default:
16200 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16201 			break;
16202 		}
16203 	}
16204 }
16205 
16206 /*
16207  * ip_rput_other is called by ip_rput to handle messages modifying the global
16208  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16209  */
16210 /* ARGSUSED */
16211 void
16212 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16213 {
16214 	ill_t		*ill;
16215 	struct iocblk	*iocp;
16216 	mblk_t		*mp1;
16217 	conn_t		*connp = NULL;
16218 
16219 	ip1dbg(("ip_rput_other "));
16220 	ill = (ill_t *)q->q_ptr;
16221 	/*
16222 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16223 	 * in which case ipsq is NULL.
16224 	 */
16225 	if (ipsq != NULL) {
16226 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16227 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16228 	}
16229 
16230 	switch (mp->b_datap->db_type) {
16231 	case M_ERROR:
16232 	case M_HANGUP:
16233 		/*
16234 		 * The device has a problem.  We force the ILL down.  It can
16235 		 * be brought up again manually using SIOCSIFFLAGS (via
16236 		 * ifconfig or equivalent).
16237 		 */
16238 		ASSERT(ipsq != NULL);
16239 		if (mp->b_rptr < mp->b_wptr)
16240 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16241 		if (ill->ill_error == 0)
16242 			ill->ill_error = ENXIO;
16243 		if (!ill_down_start(q, mp))
16244 			return;
16245 		ipif_all_down_tail(ipsq, q, mp, NULL);
16246 		break;
16247 	case M_IOCACK:
16248 		iocp = (struct iocblk *)mp->b_rptr;
16249 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16250 		switch (iocp->ioc_cmd) {
16251 		case SIOCSTUNPARAM:
16252 		case OSIOCSTUNPARAM:
16253 			ASSERT(ipsq != NULL);
16254 			/*
16255 			 * Finish socket ioctl passed through to tun.
16256 			 * We should have an IOCTL waiting on this.
16257 			 */
16258 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16259 			if (ill->ill_isv6) {
16260 				struct iftun_req *ta;
16261 
16262 				/*
16263 				 * if a source or destination is
16264 				 * being set, try and set the link
16265 				 * local address for the tunnel
16266 				 */
16267 				ta = (struct iftun_req *)mp->b_cont->
16268 				    b_cont->b_rptr;
16269 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16270 					ipif_set_tun_llink(ill, ta);
16271 				}
16272 
16273 			}
16274 			if (mp1 != NULL) {
16275 				/*
16276 				 * Now copy back the b_next/b_prev used by
16277 				 * mi code for the mi_copy* functions.
16278 				 * See ip_sioctl_tunparam() for the reason.
16279 				 * Also protect against missing b_cont.
16280 				 */
16281 				if (mp->b_cont != NULL) {
16282 					mp->b_cont->b_next =
16283 					    mp1->b_cont->b_next;
16284 					mp->b_cont->b_prev =
16285 					    mp1->b_cont->b_prev;
16286 				}
16287 				inet_freemsg(mp1);
16288 				ASSERT(connp != NULL);
16289 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16290 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16291 			} else {
16292 				ASSERT(connp == NULL);
16293 				putnext(q, mp);
16294 			}
16295 			break;
16296 		case SIOCGTUNPARAM:
16297 		case OSIOCGTUNPARAM:
16298 			/*
16299 			 * This is really M_IOCDATA from the tunnel driver.
16300 			 * convert back and complete the ioctl.
16301 			 * We should have an IOCTL waiting on this.
16302 			 */
16303 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16304 			if (mp1) {
16305 				/*
16306 				 * Now copy back the b_next/b_prev used by
16307 				 * mi code for the mi_copy* functions.
16308 				 * See ip_sioctl_tunparam() for the reason.
16309 				 * Also protect against missing b_cont.
16310 				 */
16311 				if (mp->b_cont != NULL) {
16312 					mp->b_cont->b_next =
16313 					    mp1->b_cont->b_next;
16314 					mp->b_cont->b_prev =
16315 					    mp1->b_cont->b_prev;
16316 				}
16317 				inet_freemsg(mp1);
16318 				if (iocp->ioc_error == 0)
16319 					mp->b_datap->db_type = M_IOCDATA;
16320 				ASSERT(connp != NULL);
16321 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16322 				    iocp->ioc_error, COPYOUT, NULL);
16323 			} else {
16324 				ASSERT(connp == NULL);
16325 				putnext(q, mp);
16326 			}
16327 			break;
16328 		default:
16329 			break;
16330 		}
16331 		break;
16332 	case M_IOCNAK:
16333 		iocp = (struct iocblk *)mp->b_rptr;
16334 
16335 		switch (iocp->ioc_cmd) {
16336 		int mode;
16337 
16338 		case DL_IOC_HDR_INFO:
16339 			/*
16340 			 * If this was the first attempt turn of the
16341 			 * fastpath probing.
16342 			 */
16343 			mutex_enter(&ill->ill_lock);
16344 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16345 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16346 				mutex_exit(&ill->ill_lock);
16347 				ill_fastpath_nack(ill);
16348 				ip1dbg(("ip_rput: DLPI fastpath off on "
16349 				    "interface %s\n",
16350 				    ill->ill_name));
16351 			} else {
16352 				mutex_exit(&ill->ill_lock);
16353 			}
16354 			freemsg(mp);
16355 			break;
16356 		case SIOCSTUNPARAM:
16357 		case OSIOCSTUNPARAM:
16358 			ASSERT(ipsq != NULL);
16359 			/*
16360 			 * Finish socket ioctl passed through to tun
16361 			 * We should have an IOCTL waiting on this.
16362 			 */
16363 			/* FALLTHRU */
16364 		case SIOCGTUNPARAM:
16365 		case OSIOCGTUNPARAM:
16366 			/*
16367 			 * This is really M_IOCDATA from the tunnel driver.
16368 			 * convert back and complete the ioctl.
16369 			 * We should have an IOCTL waiting on this.
16370 			 */
16371 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16372 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16373 				mp1 = ill_pending_mp_get(ill, &connp,
16374 				    iocp->ioc_id);
16375 				mode = COPYOUT;
16376 				ipsq = NULL;
16377 			} else {
16378 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16379 				mode = NO_COPYOUT;
16380 			}
16381 			if (mp1 != NULL) {
16382 				/*
16383 				 * Now copy back the b_next/b_prev used by
16384 				 * mi code for the mi_copy* functions.
16385 				 * See ip_sioctl_tunparam() for the reason.
16386 				 * Also protect against missing b_cont.
16387 				 */
16388 				if (mp->b_cont != NULL) {
16389 					mp->b_cont->b_next =
16390 					    mp1->b_cont->b_next;
16391 					mp->b_cont->b_prev =
16392 					    mp1->b_cont->b_prev;
16393 				}
16394 				inet_freemsg(mp1);
16395 				if (iocp->ioc_error == 0)
16396 					iocp->ioc_error = EINVAL;
16397 				ASSERT(connp != NULL);
16398 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16399 				    iocp->ioc_error, mode, ipsq);
16400 			} else {
16401 				ASSERT(connp == NULL);
16402 				putnext(q, mp);
16403 			}
16404 			break;
16405 		default:
16406 			break;
16407 		}
16408 	default:
16409 		break;
16410 	}
16411 }
16412 
16413 /*
16414  * NOTE : This function does not ire_refrele the ire argument passed in.
16415  *
16416  * IPQoS notes
16417  * IP policy is invoked twice for a forwarded packet, once on the read side
16418  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16419  * enabled. An additional parameter, in_ill, has been added for this purpose.
16420  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16421  * because ip_mroute drops this information.
16422  *
16423  */
16424 void
16425 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16426 {
16427 	uint32_t	old_pkt_len;
16428 	uint32_t	pkt_len;
16429 	queue_t	*q;
16430 	uint32_t	sum;
16431 #define	rptr	((uchar_t *)ipha)
16432 	uint32_t	max_frag;
16433 	uint32_t	ill_index;
16434 	ill_t		*out_ill;
16435 	mib2_ipIfStatsEntry_t *mibptr;
16436 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16437 
16438 	/* Get the ill_index of the incoming ILL */
16439 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16440 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16441 
16442 	/* Initiate Read side IPPF processing */
16443 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16444 		ip_process(IPP_FWD_IN, &mp, ill_index);
16445 		if (mp == NULL) {
16446 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16447 			    "during IPPF processing\n"));
16448 			return;
16449 		}
16450 	}
16451 
16452 	/* Adjust the checksum to reflect the ttl decrement. */
16453 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16454 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16455 
16456 	if (ipha->ipha_ttl-- <= 1) {
16457 		if (ip_csum_hdr(ipha)) {
16458 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16459 			goto drop_pkt;
16460 		}
16461 		/*
16462 		 * Note: ire_stq this will be NULL for multicast
16463 		 * datagrams using the long path through arp (the IRE
16464 		 * is not an IRE_CACHE). This should not cause
16465 		 * problems since we don't generate ICMP errors for
16466 		 * multicast packets.
16467 		 */
16468 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16469 		q = ire->ire_stq;
16470 		if (q != NULL) {
16471 			/* Sent by forwarding path, and router is global zone */
16472 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16473 			    GLOBAL_ZONEID, ipst);
16474 		} else
16475 			freemsg(mp);
16476 		return;
16477 	}
16478 
16479 	/*
16480 	 * Don't forward if the interface is down
16481 	 */
16482 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16483 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16484 		ip2dbg(("ip_rput_forward:interface is down\n"));
16485 		goto drop_pkt;
16486 	}
16487 
16488 	/* Get the ill_index of the outgoing ILL */
16489 	out_ill = ire_to_ill(ire);
16490 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16491 
16492 	DTRACE_PROBE4(ip4__forwarding__start,
16493 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16494 
16495 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16496 	    ipst->ips_ipv4firewall_forwarding,
16497 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16498 
16499 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16500 
16501 	if (mp == NULL)
16502 		return;
16503 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16504 
16505 	if (is_system_labeled()) {
16506 		mblk_t *mp1;
16507 
16508 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16509 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16510 			goto drop_pkt;
16511 		}
16512 		/* Size may have changed */
16513 		mp = mp1;
16514 		ipha = (ipha_t *)mp->b_rptr;
16515 		pkt_len = ntohs(ipha->ipha_length);
16516 	}
16517 
16518 	/* Check if there are options to update */
16519 	if (!IS_SIMPLE_IPH(ipha)) {
16520 		if (ip_csum_hdr(ipha)) {
16521 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16522 			goto drop_pkt;
16523 		}
16524 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16525 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16526 			return;
16527 		}
16528 
16529 		ipha->ipha_hdr_checksum = 0;
16530 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16531 	}
16532 	max_frag = ire->ire_max_frag;
16533 	if (pkt_len > max_frag) {
16534 		/*
16535 		 * It needs fragging on its way out.  We haven't
16536 		 * verified the header checksum yet.  Since we
16537 		 * are going to put a surely good checksum in the
16538 		 * outgoing header, we have to make sure that it
16539 		 * was good coming in.
16540 		 */
16541 		if (ip_csum_hdr(ipha)) {
16542 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16543 			goto drop_pkt;
16544 		}
16545 		/* Initiate Write side IPPF processing */
16546 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16547 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16548 			if (mp == NULL) {
16549 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16550 				    " during IPPF processing\n"));
16551 				return;
16552 			}
16553 		}
16554 		/*
16555 		 * Handle labeled packet resizing.
16556 		 *
16557 		 * If we have added a label, inform ip_wput_frag() of its
16558 		 * effect on the MTU for ICMP messages.
16559 		 */
16560 		if (pkt_len > old_pkt_len) {
16561 			uint32_t secopt_size;
16562 
16563 			secopt_size = pkt_len - old_pkt_len;
16564 			if (secopt_size < max_frag)
16565 				max_frag -= secopt_size;
16566 		}
16567 
16568 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16569 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16570 		return;
16571 	}
16572 
16573 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16574 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16575 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16576 	    ipst->ips_ipv4firewall_physical_out,
16577 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16578 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16579 	if (mp == NULL)
16580 		return;
16581 
16582 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16583 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16584 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16585 	/* ip_xmit_v4 always consumes the packet */
16586 	return;
16587 
16588 drop_pkt:;
16589 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16590 	freemsg(mp);
16591 #undef	rptr
16592 }
16593 
16594 void
16595 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16596 {
16597 	ire_t	*ire;
16598 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16599 
16600 	ASSERT(!ipif->ipif_isv6);
16601 	/*
16602 	 * Find an IRE which matches the destination and the outgoing
16603 	 * queue in the cache table. All we need is an IRE_CACHE which
16604 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16605 	 * then it is enough to have some IRE_CACHE in the group.
16606 	 */
16607 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16608 		dst = ipif->ipif_pp_dst_addr;
16609 
16610 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16611 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16612 	if (ire == NULL) {
16613 		/*
16614 		 * Mark this packet to make it be delivered to
16615 		 * ip_rput_forward after the new ire has been
16616 		 * created.
16617 		 */
16618 		mp->b_prev = NULL;
16619 		mp->b_next = mp;
16620 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16621 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16622 	} else {
16623 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16624 		IRE_REFRELE(ire);
16625 	}
16626 }
16627 
16628 /* Update any source route, record route or timestamp options */
16629 static int
16630 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16631 {
16632 	ipoptp_t	opts;
16633 	uchar_t		*opt;
16634 	uint8_t		optval;
16635 	uint8_t		optlen;
16636 	ipaddr_t	dst;
16637 	uint32_t	ts;
16638 	ire_t		*dst_ire = NULL;
16639 	ire_t		*tmp_ire = NULL;
16640 	timestruc_t	now;
16641 
16642 	ip2dbg(("ip_rput_forward_options\n"));
16643 	dst = ipha->ipha_dst;
16644 	for (optval = ipoptp_first(&opts, ipha);
16645 	    optval != IPOPT_EOL;
16646 	    optval = ipoptp_next(&opts)) {
16647 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16648 		opt = opts.ipoptp_cur;
16649 		optlen = opts.ipoptp_len;
16650 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16651 		    optval, opts.ipoptp_len));
16652 		switch (optval) {
16653 			uint32_t off;
16654 		case IPOPT_SSRR:
16655 		case IPOPT_LSRR:
16656 			/* Check if adminstratively disabled */
16657 			if (!ipst->ips_ip_forward_src_routed) {
16658 				if (ire->ire_stq != NULL) {
16659 					/*
16660 					 * Sent by forwarding path, and router
16661 					 * is global zone
16662 					 */
16663 					icmp_unreachable(ire->ire_stq, mp,
16664 					    ICMP_SOURCE_ROUTE_FAILED,
16665 					    GLOBAL_ZONEID, ipst);
16666 				} else {
16667 					ip0dbg(("ip_rput_forward_options: "
16668 					    "unable to send unreach\n"));
16669 					freemsg(mp);
16670 				}
16671 				return (-1);
16672 			}
16673 
16674 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16675 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16676 			if (dst_ire == NULL) {
16677 				/*
16678 				 * Must be partial since ip_rput_options
16679 				 * checked for strict.
16680 				 */
16681 				break;
16682 			}
16683 			off = opt[IPOPT_OFFSET];
16684 			off--;
16685 		redo_srr:
16686 			if (optlen < IP_ADDR_LEN ||
16687 			    off > optlen - IP_ADDR_LEN) {
16688 				/* End of source route */
16689 				ip1dbg((
16690 				    "ip_rput_forward_options: end of SR\n"));
16691 				ire_refrele(dst_ire);
16692 				break;
16693 			}
16694 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16695 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16696 			    IP_ADDR_LEN);
16697 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16698 			    ntohl(dst)));
16699 
16700 			/*
16701 			 * Check if our address is present more than
16702 			 * once as consecutive hops in source route.
16703 			 */
16704 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16705 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16706 			if (tmp_ire != NULL) {
16707 				ire_refrele(tmp_ire);
16708 				off += IP_ADDR_LEN;
16709 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16710 				goto redo_srr;
16711 			}
16712 			ipha->ipha_dst = dst;
16713 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16714 			ire_refrele(dst_ire);
16715 			break;
16716 		case IPOPT_RR:
16717 			off = opt[IPOPT_OFFSET];
16718 			off--;
16719 			if (optlen < IP_ADDR_LEN ||
16720 			    off > optlen - IP_ADDR_LEN) {
16721 				/* No more room - ignore */
16722 				ip1dbg((
16723 				    "ip_rput_forward_options: end of RR\n"));
16724 				break;
16725 			}
16726 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16727 			    IP_ADDR_LEN);
16728 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16729 			break;
16730 		case IPOPT_TS:
16731 			/* Insert timestamp if there is room */
16732 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16733 			case IPOPT_TS_TSONLY:
16734 				off = IPOPT_TS_TIMELEN;
16735 				break;
16736 			case IPOPT_TS_PRESPEC:
16737 			case IPOPT_TS_PRESPEC_RFC791:
16738 				/* Verify that the address matched */
16739 				off = opt[IPOPT_OFFSET] - 1;
16740 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16741 				dst_ire = ire_ctable_lookup(dst, 0,
16742 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16743 				    MATCH_IRE_TYPE, ipst);
16744 				if (dst_ire == NULL) {
16745 					/* Not for us */
16746 					break;
16747 				}
16748 				ire_refrele(dst_ire);
16749 				/* FALLTHRU */
16750 			case IPOPT_TS_TSANDADDR:
16751 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16752 				break;
16753 			default:
16754 				/*
16755 				 * ip_*put_options should have already
16756 				 * dropped this packet.
16757 				 */
16758 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16759 				    "unknown IT - bug in ip_rput_options?\n");
16760 				return (0);	/* Keep "lint" happy */
16761 			}
16762 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16763 				/* Increase overflow counter */
16764 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16765 				opt[IPOPT_POS_OV_FLG] =
16766 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16767 				    (off << 4));
16768 				break;
16769 			}
16770 			off = opt[IPOPT_OFFSET] - 1;
16771 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16772 			case IPOPT_TS_PRESPEC:
16773 			case IPOPT_TS_PRESPEC_RFC791:
16774 			case IPOPT_TS_TSANDADDR:
16775 				bcopy(&ire->ire_src_addr,
16776 				    (char *)opt + off, IP_ADDR_LEN);
16777 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16778 				/* FALLTHRU */
16779 			case IPOPT_TS_TSONLY:
16780 				off = opt[IPOPT_OFFSET] - 1;
16781 				/* Compute # of milliseconds since midnight */
16782 				gethrestime(&now);
16783 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16784 				    now.tv_nsec / (NANOSEC / MILLISEC);
16785 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16786 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16787 				break;
16788 			}
16789 			break;
16790 		}
16791 	}
16792 	return (0);
16793 }
16794 
16795 /*
16796  * This is called after processing at least one of AH/ESP headers.
16797  *
16798  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16799  * the actual, physical interface on which the packet was received,
16800  * but, when ip_strict_dst_multihoming is set to 1, could be the
16801  * interface which had the ipha_dst configured when the packet went
16802  * through ip_rput. The ill_index corresponding to the recv_ill
16803  * is saved in ipsec_in_rill_index
16804  *
16805  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16806  * cannot assume "ire" points to valid data for any IPv6 cases.
16807  */
16808 void
16809 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16810 {
16811 	mblk_t *mp;
16812 	ipaddr_t dst;
16813 	in6_addr_t *v6dstp;
16814 	ipha_t *ipha;
16815 	ip6_t *ip6h;
16816 	ipsec_in_t *ii;
16817 	boolean_t ill_need_rele = B_FALSE;
16818 	boolean_t rill_need_rele = B_FALSE;
16819 	boolean_t ire_need_rele = B_FALSE;
16820 	netstack_t	*ns;
16821 	ip_stack_t	*ipst;
16822 
16823 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16824 	ASSERT(ii->ipsec_in_ill_index != 0);
16825 	ns = ii->ipsec_in_ns;
16826 	ASSERT(ii->ipsec_in_ns != NULL);
16827 	ipst = ns->netstack_ip;
16828 
16829 	mp = ipsec_mp->b_cont;
16830 	ASSERT(mp != NULL);
16831 
16832 
16833 	if (ill == NULL) {
16834 		ASSERT(recv_ill == NULL);
16835 		/*
16836 		 * We need to get the original queue on which ip_rput_local
16837 		 * or ip_rput_data_v6 was called.
16838 		 */
16839 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16840 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16841 		ill_need_rele = B_TRUE;
16842 
16843 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16844 			recv_ill = ill_lookup_on_ifindex(
16845 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16846 			    NULL, NULL, NULL, NULL, ipst);
16847 			rill_need_rele = B_TRUE;
16848 		} else {
16849 			recv_ill = ill;
16850 		}
16851 
16852 		if ((ill == NULL) || (recv_ill == NULL)) {
16853 			ip0dbg(("ip_fanout_proto_again: interface "
16854 			    "disappeared\n"));
16855 			if (ill != NULL)
16856 				ill_refrele(ill);
16857 			if (recv_ill != NULL)
16858 				ill_refrele(recv_ill);
16859 			freemsg(ipsec_mp);
16860 			return;
16861 		}
16862 	}
16863 
16864 	ASSERT(ill != NULL && recv_ill != NULL);
16865 
16866 	if (mp->b_datap->db_type == M_CTL) {
16867 		/*
16868 		 * AH/ESP is returning the ICMP message after
16869 		 * removing their headers. Fanout again till
16870 		 * it gets to the right protocol.
16871 		 */
16872 		if (ii->ipsec_in_v4) {
16873 			icmph_t *icmph;
16874 			int iph_hdr_length;
16875 			int hdr_length;
16876 
16877 			ipha = (ipha_t *)mp->b_rptr;
16878 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16879 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16880 			ipha = (ipha_t *)&icmph[1];
16881 			hdr_length = IPH_HDR_LENGTH(ipha);
16882 			/*
16883 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16884 			 * Reset the type to M_DATA.
16885 			 */
16886 			mp->b_datap->db_type = M_DATA;
16887 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16888 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16889 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16890 		} else {
16891 			icmp6_t *icmp6;
16892 			int hdr_length;
16893 
16894 			ip6h = (ip6_t *)mp->b_rptr;
16895 			/* Don't call hdr_length_v6() unless you have to. */
16896 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16897 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16898 			else
16899 				hdr_length = IPV6_HDR_LEN;
16900 
16901 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16902 			/*
16903 			 * icmp_inbound_error_fanout_v6 may need to do
16904 			 * pullupmsg.  Reset the type to M_DATA.
16905 			 */
16906 			mp->b_datap->db_type = M_DATA;
16907 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16908 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16909 		}
16910 		if (ill_need_rele)
16911 			ill_refrele(ill);
16912 		if (rill_need_rele)
16913 			ill_refrele(recv_ill);
16914 		return;
16915 	}
16916 
16917 	if (ii->ipsec_in_v4) {
16918 		ipha = (ipha_t *)mp->b_rptr;
16919 		dst = ipha->ipha_dst;
16920 		if (CLASSD(dst)) {
16921 			/*
16922 			 * Multicast has to be delivered to all streams.
16923 			 */
16924 			dst = INADDR_BROADCAST;
16925 		}
16926 
16927 		if (ire == NULL) {
16928 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16929 			    MBLK_GETLABEL(mp), ipst);
16930 			if (ire == NULL) {
16931 				if (ill_need_rele)
16932 					ill_refrele(ill);
16933 				if (rill_need_rele)
16934 					ill_refrele(recv_ill);
16935 				ip1dbg(("ip_fanout_proto_again: "
16936 				    "IRE not found"));
16937 				freemsg(ipsec_mp);
16938 				return;
16939 			}
16940 			ire_need_rele = B_TRUE;
16941 		}
16942 
16943 		switch (ipha->ipha_protocol) {
16944 			case IPPROTO_UDP:
16945 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16946 				    recv_ill);
16947 				if (ire_need_rele)
16948 					ire_refrele(ire);
16949 				break;
16950 			case IPPROTO_TCP:
16951 				if (!ire_need_rele)
16952 					IRE_REFHOLD(ire);
16953 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16954 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16955 				IRE_REFRELE(ire);
16956 				if (mp != NULL)
16957 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16958 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16959 				break;
16960 			case IPPROTO_SCTP:
16961 				if (!ire_need_rele)
16962 					IRE_REFHOLD(ire);
16963 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16964 				    ipsec_mp, 0, ill->ill_rq, dst);
16965 				break;
16966 			default:
16967 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16968 				    recv_ill, B_FALSE);
16969 				if (ire_need_rele)
16970 					ire_refrele(ire);
16971 				break;
16972 		}
16973 	} else {
16974 		uint32_t rput_flags = 0;
16975 
16976 		ip6h = (ip6_t *)mp->b_rptr;
16977 		v6dstp = &ip6h->ip6_dst;
16978 		/*
16979 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16980 		 * address.
16981 		 *
16982 		 * Currently, we don't store that state in the IPSEC_IN
16983 		 * message, and we may need to.
16984 		 */
16985 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16986 		    IP6_IN_LLMCAST : 0);
16987 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16988 		    NULL, NULL);
16989 	}
16990 	if (ill_need_rele)
16991 		ill_refrele(ill);
16992 	if (rill_need_rele)
16993 		ill_refrele(recv_ill);
16994 }
16995 
16996 /*
16997  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
16998  * returns 'true' if there are still fragments left on the queue, in
16999  * which case we restart the timer.
17000  */
17001 void
17002 ill_frag_timer(void *arg)
17003 {
17004 	ill_t	*ill = (ill_t *)arg;
17005 	boolean_t frag_pending;
17006 	ip_stack_t	*ipst = ill->ill_ipst;
17007 
17008 	mutex_enter(&ill->ill_lock);
17009 	ASSERT(!ill->ill_fragtimer_executing);
17010 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17011 		ill->ill_frag_timer_id = 0;
17012 		mutex_exit(&ill->ill_lock);
17013 		return;
17014 	}
17015 	ill->ill_fragtimer_executing = 1;
17016 	mutex_exit(&ill->ill_lock);
17017 
17018 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17019 
17020 	/*
17021 	 * Restart the timer, if we have fragments pending or if someone
17022 	 * wanted us to be scheduled again.
17023 	 */
17024 	mutex_enter(&ill->ill_lock);
17025 	ill->ill_fragtimer_executing = 0;
17026 	ill->ill_frag_timer_id = 0;
17027 	if (frag_pending || ill->ill_fragtimer_needrestart)
17028 		ill_frag_timer_start(ill);
17029 	mutex_exit(&ill->ill_lock);
17030 }
17031 
17032 void
17033 ill_frag_timer_start(ill_t *ill)
17034 {
17035 	ip_stack_t	*ipst = ill->ill_ipst;
17036 
17037 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17038 
17039 	/* If the ill is closing or opening don't proceed */
17040 	if (ill->ill_state_flags & ILL_CONDEMNED)
17041 		return;
17042 
17043 	if (ill->ill_fragtimer_executing) {
17044 		/*
17045 		 * ill_frag_timer is currently executing. Just record the
17046 		 * the fact that we want the timer to be restarted.
17047 		 * ill_frag_timer will post a timeout before it returns,
17048 		 * ensuring it will be called again.
17049 		 */
17050 		ill->ill_fragtimer_needrestart = 1;
17051 		return;
17052 	}
17053 
17054 	if (ill->ill_frag_timer_id == 0) {
17055 		/*
17056 		 * The timer is neither running nor is the timeout handler
17057 		 * executing. Post a timeout so that ill_frag_timer will be
17058 		 * called
17059 		 */
17060 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17061 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17062 		ill->ill_fragtimer_needrestart = 0;
17063 	}
17064 }
17065 
17066 /*
17067  * This routine is needed for loopback when forwarding multicasts.
17068  *
17069  * IPQoS Notes:
17070  * IPPF processing is done in fanout routines.
17071  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17072  * processing for IPsec packets is done when it comes back in clear.
17073  * NOTE : The callers of this function need to do the ire_refrele for the
17074  *	  ire that is being passed in.
17075  */
17076 void
17077 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17078     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17079 {
17080 	ill_t	*ill = (ill_t *)q->q_ptr;
17081 	uint32_t	sum;
17082 	uint32_t	u1;
17083 	uint32_t	u2;
17084 	int		hdr_length;
17085 	boolean_t	mctl_present;
17086 	mblk_t		*first_mp = mp;
17087 	mblk_t		*hada_mp = NULL;
17088 	ipha_t		*inner_ipha;
17089 	ip_stack_t	*ipst;
17090 
17091 	ASSERT(recv_ill != NULL);
17092 	ipst = recv_ill->ill_ipst;
17093 
17094 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17095 	    "ip_rput_locl_start: q %p", q);
17096 
17097 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17098 	ASSERT(ill != NULL);
17099 
17100 
17101 #define	rptr	((uchar_t *)ipha)
17102 #define	iphs	((uint16_t *)ipha)
17103 
17104 	/*
17105 	 * no UDP or TCP packet should come here anymore.
17106 	 */
17107 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17108 	    ipha->ipha_protocol != IPPROTO_UDP);
17109 
17110 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17111 	if (mctl_present &&
17112 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17113 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17114 
17115 		/*
17116 		 * It's an IPsec accelerated packet.
17117 		 * Keep a pointer to the data attributes around until
17118 		 * we allocate the ipsec_info_t.
17119 		 */
17120 		IPSECHW_DEBUG(IPSECHW_PKT,
17121 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17122 		hada_mp = first_mp;
17123 		hada_mp->b_cont = NULL;
17124 		/*
17125 		 * Since it is accelerated, it comes directly from
17126 		 * the ill and the data attributes is followed by
17127 		 * the packet data.
17128 		 */
17129 		ASSERT(mp->b_datap->db_type != M_CTL);
17130 		first_mp = mp;
17131 		mctl_present = B_FALSE;
17132 	}
17133 
17134 	/*
17135 	 * IF M_CTL is not present, then ipsec_in_is_secure
17136 	 * should return B_TRUE. There is a case where loopback
17137 	 * packets has an M_CTL in the front with all the
17138 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17139 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17140 	 * packets never comes here, it is safe to ASSERT the
17141 	 * following.
17142 	 */
17143 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17144 
17145 	/*
17146 	 * Also, we should never have an mctl_present if this is an
17147 	 * ESP-in-UDP packet.
17148 	 */
17149 	ASSERT(!mctl_present || !esp_in_udp_packet);
17150 
17151 
17152 	/* u1 is # words of IP options */
17153 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17154 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17155 
17156 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17157 		if (u1) {
17158 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17159 				if (hada_mp != NULL)
17160 					freemsg(hada_mp);
17161 				return;
17162 			}
17163 		} else {
17164 			/* Check the IP header checksum.  */
17165 #define	uph	((uint16_t *)ipha)
17166 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17167 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17168 #undef  uph
17169 			/* finish doing IP checksum */
17170 			sum = (sum & 0xFFFF) + (sum >> 16);
17171 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17172 			if (sum && sum != 0xFFFF) {
17173 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17174 				goto drop_pkt;
17175 			}
17176 		}
17177 	}
17178 
17179 	/*
17180 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17181 	 * might be called more than once for secure packets, count only
17182 	 * the first time.
17183 	 */
17184 	if (!mctl_present) {
17185 		UPDATE_IB_PKT_COUNT(ire);
17186 		ire->ire_last_used_time = lbolt;
17187 	}
17188 
17189 	/* Check for fragmentation offset. */
17190 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17191 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17192 	if (u1) {
17193 		/*
17194 		 * We re-assemble fragments before we do the AH/ESP
17195 		 * processing. Thus, M_CTL should not be present
17196 		 * while we are re-assembling.
17197 		 */
17198 		ASSERT(!mctl_present);
17199 		ASSERT(first_mp == mp);
17200 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17201 			return;
17202 		}
17203 		/*
17204 		 * Make sure that first_mp points back to mp as
17205 		 * the mp we came in with could have changed in
17206 		 * ip_rput_fragment().
17207 		 */
17208 		ipha = (ipha_t *)mp->b_rptr;
17209 		first_mp = mp;
17210 	}
17211 
17212 	/*
17213 	 * Clear hardware checksumming flag as it is currently only
17214 	 * used by TCP and UDP.
17215 	 */
17216 	DB_CKSUMFLAGS(mp) = 0;
17217 
17218 	/* Now we have a complete datagram, destined for this machine. */
17219 	u1 = IPH_HDR_LENGTH(ipha);
17220 	switch (ipha->ipha_protocol) {
17221 	case IPPROTO_ICMP: {
17222 		ire_t		*ire_zone;
17223 		ilm_t		*ilm;
17224 		mblk_t		*mp1;
17225 		zoneid_t	last_zoneid;
17226 
17227 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17228 			ASSERT(ire->ire_type == IRE_BROADCAST);
17229 			/*
17230 			 * In the multicast case, applications may have joined
17231 			 * the group from different zones, so we need to deliver
17232 			 * the packet to each of them. Loop through the
17233 			 * multicast memberships structures (ilm) on the receive
17234 			 * ill and send a copy of the packet up each matching
17235 			 * one. However, we don't do this for multicasts sent on
17236 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17237 			 * they must stay in the sender's zone.
17238 			 *
17239 			 * ilm_add_v6() ensures that ilms in the same zone are
17240 			 * contiguous in the ill_ilm list. We use this property
17241 			 * to avoid sending duplicates needed when two
17242 			 * applications in the same zone join the same group on
17243 			 * different logical interfaces: we ignore the ilm if
17244 			 * its zoneid is the same as the last matching one.
17245 			 * In addition, the sending of the packet for
17246 			 * ire_zoneid is delayed until all of the other ilms
17247 			 * have been exhausted.
17248 			 */
17249 			last_zoneid = -1;
17250 			ILM_WALKER_HOLD(recv_ill);
17251 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17252 			    ilm = ilm->ilm_next) {
17253 				if ((ilm->ilm_flags & ILM_DELETED) ||
17254 				    ipha->ipha_dst != ilm->ilm_addr ||
17255 				    ilm->ilm_zoneid == last_zoneid ||
17256 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17257 				    ilm->ilm_zoneid == ALL_ZONES ||
17258 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17259 					continue;
17260 				mp1 = ip_copymsg(first_mp);
17261 				if (mp1 == NULL)
17262 					continue;
17263 				icmp_inbound(q, mp1, B_TRUE, ill,
17264 				    0, sum, mctl_present, B_TRUE,
17265 				    recv_ill, ilm->ilm_zoneid);
17266 				last_zoneid = ilm->ilm_zoneid;
17267 			}
17268 			ILM_WALKER_RELE(recv_ill);
17269 		} else if (ire->ire_type == IRE_BROADCAST) {
17270 			/*
17271 			 * In the broadcast case, there may be many zones
17272 			 * which need a copy of the packet delivered to them.
17273 			 * There is one IRE_BROADCAST per broadcast address
17274 			 * and per zone; we walk those using a helper function.
17275 			 * In addition, the sending of the packet for ire is
17276 			 * delayed until all of the other ires have been
17277 			 * processed.
17278 			 */
17279 			IRB_REFHOLD(ire->ire_bucket);
17280 			ire_zone = NULL;
17281 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17282 			    ire)) != NULL) {
17283 				mp1 = ip_copymsg(first_mp);
17284 				if (mp1 == NULL)
17285 					continue;
17286 
17287 				UPDATE_IB_PKT_COUNT(ire_zone);
17288 				ire_zone->ire_last_used_time = lbolt;
17289 				icmp_inbound(q, mp1, B_TRUE, ill,
17290 				    0, sum, mctl_present, B_TRUE,
17291 				    recv_ill, ire_zone->ire_zoneid);
17292 			}
17293 			IRB_REFRELE(ire->ire_bucket);
17294 		}
17295 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17296 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17297 		    ire->ire_zoneid);
17298 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17299 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17300 		return;
17301 	}
17302 	case IPPROTO_IGMP:
17303 		/*
17304 		 * If we are not willing to accept IGMP packets in clear,
17305 		 * then check with global policy.
17306 		 */
17307 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17308 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17309 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17310 			if (first_mp == NULL)
17311 				return;
17312 		}
17313 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17314 			freemsg(first_mp);
17315 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17316 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17317 			return;
17318 		}
17319 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17320 			/* Bad packet - discarded by igmp_input */
17321 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17322 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17323 			if (mctl_present)
17324 				freeb(first_mp);
17325 			return;
17326 		}
17327 		/*
17328 		 * igmp_input() may have returned the pulled up message.
17329 		 * So first_mp and ipha need to be reinitialized.
17330 		 */
17331 		ipha = (ipha_t *)mp->b_rptr;
17332 		if (mctl_present)
17333 			first_mp->b_cont = mp;
17334 		else
17335 			first_mp = mp;
17336 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17337 		    connf_head != NULL) {
17338 			/* No user-level listener for IGMP packets */
17339 			goto drop_pkt;
17340 		}
17341 		/* deliver to local raw users */
17342 		break;
17343 	case IPPROTO_PIM:
17344 		/*
17345 		 * If we are not willing to accept PIM packets in clear,
17346 		 * then check with global policy.
17347 		 */
17348 		if (ipst->ips_pim_accept_clear_messages == 0) {
17349 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17350 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17351 			if (first_mp == NULL)
17352 				return;
17353 		}
17354 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17355 			freemsg(first_mp);
17356 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17357 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17358 			return;
17359 		}
17360 		if (pim_input(q, mp, ill) != 0) {
17361 			/* Bad packet - discarded by pim_input */
17362 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17363 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17364 			if (mctl_present)
17365 				freeb(first_mp);
17366 			return;
17367 		}
17368 
17369 		/*
17370 		 * pim_input() may have pulled up the message so ipha needs to
17371 		 * be reinitialized.
17372 		 */
17373 		ipha = (ipha_t *)mp->b_rptr;
17374 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17375 		    connf_head != NULL) {
17376 			/* No user-level listener for PIM packets */
17377 			goto drop_pkt;
17378 		}
17379 		/* deliver to local raw users */
17380 		break;
17381 	case IPPROTO_ENCAP:
17382 		/*
17383 		 * Handle self-encapsulated packets (IP-in-IP where
17384 		 * the inner addresses == the outer addresses).
17385 		 */
17386 		hdr_length = IPH_HDR_LENGTH(ipha);
17387 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17388 		    mp->b_wptr) {
17389 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17390 			    sizeof (ipha_t) - mp->b_rptr)) {
17391 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17392 				freemsg(first_mp);
17393 				return;
17394 			}
17395 			ipha = (ipha_t *)mp->b_rptr;
17396 		}
17397 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17398 		/*
17399 		 * Check the sanity of the inner IP header.
17400 		 */
17401 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17402 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17403 			freemsg(first_mp);
17404 			return;
17405 		}
17406 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17407 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17408 			freemsg(first_mp);
17409 			return;
17410 		}
17411 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17412 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17413 			ipsec_in_t *ii;
17414 
17415 			/*
17416 			 * Self-encapsulated tunnel packet. Remove
17417 			 * the outer IP header and fanout again.
17418 			 * We also need to make sure that the inner
17419 			 * header is pulled up until options.
17420 			 */
17421 			mp->b_rptr = (uchar_t *)inner_ipha;
17422 			ipha = inner_ipha;
17423 			hdr_length = IPH_HDR_LENGTH(ipha);
17424 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17425 				if (!pullupmsg(mp, (uchar_t *)ipha +
17426 				    + hdr_length - mp->b_rptr)) {
17427 					freemsg(first_mp);
17428 					return;
17429 				}
17430 				ipha = (ipha_t *)mp->b_rptr;
17431 			}
17432 			if (!mctl_present) {
17433 				ASSERT(first_mp == mp);
17434 				/*
17435 				 * This means that somebody is sending
17436 				 * Self-encapsualted packets without AH/ESP.
17437 				 * If AH/ESP was present, we would have already
17438 				 * allocated the first_mp.
17439 				 */
17440 				first_mp = ipsec_in_alloc(B_TRUE,
17441 				    ipst->ips_netstack);
17442 				if (first_mp == NULL) {
17443 					ip1dbg(("ip_proto_input: IPSEC_IN "
17444 					    "allocation failure.\n"));
17445 					BUMP_MIB(ill->ill_ip_mib,
17446 					    ipIfStatsInDiscards);
17447 					freemsg(mp);
17448 					return;
17449 				}
17450 				first_mp->b_cont = mp;
17451 			}
17452 			/*
17453 			 * We generally store the ill_index if we need to
17454 			 * do IPsec processing as we lose the ill queue when
17455 			 * we come back. But in this case, we never should
17456 			 * have to store the ill_index here as it should have
17457 			 * been stored previously when we processed the
17458 			 * AH/ESP header in this routine or for non-ipsec
17459 			 * cases, we still have the queue. But for some bad
17460 			 * packets from the wire, we can get to IPsec after
17461 			 * this and we better store the index for that case.
17462 			 */
17463 			ill = (ill_t *)q->q_ptr;
17464 			ii = (ipsec_in_t *)first_mp->b_rptr;
17465 			ii->ipsec_in_ill_index =
17466 			    ill->ill_phyint->phyint_ifindex;
17467 			ii->ipsec_in_rill_index =
17468 			    recv_ill->ill_phyint->phyint_ifindex;
17469 			if (ii->ipsec_in_decaps) {
17470 				/*
17471 				 * This packet is self-encapsulated multiple
17472 				 * times. We don't want to recurse infinitely.
17473 				 * To keep it simple, drop the packet.
17474 				 */
17475 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17476 				freemsg(first_mp);
17477 				return;
17478 			}
17479 			ii->ipsec_in_decaps = B_TRUE;
17480 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17481 			    ire);
17482 			return;
17483 		}
17484 		break;
17485 	case IPPROTO_AH:
17486 	case IPPROTO_ESP: {
17487 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17488 
17489 		/*
17490 		 * Fast path for AH/ESP. If this is the first time
17491 		 * we are sending a datagram to AH/ESP, allocate
17492 		 * a IPSEC_IN message and prepend it. Otherwise,
17493 		 * just fanout.
17494 		 */
17495 
17496 		int ipsec_rc;
17497 		ipsec_in_t *ii;
17498 		netstack_t *ns = ipst->ips_netstack;
17499 
17500 		IP_STAT(ipst, ipsec_proto_ahesp);
17501 		if (!mctl_present) {
17502 			ASSERT(first_mp == mp);
17503 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17504 			if (first_mp == NULL) {
17505 				ip1dbg(("ip_proto_input: IPSEC_IN "
17506 				    "allocation failure.\n"));
17507 				freemsg(hada_mp); /* okay ifnull */
17508 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17509 				freemsg(mp);
17510 				return;
17511 			}
17512 			/*
17513 			 * Store the ill_index so that when we come back
17514 			 * from IPsec we ride on the same queue.
17515 			 */
17516 			ill = (ill_t *)q->q_ptr;
17517 			ii = (ipsec_in_t *)first_mp->b_rptr;
17518 			ii->ipsec_in_ill_index =
17519 			    ill->ill_phyint->phyint_ifindex;
17520 			ii->ipsec_in_rill_index =
17521 			    recv_ill->ill_phyint->phyint_ifindex;
17522 			first_mp->b_cont = mp;
17523 			/*
17524 			 * Cache hardware acceleration info.
17525 			 */
17526 			if (hada_mp != NULL) {
17527 				IPSECHW_DEBUG(IPSECHW_PKT,
17528 				    ("ip_rput_local: caching data attr.\n"));
17529 				ii->ipsec_in_accelerated = B_TRUE;
17530 				ii->ipsec_in_da = hada_mp;
17531 				hada_mp = NULL;
17532 			}
17533 		} else {
17534 			ii = (ipsec_in_t *)first_mp->b_rptr;
17535 		}
17536 
17537 		if (!ipsec_loaded(ipss)) {
17538 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17539 			    ire->ire_zoneid, ipst);
17540 			return;
17541 		}
17542 
17543 		ns = ipst->ips_netstack;
17544 		/* select inbound SA and have IPsec process the pkt */
17545 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17546 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17547 			boolean_t esp_in_udp_sa;
17548 			if (esph == NULL)
17549 				return;
17550 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17551 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17552 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17553 			    IPSA_F_NATT) != 0);
17554 			/*
17555 			 * The following is a fancy, but quick, way of saying:
17556 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17557 			 *    OR
17558 			 * ESP SA and ESP-in-UDP packet --> drop
17559 			 */
17560 			if (esp_in_udp_sa != esp_in_udp_packet) {
17561 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17562 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17563 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17564 				    &ns->netstack_ipsec->ipsec_dropper);
17565 				return;
17566 			}
17567 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17568 			    first_mp, esph);
17569 		} else {
17570 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17571 			if (ah == NULL)
17572 				return;
17573 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17574 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17575 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17576 			    first_mp, ah);
17577 		}
17578 
17579 		switch (ipsec_rc) {
17580 		case IPSEC_STATUS_SUCCESS:
17581 			break;
17582 		case IPSEC_STATUS_FAILED:
17583 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17584 			/* FALLTHRU */
17585 		case IPSEC_STATUS_PENDING:
17586 			return;
17587 		}
17588 		/* we're done with IPsec processing, send it up */
17589 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17590 		return;
17591 	}
17592 	default:
17593 		break;
17594 	}
17595 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17596 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17597 		    ire->ire_zoneid));
17598 		goto drop_pkt;
17599 	}
17600 	/*
17601 	 * Handle protocols with which IP is less intimate.  There
17602 	 * can be more than one stream bound to a particular
17603 	 * protocol.  When this is the case, each one gets a copy
17604 	 * of any incoming packets.
17605 	 */
17606 	ip_fanout_proto(q, first_mp, ill, ipha,
17607 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17608 	    B_TRUE, recv_ill, ire->ire_zoneid);
17609 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17610 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17611 	return;
17612 
17613 drop_pkt:
17614 	freemsg(first_mp);
17615 	if (hada_mp != NULL)
17616 		freeb(hada_mp);
17617 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17618 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17619 #undef	rptr
17620 #undef  iphs
17621 
17622 }
17623 
17624 /*
17625  * Update any source route, record route or timestamp options.
17626  * Check that we are at end of strict source route.
17627  * The options have already been checked for sanity in ip_rput_options().
17628  */
17629 static boolean_t
17630 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17631     ip_stack_t *ipst)
17632 {
17633 	ipoptp_t	opts;
17634 	uchar_t		*opt;
17635 	uint8_t		optval;
17636 	uint8_t		optlen;
17637 	ipaddr_t	dst;
17638 	uint32_t	ts;
17639 	ire_t		*dst_ire;
17640 	timestruc_t	now;
17641 	zoneid_t	zoneid;
17642 	ill_t		*ill;
17643 
17644 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17645 
17646 	ip2dbg(("ip_rput_local_options\n"));
17647 
17648 	for (optval = ipoptp_first(&opts, ipha);
17649 	    optval != IPOPT_EOL;
17650 	    optval = ipoptp_next(&opts)) {
17651 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17652 		opt = opts.ipoptp_cur;
17653 		optlen = opts.ipoptp_len;
17654 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17655 		    optval, optlen));
17656 		switch (optval) {
17657 			uint32_t off;
17658 		case IPOPT_SSRR:
17659 		case IPOPT_LSRR:
17660 			off = opt[IPOPT_OFFSET];
17661 			off--;
17662 			if (optlen < IP_ADDR_LEN ||
17663 			    off > optlen - IP_ADDR_LEN) {
17664 				/* End of source route */
17665 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17666 				break;
17667 			}
17668 			/*
17669 			 * This will only happen if two consecutive entries
17670 			 * in the source route contains our address or if
17671 			 * it is a packet with a loose source route which
17672 			 * reaches us before consuming the whole source route
17673 			 */
17674 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17675 			if (optval == IPOPT_SSRR) {
17676 				goto bad_src_route;
17677 			}
17678 			/*
17679 			 * Hack: instead of dropping the packet truncate the
17680 			 * source route to what has been used by filling the
17681 			 * rest with IPOPT_NOP.
17682 			 */
17683 			opt[IPOPT_OLEN] = (uint8_t)off;
17684 			while (off < optlen) {
17685 				opt[off++] = IPOPT_NOP;
17686 			}
17687 			break;
17688 		case IPOPT_RR:
17689 			off = opt[IPOPT_OFFSET];
17690 			off--;
17691 			if (optlen < IP_ADDR_LEN ||
17692 			    off > optlen - IP_ADDR_LEN) {
17693 				/* No more room - ignore */
17694 				ip1dbg((
17695 				    "ip_rput_local_options: end of RR\n"));
17696 				break;
17697 			}
17698 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17699 			    IP_ADDR_LEN);
17700 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17701 			break;
17702 		case IPOPT_TS:
17703 			/* Insert timestamp if there is romm */
17704 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17705 			case IPOPT_TS_TSONLY:
17706 				off = IPOPT_TS_TIMELEN;
17707 				break;
17708 			case IPOPT_TS_PRESPEC:
17709 			case IPOPT_TS_PRESPEC_RFC791:
17710 				/* Verify that the address matched */
17711 				off = opt[IPOPT_OFFSET] - 1;
17712 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17713 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17714 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17715 				    ipst);
17716 				if (dst_ire == NULL) {
17717 					/* Not for us */
17718 					break;
17719 				}
17720 				ire_refrele(dst_ire);
17721 				/* FALLTHRU */
17722 			case IPOPT_TS_TSANDADDR:
17723 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17724 				break;
17725 			default:
17726 				/*
17727 				 * ip_*put_options should have already
17728 				 * dropped this packet.
17729 				 */
17730 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17731 				    "unknown IT - bug in ip_rput_options?\n");
17732 				return (B_TRUE);	/* Keep "lint" happy */
17733 			}
17734 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17735 				/* Increase overflow counter */
17736 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17737 				opt[IPOPT_POS_OV_FLG] =
17738 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17739 				    (off << 4));
17740 				break;
17741 			}
17742 			off = opt[IPOPT_OFFSET] - 1;
17743 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17744 			case IPOPT_TS_PRESPEC:
17745 			case IPOPT_TS_PRESPEC_RFC791:
17746 			case IPOPT_TS_TSANDADDR:
17747 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17748 				    IP_ADDR_LEN);
17749 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17750 				/* FALLTHRU */
17751 			case IPOPT_TS_TSONLY:
17752 				off = opt[IPOPT_OFFSET] - 1;
17753 				/* Compute # of milliseconds since midnight */
17754 				gethrestime(&now);
17755 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17756 				    now.tv_nsec / (NANOSEC / MILLISEC);
17757 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17758 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17759 				break;
17760 			}
17761 			break;
17762 		}
17763 	}
17764 	return (B_TRUE);
17765 
17766 bad_src_route:
17767 	q = WR(q);
17768 	if (q->q_next != NULL)
17769 		ill = q->q_ptr;
17770 	else
17771 		ill = NULL;
17772 
17773 	/* make sure we clear any indication of a hardware checksum */
17774 	DB_CKSUMFLAGS(mp) = 0;
17775 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17776 	if (zoneid == ALL_ZONES)
17777 		freemsg(mp);
17778 	else
17779 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17780 	return (B_FALSE);
17781 
17782 }
17783 
17784 /*
17785  * Process IP options in an inbound packet.  If an option affects the
17786  * effective destination address, return the next hop address via dstp.
17787  * Returns -1 if something fails in which case an ICMP error has been sent
17788  * and mp freed.
17789  */
17790 static int
17791 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17792     ip_stack_t *ipst)
17793 {
17794 	ipoptp_t	opts;
17795 	uchar_t		*opt;
17796 	uint8_t		optval;
17797 	uint8_t		optlen;
17798 	ipaddr_t	dst;
17799 	intptr_t	code = 0;
17800 	ire_t		*ire = NULL;
17801 	zoneid_t	zoneid;
17802 	ill_t		*ill;
17803 
17804 	ip2dbg(("ip_rput_options\n"));
17805 	dst = ipha->ipha_dst;
17806 	for (optval = ipoptp_first(&opts, ipha);
17807 	    optval != IPOPT_EOL;
17808 	    optval = ipoptp_next(&opts)) {
17809 		opt = opts.ipoptp_cur;
17810 		optlen = opts.ipoptp_len;
17811 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17812 		    optval, optlen));
17813 		/*
17814 		 * Note: we need to verify the checksum before we
17815 		 * modify anything thus this routine only extracts the next
17816 		 * hop dst from any source route.
17817 		 */
17818 		switch (optval) {
17819 			uint32_t off;
17820 		case IPOPT_SSRR:
17821 		case IPOPT_LSRR:
17822 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17823 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17824 			if (ire == NULL) {
17825 				if (optval == IPOPT_SSRR) {
17826 					ip1dbg(("ip_rput_options: not next"
17827 					    " strict source route 0x%x\n",
17828 					    ntohl(dst)));
17829 					code = (char *)&ipha->ipha_dst -
17830 					    (char *)ipha;
17831 					goto param_prob; /* RouterReq's */
17832 				}
17833 				ip2dbg(("ip_rput_options: "
17834 				    "not next source route 0x%x\n",
17835 				    ntohl(dst)));
17836 				break;
17837 			}
17838 			ire_refrele(ire);
17839 
17840 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17841 				ip1dbg((
17842 				    "ip_rput_options: bad option offset\n"));
17843 				code = (char *)&opt[IPOPT_OLEN] -
17844 				    (char *)ipha;
17845 				goto param_prob;
17846 			}
17847 			off = opt[IPOPT_OFFSET];
17848 			off--;
17849 		redo_srr:
17850 			if (optlen < IP_ADDR_LEN ||
17851 			    off > optlen - IP_ADDR_LEN) {
17852 				/* End of source route */
17853 				ip1dbg(("ip_rput_options: end of SR\n"));
17854 				break;
17855 			}
17856 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17857 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17858 			    ntohl(dst)));
17859 
17860 			/*
17861 			 * Check if our address is present more than
17862 			 * once as consecutive hops in source route.
17863 			 * XXX verify per-interface ip_forwarding
17864 			 * for source route?
17865 			 */
17866 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17867 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17868 
17869 			if (ire != NULL) {
17870 				ire_refrele(ire);
17871 				off += IP_ADDR_LEN;
17872 				goto redo_srr;
17873 			}
17874 
17875 			if (dst == htonl(INADDR_LOOPBACK)) {
17876 				ip1dbg(("ip_rput_options: loopback addr in "
17877 				    "source route!\n"));
17878 				goto bad_src_route;
17879 			}
17880 			/*
17881 			 * For strict: verify that dst is directly
17882 			 * reachable.
17883 			 */
17884 			if (optval == IPOPT_SSRR) {
17885 				ire = ire_ftable_lookup(dst, 0, 0,
17886 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17887 				    MBLK_GETLABEL(mp),
17888 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17889 				if (ire == NULL) {
17890 					ip1dbg(("ip_rput_options: SSRR not "
17891 					    "directly reachable: 0x%x\n",
17892 					    ntohl(dst)));
17893 					goto bad_src_route;
17894 				}
17895 				ire_refrele(ire);
17896 			}
17897 			/*
17898 			 * Defer update of the offset and the record route
17899 			 * until the packet is forwarded.
17900 			 */
17901 			break;
17902 		case IPOPT_RR:
17903 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17904 				ip1dbg((
17905 				    "ip_rput_options: bad option offset\n"));
17906 				code = (char *)&opt[IPOPT_OLEN] -
17907 				    (char *)ipha;
17908 				goto param_prob;
17909 			}
17910 			break;
17911 		case IPOPT_TS:
17912 			/*
17913 			 * Verify that length >= 5 and that there is either
17914 			 * room for another timestamp or that the overflow
17915 			 * counter is not maxed out.
17916 			 */
17917 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17918 			if (optlen < IPOPT_MINLEN_IT) {
17919 				goto param_prob;
17920 			}
17921 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17922 				ip1dbg((
17923 				    "ip_rput_options: bad option offset\n"));
17924 				code = (char *)&opt[IPOPT_OFFSET] -
17925 				    (char *)ipha;
17926 				goto param_prob;
17927 			}
17928 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17929 			case IPOPT_TS_TSONLY:
17930 				off = IPOPT_TS_TIMELEN;
17931 				break;
17932 			case IPOPT_TS_TSANDADDR:
17933 			case IPOPT_TS_PRESPEC:
17934 			case IPOPT_TS_PRESPEC_RFC791:
17935 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17936 				break;
17937 			default:
17938 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17939 				    (char *)ipha;
17940 				goto param_prob;
17941 			}
17942 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17943 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17944 				/*
17945 				 * No room and the overflow counter is 15
17946 				 * already.
17947 				 */
17948 				goto param_prob;
17949 			}
17950 			break;
17951 		}
17952 	}
17953 
17954 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17955 		*dstp = dst;
17956 		return (0);
17957 	}
17958 
17959 	ip1dbg(("ip_rput_options: error processing IP options."));
17960 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17961 
17962 param_prob:
17963 	q = WR(q);
17964 	if (q->q_next != NULL)
17965 		ill = q->q_ptr;
17966 	else
17967 		ill = NULL;
17968 
17969 	/* make sure we clear any indication of a hardware checksum */
17970 	DB_CKSUMFLAGS(mp) = 0;
17971 	/* Don't know whether this is for non-global or global/forwarding */
17972 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17973 	if (zoneid == ALL_ZONES)
17974 		freemsg(mp);
17975 	else
17976 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
17977 	return (-1);
17978 
17979 bad_src_route:
17980 	q = WR(q);
17981 	if (q->q_next != NULL)
17982 		ill = q->q_ptr;
17983 	else
17984 		ill = NULL;
17985 
17986 	/* make sure we clear any indication of a hardware checksum */
17987 	DB_CKSUMFLAGS(mp) = 0;
17988 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
17989 	if (zoneid == ALL_ZONES)
17990 		freemsg(mp);
17991 	else
17992 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17993 	return (-1);
17994 }
17995 
17996 /*
17997  * IP & ICMP info in >=14 msg's ...
17998  *  - ip fixed part (mib2_ip_t)
17999  *  - icmp fixed part (mib2_icmp_t)
18000  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18001  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18002  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18003  *  - ipRouteAttributeTable (ip 102)	labeled routes
18004  *  - ip multicast membership (ip_member_t)
18005  *  - ip multicast source filtering (ip_grpsrc_t)
18006  *  - igmp fixed part (struct igmpstat)
18007  *  - multicast routing stats (struct mrtstat)
18008  *  - multicast routing vifs (array of struct vifctl)
18009  *  - multicast routing routes (array of struct mfcctl)
18010  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18011  *					One per ill plus one generic
18012  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18013  *					One per ill plus one generic
18014  *  - ipv6RouteEntry			all IPv6 IREs
18015  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18016  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18017  *  - ipv6AddrEntry			all IPv6 ipifs
18018  *  - ipv6 multicast membership (ipv6_member_t)
18019  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18020  *
18021  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18022  *
18023  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18024  * already filled in by the caller.
18025  * Return value of 0 indicates that no messages were sent and caller
18026  * should free mpctl.
18027  */
18028 int
18029 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18030 {
18031 	ip_stack_t *ipst;
18032 	sctp_stack_t *sctps;
18033 
18034 	if (q->q_next != NULL) {
18035 		ipst = ILLQ_TO_IPST(q);
18036 	} else {
18037 		ipst = CONNQ_TO_IPST(q);
18038 	}
18039 	ASSERT(ipst != NULL);
18040 	sctps = ipst->ips_netstack->netstack_sctp;
18041 
18042 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18043 		return (0);
18044 	}
18045 
18046 	/*
18047 	 * For the purposes of the (broken) packet shell use
18048 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18049 	 * to make TCP and UDP appear first in the list of mib items.
18050 	 * TBD: We could expand this and use it in netstat so that
18051 	 * the kernel doesn't have to produce large tables (connections,
18052 	 * routes, etc) when netstat only wants the statistics or a particular
18053 	 * table.
18054 	 */
18055 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18056 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18057 			return (1);
18058 		}
18059 	}
18060 
18061 	if (level != MIB2_TCP) {
18062 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18063 			return (1);
18064 		}
18065 	}
18066 
18067 	if (level != MIB2_UDP) {
18068 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18069 			return (1);
18070 		}
18071 	}
18072 
18073 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18074 	    ipst)) == NULL) {
18075 		return (1);
18076 	}
18077 
18078 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18079 		return (1);
18080 	}
18081 
18082 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18083 		return (1);
18084 	}
18085 
18086 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18087 		return (1);
18088 	}
18089 
18090 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18091 		return (1);
18092 	}
18093 
18094 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18095 		return (1);
18096 	}
18097 
18098 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18099 		return (1);
18100 	}
18101 
18102 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18103 		return (1);
18104 	}
18105 
18106 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18107 		return (1);
18108 	}
18109 
18110 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18111 		return (1);
18112 	}
18113 
18114 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18115 		return (1);
18116 	}
18117 
18118 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18119 		return (1);
18120 	}
18121 
18122 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18123 		return (1);
18124 	}
18125 
18126 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18127 		return (1);
18128 	}
18129 
18130 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18131 		return (1);
18132 	}
18133 
18134 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18135 	if (mpctl == NULL) {
18136 		return (1);
18137 	}
18138 
18139 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18140 		return (1);
18141 	}
18142 	freemsg(mpctl);
18143 	return (1);
18144 }
18145 
18146 
18147 /* Get global (legacy) IPv4 statistics */
18148 static mblk_t *
18149 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18150     ip_stack_t *ipst)
18151 {
18152 	mib2_ip_t		old_ip_mib;
18153 	struct opthdr		*optp;
18154 	mblk_t			*mp2ctl;
18155 
18156 	/*
18157 	 * make a copy of the original message
18158 	 */
18159 	mp2ctl = copymsg(mpctl);
18160 
18161 	/* fixed length IP structure... */
18162 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18163 	optp->level = MIB2_IP;
18164 	optp->name = 0;
18165 	SET_MIB(old_ip_mib.ipForwarding,
18166 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18167 	SET_MIB(old_ip_mib.ipDefaultTTL,
18168 	    (uint32_t)ipst->ips_ip_def_ttl);
18169 	SET_MIB(old_ip_mib.ipReasmTimeout,
18170 	    ipst->ips_ip_g_frag_timeout);
18171 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18172 	    sizeof (mib2_ipAddrEntry_t));
18173 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18174 	    sizeof (mib2_ipRouteEntry_t));
18175 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18176 	    sizeof (mib2_ipNetToMediaEntry_t));
18177 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18178 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18179 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18180 	    sizeof (mib2_ipAttributeEntry_t));
18181 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18182 
18183 	/*
18184 	 * Grab the statistics from the new IP MIB
18185 	 */
18186 	SET_MIB(old_ip_mib.ipInReceives,
18187 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18188 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18189 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18190 	SET_MIB(old_ip_mib.ipForwDatagrams,
18191 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18192 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18193 	    ipmib->ipIfStatsInUnknownProtos);
18194 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18195 	SET_MIB(old_ip_mib.ipInDelivers,
18196 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18197 	SET_MIB(old_ip_mib.ipOutRequests,
18198 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18199 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18200 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18201 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18202 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18203 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18204 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18205 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18206 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18207 
18208 	/* ipRoutingDiscards is not being used */
18209 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18210 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18211 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18212 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18213 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18214 	    ipmib->ipIfStatsReasmDuplicates);
18215 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18216 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18217 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18218 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18219 	SET_MIB(old_ip_mib.rawipInOverflows,
18220 	    ipmib->rawipIfStatsInOverflows);
18221 
18222 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18223 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18224 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18225 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18226 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18227 	    ipmib->ipIfStatsOutSwitchIPVersion);
18228 
18229 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18230 	    (int)sizeof (old_ip_mib))) {
18231 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18232 		    (uint_t)sizeof (old_ip_mib)));
18233 	}
18234 
18235 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18236 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18237 	    (int)optp->level, (int)optp->name, (int)optp->len));
18238 	qreply(q, mpctl);
18239 	return (mp2ctl);
18240 }
18241 
18242 /* Per interface IPv4 statistics */
18243 static mblk_t *
18244 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18245 {
18246 	struct opthdr		*optp;
18247 	mblk_t			*mp2ctl;
18248 	ill_t			*ill;
18249 	ill_walk_context_t	ctx;
18250 	mblk_t			*mp_tail = NULL;
18251 	mib2_ipIfStatsEntry_t	global_ip_mib;
18252 
18253 	/*
18254 	 * Make a copy of the original message
18255 	 */
18256 	mp2ctl = copymsg(mpctl);
18257 
18258 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18259 	optp->level = MIB2_IP;
18260 	optp->name = MIB2_IP_TRAFFIC_STATS;
18261 	/* Include "unknown interface" ip_mib */
18262 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18263 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18264 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18265 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18266 	    (ipst->ips_ip_g_forward ? 1 : 2));
18267 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18268 	    (uint32_t)ipst->ips_ip_def_ttl);
18269 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18270 	    sizeof (mib2_ipIfStatsEntry_t));
18271 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18272 	    sizeof (mib2_ipAddrEntry_t));
18273 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18274 	    sizeof (mib2_ipRouteEntry_t));
18275 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18276 	    sizeof (mib2_ipNetToMediaEntry_t));
18277 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18278 	    sizeof (ip_member_t));
18279 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18280 	    sizeof (ip_grpsrc_t));
18281 
18282 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18283 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18284 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18285 		    "failed to allocate %u bytes\n",
18286 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18287 	}
18288 
18289 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18290 
18291 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18292 	ill = ILL_START_WALK_V4(&ctx, ipst);
18293 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18294 		ill->ill_ip_mib->ipIfStatsIfIndex =
18295 		    ill->ill_phyint->phyint_ifindex;
18296 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18297 		    (ipst->ips_ip_g_forward ? 1 : 2));
18298 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18299 		    (uint32_t)ipst->ips_ip_def_ttl);
18300 
18301 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18302 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18303 		    (char *)ill->ill_ip_mib,
18304 		    (int)sizeof (*ill->ill_ip_mib))) {
18305 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18306 			    "failed to allocate %u bytes\n",
18307 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18308 		}
18309 	}
18310 	rw_exit(&ipst->ips_ill_g_lock);
18311 
18312 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18313 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18314 	    "level %d, name %d, len %d\n",
18315 	    (int)optp->level, (int)optp->name, (int)optp->len));
18316 	qreply(q, mpctl);
18317 
18318 	if (mp2ctl == NULL)
18319 		return (NULL);
18320 
18321 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18322 }
18323 
18324 /* Global IPv4 ICMP statistics */
18325 static mblk_t *
18326 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18327 {
18328 	struct opthdr		*optp;
18329 	mblk_t			*mp2ctl;
18330 
18331 	/*
18332 	 * Make a copy of the original message
18333 	 */
18334 	mp2ctl = copymsg(mpctl);
18335 
18336 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18337 	optp->level = MIB2_ICMP;
18338 	optp->name = 0;
18339 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18340 	    (int)sizeof (ipst->ips_icmp_mib))) {
18341 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18342 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18343 	}
18344 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18345 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18346 	    (int)optp->level, (int)optp->name, (int)optp->len));
18347 	qreply(q, mpctl);
18348 	return (mp2ctl);
18349 }
18350 
18351 /* Global IPv4 IGMP statistics */
18352 static mblk_t *
18353 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18354 {
18355 	struct opthdr		*optp;
18356 	mblk_t			*mp2ctl;
18357 
18358 	/*
18359 	 * make a copy of the original message
18360 	 */
18361 	mp2ctl = copymsg(mpctl);
18362 
18363 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18364 	optp->level = EXPER_IGMP;
18365 	optp->name = 0;
18366 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18367 	    (int)sizeof (ipst->ips_igmpstat))) {
18368 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18369 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18370 	}
18371 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18372 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18373 	    (int)optp->level, (int)optp->name, (int)optp->len));
18374 	qreply(q, mpctl);
18375 	return (mp2ctl);
18376 }
18377 
18378 /* Global IPv4 Multicast Routing statistics */
18379 static mblk_t *
18380 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18381 {
18382 	struct opthdr		*optp;
18383 	mblk_t			*mp2ctl;
18384 
18385 	/*
18386 	 * make a copy of the original message
18387 	 */
18388 	mp2ctl = copymsg(mpctl);
18389 
18390 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18391 	optp->level = EXPER_DVMRP;
18392 	optp->name = 0;
18393 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18394 		ip0dbg(("ip_mroute_stats: failed\n"));
18395 	}
18396 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18397 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18398 	    (int)optp->level, (int)optp->name, (int)optp->len));
18399 	qreply(q, mpctl);
18400 	return (mp2ctl);
18401 }
18402 
18403 /* IPv4 address information */
18404 static mblk_t *
18405 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18406 {
18407 	struct opthdr		*optp;
18408 	mblk_t			*mp2ctl;
18409 	mblk_t			*mp_tail = NULL;
18410 	ill_t			*ill;
18411 	ipif_t			*ipif;
18412 	uint_t			bitval;
18413 	mib2_ipAddrEntry_t	mae;
18414 	zoneid_t		zoneid;
18415 	ill_walk_context_t ctx;
18416 
18417 	/*
18418 	 * make a copy of the original message
18419 	 */
18420 	mp2ctl = copymsg(mpctl);
18421 
18422 	/* ipAddrEntryTable */
18423 
18424 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18425 	optp->level = MIB2_IP;
18426 	optp->name = MIB2_IP_ADDR;
18427 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18428 
18429 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18430 	ill = ILL_START_WALK_V4(&ctx, ipst);
18431 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18432 		for (ipif = ill->ill_ipif; ipif != NULL;
18433 		    ipif = ipif->ipif_next) {
18434 			if (ipif->ipif_zoneid != zoneid &&
18435 			    ipif->ipif_zoneid != ALL_ZONES)
18436 				continue;
18437 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18438 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18439 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18440 
18441 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18442 			    OCTET_LENGTH);
18443 			mae.ipAdEntIfIndex.o_length =
18444 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18445 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18446 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18447 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18448 			mae.ipAdEntInfo.ae_subnet_len =
18449 			    ip_mask_to_plen(ipif->ipif_net_mask);
18450 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18451 			for (bitval = 1;
18452 			    bitval &&
18453 			    !(bitval & ipif->ipif_brd_addr);
18454 			    bitval <<= 1)
18455 				noop;
18456 			mae.ipAdEntBcastAddr = bitval;
18457 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18458 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18459 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18460 			mae.ipAdEntInfo.ae_broadcast_addr =
18461 			    ipif->ipif_brd_addr;
18462 			mae.ipAdEntInfo.ae_pp_dst_addr =
18463 			    ipif->ipif_pp_dst_addr;
18464 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18465 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18466 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18467 
18468 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18469 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18470 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18471 				    "allocate %u bytes\n",
18472 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18473 			}
18474 		}
18475 	}
18476 	rw_exit(&ipst->ips_ill_g_lock);
18477 
18478 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18479 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18480 	    (int)optp->level, (int)optp->name, (int)optp->len));
18481 	qreply(q, mpctl);
18482 	return (mp2ctl);
18483 }
18484 
18485 /* IPv6 address information */
18486 static mblk_t *
18487 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18488 {
18489 	struct opthdr		*optp;
18490 	mblk_t			*mp2ctl;
18491 	mblk_t			*mp_tail = NULL;
18492 	ill_t			*ill;
18493 	ipif_t			*ipif;
18494 	mib2_ipv6AddrEntry_t	mae6;
18495 	zoneid_t		zoneid;
18496 	ill_walk_context_t	ctx;
18497 
18498 	/*
18499 	 * make a copy of the original message
18500 	 */
18501 	mp2ctl = copymsg(mpctl);
18502 
18503 	/* ipv6AddrEntryTable */
18504 
18505 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18506 	optp->level = MIB2_IP6;
18507 	optp->name = MIB2_IP6_ADDR;
18508 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18509 
18510 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18511 	ill = ILL_START_WALK_V6(&ctx, ipst);
18512 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18513 		for (ipif = ill->ill_ipif; ipif != NULL;
18514 		    ipif = ipif->ipif_next) {
18515 			if (ipif->ipif_zoneid != zoneid &&
18516 			    ipif->ipif_zoneid != ALL_ZONES)
18517 				continue;
18518 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18519 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18520 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18521 
18522 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18523 			    OCTET_LENGTH);
18524 			mae6.ipv6AddrIfIndex.o_length =
18525 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18526 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18527 			mae6.ipv6AddrPfxLength =
18528 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18529 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18530 			mae6.ipv6AddrInfo.ae_subnet_len =
18531 			    mae6.ipv6AddrPfxLength;
18532 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18533 
18534 			/* Type: stateless(1), stateful(2), unknown(3) */
18535 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18536 				mae6.ipv6AddrType = 1;
18537 			else
18538 				mae6.ipv6AddrType = 2;
18539 			/* Anycast: true(1), false(2) */
18540 			if (ipif->ipif_flags & IPIF_ANYCAST)
18541 				mae6.ipv6AddrAnycastFlag = 1;
18542 			else
18543 				mae6.ipv6AddrAnycastFlag = 2;
18544 
18545 			/*
18546 			 * Address status: preferred(1), deprecated(2),
18547 			 * invalid(3), inaccessible(4), unknown(5)
18548 			 */
18549 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18550 				mae6.ipv6AddrStatus = 3;
18551 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18552 				mae6.ipv6AddrStatus = 2;
18553 			else
18554 				mae6.ipv6AddrStatus = 1;
18555 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18556 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18557 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18558 			    ipif->ipif_v6pp_dst_addr;
18559 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18560 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18561 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18562 			mae6.ipv6AddrIdentifier = ill->ill_token;
18563 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18564 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18565 			mae6.ipv6AddrRetransmitTime =
18566 			    ill->ill_reachable_retrans_time;
18567 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18568 			    (char *)&mae6,
18569 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18570 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18571 				    "allocate %u bytes\n",
18572 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18573 			}
18574 		}
18575 	}
18576 	rw_exit(&ipst->ips_ill_g_lock);
18577 
18578 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18579 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18580 	    (int)optp->level, (int)optp->name, (int)optp->len));
18581 	qreply(q, mpctl);
18582 	return (mp2ctl);
18583 }
18584 
18585 /* IPv4 multicast group membership. */
18586 static mblk_t *
18587 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18588 {
18589 	struct opthdr		*optp;
18590 	mblk_t			*mp2ctl;
18591 	ill_t			*ill;
18592 	ipif_t			*ipif;
18593 	ilm_t			*ilm;
18594 	ip_member_t		ipm;
18595 	mblk_t			*mp_tail = NULL;
18596 	ill_walk_context_t	ctx;
18597 	zoneid_t		zoneid;
18598 
18599 	/*
18600 	 * make a copy of the original message
18601 	 */
18602 	mp2ctl = copymsg(mpctl);
18603 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18604 
18605 	/* ipGroupMember table */
18606 	optp = (struct opthdr *)&mpctl->b_rptr[
18607 	    sizeof (struct T_optmgmt_ack)];
18608 	optp->level = MIB2_IP;
18609 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18610 
18611 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18612 	ill = ILL_START_WALK_V4(&ctx, ipst);
18613 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18614 		ILM_WALKER_HOLD(ill);
18615 		for (ipif = ill->ill_ipif; ipif != NULL;
18616 		    ipif = ipif->ipif_next) {
18617 			if (ipif->ipif_zoneid != zoneid &&
18618 			    ipif->ipif_zoneid != ALL_ZONES)
18619 				continue;	/* not this zone */
18620 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18621 			    OCTET_LENGTH);
18622 			ipm.ipGroupMemberIfIndex.o_length =
18623 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18624 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18625 				ASSERT(ilm->ilm_ipif != NULL);
18626 				ASSERT(ilm->ilm_ill == NULL);
18627 				if (ilm->ilm_ipif != ipif)
18628 					continue;
18629 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18630 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18631 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18632 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18633 				    (char *)&ipm, (int)sizeof (ipm))) {
18634 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18635 					    "failed to allocate %u bytes\n",
18636 					    (uint_t)sizeof (ipm)));
18637 				}
18638 			}
18639 		}
18640 		ILM_WALKER_RELE(ill);
18641 	}
18642 	rw_exit(&ipst->ips_ill_g_lock);
18643 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18644 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18645 	    (int)optp->level, (int)optp->name, (int)optp->len));
18646 	qreply(q, mpctl);
18647 	return (mp2ctl);
18648 }
18649 
18650 /* IPv6 multicast group membership. */
18651 static mblk_t *
18652 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18653 {
18654 	struct opthdr		*optp;
18655 	mblk_t			*mp2ctl;
18656 	ill_t			*ill;
18657 	ilm_t			*ilm;
18658 	ipv6_member_t		ipm6;
18659 	mblk_t			*mp_tail = NULL;
18660 	ill_walk_context_t	ctx;
18661 	zoneid_t		zoneid;
18662 
18663 	/*
18664 	 * make a copy of the original message
18665 	 */
18666 	mp2ctl = copymsg(mpctl);
18667 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18668 
18669 	/* ip6GroupMember table */
18670 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18671 	optp->level = MIB2_IP6;
18672 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18673 
18674 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18675 	ill = ILL_START_WALK_V6(&ctx, ipst);
18676 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18677 		ILM_WALKER_HOLD(ill);
18678 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18679 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18680 			ASSERT(ilm->ilm_ipif == NULL);
18681 			ASSERT(ilm->ilm_ill != NULL);
18682 			if (ilm->ilm_zoneid != zoneid)
18683 				continue;	/* not this zone */
18684 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18685 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18686 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18687 			if (!snmp_append_data2(mpctl->b_cont,
18688 			    &mp_tail,
18689 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18690 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18691 				    "failed to allocate %u bytes\n",
18692 				    (uint_t)sizeof (ipm6)));
18693 			}
18694 		}
18695 		ILM_WALKER_RELE(ill);
18696 	}
18697 	rw_exit(&ipst->ips_ill_g_lock);
18698 
18699 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18700 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18701 	    (int)optp->level, (int)optp->name, (int)optp->len));
18702 	qreply(q, mpctl);
18703 	return (mp2ctl);
18704 }
18705 
18706 /* IP multicast filtered sources */
18707 static mblk_t *
18708 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18709 {
18710 	struct opthdr		*optp;
18711 	mblk_t			*mp2ctl;
18712 	ill_t			*ill;
18713 	ipif_t			*ipif;
18714 	ilm_t			*ilm;
18715 	ip_grpsrc_t		ips;
18716 	mblk_t			*mp_tail = NULL;
18717 	ill_walk_context_t	ctx;
18718 	zoneid_t		zoneid;
18719 	int			i;
18720 	slist_t			*sl;
18721 
18722 	/*
18723 	 * make a copy of the original message
18724 	 */
18725 	mp2ctl = copymsg(mpctl);
18726 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18727 
18728 	/* ipGroupSource table */
18729 	optp = (struct opthdr *)&mpctl->b_rptr[
18730 	    sizeof (struct T_optmgmt_ack)];
18731 	optp->level = MIB2_IP;
18732 	optp->name = EXPER_IP_GROUP_SOURCES;
18733 
18734 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18735 	ill = ILL_START_WALK_V4(&ctx, ipst);
18736 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18737 		ILM_WALKER_HOLD(ill);
18738 		for (ipif = ill->ill_ipif; ipif != NULL;
18739 		    ipif = ipif->ipif_next) {
18740 			if (ipif->ipif_zoneid != zoneid)
18741 				continue;	/* not this zone */
18742 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18743 			    OCTET_LENGTH);
18744 			ips.ipGroupSourceIfIndex.o_length =
18745 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18746 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18747 				ASSERT(ilm->ilm_ipif != NULL);
18748 				ASSERT(ilm->ilm_ill == NULL);
18749 				sl = ilm->ilm_filter;
18750 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18751 					continue;
18752 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18753 				for (i = 0; i < sl->sl_numsrc; i++) {
18754 					if (!IN6_IS_ADDR_V4MAPPED(
18755 					    &sl->sl_addr[i]))
18756 						continue;
18757 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18758 					    ips.ipGroupSourceAddress);
18759 					if (snmp_append_data2(mpctl->b_cont,
18760 					    &mp_tail, (char *)&ips,
18761 					    (int)sizeof (ips)) == 0) {
18762 						ip1dbg(("ip_snmp_get_mib2_"
18763 						    "ip_group_src: failed to "
18764 						    "allocate %u bytes\n",
18765 						    (uint_t)sizeof (ips)));
18766 					}
18767 				}
18768 			}
18769 		}
18770 		ILM_WALKER_RELE(ill);
18771 	}
18772 	rw_exit(&ipst->ips_ill_g_lock);
18773 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18774 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18775 	    (int)optp->level, (int)optp->name, (int)optp->len));
18776 	qreply(q, mpctl);
18777 	return (mp2ctl);
18778 }
18779 
18780 /* IPv6 multicast filtered sources. */
18781 static mblk_t *
18782 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18783 {
18784 	struct opthdr		*optp;
18785 	mblk_t			*mp2ctl;
18786 	ill_t			*ill;
18787 	ilm_t			*ilm;
18788 	ipv6_grpsrc_t		ips6;
18789 	mblk_t			*mp_tail = NULL;
18790 	ill_walk_context_t	ctx;
18791 	zoneid_t		zoneid;
18792 	int			i;
18793 	slist_t			*sl;
18794 
18795 	/*
18796 	 * make a copy of the original message
18797 	 */
18798 	mp2ctl = copymsg(mpctl);
18799 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18800 
18801 	/* ip6GroupMember table */
18802 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18803 	optp->level = MIB2_IP6;
18804 	optp->name = EXPER_IP6_GROUP_SOURCES;
18805 
18806 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18807 	ill = ILL_START_WALK_V6(&ctx, ipst);
18808 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18809 		ILM_WALKER_HOLD(ill);
18810 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18811 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18812 			ASSERT(ilm->ilm_ipif == NULL);
18813 			ASSERT(ilm->ilm_ill != NULL);
18814 			sl = ilm->ilm_filter;
18815 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18816 				continue;
18817 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18818 			for (i = 0; i < sl->sl_numsrc; i++) {
18819 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18820 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18821 				    (char *)&ips6, (int)sizeof (ips6))) {
18822 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18823 					    "group_src: failed to allocate "
18824 					    "%u bytes\n",
18825 					    (uint_t)sizeof (ips6)));
18826 				}
18827 			}
18828 		}
18829 		ILM_WALKER_RELE(ill);
18830 	}
18831 	rw_exit(&ipst->ips_ill_g_lock);
18832 
18833 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18834 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18835 	    (int)optp->level, (int)optp->name, (int)optp->len));
18836 	qreply(q, mpctl);
18837 	return (mp2ctl);
18838 }
18839 
18840 /* Multicast routing virtual interface table. */
18841 static mblk_t *
18842 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18843 {
18844 	struct opthdr		*optp;
18845 	mblk_t			*mp2ctl;
18846 
18847 	/*
18848 	 * make a copy of the original message
18849 	 */
18850 	mp2ctl = copymsg(mpctl);
18851 
18852 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18853 	optp->level = EXPER_DVMRP;
18854 	optp->name = EXPER_DVMRP_VIF;
18855 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18856 		ip0dbg(("ip_mroute_vif: failed\n"));
18857 	}
18858 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18859 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18860 	    (int)optp->level, (int)optp->name, (int)optp->len));
18861 	qreply(q, mpctl);
18862 	return (mp2ctl);
18863 }
18864 
18865 /* Multicast routing table. */
18866 static mblk_t *
18867 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18868 {
18869 	struct opthdr		*optp;
18870 	mblk_t			*mp2ctl;
18871 
18872 	/*
18873 	 * make a copy of the original message
18874 	 */
18875 	mp2ctl = copymsg(mpctl);
18876 
18877 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18878 	optp->level = EXPER_DVMRP;
18879 	optp->name = EXPER_DVMRP_MRT;
18880 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18881 		ip0dbg(("ip_mroute_mrt: failed\n"));
18882 	}
18883 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18884 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18885 	    (int)optp->level, (int)optp->name, (int)optp->len));
18886 	qreply(q, mpctl);
18887 	return (mp2ctl);
18888 }
18889 
18890 /*
18891  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18892  * in one IRE walk.
18893  */
18894 static mblk_t *
18895 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18896 {
18897 	struct opthdr	*optp;
18898 	mblk_t		*mp2ctl;	/* Returned */
18899 	mblk_t		*mp3ctl;	/* nettomedia */
18900 	mblk_t		*mp4ctl;	/* routeattrs */
18901 	iproutedata_t	ird;
18902 	zoneid_t	zoneid;
18903 
18904 	/*
18905 	 * make copies of the original message
18906 	 *	- mp2ctl is returned unchanged to the caller for his use
18907 	 *	- mpctl is sent upstream as ipRouteEntryTable
18908 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18909 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18910 	 */
18911 	mp2ctl = copymsg(mpctl);
18912 	mp3ctl = copymsg(mpctl);
18913 	mp4ctl = copymsg(mpctl);
18914 	if (mp3ctl == NULL || mp4ctl == NULL) {
18915 		freemsg(mp4ctl);
18916 		freemsg(mp3ctl);
18917 		freemsg(mp2ctl);
18918 		freemsg(mpctl);
18919 		return (NULL);
18920 	}
18921 
18922 	bzero(&ird, sizeof (ird));
18923 
18924 	ird.ird_route.lp_head = mpctl->b_cont;
18925 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18926 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18927 
18928 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18929 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18930 
18931 	/* ipRouteEntryTable in mpctl */
18932 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18933 	optp->level = MIB2_IP;
18934 	optp->name = MIB2_IP_ROUTE;
18935 	optp->len = msgdsize(ird.ird_route.lp_head);
18936 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18937 	    (int)optp->level, (int)optp->name, (int)optp->len));
18938 	qreply(q, mpctl);
18939 
18940 	/* ipNetToMediaEntryTable in mp3ctl */
18941 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18942 	optp->level = MIB2_IP;
18943 	optp->name = MIB2_IP_MEDIA;
18944 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18945 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18946 	    (int)optp->level, (int)optp->name, (int)optp->len));
18947 	qreply(q, mp3ctl);
18948 
18949 	/* ipRouteAttributeTable in mp4ctl */
18950 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18951 	optp->level = MIB2_IP;
18952 	optp->name = EXPER_IP_RTATTR;
18953 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18954 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18955 	    (int)optp->level, (int)optp->name, (int)optp->len));
18956 	if (optp->len == 0)
18957 		freemsg(mp4ctl);
18958 	else
18959 		qreply(q, mp4ctl);
18960 
18961 	return (mp2ctl);
18962 }
18963 
18964 /*
18965  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18966  * ipv6NetToMediaEntryTable in an NDP walk.
18967  */
18968 static mblk_t *
18969 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18970 {
18971 	struct opthdr	*optp;
18972 	mblk_t		*mp2ctl;	/* Returned */
18973 	mblk_t		*mp3ctl;	/* nettomedia */
18974 	mblk_t		*mp4ctl;	/* routeattrs */
18975 	iproutedata_t	ird;
18976 	zoneid_t	zoneid;
18977 
18978 	/*
18979 	 * make copies of the original message
18980 	 *	- mp2ctl is returned unchanged to the caller for his use
18981 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
18982 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
18983 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
18984 	 */
18985 	mp2ctl = copymsg(mpctl);
18986 	mp3ctl = copymsg(mpctl);
18987 	mp4ctl = copymsg(mpctl);
18988 	if (mp3ctl == NULL || mp4ctl == NULL) {
18989 		freemsg(mp4ctl);
18990 		freemsg(mp3ctl);
18991 		freemsg(mp2ctl);
18992 		freemsg(mpctl);
18993 		return (NULL);
18994 	}
18995 
18996 	bzero(&ird, sizeof (ird));
18997 
18998 	ird.ird_route.lp_head = mpctl->b_cont;
18999 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19000 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19001 
19002 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19003 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19004 
19005 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19006 	optp->level = MIB2_IP6;
19007 	optp->name = MIB2_IP6_ROUTE;
19008 	optp->len = msgdsize(ird.ird_route.lp_head);
19009 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19010 	    (int)optp->level, (int)optp->name, (int)optp->len));
19011 	qreply(q, mpctl);
19012 
19013 	/* ipv6NetToMediaEntryTable in mp3ctl */
19014 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19015 
19016 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19017 	optp->level = MIB2_IP6;
19018 	optp->name = MIB2_IP6_MEDIA;
19019 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19020 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19021 	    (int)optp->level, (int)optp->name, (int)optp->len));
19022 	qreply(q, mp3ctl);
19023 
19024 	/* ipv6RouteAttributeTable in mp4ctl */
19025 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19026 	optp->level = MIB2_IP6;
19027 	optp->name = EXPER_IP_RTATTR;
19028 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19029 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19030 	    (int)optp->level, (int)optp->name, (int)optp->len));
19031 	if (optp->len == 0)
19032 		freemsg(mp4ctl);
19033 	else
19034 		qreply(q, mp4ctl);
19035 
19036 	return (mp2ctl);
19037 }
19038 
19039 /*
19040  * IPv6 mib: One per ill
19041  */
19042 static mblk_t *
19043 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19044 {
19045 	struct opthdr		*optp;
19046 	mblk_t			*mp2ctl;
19047 	ill_t			*ill;
19048 	ill_walk_context_t	ctx;
19049 	mblk_t			*mp_tail = NULL;
19050 
19051 	/*
19052 	 * Make a copy of the original message
19053 	 */
19054 	mp2ctl = copymsg(mpctl);
19055 
19056 	/* fixed length IPv6 structure ... */
19057 
19058 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19059 	optp->level = MIB2_IP6;
19060 	optp->name = 0;
19061 	/* Include "unknown interface" ip6_mib */
19062 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19063 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19064 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19065 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19066 	    ipst->ips_ipv6_forward ? 1 : 2);
19067 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19068 	    ipst->ips_ipv6_def_hops);
19069 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19070 	    sizeof (mib2_ipIfStatsEntry_t));
19071 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19072 	    sizeof (mib2_ipv6AddrEntry_t));
19073 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19074 	    sizeof (mib2_ipv6RouteEntry_t));
19075 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19076 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19077 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19078 	    sizeof (ipv6_member_t));
19079 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19080 	    sizeof (ipv6_grpsrc_t));
19081 
19082 	/*
19083 	 * Synchronize 64- and 32-bit counters
19084 	 */
19085 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19086 	    ipIfStatsHCInReceives);
19087 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19088 	    ipIfStatsHCInDelivers);
19089 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19090 	    ipIfStatsHCOutRequests);
19091 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19092 	    ipIfStatsHCOutForwDatagrams);
19093 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19094 	    ipIfStatsHCOutMcastPkts);
19095 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19096 	    ipIfStatsHCInMcastPkts);
19097 
19098 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19099 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19100 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19101 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19102 	}
19103 
19104 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19105 	ill = ILL_START_WALK_V6(&ctx, ipst);
19106 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19107 		ill->ill_ip_mib->ipIfStatsIfIndex =
19108 		    ill->ill_phyint->phyint_ifindex;
19109 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19110 		    ipst->ips_ipv6_forward ? 1 : 2);
19111 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19112 		    ill->ill_max_hops);
19113 
19114 		/*
19115 		 * Synchronize 64- and 32-bit counters
19116 		 */
19117 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19118 		    ipIfStatsHCInReceives);
19119 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19120 		    ipIfStatsHCInDelivers);
19121 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19122 		    ipIfStatsHCOutRequests);
19123 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19124 		    ipIfStatsHCOutForwDatagrams);
19125 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19126 		    ipIfStatsHCOutMcastPkts);
19127 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19128 		    ipIfStatsHCInMcastPkts);
19129 
19130 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19131 		    (char *)ill->ill_ip_mib,
19132 		    (int)sizeof (*ill->ill_ip_mib))) {
19133 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19134 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19135 		}
19136 	}
19137 	rw_exit(&ipst->ips_ill_g_lock);
19138 
19139 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19140 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19141 	    (int)optp->level, (int)optp->name, (int)optp->len));
19142 	qreply(q, mpctl);
19143 	return (mp2ctl);
19144 }
19145 
19146 /*
19147  * ICMPv6 mib: One per ill
19148  */
19149 static mblk_t *
19150 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19151 {
19152 	struct opthdr		*optp;
19153 	mblk_t			*mp2ctl;
19154 	ill_t			*ill;
19155 	ill_walk_context_t	ctx;
19156 	mblk_t			*mp_tail = NULL;
19157 	/*
19158 	 * Make a copy of the original message
19159 	 */
19160 	mp2ctl = copymsg(mpctl);
19161 
19162 	/* fixed length ICMPv6 structure ... */
19163 
19164 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19165 	optp->level = MIB2_ICMP6;
19166 	optp->name = 0;
19167 	/* Include "unknown interface" icmp6_mib */
19168 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19169 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19170 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19171 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19172 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19173 	    (char *)&ipst->ips_icmp6_mib,
19174 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19175 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19176 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19177 	}
19178 
19179 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19180 	ill = ILL_START_WALK_V6(&ctx, ipst);
19181 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19182 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19183 		    ill->ill_phyint->phyint_ifindex;
19184 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19185 		    (char *)ill->ill_icmp6_mib,
19186 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19187 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19188 			    "%u bytes\n",
19189 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19190 		}
19191 	}
19192 	rw_exit(&ipst->ips_ill_g_lock);
19193 
19194 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19195 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19196 	    (int)optp->level, (int)optp->name, (int)optp->len));
19197 	qreply(q, mpctl);
19198 	return (mp2ctl);
19199 }
19200 
19201 /*
19202  * ire_walk routine to create both ipRouteEntryTable and
19203  * ipRouteAttributeTable in one IRE walk
19204  */
19205 static void
19206 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19207 {
19208 	ill_t				*ill;
19209 	ipif_t				*ipif;
19210 	mib2_ipRouteEntry_t		*re;
19211 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19212 	ipaddr_t			gw_addr;
19213 	tsol_ire_gw_secattr_t		*attrp;
19214 	tsol_gc_t			*gc = NULL;
19215 	tsol_gcgrp_t			*gcgrp = NULL;
19216 	uint_t				sacnt = 0;
19217 	int				i;
19218 
19219 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19220 
19221 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19222 		return;
19223 
19224 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19225 		mutex_enter(&attrp->igsa_lock);
19226 		if ((gc = attrp->igsa_gc) != NULL) {
19227 			gcgrp = gc->gc_grp;
19228 			ASSERT(gcgrp != NULL);
19229 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19230 			sacnt = 1;
19231 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19232 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19233 			gc = gcgrp->gcgrp_head;
19234 			sacnt = gcgrp->gcgrp_count;
19235 		}
19236 		mutex_exit(&attrp->igsa_lock);
19237 
19238 		/* do nothing if there's no gc to report */
19239 		if (gc == NULL) {
19240 			ASSERT(sacnt == 0);
19241 			if (gcgrp != NULL) {
19242 				/* we might as well drop the lock now */
19243 				rw_exit(&gcgrp->gcgrp_rwlock);
19244 				gcgrp = NULL;
19245 			}
19246 			attrp = NULL;
19247 		}
19248 
19249 		ASSERT(gc == NULL || (gcgrp != NULL &&
19250 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19251 	}
19252 	ASSERT(sacnt == 0 || gc != NULL);
19253 
19254 	if (sacnt != 0 &&
19255 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19256 		kmem_free(re, sizeof (*re));
19257 		rw_exit(&gcgrp->gcgrp_rwlock);
19258 		return;
19259 	}
19260 
19261 	/*
19262 	 * Return all IRE types for route table... let caller pick and choose
19263 	 */
19264 	re->ipRouteDest = ire->ire_addr;
19265 	ipif = ire->ire_ipif;
19266 	re->ipRouteIfIndex.o_length = 0;
19267 	if (ire->ire_type == IRE_CACHE) {
19268 		ill = (ill_t *)ire->ire_stq->q_ptr;
19269 		re->ipRouteIfIndex.o_length =
19270 		    ill->ill_name_length == 0 ? 0 :
19271 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19272 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19273 		    re->ipRouteIfIndex.o_length);
19274 	} else if (ipif != NULL) {
19275 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19276 		re->ipRouteIfIndex.o_length =
19277 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19278 	}
19279 	re->ipRouteMetric1 = -1;
19280 	re->ipRouteMetric2 = -1;
19281 	re->ipRouteMetric3 = -1;
19282 	re->ipRouteMetric4 = -1;
19283 
19284 	gw_addr = ire->ire_gateway_addr;
19285 
19286 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19287 		re->ipRouteNextHop = ire->ire_src_addr;
19288 	else
19289 		re->ipRouteNextHop = gw_addr;
19290 	/* indirect(4), direct(3), or invalid(2) */
19291 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19292 		re->ipRouteType = 2;
19293 	else
19294 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19295 	re->ipRouteProto = -1;
19296 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19297 	re->ipRouteMask = ire->ire_mask;
19298 	re->ipRouteMetric5 = -1;
19299 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19300 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19301 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19302 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19303 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19304 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19305 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19306 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19307 
19308 	if (ire->ire_flags & RTF_DYNAMIC) {
19309 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19310 	} else {
19311 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19312 	}
19313 
19314 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19315 	    (char *)re, (int)sizeof (*re))) {
19316 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19317 		    (uint_t)sizeof (*re)));
19318 	}
19319 
19320 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19321 		iaeptr->iae_routeidx = ird->ird_idx;
19322 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19323 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19324 	}
19325 
19326 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19327 	    (char *)iae, sacnt * sizeof (*iae))) {
19328 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19329 		    (unsigned)(sacnt * sizeof (*iae))));
19330 	}
19331 
19332 	/* bump route index for next pass */
19333 	ird->ird_idx++;
19334 
19335 	kmem_free(re, sizeof (*re));
19336 	if (sacnt != 0)
19337 		kmem_free(iae, sacnt * sizeof (*iae));
19338 
19339 	if (gcgrp != NULL)
19340 		rw_exit(&gcgrp->gcgrp_rwlock);
19341 }
19342 
19343 /*
19344  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19345  */
19346 static void
19347 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19348 {
19349 	ill_t				*ill;
19350 	ipif_t				*ipif;
19351 	mib2_ipv6RouteEntry_t		*re;
19352 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19353 	in6_addr_t			gw_addr_v6;
19354 	tsol_ire_gw_secattr_t		*attrp;
19355 	tsol_gc_t			*gc = NULL;
19356 	tsol_gcgrp_t			*gcgrp = NULL;
19357 	uint_t				sacnt = 0;
19358 	int				i;
19359 
19360 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19361 
19362 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19363 		return;
19364 
19365 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19366 		mutex_enter(&attrp->igsa_lock);
19367 		if ((gc = attrp->igsa_gc) != NULL) {
19368 			gcgrp = gc->gc_grp;
19369 			ASSERT(gcgrp != NULL);
19370 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19371 			sacnt = 1;
19372 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19373 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19374 			gc = gcgrp->gcgrp_head;
19375 			sacnt = gcgrp->gcgrp_count;
19376 		}
19377 		mutex_exit(&attrp->igsa_lock);
19378 
19379 		/* do nothing if there's no gc to report */
19380 		if (gc == NULL) {
19381 			ASSERT(sacnt == 0);
19382 			if (gcgrp != NULL) {
19383 				/* we might as well drop the lock now */
19384 				rw_exit(&gcgrp->gcgrp_rwlock);
19385 				gcgrp = NULL;
19386 			}
19387 			attrp = NULL;
19388 		}
19389 
19390 		ASSERT(gc == NULL || (gcgrp != NULL &&
19391 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19392 	}
19393 	ASSERT(sacnt == 0 || gc != NULL);
19394 
19395 	if (sacnt != 0 &&
19396 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19397 		kmem_free(re, sizeof (*re));
19398 		rw_exit(&gcgrp->gcgrp_rwlock);
19399 		return;
19400 	}
19401 
19402 	/*
19403 	 * Return all IRE types for route table... let caller pick and choose
19404 	 */
19405 	re->ipv6RouteDest = ire->ire_addr_v6;
19406 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19407 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19408 	re->ipv6RouteIfIndex.o_length = 0;
19409 	ipif = ire->ire_ipif;
19410 	if (ire->ire_type == IRE_CACHE) {
19411 		ill = (ill_t *)ire->ire_stq->q_ptr;
19412 		re->ipv6RouteIfIndex.o_length =
19413 		    ill->ill_name_length == 0 ? 0 :
19414 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19415 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19416 		    re->ipv6RouteIfIndex.o_length);
19417 	} else if (ipif != NULL) {
19418 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19419 		re->ipv6RouteIfIndex.o_length =
19420 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19421 	}
19422 
19423 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19424 
19425 	mutex_enter(&ire->ire_lock);
19426 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19427 	mutex_exit(&ire->ire_lock);
19428 
19429 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19430 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19431 	else
19432 		re->ipv6RouteNextHop = gw_addr_v6;
19433 
19434 	/* remote(4), local(3), or discard(2) */
19435 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19436 		re->ipv6RouteType = 2;
19437 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19438 		re->ipv6RouteType = 3;
19439 	else
19440 		re->ipv6RouteType = 4;
19441 
19442 	re->ipv6RouteProtocol	= -1;
19443 	re->ipv6RoutePolicy	= 0;
19444 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19445 	re->ipv6RouteNextHopRDI	= 0;
19446 	re->ipv6RouteWeight	= 0;
19447 	re->ipv6RouteMetric	= 0;
19448 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19449 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19450 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19451 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19452 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19453 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19454 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19455 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19456 
19457 	if (ire->ire_flags & RTF_DYNAMIC) {
19458 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19459 	} else {
19460 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19461 	}
19462 
19463 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19464 	    (char *)re, (int)sizeof (*re))) {
19465 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19466 		    (uint_t)sizeof (*re)));
19467 	}
19468 
19469 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19470 		iaeptr->iae_routeidx = ird->ird_idx;
19471 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19472 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19473 	}
19474 
19475 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19476 	    (char *)iae, sacnt * sizeof (*iae))) {
19477 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19478 		    (unsigned)(sacnt * sizeof (*iae))));
19479 	}
19480 
19481 	/* bump route index for next pass */
19482 	ird->ird_idx++;
19483 
19484 	kmem_free(re, sizeof (*re));
19485 	if (sacnt != 0)
19486 		kmem_free(iae, sacnt * sizeof (*iae));
19487 
19488 	if (gcgrp != NULL)
19489 		rw_exit(&gcgrp->gcgrp_rwlock);
19490 }
19491 
19492 /*
19493  * ndp_walk routine to create ipv6NetToMediaEntryTable
19494  */
19495 static int
19496 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19497 {
19498 	ill_t				*ill;
19499 	mib2_ipv6NetToMediaEntry_t	ntme;
19500 	dl_unitdata_req_t		*dl;
19501 
19502 	ill = nce->nce_ill;
19503 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19504 		return (0);
19505 
19506 	/*
19507 	 * Neighbor cache entry attached to IRE with on-link
19508 	 * destination.
19509 	 */
19510 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19511 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19512 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19513 	    (nce->nce_res_mp != NULL)) {
19514 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19515 		ntme.ipv6NetToMediaPhysAddress.o_length =
19516 		    dl->dl_dest_addr_length;
19517 	} else {
19518 		ntme.ipv6NetToMediaPhysAddress.o_length =
19519 		    ill->ill_phys_addr_length;
19520 	}
19521 	if (nce->nce_res_mp != NULL) {
19522 		bcopy((char *)nce->nce_res_mp->b_rptr +
19523 		    NCE_LL_ADDR_OFFSET(ill),
19524 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19525 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19526 	} else {
19527 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19528 		    ill->ill_phys_addr_length);
19529 	}
19530 	/*
19531 	 * Note: Returns ND_* states. Should be:
19532 	 * reachable(1), stale(2), delay(3), probe(4),
19533 	 * invalid(5), unknown(6)
19534 	 */
19535 	ntme.ipv6NetToMediaState = nce->nce_state;
19536 	ntme.ipv6NetToMediaLastUpdated = 0;
19537 
19538 	/* other(1), dynamic(2), static(3), local(4) */
19539 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19540 		ntme.ipv6NetToMediaType = 4;
19541 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19542 		ntme.ipv6NetToMediaType = 1;
19543 	} else {
19544 		ntme.ipv6NetToMediaType = 2;
19545 	}
19546 
19547 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19548 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19549 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19550 		    (uint_t)sizeof (ntme)));
19551 	}
19552 	return (0);
19553 }
19554 
19555 /*
19556  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19557  */
19558 /* ARGSUSED */
19559 int
19560 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19561 {
19562 	switch (level) {
19563 	case MIB2_IP:
19564 	case MIB2_ICMP:
19565 		switch (name) {
19566 		default:
19567 			break;
19568 		}
19569 		return (1);
19570 	default:
19571 		return (1);
19572 	}
19573 }
19574 
19575 /*
19576  * When there exists both a 64- and 32-bit counter of a particular type
19577  * (i.e., InReceives), only the 64-bit counters are added.
19578  */
19579 void
19580 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19581 {
19582 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19583 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19584 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19585 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19586 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19587 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19588 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19589 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19590 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19591 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19592 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19593 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19594 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19595 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19596 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19597 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19598 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19599 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19600 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19601 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19602 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19603 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19604 	    o2->ipIfStatsInWrongIPVersion);
19605 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19606 	    o2->ipIfStatsInWrongIPVersion);
19607 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19608 	    o2->ipIfStatsOutSwitchIPVersion);
19609 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19610 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19611 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19612 	    o2->ipIfStatsHCInForwDatagrams);
19613 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19614 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19615 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19616 	    o2->ipIfStatsHCOutForwDatagrams);
19617 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19618 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19619 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19620 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19621 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19622 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19623 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19624 	    o2->ipIfStatsHCOutMcastOctets);
19625 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19626 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19627 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19628 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19629 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19630 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19631 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19632 }
19633 
19634 void
19635 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19636 {
19637 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19638 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19639 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19640 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19641 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19642 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19643 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19644 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19645 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19646 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19647 	    o2->ipv6IfIcmpInRouterSolicits);
19648 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19649 	    o2->ipv6IfIcmpInRouterAdvertisements);
19650 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19651 	    o2->ipv6IfIcmpInNeighborSolicits);
19652 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19653 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19654 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19655 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19656 	    o2->ipv6IfIcmpInGroupMembQueries);
19657 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19658 	    o2->ipv6IfIcmpInGroupMembResponses);
19659 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19660 	    o2->ipv6IfIcmpInGroupMembReductions);
19661 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19662 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19663 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19664 	    o2->ipv6IfIcmpOutDestUnreachs);
19665 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19666 	    o2->ipv6IfIcmpOutAdminProhibs);
19667 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19668 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19669 	    o2->ipv6IfIcmpOutParmProblems);
19670 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19671 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19672 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19673 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19674 	    o2->ipv6IfIcmpOutRouterSolicits);
19675 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19676 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19677 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19678 	    o2->ipv6IfIcmpOutNeighborSolicits);
19679 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19680 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19681 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19682 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19683 	    o2->ipv6IfIcmpOutGroupMembQueries);
19684 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19685 	    o2->ipv6IfIcmpOutGroupMembResponses);
19686 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19687 	    o2->ipv6IfIcmpOutGroupMembReductions);
19688 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19689 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19690 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19691 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19692 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19693 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19694 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19695 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19696 	    o2->ipv6IfIcmpInGroupMembTotal);
19697 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19698 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19699 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19700 	    o2->ipv6IfIcmpInGroupMembBadReports);
19701 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19702 	    o2->ipv6IfIcmpInGroupMembOurReports);
19703 }
19704 
19705 /*
19706  * Called before the options are updated to check if this packet will
19707  * be source routed from here.
19708  * This routine assumes that the options are well formed i.e. that they
19709  * have already been checked.
19710  */
19711 static boolean_t
19712 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19713 {
19714 	ipoptp_t	opts;
19715 	uchar_t		*opt;
19716 	uint8_t		optval;
19717 	uint8_t		optlen;
19718 	ipaddr_t	dst;
19719 	ire_t		*ire;
19720 
19721 	if (IS_SIMPLE_IPH(ipha)) {
19722 		ip2dbg(("not source routed\n"));
19723 		return (B_FALSE);
19724 	}
19725 	dst = ipha->ipha_dst;
19726 	for (optval = ipoptp_first(&opts, ipha);
19727 	    optval != IPOPT_EOL;
19728 	    optval = ipoptp_next(&opts)) {
19729 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19730 		opt = opts.ipoptp_cur;
19731 		optlen = opts.ipoptp_len;
19732 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19733 		    optval, optlen));
19734 		switch (optval) {
19735 			uint32_t off;
19736 		case IPOPT_SSRR:
19737 		case IPOPT_LSRR:
19738 			/*
19739 			 * If dst is one of our addresses and there are some
19740 			 * entries left in the source route return (true).
19741 			 */
19742 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19743 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19744 			if (ire == NULL) {
19745 				ip2dbg(("ip_source_routed: not next"
19746 				    " source route 0x%x\n",
19747 				    ntohl(dst)));
19748 				return (B_FALSE);
19749 			}
19750 			ire_refrele(ire);
19751 			off = opt[IPOPT_OFFSET];
19752 			off--;
19753 			if (optlen < IP_ADDR_LEN ||
19754 			    off > optlen - IP_ADDR_LEN) {
19755 				/* End of source route */
19756 				ip1dbg(("ip_source_routed: end of SR\n"));
19757 				return (B_FALSE);
19758 			}
19759 			return (B_TRUE);
19760 		}
19761 	}
19762 	ip2dbg(("not source routed\n"));
19763 	return (B_FALSE);
19764 }
19765 
19766 /*
19767  * Check if the packet contains any source route.
19768  */
19769 static boolean_t
19770 ip_source_route_included(ipha_t *ipha)
19771 {
19772 	ipoptp_t	opts;
19773 	uint8_t		optval;
19774 
19775 	if (IS_SIMPLE_IPH(ipha))
19776 		return (B_FALSE);
19777 	for (optval = ipoptp_first(&opts, ipha);
19778 	    optval != IPOPT_EOL;
19779 	    optval = ipoptp_next(&opts)) {
19780 		switch (optval) {
19781 		case IPOPT_SSRR:
19782 		case IPOPT_LSRR:
19783 			return (B_TRUE);
19784 		}
19785 	}
19786 	return (B_FALSE);
19787 }
19788 
19789 /*
19790  * Called when the IRE expiration timer fires.
19791  */
19792 void
19793 ip_trash_timer_expire(void *args)
19794 {
19795 	int			flush_flag = 0;
19796 	ire_expire_arg_t	iea;
19797 	ip_stack_t		*ipst = (ip_stack_t *)args;
19798 
19799 	iea.iea_ipst = ipst;	/* No netstack_hold */
19800 
19801 	/*
19802 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19803 	 * This lock makes sure that a new invocation of this function
19804 	 * that occurs due to an almost immediate timer firing will not
19805 	 * progress beyond this point until the current invocation is done
19806 	 */
19807 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19808 	ipst->ips_ip_ire_expire_id = 0;
19809 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19810 
19811 	/* Periodic timer */
19812 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19813 	    ipst->ips_ip_ire_arp_interval) {
19814 		/*
19815 		 * Remove all IRE_CACHE entries since they might
19816 		 * contain arp information.
19817 		 */
19818 		flush_flag |= FLUSH_ARP_TIME;
19819 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19820 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19821 	}
19822 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19823 	    ipst->ips_ip_ire_redir_interval) {
19824 		/* Remove all redirects */
19825 		flush_flag |= FLUSH_REDIRECT_TIME;
19826 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19827 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19828 	}
19829 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19830 	    ipst->ips_ip_ire_pathmtu_interval) {
19831 		/* Increase path mtu */
19832 		flush_flag |= FLUSH_MTU_TIME;
19833 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19834 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19835 	}
19836 
19837 	/*
19838 	 * Optimize for the case when there are no redirects in the
19839 	 * ftable, that is, no need to walk the ftable in that case.
19840 	 */
19841 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19842 		iea.iea_flush_flag = flush_flag;
19843 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19844 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19845 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19846 		    NULL, ALL_ZONES, ipst);
19847 	}
19848 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19849 	    ipst->ips_ip_redirect_cnt > 0) {
19850 		iea.iea_flush_flag = flush_flag;
19851 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19852 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19853 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19854 	}
19855 	if (flush_flag & FLUSH_MTU_TIME) {
19856 		/*
19857 		 * Walk all IPv6 IRE's and update them
19858 		 * Note that ARP and redirect timers are not
19859 		 * needed since NUD handles stale entries.
19860 		 */
19861 		flush_flag = FLUSH_MTU_TIME;
19862 		iea.iea_flush_flag = flush_flag;
19863 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19864 		    ALL_ZONES, ipst);
19865 	}
19866 
19867 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19868 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19869 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19870 
19871 	/*
19872 	 * Hold the lock to serialize timeout calls and prevent
19873 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19874 	 * for the timer to fire and a new invocation of this function
19875 	 * to start before the return value of timeout has been stored
19876 	 * in ip_ire_expire_id by the current invocation.
19877 	 */
19878 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19879 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19880 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19881 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19882 }
19883 
19884 /*
19885  * Called by the memory allocator subsystem directly, when the system
19886  * is running low on memory.
19887  */
19888 /* ARGSUSED */
19889 void
19890 ip_trash_ire_reclaim(void *args)
19891 {
19892 	netstack_handle_t nh;
19893 	netstack_t *ns;
19894 
19895 	netstack_next_init(&nh);
19896 	while ((ns = netstack_next(&nh)) != NULL) {
19897 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19898 		netstack_rele(ns);
19899 	}
19900 	netstack_next_fini(&nh);
19901 }
19902 
19903 static void
19904 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19905 {
19906 	ire_cache_count_t icc;
19907 	ire_cache_reclaim_t icr;
19908 	ncc_cache_count_t ncc;
19909 	nce_cache_reclaim_t ncr;
19910 	uint_t delete_cnt;
19911 	/*
19912 	 * Memory reclaim call back.
19913 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19914 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19915 	 * entries, determine what fraction to free for
19916 	 * each category of IRE_CACHE entries giving absolute priority
19917 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19918 	 * entry will be freed unless all offlink entries are freed).
19919 	 */
19920 	icc.icc_total = 0;
19921 	icc.icc_unused = 0;
19922 	icc.icc_offlink = 0;
19923 	icc.icc_pmtu = 0;
19924 	icc.icc_onlink = 0;
19925 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19926 
19927 	/*
19928 	 * Free NCEs for IPv6 like the onlink ires.
19929 	 */
19930 	ncc.ncc_total = 0;
19931 	ncc.ncc_host = 0;
19932 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19933 
19934 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19935 	    icc.icc_pmtu + icc.icc_onlink);
19936 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19937 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19938 	if (delete_cnt == 0)
19939 		return;
19940 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19941 	/* Always delete all unused offlink entries */
19942 	icr.icr_ipst = ipst;
19943 	icr.icr_unused = 1;
19944 	if (delete_cnt <= icc.icc_unused) {
19945 		/*
19946 		 * Only need to free unused entries.  In other words,
19947 		 * there are enough unused entries to free to meet our
19948 		 * target number of freed ire cache entries.
19949 		 */
19950 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19951 		ncr.ncr_host = 0;
19952 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19953 		/*
19954 		 * Only need to free unused entries, plus a fraction of offlink
19955 		 * entries.  It follows from the first if statement that
19956 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19957 		 */
19958 		delete_cnt -= icc.icc_unused;
19959 		/* Round up # deleted by truncating fraction */
19960 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19961 		icr.icr_pmtu = icr.icr_onlink = 0;
19962 		ncr.ncr_host = 0;
19963 	} else if (delete_cnt <=
19964 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19965 		/*
19966 		 * Free all unused and offlink entries, plus a fraction of
19967 		 * pmtu entries.  It follows from the previous if statement
19968 		 * that icc_pmtu is non-zero, and that
19969 		 * delete_cnt != icc_unused + icc_offlink.
19970 		 */
19971 		icr.icr_offlink = 1;
19972 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
19973 		/* Round up # deleted by truncating fraction */
19974 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
19975 		icr.icr_onlink = 0;
19976 		ncr.ncr_host = 0;
19977 	} else {
19978 		/*
19979 		 * Free all unused, offlink, and pmtu entries, plus a fraction
19980 		 * of onlink entries.  If we're here, then we know that
19981 		 * icc_onlink is non-zero, and that
19982 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
19983 		 */
19984 		icr.icr_offlink = icr.icr_pmtu = 1;
19985 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
19986 		    icc.icc_pmtu;
19987 		/* Round up # deleted by truncating fraction */
19988 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
19989 		/* Using the same delete fraction as for onlink IREs */
19990 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
19991 	}
19992 #ifdef DEBUG
19993 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
19994 	    "fractions %d/%d/%d/%d\n",
19995 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
19996 	    icc.icc_unused, icc.icc_offlink,
19997 	    icc.icc_pmtu, icc.icc_onlink,
19998 	    icr.icr_unused, icr.icr_offlink,
19999 	    icr.icr_pmtu, icr.icr_onlink));
20000 #endif
20001 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20002 	if (ncr.ncr_host != 0)
20003 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20004 		    (uchar_t *)&ncr, ipst);
20005 #ifdef DEBUG
20006 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20007 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20008 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20009 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20010 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20011 	    icc.icc_pmtu, icc.icc_onlink));
20012 #endif
20013 }
20014 
20015 /*
20016  * ip_unbind is called when a copy of an unbind request is received from the
20017  * upper level protocol.  We remove this conn from any fanout hash list it is
20018  * on, and zero out the bind information.  No reply is expected up above.
20019  */
20020 mblk_t *
20021 ip_unbind(queue_t *q, mblk_t *mp)
20022 {
20023 	conn_t	*connp = Q_TO_CONN(q);
20024 
20025 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20026 
20027 	if (is_system_labeled() && connp->conn_anon_port) {
20028 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20029 		    connp->conn_mlp_type, connp->conn_ulp,
20030 		    ntohs(connp->conn_lport), B_FALSE);
20031 		connp->conn_anon_port = 0;
20032 	}
20033 	connp->conn_mlp_type = mlptSingle;
20034 
20035 	ipcl_hash_remove(connp);
20036 
20037 	ASSERT(mp->b_cont == NULL);
20038 	/*
20039 	 * Convert mp into a T_OK_ACK
20040 	 */
20041 	mp = mi_tpi_ok_ack_alloc(mp);
20042 
20043 	/*
20044 	 * should not happen in practice... T_OK_ACK is smaller than the
20045 	 * original message.
20046 	 */
20047 	if (mp == NULL)
20048 		return (NULL);
20049 
20050 	return (mp);
20051 }
20052 
20053 /*
20054  * Write side put procedure.  Outbound data, IOCTLs, responses from
20055  * resolvers, etc, come down through here.
20056  *
20057  * arg2 is always a queue_t *.
20058  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20059  * the zoneid.
20060  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20061  */
20062 void
20063 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20064 {
20065 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20066 }
20067 
20068 void
20069 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20070     ip_opt_info_t *infop)
20071 {
20072 	conn_t		*connp = NULL;
20073 	queue_t		*q = (queue_t *)arg2;
20074 	ipha_t		*ipha;
20075 #define	rptr	((uchar_t *)ipha)
20076 	ire_t		*ire = NULL;
20077 	ire_t		*sctp_ire = NULL;
20078 	uint32_t	v_hlen_tos_len;
20079 	ipaddr_t	dst;
20080 	mblk_t		*first_mp = NULL;
20081 	boolean_t	mctl_present;
20082 	ipsec_out_t	*io;
20083 	int		match_flags;
20084 	ill_t		*attach_ill = NULL;
20085 					/* Bind to IPIF_NOFAILOVER ill etc. */
20086 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20087 	ipif_t		*dst_ipif;
20088 	boolean_t	multirt_need_resolve = B_FALSE;
20089 	mblk_t		*copy_mp = NULL;
20090 	int		err;
20091 	zoneid_t	zoneid;
20092 	int	adjust;
20093 	uint16_t iplen;
20094 	boolean_t	need_decref = B_FALSE;
20095 	boolean_t	ignore_dontroute = B_FALSE;
20096 	boolean_t	ignore_nexthop = B_FALSE;
20097 	boolean_t	ip_nexthop = B_FALSE;
20098 	ipaddr_t	nexthop_addr;
20099 	ip_stack_t	*ipst;
20100 
20101 #ifdef	_BIG_ENDIAN
20102 #define	V_HLEN	(v_hlen_tos_len >> 24)
20103 #else
20104 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20105 #endif
20106 
20107 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20108 	    "ip_wput_start: q %p", q);
20109 
20110 	/*
20111 	 * ip_wput fast path
20112 	 */
20113 
20114 	/* is packet from ARP ? */
20115 	if (q->q_next != NULL) {
20116 		zoneid = (zoneid_t)(uintptr_t)arg;
20117 		goto qnext;
20118 	}
20119 
20120 	connp = (conn_t *)arg;
20121 	ASSERT(connp != NULL);
20122 	zoneid = connp->conn_zoneid;
20123 	ipst = connp->conn_netstack->netstack_ip;
20124 
20125 	/* is queue flow controlled? */
20126 	if ((q->q_first != NULL || connp->conn_draining) &&
20127 	    (caller == IP_WPUT)) {
20128 		ASSERT(!need_decref);
20129 		(void) putq(q, mp);
20130 		return;
20131 	}
20132 
20133 	/* Multidata transmit? */
20134 	if (DB_TYPE(mp) == M_MULTIDATA) {
20135 		/*
20136 		 * We should never get here, since all Multidata messages
20137 		 * originating from tcp should have been directed over to
20138 		 * tcp_multisend() in the first place.
20139 		 */
20140 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20141 		freemsg(mp);
20142 		return;
20143 	} else if (DB_TYPE(mp) != M_DATA)
20144 		goto notdata;
20145 
20146 	if (mp->b_flag & MSGHASREF) {
20147 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20148 		mp->b_flag &= ~MSGHASREF;
20149 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20150 		need_decref = B_TRUE;
20151 	}
20152 	ipha = (ipha_t *)mp->b_rptr;
20153 
20154 	/* is IP header non-aligned or mblk smaller than basic IP header */
20155 #ifndef SAFETY_BEFORE_SPEED
20156 	if (!OK_32PTR(rptr) ||
20157 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20158 		goto hdrtoosmall;
20159 #endif
20160 
20161 	ASSERT(OK_32PTR(ipha));
20162 
20163 	/*
20164 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20165 	 * wrong version, we'll catch it again in ip_output_v6.
20166 	 *
20167 	 * Note that this is *only* locally-generated output here, and never
20168 	 * forwarded data, and that we need to deal only with transports that
20169 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20170 	 * label.)
20171 	 */
20172 	if (is_system_labeled() &&
20173 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20174 	    !connp->conn_ulp_labeled) {
20175 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20176 		    connp->conn_mac_exempt, ipst);
20177 		ipha = (ipha_t *)mp->b_rptr;
20178 		if (err != 0) {
20179 			first_mp = mp;
20180 			if (err == EINVAL)
20181 				goto icmp_parameter_problem;
20182 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20183 			goto discard_pkt;
20184 		}
20185 		iplen = ntohs(ipha->ipha_length) + adjust;
20186 		ipha->ipha_length = htons(iplen);
20187 	}
20188 
20189 	ASSERT(infop != NULL);
20190 
20191 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20192 		/*
20193 		 * IP_PKTINFO ancillary option is present.
20194 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20195 		 * allows using address of any zone as the source address.
20196 		 */
20197 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20198 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20199 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20200 		if (ire == NULL)
20201 			goto drop_pkt;
20202 		ire_refrele(ire);
20203 		ire = NULL;
20204 	}
20205 
20206 	/*
20207 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20208 	 * passed in IP_PKTINFO.
20209 	 */
20210 	if (infop->ip_opt_ill_index != 0 &&
20211 	    connp->conn_outgoing_ill == NULL &&
20212 	    connp->conn_nofailover_ill == NULL) {
20213 
20214 		xmit_ill = ill_lookup_on_ifindex(
20215 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20216 		    ipst);
20217 
20218 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20219 			goto drop_pkt;
20220 		/*
20221 		 * check that there is an ipif belonging
20222 		 * to our zone. IPCL_ZONEID is not used because
20223 		 * IP_ALLZONES option is valid only when the ill is
20224 		 * accessible from all zones i.e has a valid ipif in
20225 		 * all zones.
20226 		 */
20227 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20228 			goto drop_pkt;
20229 		}
20230 	}
20231 
20232 	/*
20233 	 * If there is a policy, try to attach an ipsec_out in
20234 	 * the front. At the end, first_mp either points to a
20235 	 * M_DATA message or IPSEC_OUT message linked to a
20236 	 * M_DATA message. We have to do it now as we might
20237 	 * lose the "conn" if we go through ip_newroute.
20238 	 */
20239 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20240 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20241 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20242 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20243 			if (need_decref)
20244 				CONN_DEC_REF(connp);
20245 			return;
20246 		} else {
20247 			ASSERT(mp->b_datap->db_type == M_CTL);
20248 			first_mp = mp;
20249 			mp = mp->b_cont;
20250 			mctl_present = B_TRUE;
20251 		}
20252 	} else {
20253 		first_mp = mp;
20254 		mctl_present = B_FALSE;
20255 	}
20256 
20257 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20258 
20259 	/* is wrong version or IP options present */
20260 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20261 		goto version_hdrlen_check;
20262 	dst = ipha->ipha_dst;
20263 
20264 	if (connp->conn_nofailover_ill != NULL) {
20265 		attach_ill = conn_get_held_ill(connp,
20266 		    &connp->conn_nofailover_ill, &err);
20267 		if (err == ILL_LOOKUP_FAILED) {
20268 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20269 			if (need_decref)
20270 				CONN_DEC_REF(connp);
20271 			freemsg(first_mp);
20272 			return;
20273 		}
20274 	}
20275 
20276 	/* If IP_BOUND_IF has been set, use that ill. */
20277 	if (connp->conn_outgoing_ill != NULL) {
20278 		xmit_ill = conn_get_held_ill(connp,
20279 		    &connp->conn_outgoing_ill, &err);
20280 		if (err == ILL_LOOKUP_FAILED)
20281 			goto drop_pkt;
20282 
20283 		goto send_from_ill;
20284 	}
20285 
20286 	/* is packet multicast? */
20287 	if (CLASSD(dst))
20288 		goto multicast;
20289 
20290 	/*
20291 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20292 	 * takes precedence over conn_dontroute and conn_nexthop_set
20293 	 */
20294 	if (xmit_ill != NULL)
20295 		goto send_from_ill;
20296 
20297 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20298 		/*
20299 		 * If the destination is a broadcast, local, or loopback
20300 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20301 		 * standard path.
20302 		 */
20303 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20304 		if ((ire == NULL) || (ire->ire_type &
20305 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20306 			if (ire != NULL) {
20307 				ire_refrele(ire);
20308 				/* No more access to ire */
20309 				ire = NULL;
20310 			}
20311 			/*
20312 			 * bypass routing checks and go directly to interface.
20313 			 */
20314 			if (connp->conn_dontroute)
20315 				goto dontroute;
20316 
20317 			ASSERT(connp->conn_nexthop_set);
20318 			ip_nexthop = B_TRUE;
20319 			nexthop_addr = connp->conn_nexthop_v4;
20320 			goto send_from_ill;
20321 		}
20322 
20323 		/* Must be a broadcast, a loopback or a local ire */
20324 		ire_refrele(ire);
20325 		/* No more access to ire */
20326 		ire = NULL;
20327 	}
20328 
20329 	if (attach_ill != NULL)
20330 		goto send_from_ill;
20331 
20332 	/*
20333 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20334 	 * this for the tcp global queue and listen end point
20335 	 * as it does not really have a real destination to
20336 	 * talk to.  This is also true for SCTP.
20337 	 */
20338 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20339 	    !connp->conn_fully_bound) {
20340 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20341 		if (ire == NULL)
20342 			goto noirefound;
20343 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20344 		    "ip_wput_end: q %p (%S)", q, "end");
20345 
20346 		/*
20347 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20348 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20349 		 */
20350 		if (ire->ire_flags & RTF_MULTIRT) {
20351 
20352 			/*
20353 			 * Force the TTL of multirouted packets if required.
20354 			 * The TTL of such packets is bounded by the
20355 			 * ip_multirt_ttl ndd variable.
20356 			 */
20357 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20358 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20359 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20360 				    "(was %d), dst 0x%08x\n",
20361 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20362 				    ntohl(ire->ire_addr)));
20363 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20364 			}
20365 			/*
20366 			 * We look at this point if there are pending
20367 			 * unresolved routes. ire_multirt_resolvable()
20368 			 * checks in O(n) that all IRE_OFFSUBNET ire
20369 			 * entries for the packet's destination and
20370 			 * flagged RTF_MULTIRT are currently resolved.
20371 			 * If some remain unresolved, we make a copy
20372 			 * of the current message. It will be used
20373 			 * to initiate additional route resolutions.
20374 			 */
20375 			multirt_need_resolve =
20376 			    ire_multirt_need_resolve(ire->ire_addr,
20377 			    MBLK_GETLABEL(first_mp), ipst);
20378 			ip2dbg(("ip_wput[TCP]: ire %p, "
20379 			    "multirt_need_resolve %d, first_mp %p\n",
20380 			    (void *)ire, multirt_need_resolve,
20381 			    (void *)first_mp));
20382 			if (multirt_need_resolve) {
20383 				copy_mp = copymsg(first_mp);
20384 				if (copy_mp != NULL) {
20385 					MULTIRT_DEBUG_TAG(copy_mp);
20386 				}
20387 			}
20388 		}
20389 
20390 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20391 
20392 		/*
20393 		 * Try to resolve another multiroute if
20394 		 * ire_multirt_need_resolve() deemed it necessary.
20395 		 */
20396 		if (copy_mp != NULL)
20397 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20398 		if (need_decref)
20399 			CONN_DEC_REF(connp);
20400 		return;
20401 	}
20402 
20403 	/*
20404 	 * Access to conn_ire_cache. (protected by conn_lock)
20405 	 *
20406 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20407 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20408 	 * send a packet or two with the IRE_CACHE that is going away.
20409 	 * Access to the ire requires an ire refhold on the ire prior to
20410 	 * its use since an interface unplumb thread may delete the cached
20411 	 * ire and release the refhold at any time.
20412 	 *
20413 	 * Caching an ire in the conn_ire_cache
20414 	 *
20415 	 * o Caching an ire pointer in the conn requires a strict check for
20416 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20417 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20418 	 * in the conn is done after making sure under the bucket lock that the
20419 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20420 	 * caching an ire after the unplumb thread has cleaned up the conn.
20421 	 * If the conn does not send a packet subsequently the unplumb thread
20422 	 * will be hanging waiting for the ire count to drop to zero.
20423 	 *
20424 	 * o We also need to atomically test for a null conn_ire_cache and
20425 	 * set the conn_ire_cache under the the protection of the conn_lock
20426 	 * to avoid races among concurrent threads trying to simultaneously
20427 	 * cache an ire in the conn_ire_cache.
20428 	 */
20429 	mutex_enter(&connp->conn_lock);
20430 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20431 
20432 	if (ire != NULL && ire->ire_addr == dst &&
20433 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20434 
20435 		IRE_REFHOLD(ire);
20436 		mutex_exit(&connp->conn_lock);
20437 
20438 	} else {
20439 		boolean_t cached = B_FALSE;
20440 		connp->conn_ire_cache = NULL;
20441 		mutex_exit(&connp->conn_lock);
20442 		/* Release the old ire */
20443 		if (ire != NULL && sctp_ire == NULL)
20444 			IRE_REFRELE_NOTR(ire);
20445 
20446 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20447 		if (ire == NULL)
20448 			goto noirefound;
20449 		IRE_REFHOLD_NOTR(ire);
20450 
20451 		mutex_enter(&connp->conn_lock);
20452 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20453 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20454 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20455 				if (connp->conn_ulp == IPPROTO_TCP)
20456 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20457 				connp->conn_ire_cache = ire;
20458 				cached = B_TRUE;
20459 			}
20460 			rw_exit(&ire->ire_bucket->irb_lock);
20461 		}
20462 		mutex_exit(&connp->conn_lock);
20463 
20464 		/*
20465 		 * We can continue to use the ire but since it was
20466 		 * not cached, we should drop the extra reference.
20467 		 */
20468 		if (!cached)
20469 			IRE_REFRELE_NOTR(ire);
20470 	}
20471 
20472 
20473 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20474 	    "ip_wput_end: q %p (%S)", q, "end");
20475 
20476 	/*
20477 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20478 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20479 	 */
20480 	if (ire->ire_flags & RTF_MULTIRT) {
20481 
20482 		/*
20483 		 * Force the TTL of multirouted packets if required.
20484 		 * The TTL of such packets is bounded by the
20485 		 * ip_multirt_ttl ndd variable.
20486 		 */
20487 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20488 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20489 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20490 			    "(was %d), dst 0x%08x\n",
20491 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20492 			    ntohl(ire->ire_addr)));
20493 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20494 		}
20495 
20496 		/*
20497 		 * At this point, we check to see if there are any pending
20498 		 * unresolved routes. ire_multirt_resolvable()
20499 		 * checks in O(n) that all IRE_OFFSUBNET ire
20500 		 * entries for the packet's destination and
20501 		 * flagged RTF_MULTIRT are currently resolved.
20502 		 * If some remain unresolved, we make a copy
20503 		 * of the current message. It will be used
20504 		 * to initiate additional route resolutions.
20505 		 */
20506 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20507 		    MBLK_GETLABEL(first_mp), ipst);
20508 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20509 		    "multirt_need_resolve %d, first_mp %p\n",
20510 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20511 		if (multirt_need_resolve) {
20512 			copy_mp = copymsg(first_mp);
20513 			if (copy_mp != NULL) {
20514 				MULTIRT_DEBUG_TAG(copy_mp);
20515 			}
20516 		}
20517 	}
20518 
20519 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20520 
20521 	/*
20522 	 * Try to resolve another multiroute if
20523 	 * ire_multirt_resolvable() deemed it necessary
20524 	 */
20525 	if (copy_mp != NULL)
20526 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20527 	if (need_decref)
20528 		CONN_DEC_REF(connp);
20529 	return;
20530 
20531 qnext:
20532 	/*
20533 	 * Upper Level Protocols pass down complete IP datagrams
20534 	 * as M_DATA messages.	Everything else is a sideshow.
20535 	 *
20536 	 * 1) We could be re-entering ip_wput because of ip_neworute
20537 	 *    in which case we could have a IPSEC_OUT message. We
20538 	 *    need to pass through ip_wput like other datagrams and
20539 	 *    hence cannot branch to ip_wput_nondata.
20540 	 *
20541 	 * 2) ARP, AH, ESP, and other clients who are on the module
20542 	 *    instance of IP stream, give us something to deal with.
20543 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20544 	 *
20545 	 * 3) ICMP replies also could come here.
20546 	 */
20547 	ipst = ILLQ_TO_IPST(q);
20548 
20549 	if (DB_TYPE(mp) != M_DATA) {
20550 notdata:
20551 		if (DB_TYPE(mp) == M_CTL) {
20552 			/*
20553 			 * M_CTL messages are used by ARP, AH and ESP to
20554 			 * communicate with IP. We deal with IPSEC_IN and
20555 			 * IPSEC_OUT here. ip_wput_nondata handles other
20556 			 * cases.
20557 			 */
20558 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20559 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20560 				first_mp = mp->b_cont;
20561 				first_mp->b_flag &= ~MSGHASREF;
20562 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20563 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20564 				CONN_DEC_REF(connp);
20565 				connp = NULL;
20566 			}
20567 			if (ii->ipsec_info_type == IPSEC_IN) {
20568 				/*
20569 				 * Either this message goes back to
20570 				 * IPsec for further processing or to
20571 				 * ULP after policy checks.
20572 				 */
20573 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20574 				return;
20575 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20576 				io = (ipsec_out_t *)ii;
20577 				if (io->ipsec_out_proc_begin) {
20578 					/*
20579 					 * IPsec processing has already started.
20580 					 * Complete it.
20581 					 * IPQoS notes: We don't care what is
20582 					 * in ipsec_out_ill_index since this
20583 					 * won't be processed for IPQoS policies
20584 					 * in ipsec_out_process.
20585 					 */
20586 					ipsec_out_process(q, mp, NULL,
20587 					    io->ipsec_out_ill_index);
20588 					return;
20589 				} else {
20590 					connp = (q->q_next != NULL) ?
20591 					    NULL : Q_TO_CONN(q);
20592 					first_mp = mp;
20593 					mp = mp->b_cont;
20594 					mctl_present = B_TRUE;
20595 				}
20596 				zoneid = io->ipsec_out_zoneid;
20597 				ASSERT(zoneid != ALL_ZONES);
20598 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20599 				/*
20600 				 * It's an IPsec control message requesting
20601 				 * an SADB update to be sent to the IPsec
20602 				 * hardware acceleration capable ills.
20603 				 */
20604 				ipsec_ctl_t *ipsec_ctl =
20605 				    (ipsec_ctl_t *)mp->b_rptr;
20606 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20607 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20608 				mblk_t *cmp = mp->b_cont;
20609 
20610 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20611 				ASSERT(cmp != NULL);
20612 
20613 				freeb(mp);
20614 				ill_ipsec_capab_send_all(satype, cmp, sa,
20615 				    ipst->ips_netstack);
20616 				return;
20617 			} else {
20618 				/*
20619 				 * This must be ARP or special TSOL signaling.
20620 				 */
20621 				ip_wput_nondata(NULL, q, mp, NULL);
20622 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20623 				    "ip_wput_end: q %p (%S)", q, "nondata");
20624 				return;
20625 			}
20626 		} else {
20627 			/*
20628 			 * This must be non-(ARP/AH/ESP) messages.
20629 			 */
20630 			ASSERT(!need_decref);
20631 			ip_wput_nondata(NULL, q, mp, NULL);
20632 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20633 			    "ip_wput_end: q %p (%S)", q, "nondata");
20634 			return;
20635 		}
20636 	} else {
20637 		first_mp = mp;
20638 		mctl_present = B_FALSE;
20639 	}
20640 
20641 	ASSERT(first_mp != NULL);
20642 	/*
20643 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20644 	 * to make sure that this packet goes out on the same interface it
20645 	 * came in. We handle that here.
20646 	 */
20647 	if (mctl_present) {
20648 		uint_t ifindex;
20649 
20650 		io = (ipsec_out_t *)first_mp->b_rptr;
20651 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20652 			/*
20653 			 * We may have lost the conn context if we are
20654 			 * coming here from ip_newroute(). Copy the
20655 			 * nexthop information.
20656 			 */
20657 			if (io->ipsec_out_ip_nexthop) {
20658 				ip_nexthop = B_TRUE;
20659 				nexthop_addr = io->ipsec_out_nexthop_addr;
20660 
20661 				ipha = (ipha_t *)mp->b_rptr;
20662 				dst = ipha->ipha_dst;
20663 				goto send_from_ill;
20664 			} else {
20665 				ASSERT(io->ipsec_out_ill_index != 0);
20666 				ifindex = io->ipsec_out_ill_index;
20667 				attach_ill = ill_lookup_on_ifindex(ifindex,
20668 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20669 				if (attach_ill == NULL) {
20670 					ASSERT(xmit_ill == NULL);
20671 					ip1dbg(("ip_output: bad ifindex for "
20672 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20673 					    ifindex));
20674 					freemsg(first_mp);
20675 					BUMP_MIB(&ipst->ips_ip_mib,
20676 					    ipIfStatsOutDiscards);
20677 					ASSERT(!need_decref);
20678 					return;
20679 				}
20680 			}
20681 		}
20682 	}
20683 
20684 	ASSERT(xmit_ill == NULL);
20685 
20686 	/* We have a complete IP datagram heading outbound. */
20687 	ipha = (ipha_t *)mp->b_rptr;
20688 
20689 #ifndef SPEED_BEFORE_SAFETY
20690 	/*
20691 	 * Make sure we have a full-word aligned message and that at least
20692 	 * a simple IP header is accessible in the first message.  If not,
20693 	 * try a pullup.
20694 	 */
20695 	if (!OK_32PTR(rptr) ||
20696 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20697 hdrtoosmall:
20698 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20699 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20700 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20701 			if (first_mp == NULL)
20702 				first_mp = mp;
20703 			goto discard_pkt;
20704 		}
20705 
20706 		/* This function assumes that mp points to an IPv4 packet. */
20707 		if (is_system_labeled() && q->q_next == NULL &&
20708 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20709 		    !connp->conn_ulp_labeled) {
20710 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20711 			    &adjust, connp->conn_mac_exempt, ipst);
20712 			ipha = (ipha_t *)mp->b_rptr;
20713 			if (first_mp != NULL)
20714 				first_mp->b_cont = mp;
20715 			if (err != 0) {
20716 				if (first_mp == NULL)
20717 					first_mp = mp;
20718 				if (err == EINVAL)
20719 					goto icmp_parameter_problem;
20720 				ip2dbg(("ip_wput: label check failed (%d)\n",
20721 				    err));
20722 				goto discard_pkt;
20723 			}
20724 			iplen = ntohs(ipha->ipha_length) + adjust;
20725 			ipha->ipha_length = htons(iplen);
20726 		}
20727 
20728 		ipha = (ipha_t *)mp->b_rptr;
20729 		if (first_mp == NULL) {
20730 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20731 			/*
20732 			 * If we got here because of "goto hdrtoosmall"
20733 			 * We need to attach a IPSEC_OUT.
20734 			 */
20735 			if (connp->conn_out_enforce_policy) {
20736 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20737 				    NULL, ipha->ipha_protocol,
20738 				    ipst->ips_netstack)) == NULL)) {
20739 					BUMP_MIB(&ipst->ips_ip_mib,
20740 					    ipIfStatsOutDiscards);
20741 					if (need_decref)
20742 						CONN_DEC_REF(connp);
20743 					return;
20744 				} else {
20745 					ASSERT(mp->b_datap->db_type == M_CTL);
20746 					first_mp = mp;
20747 					mp = mp->b_cont;
20748 					mctl_present = B_TRUE;
20749 				}
20750 			} else {
20751 				first_mp = mp;
20752 				mctl_present = B_FALSE;
20753 			}
20754 		}
20755 	}
20756 #endif
20757 
20758 	/* Most of the code below is written for speed, not readability */
20759 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20760 
20761 	/*
20762 	 * If ip_newroute() fails, we're going to need a full
20763 	 * header for the icmp wraparound.
20764 	 */
20765 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20766 		uint_t	v_hlen;
20767 version_hdrlen_check:
20768 		ASSERT(first_mp != NULL);
20769 		v_hlen = V_HLEN;
20770 		/*
20771 		 * siphon off IPv6 packets coming down from transport
20772 		 * layer modules here.
20773 		 * Note: high-order bit carries NUD reachability confirmation
20774 		 */
20775 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20776 			/*
20777 			 * FIXME: assume that callers of ip_output* call
20778 			 * the right version?
20779 			 */
20780 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20781 			ASSERT(xmit_ill == NULL);
20782 			if (attach_ill != NULL)
20783 				ill_refrele(attach_ill);
20784 			if (need_decref)
20785 				mp->b_flag |= MSGHASREF;
20786 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20787 			return;
20788 		}
20789 
20790 		if ((v_hlen >> 4) != IP_VERSION) {
20791 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20792 			    "ip_wput_end: q %p (%S)", q, "badvers");
20793 			goto discard_pkt;
20794 		}
20795 		/*
20796 		 * Is the header length at least 20 bytes?
20797 		 *
20798 		 * Are there enough bytes accessible in the header?  If
20799 		 * not, try a pullup.
20800 		 */
20801 		v_hlen &= 0xF;
20802 		v_hlen <<= 2;
20803 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20804 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20805 			    "ip_wput_end: q %p (%S)", q, "badlen");
20806 			goto discard_pkt;
20807 		}
20808 		if (v_hlen > (mp->b_wptr - rptr)) {
20809 			if (!pullupmsg(mp, v_hlen)) {
20810 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20811 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20812 				goto discard_pkt;
20813 			}
20814 			ipha = (ipha_t *)mp->b_rptr;
20815 		}
20816 		/*
20817 		 * Move first entry from any source route into ipha_dst and
20818 		 * verify the options
20819 		 */
20820 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20821 		    zoneid, ipst)) {
20822 			ASSERT(xmit_ill == NULL);
20823 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20824 			if (attach_ill != NULL)
20825 				ill_refrele(attach_ill);
20826 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20827 			    "ip_wput_end: q %p (%S)", q, "badopts");
20828 			if (need_decref)
20829 				CONN_DEC_REF(connp);
20830 			return;
20831 		}
20832 	}
20833 	dst = ipha->ipha_dst;
20834 
20835 	/*
20836 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20837 	 * we have to run the packet through ip_newroute which will take
20838 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20839 	 * a resolver, or assigning a default gateway, etc.
20840 	 */
20841 	if (CLASSD(dst)) {
20842 		ipif_t	*ipif;
20843 		uint32_t setsrc = 0;
20844 
20845 multicast:
20846 		ASSERT(first_mp != NULL);
20847 		ip2dbg(("ip_wput: CLASSD\n"));
20848 		if (connp == NULL) {
20849 			/*
20850 			 * Use the first good ipif on the ill.
20851 			 * XXX Should this ever happen? (Appears
20852 			 * to show up with just ppp and no ethernet due
20853 			 * to in.rdisc.)
20854 			 * However, ire_send should be able to
20855 			 * call ip_wput_ire directly.
20856 			 *
20857 			 * XXX Also, this can happen for ICMP and other packets
20858 			 * with multicast source addresses.  Perhaps we should
20859 			 * fix things so that we drop the packet in question,
20860 			 * but for now, just run with it.
20861 			 */
20862 			ill_t *ill = (ill_t *)q->q_ptr;
20863 
20864 			/*
20865 			 * Don't honor attach_if for this case. If ill
20866 			 * is part of the group, ipif could belong to
20867 			 * any ill and we cannot maintain attach_ill
20868 			 * and ipif_ill same anymore and the assert
20869 			 * below would fail.
20870 			 */
20871 			if (mctl_present && io->ipsec_out_attach_if) {
20872 				io->ipsec_out_ill_index = 0;
20873 				io->ipsec_out_attach_if = B_FALSE;
20874 				ASSERT(attach_ill != NULL);
20875 				ill_refrele(attach_ill);
20876 				attach_ill = NULL;
20877 			}
20878 
20879 			ASSERT(attach_ill == NULL);
20880 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20881 			if (ipif == NULL) {
20882 				if (need_decref)
20883 					CONN_DEC_REF(connp);
20884 				freemsg(first_mp);
20885 				return;
20886 			}
20887 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20888 			    ntohl(dst), ill->ill_name));
20889 		} else {
20890 			/*
20891 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20892 			 * and IP_MULTICAST_IF.  The block comment above this
20893 			 * function explains the locking mechanism used here.
20894 			 */
20895 			if (xmit_ill == NULL) {
20896 				xmit_ill = conn_get_held_ill(connp,
20897 				    &connp->conn_outgoing_ill, &err);
20898 				if (err == ILL_LOOKUP_FAILED) {
20899 					ip1dbg(("ip_wput: No ill for "
20900 					    "IP_BOUND_IF\n"));
20901 					BUMP_MIB(&ipst->ips_ip_mib,
20902 					    ipIfStatsOutNoRoutes);
20903 					goto drop_pkt;
20904 				}
20905 			}
20906 
20907 			if (xmit_ill == NULL) {
20908 				ipif = conn_get_held_ipif(connp,
20909 				    &connp->conn_multicast_ipif, &err);
20910 				if (err == IPIF_LOOKUP_FAILED) {
20911 					ip1dbg(("ip_wput: No ipif for "
20912 					    "multicast\n"));
20913 					BUMP_MIB(&ipst->ips_ip_mib,
20914 					    ipIfStatsOutNoRoutes);
20915 					goto drop_pkt;
20916 				}
20917 			}
20918 			if (xmit_ill != NULL) {
20919 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20920 				if (ipif == NULL) {
20921 					ip1dbg(("ip_wput: No ipif for "
20922 					    "xmit_ill\n"));
20923 					BUMP_MIB(&ipst->ips_ip_mib,
20924 					    ipIfStatsOutNoRoutes);
20925 					goto drop_pkt;
20926 				}
20927 			} else if (ipif == NULL || ipif->ipif_isv6) {
20928 				/*
20929 				 * We must do this ipif determination here
20930 				 * else we could pass through ip_newroute
20931 				 * and come back here without the conn context.
20932 				 *
20933 				 * Note: we do late binding i.e. we bind to
20934 				 * the interface when the first packet is sent.
20935 				 * For performance reasons we do not rebind on
20936 				 * each packet but keep the binding until the
20937 				 * next IP_MULTICAST_IF option.
20938 				 *
20939 				 * conn_multicast_{ipif,ill} are shared between
20940 				 * IPv4 and IPv6 and AF_INET6 sockets can
20941 				 * send both IPv4 and IPv6 packets. Hence
20942 				 * we have to check that "isv6" matches above.
20943 				 */
20944 				if (ipif != NULL)
20945 					ipif_refrele(ipif);
20946 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20947 				if (ipif == NULL) {
20948 					ip1dbg(("ip_wput: No ipif for "
20949 					    "multicast\n"));
20950 					BUMP_MIB(&ipst->ips_ip_mib,
20951 					    ipIfStatsOutNoRoutes);
20952 					goto drop_pkt;
20953 				}
20954 				err = conn_set_held_ipif(connp,
20955 				    &connp->conn_multicast_ipif, ipif);
20956 				if (err == IPIF_LOOKUP_FAILED) {
20957 					ipif_refrele(ipif);
20958 					ip1dbg(("ip_wput: No ipif for "
20959 					    "multicast\n"));
20960 					BUMP_MIB(&ipst->ips_ip_mib,
20961 					    ipIfStatsOutNoRoutes);
20962 					goto drop_pkt;
20963 				}
20964 			}
20965 		}
20966 		ASSERT(!ipif->ipif_isv6);
20967 		/*
20968 		 * As we may lose the conn by the time we reach ip_wput_ire,
20969 		 * we copy conn_multicast_loop and conn_dontroute on to an
20970 		 * ipsec_out. In case if this datagram goes out secure,
20971 		 * we need the ill_index also. Copy that also into the
20972 		 * ipsec_out.
20973 		 */
20974 		if (mctl_present) {
20975 			io = (ipsec_out_t *)first_mp->b_rptr;
20976 			ASSERT(first_mp->b_datap->db_type == M_CTL);
20977 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
20978 		} else {
20979 			ASSERT(mp == first_mp);
20980 			if ((first_mp = allocb(sizeof (ipsec_info_t),
20981 			    BPRI_HI)) == NULL) {
20982 				ipif_refrele(ipif);
20983 				first_mp = mp;
20984 				goto discard_pkt;
20985 			}
20986 			first_mp->b_datap->db_type = M_CTL;
20987 			first_mp->b_wptr += sizeof (ipsec_info_t);
20988 			/* ipsec_out_secure is B_FALSE now */
20989 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
20990 			io = (ipsec_out_t *)first_mp->b_rptr;
20991 			io->ipsec_out_type = IPSEC_OUT;
20992 			io->ipsec_out_len = sizeof (ipsec_out_t);
20993 			io->ipsec_out_use_global_policy = B_TRUE;
20994 			io->ipsec_out_ns = ipst->ips_netstack;
20995 			first_mp->b_cont = mp;
20996 			mctl_present = B_TRUE;
20997 		}
20998 		if (attach_ill != NULL) {
20999 			ASSERT(attach_ill == ipif->ipif_ill);
21000 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21001 
21002 			/*
21003 			 * Check if we need an ire that will not be
21004 			 * looked up by anybody else i.e. HIDDEN.
21005 			 */
21006 			if (ill_is_probeonly(attach_ill)) {
21007 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21008 			}
21009 			io->ipsec_out_ill_index =
21010 			    attach_ill->ill_phyint->phyint_ifindex;
21011 			io->ipsec_out_attach_if = B_TRUE;
21012 		} else {
21013 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21014 			io->ipsec_out_ill_index =
21015 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21016 		}
21017 		if (connp != NULL) {
21018 			io->ipsec_out_multicast_loop =
21019 			    connp->conn_multicast_loop;
21020 			io->ipsec_out_dontroute = connp->conn_dontroute;
21021 			io->ipsec_out_zoneid = connp->conn_zoneid;
21022 		}
21023 		/*
21024 		 * If the application uses IP_MULTICAST_IF with
21025 		 * different logical addresses of the same ILL, we
21026 		 * need to make sure that the soruce address of
21027 		 * the packet matches the logical IP address used
21028 		 * in the option. We do it by initializing ipha_src
21029 		 * here. This should keep IPsec also happy as
21030 		 * when we return from IPsec processing, we don't
21031 		 * have to worry about getting the right address on
21032 		 * the packet. Thus it is sufficient to look for
21033 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21034 		 * MATCH_IRE_IPIF.
21035 		 *
21036 		 * NOTE : We need to do it for non-secure case also as
21037 		 * this might go out secure if there is a global policy
21038 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21039 		 * address, the source should be initialized already and
21040 		 * hence we won't be initializing here.
21041 		 *
21042 		 * As we do not have the ire yet, it is possible that
21043 		 * we set the source address here and then later discover
21044 		 * that the ire implies the source address to be assigned
21045 		 * through the RTF_SETSRC flag.
21046 		 * In that case, the setsrc variable will remind us
21047 		 * that overwritting the source address by the one
21048 		 * of the RTF_SETSRC-flagged ire is allowed.
21049 		 */
21050 		if (ipha->ipha_src == INADDR_ANY &&
21051 		    (connp == NULL || !connp->conn_unspec_src)) {
21052 			ipha->ipha_src = ipif->ipif_src_addr;
21053 			setsrc = RTF_SETSRC;
21054 		}
21055 		/*
21056 		 * Find an IRE which matches the destination and the outgoing
21057 		 * queue (i.e. the outgoing interface.)
21058 		 * For loopback use a unicast IP address for
21059 		 * the ire lookup.
21060 		 */
21061 		if (IS_LOOPBACK(ipif->ipif_ill))
21062 			dst = ipif->ipif_lcl_addr;
21063 
21064 		/*
21065 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21066 		 * We don't need to lookup ire in ctable as the packet
21067 		 * needs to be sent to the destination through the specified
21068 		 * ill irrespective of ires in the cache table.
21069 		 */
21070 		ire = NULL;
21071 		if (xmit_ill == NULL) {
21072 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21073 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21074 		}
21075 
21076 		/*
21077 		 * refrele attach_ill as its not needed anymore.
21078 		 */
21079 		if (attach_ill != NULL) {
21080 			ill_refrele(attach_ill);
21081 			attach_ill = NULL;
21082 		}
21083 
21084 		if (ire == NULL) {
21085 			/*
21086 			 * Multicast loopback and multicast forwarding is
21087 			 * done in ip_wput_ire.
21088 			 *
21089 			 * Mark this packet to make it be delivered to
21090 			 * ip_wput_ire after the new ire has been
21091 			 * created.
21092 			 *
21093 			 * The call to ip_newroute_ipif takes into account
21094 			 * the setsrc reminder. In any case, we take care
21095 			 * of the RTF_MULTIRT flag.
21096 			 */
21097 			mp->b_prev = mp->b_next = NULL;
21098 			if (xmit_ill == NULL ||
21099 			    xmit_ill->ill_ipif_up_count > 0) {
21100 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21101 				    setsrc | RTF_MULTIRT, zoneid, infop);
21102 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21103 				    "ip_wput_end: q %p (%S)", q, "noire");
21104 			} else {
21105 				freemsg(first_mp);
21106 			}
21107 			ipif_refrele(ipif);
21108 			if (xmit_ill != NULL)
21109 				ill_refrele(xmit_ill);
21110 			if (need_decref)
21111 				CONN_DEC_REF(connp);
21112 			return;
21113 		}
21114 
21115 		ipif_refrele(ipif);
21116 		ipif = NULL;
21117 		ASSERT(xmit_ill == NULL);
21118 
21119 		/*
21120 		 * Honor the RTF_SETSRC flag for multicast packets,
21121 		 * if allowed by the setsrc reminder.
21122 		 */
21123 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21124 			ipha->ipha_src = ire->ire_src_addr;
21125 		}
21126 
21127 		/*
21128 		 * Unconditionally force the TTL to 1 for
21129 		 * multirouted multicast packets:
21130 		 * multirouted multicast should not cross
21131 		 * multicast routers.
21132 		 */
21133 		if (ire->ire_flags & RTF_MULTIRT) {
21134 			if (ipha->ipha_ttl > 1) {
21135 				ip2dbg(("ip_wput: forcing multicast "
21136 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21137 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21138 				ipha->ipha_ttl = 1;
21139 			}
21140 		}
21141 	} else {
21142 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21143 		if ((ire != NULL) && (ire->ire_type &
21144 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21145 			ignore_dontroute = B_TRUE;
21146 			ignore_nexthop = B_TRUE;
21147 		}
21148 		if (ire != NULL) {
21149 			ire_refrele(ire);
21150 			ire = NULL;
21151 		}
21152 		/*
21153 		 * Guard against coming in from arp in which case conn is NULL.
21154 		 * Also guard against non M_DATA with dontroute set but
21155 		 * destined to local, loopback or broadcast addresses.
21156 		 */
21157 		if (connp != NULL && connp->conn_dontroute &&
21158 		    !ignore_dontroute) {
21159 dontroute:
21160 			/*
21161 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21162 			 * routing protocols from seeing false direct
21163 			 * connectivity.
21164 			 */
21165 			ipha->ipha_ttl = 1;
21166 
21167 			/* If suitable ipif not found, drop packet */
21168 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21169 			if (dst_ipif == NULL) {
21170 noroute:
21171 				ip1dbg(("ip_wput: no route for dst using"
21172 				    " SO_DONTROUTE\n"));
21173 				BUMP_MIB(&ipst->ips_ip_mib,
21174 				    ipIfStatsOutNoRoutes);
21175 				mp->b_prev = mp->b_next = NULL;
21176 				if (first_mp == NULL)
21177 					first_mp = mp;
21178 				goto drop_pkt;
21179 			} else {
21180 				/*
21181 				 * If suitable ipif has been found, set
21182 				 * xmit_ill to the corresponding
21183 				 * ipif_ill because we'll be using the
21184 				 * send_from_ill logic below.
21185 				 */
21186 				ASSERT(xmit_ill == NULL);
21187 				xmit_ill = dst_ipif->ipif_ill;
21188 				mutex_enter(&xmit_ill->ill_lock);
21189 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21190 					mutex_exit(&xmit_ill->ill_lock);
21191 					xmit_ill = NULL;
21192 					ipif_refrele(dst_ipif);
21193 					goto noroute;
21194 				}
21195 				ill_refhold_locked(xmit_ill);
21196 				mutex_exit(&xmit_ill->ill_lock);
21197 				ipif_refrele(dst_ipif);
21198 			}
21199 		}
21200 		/*
21201 		 * If we are bound to IPIF_NOFAILOVER address, look for
21202 		 * an IRE_CACHE matching the ill.
21203 		 */
21204 send_from_ill:
21205 		if (attach_ill != NULL) {
21206 			ipif_t	*attach_ipif;
21207 
21208 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21209 
21210 			/*
21211 			 * Check if we need an ire that will not be
21212 			 * looked up by anybody else i.e. HIDDEN.
21213 			 */
21214 			if (ill_is_probeonly(attach_ill)) {
21215 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21216 			}
21217 
21218 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21219 			if (attach_ipif == NULL) {
21220 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21221 				goto discard_pkt;
21222 			}
21223 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21224 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21225 			ipif_refrele(attach_ipif);
21226 		} else if (xmit_ill != NULL) {
21227 			ipif_t *ipif;
21228 
21229 			/*
21230 			 * Mark this packet as originated locally
21231 			 */
21232 			mp->b_prev = mp->b_next = NULL;
21233 
21234 			/*
21235 			 * Could be SO_DONTROUTE case also.
21236 			 * Verify that at least one ipif is up on the ill.
21237 			 */
21238 			if (xmit_ill->ill_ipif_up_count == 0) {
21239 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21240 				    xmit_ill->ill_name));
21241 				goto drop_pkt;
21242 			}
21243 
21244 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21245 			if (ipif == NULL) {
21246 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21247 				    xmit_ill->ill_name));
21248 				goto drop_pkt;
21249 			}
21250 
21251 			/*
21252 			 * Look for a ire that is part of the group,
21253 			 * if found use it else call ip_newroute_ipif.
21254 			 * IPCL_ZONEID is not used for matching because
21255 			 * IP_ALLZONES option is valid only when the
21256 			 * ill is accessible from all zones i.e has a
21257 			 * valid ipif in all zones.
21258 			 */
21259 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21260 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21261 			    MBLK_GETLABEL(mp), match_flags, ipst);
21262 			/*
21263 			 * If an ire exists use it or else create
21264 			 * an ire but don't add it to the cache.
21265 			 * Adding an ire may cause issues with
21266 			 * asymmetric routing.
21267 			 * In case of multiroute always act as if
21268 			 * ire does not exist.
21269 			 */
21270 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21271 				if (ire != NULL)
21272 					ire_refrele(ire);
21273 				ip_newroute_ipif(q, first_mp, ipif,
21274 				    dst, connp, 0, zoneid, infop);
21275 				ipif_refrele(ipif);
21276 				ip1dbg(("ip_output: xmit_ill via %s\n",
21277 				    xmit_ill->ill_name));
21278 				ill_refrele(xmit_ill);
21279 				if (need_decref)
21280 					CONN_DEC_REF(connp);
21281 				return;
21282 			}
21283 			ipif_refrele(ipif);
21284 		} else if (ip_nexthop || (connp != NULL &&
21285 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21286 			if (!ip_nexthop) {
21287 				ip_nexthop = B_TRUE;
21288 				nexthop_addr = connp->conn_nexthop_v4;
21289 			}
21290 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21291 			    MATCH_IRE_GW;
21292 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21293 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21294 		} else {
21295 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21296 			    ipst);
21297 		}
21298 		if (!ire) {
21299 			/*
21300 			 * Make sure we don't load spread if this
21301 			 * is IPIF_NOFAILOVER case.
21302 			 */
21303 			if ((attach_ill != NULL) ||
21304 			    (ip_nexthop && !ignore_nexthop)) {
21305 				if (mctl_present) {
21306 					io = (ipsec_out_t *)first_mp->b_rptr;
21307 					ASSERT(first_mp->b_datap->db_type ==
21308 					    M_CTL);
21309 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21310 				} else {
21311 					ASSERT(mp == first_mp);
21312 					first_mp = allocb(
21313 					    sizeof (ipsec_info_t), BPRI_HI);
21314 					if (first_mp == NULL) {
21315 						first_mp = mp;
21316 						goto discard_pkt;
21317 					}
21318 					first_mp->b_datap->db_type = M_CTL;
21319 					first_mp->b_wptr +=
21320 					    sizeof (ipsec_info_t);
21321 					/* ipsec_out_secure is B_FALSE now */
21322 					bzero(first_mp->b_rptr,
21323 					    sizeof (ipsec_info_t));
21324 					io = (ipsec_out_t *)first_mp->b_rptr;
21325 					io->ipsec_out_type = IPSEC_OUT;
21326 					io->ipsec_out_len =
21327 					    sizeof (ipsec_out_t);
21328 					io->ipsec_out_use_global_policy =
21329 					    B_TRUE;
21330 					io->ipsec_out_ns = ipst->ips_netstack;
21331 					first_mp->b_cont = mp;
21332 					mctl_present = B_TRUE;
21333 				}
21334 				if (attach_ill != NULL) {
21335 					io->ipsec_out_ill_index = attach_ill->
21336 					    ill_phyint->phyint_ifindex;
21337 					io->ipsec_out_attach_if = B_TRUE;
21338 				} else {
21339 					io->ipsec_out_ip_nexthop = ip_nexthop;
21340 					io->ipsec_out_nexthop_addr =
21341 					    nexthop_addr;
21342 				}
21343 			}
21344 noirefound:
21345 			/*
21346 			 * Mark this packet as having originated on
21347 			 * this machine.  This will be noted in
21348 			 * ire_add_then_send, which needs to know
21349 			 * whether to run it back through ip_wput or
21350 			 * ip_rput following successful resolution.
21351 			 */
21352 			mp->b_prev = NULL;
21353 			mp->b_next = NULL;
21354 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21355 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21356 			    "ip_wput_end: q %p (%S)", q, "newroute");
21357 			if (attach_ill != NULL)
21358 				ill_refrele(attach_ill);
21359 			if (xmit_ill != NULL)
21360 				ill_refrele(xmit_ill);
21361 			if (need_decref)
21362 				CONN_DEC_REF(connp);
21363 			return;
21364 		}
21365 	}
21366 
21367 	/* We now know where we are going with it. */
21368 
21369 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21370 	    "ip_wput_end: q %p (%S)", q, "end");
21371 
21372 	/*
21373 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21374 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21375 	 */
21376 	if (ire->ire_flags & RTF_MULTIRT) {
21377 		/*
21378 		 * Force the TTL of multirouted packets if required.
21379 		 * The TTL of such packets is bounded by the
21380 		 * ip_multirt_ttl ndd variable.
21381 		 */
21382 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21383 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21384 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21385 			    "(was %d), dst 0x%08x\n",
21386 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21387 			    ntohl(ire->ire_addr)));
21388 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21389 		}
21390 		/*
21391 		 * At this point, we check to see if there are any pending
21392 		 * unresolved routes. ire_multirt_resolvable()
21393 		 * checks in O(n) that all IRE_OFFSUBNET ire
21394 		 * entries for the packet's destination and
21395 		 * flagged RTF_MULTIRT are currently resolved.
21396 		 * If some remain unresolved, we make a copy
21397 		 * of the current message. It will be used
21398 		 * to initiate additional route resolutions.
21399 		 */
21400 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21401 		    MBLK_GETLABEL(first_mp), ipst);
21402 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21403 		    "multirt_need_resolve %d, first_mp %p\n",
21404 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21405 		if (multirt_need_resolve) {
21406 			copy_mp = copymsg(first_mp);
21407 			if (copy_mp != NULL) {
21408 				MULTIRT_DEBUG_TAG(copy_mp);
21409 			}
21410 		}
21411 	}
21412 
21413 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21414 	/*
21415 	 * Try to resolve another multiroute if
21416 	 * ire_multirt_resolvable() deemed it necessary.
21417 	 * At this point, we need to distinguish
21418 	 * multicasts from other packets. For multicasts,
21419 	 * we call ip_newroute_ipif() and request that both
21420 	 * multirouting and setsrc flags are checked.
21421 	 */
21422 	if (copy_mp != NULL) {
21423 		if (CLASSD(dst)) {
21424 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21425 			if (ipif) {
21426 				ASSERT(infop->ip_opt_ill_index == 0);
21427 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21428 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21429 				ipif_refrele(ipif);
21430 			} else {
21431 				MULTIRT_DEBUG_UNTAG(copy_mp);
21432 				freemsg(copy_mp);
21433 				copy_mp = NULL;
21434 			}
21435 		} else {
21436 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21437 		}
21438 	}
21439 	if (attach_ill != NULL)
21440 		ill_refrele(attach_ill);
21441 	if (xmit_ill != NULL)
21442 		ill_refrele(xmit_ill);
21443 	if (need_decref)
21444 		CONN_DEC_REF(connp);
21445 	return;
21446 
21447 icmp_parameter_problem:
21448 	/* could not have originated externally */
21449 	ASSERT(mp->b_prev == NULL);
21450 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21451 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21452 		/* it's the IP header length that's in trouble */
21453 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21454 		first_mp = NULL;
21455 	}
21456 
21457 discard_pkt:
21458 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21459 drop_pkt:
21460 	ip1dbg(("ip_wput: dropped packet\n"));
21461 	if (ire != NULL)
21462 		ire_refrele(ire);
21463 	if (need_decref)
21464 		CONN_DEC_REF(connp);
21465 	freemsg(first_mp);
21466 	if (attach_ill != NULL)
21467 		ill_refrele(attach_ill);
21468 	if (xmit_ill != NULL)
21469 		ill_refrele(xmit_ill);
21470 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21471 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21472 }
21473 
21474 /*
21475  * If this is a conn_t queue, then we pass in the conn. This includes the
21476  * zoneid.
21477  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21478  * in which case we use the global zoneid since those are all part of
21479  * the global zone.
21480  */
21481 void
21482 ip_wput(queue_t *q, mblk_t *mp)
21483 {
21484 	if (CONN_Q(q))
21485 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21486 	else
21487 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21488 }
21489 
21490 /*
21491  *
21492  * The following rules must be observed when accessing any ipif or ill
21493  * that has been cached in the conn. Typically conn_nofailover_ill,
21494  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21495  *
21496  * Access: The ipif or ill pointed to from the conn can be accessed under
21497  * the protection of the conn_lock or after it has been refheld under the
21498  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21499  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21500  * The reason for this is that a concurrent unplumb could actually be
21501  * cleaning up these cached pointers by walking the conns and might have
21502  * finished cleaning up the conn in question. The macros check that an
21503  * unplumb has not yet started on the ipif or ill.
21504  *
21505  * Caching: An ipif or ill pointer may be cached in the conn only after
21506  * making sure that an unplumb has not started. So the caching is done
21507  * while holding both the conn_lock and the ill_lock and after using the
21508  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21509  * flag before starting the cleanup of conns.
21510  *
21511  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21512  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21513  * or a reference to the ipif or a reference to an ire that references the
21514  * ipif. An ipif does not change its ill except for failover/failback. Since
21515  * failover/failback happens only after bringing down the ipif and making sure
21516  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21517  * the above holds.
21518  */
21519 ipif_t *
21520 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21521 {
21522 	ipif_t	*ipif;
21523 	ill_t	*ill;
21524 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21525 
21526 	*err = 0;
21527 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21528 	mutex_enter(&connp->conn_lock);
21529 	ipif = *ipifp;
21530 	if (ipif != NULL) {
21531 		ill = ipif->ipif_ill;
21532 		mutex_enter(&ill->ill_lock);
21533 		if (IPIF_CAN_LOOKUP(ipif)) {
21534 			ipif_refhold_locked(ipif);
21535 			mutex_exit(&ill->ill_lock);
21536 			mutex_exit(&connp->conn_lock);
21537 			rw_exit(&ipst->ips_ill_g_lock);
21538 			return (ipif);
21539 		} else {
21540 			*err = IPIF_LOOKUP_FAILED;
21541 		}
21542 		mutex_exit(&ill->ill_lock);
21543 	}
21544 	mutex_exit(&connp->conn_lock);
21545 	rw_exit(&ipst->ips_ill_g_lock);
21546 	return (NULL);
21547 }
21548 
21549 ill_t *
21550 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21551 {
21552 	ill_t	*ill;
21553 
21554 	*err = 0;
21555 	mutex_enter(&connp->conn_lock);
21556 	ill = *illp;
21557 	if (ill != NULL) {
21558 		mutex_enter(&ill->ill_lock);
21559 		if (ILL_CAN_LOOKUP(ill)) {
21560 			ill_refhold_locked(ill);
21561 			mutex_exit(&ill->ill_lock);
21562 			mutex_exit(&connp->conn_lock);
21563 			return (ill);
21564 		} else {
21565 			*err = ILL_LOOKUP_FAILED;
21566 		}
21567 		mutex_exit(&ill->ill_lock);
21568 	}
21569 	mutex_exit(&connp->conn_lock);
21570 	return (NULL);
21571 }
21572 
21573 static int
21574 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21575 {
21576 	ill_t	*ill;
21577 
21578 	ill = ipif->ipif_ill;
21579 	mutex_enter(&connp->conn_lock);
21580 	mutex_enter(&ill->ill_lock);
21581 	if (IPIF_CAN_LOOKUP(ipif)) {
21582 		*ipifp = ipif;
21583 		mutex_exit(&ill->ill_lock);
21584 		mutex_exit(&connp->conn_lock);
21585 		return (0);
21586 	}
21587 	mutex_exit(&ill->ill_lock);
21588 	mutex_exit(&connp->conn_lock);
21589 	return (IPIF_LOOKUP_FAILED);
21590 }
21591 
21592 /*
21593  * This is called if the outbound datagram needs fragmentation.
21594  *
21595  * NOTE : This function does not ire_refrele the ire argument passed in.
21596  */
21597 static void
21598 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21599     ip_stack_t *ipst)
21600 {
21601 	ipha_t		*ipha;
21602 	mblk_t		*mp;
21603 	uint32_t	v_hlen_tos_len;
21604 	uint32_t	max_frag;
21605 	uint32_t	frag_flag;
21606 	boolean_t	dont_use;
21607 
21608 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21609 		mp = ipsec_mp->b_cont;
21610 	} else {
21611 		mp = ipsec_mp;
21612 	}
21613 
21614 	ipha = (ipha_t *)mp->b_rptr;
21615 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21616 
21617 #ifdef	_BIG_ENDIAN
21618 #define	V_HLEN	(v_hlen_tos_len >> 24)
21619 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21620 #else
21621 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21622 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21623 #endif
21624 
21625 #ifndef SPEED_BEFORE_SAFETY
21626 	/*
21627 	 * Check that ipha_length is consistent with
21628 	 * the mblk length
21629 	 */
21630 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21631 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21632 		    LENGTH, msgdsize(mp)));
21633 		freemsg(ipsec_mp);
21634 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21635 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21636 		    "packet length mismatch");
21637 		return;
21638 	}
21639 #endif
21640 	/*
21641 	 * Don't use frag_flag if pre-built packet or source
21642 	 * routed or if multicast (since multicast packets do not solicit
21643 	 * ICMP "packet too big" messages). Get the values of
21644 	 * max_frag and frag_flag atomically by acquiring the
21645 	 * ire_lock.
21646 	 */
21647 	mutex_enter(&ire->ire_lock);
21648 	max_frag = ire->ire_max_frag;
21649 	frag_flag = ire->ire_frag_flag;
21650 	mutex_exit(&ire->ire_lock);
21651 
21652 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21653 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21654 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21655 
21656 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21657 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21658 }
21659 
21660 /*
21661  * Used for deciding the MSS size for the upper layer. Thus
21662  * we need to check the outbound policy values in the conn.
21663  */
21664 int
21665 conn_ipsec_length(conn_t *connp)
21666 {
21667 	ipsec_latch_t *ipl;
21668 
21669 	ipl = connp->conn_latch;
21670 	if (ipl == NULL)
21671 		return (0);
21672 
21673 	if (ipl->ipl_out_policy == NULL)
21674 		return (0);
21675 
21676 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21677 }
21678 
21679 /*
21680  * Returns an estimate of the IPsec headers size. This is used if
21681  * we don't want to call into IPsec to get the exact size.
21682  */
21683 int
21684 ipsec_out_extra_length(mblk_t *ipsec_mp)
21685 {
21686 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21687 	ipsec_action_t *a;
21688 
21689 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21690 	if (!io->ipsec_out_secure)
21691 		return (0);
21692 
21693 	a = io->ipsec_out_act;
21694 
21695 	if (a == NULL) {
21696 		ASSERT(io->ipsec_out_policy != NULL);
21697 		a = io->ipsec_out_policy->ipsp_act;
21698 	}
21699 	ASSERT(a != NULL);
21700 
21701 	return (a->ipa_ovhd);
21702 }
21703 
21704 /*
21705  * Returns an estimate of the IPsec headers size. This is used if
21706  * we don't want to call into IPsec to get the exact size.
21707  */
21708 int
21709 ipsec_in_extra_length(mblk_t *ipsec_mp)
21710 {
21711 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21712 	ipsec_action_t *a;
21713 
21714 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21715 
21716 	a = ii->ipsec_in_action;
21717 	return (a == NULL ? 0 : a->ipa_ovhd);
21718 }
21719 
21720 /*
21721  * If there are any source route options, return the true final
21722  * destination. Otherwise, return the destination.
21723  */
21724 ipaddr_t
21725 ip_get_dst(ipha_t *ipha)
21726 {
21727 	ipoptp_t	opts;
21728 	uchar_t		*opt;
21729 	uint8_t		optval;
21730 	uint8_t		optlen;
21731 	ipaddr_t	dst;
21732 	uint32_t off;
21733 
21734 	dst = ipha->ipha_dst;
21735 
21736 	if (IS_SIMPLE_IPH(ipha))
21737 		return (dst);
21738 
21739 	for (optval = ipoptp_first(&opts, ipha);
21740 	    optval != IPOPT_EOL;
21741 	    optval = ipoptp_next(&opts)) {
21742 		opt = opts.ipoptp_cur;
21743 		optlen = opts.ipoptp_len;
21744 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21745 		switch (optval) {
21746 		case IPOPT_SSRR:
21747 		case IPOPT_LSRR:
21748 			off = opt[IPOPT_OFFSET];
21749 			/*
21750 			 * If one of the conditions is true, it means
21751 			 * end of options and dst already has the right
21752 			 * value.
21753 			 */
21754 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21755 				off = optlen - IP_ADDR_LEN;
21756 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21757 			}
21758 			return (dst);
21759 		default:
21760 			break;
21761 		}
21762 	}
21763 
21764 	return (dst);
21765 }
21766 
21767 mblk_t *
21768 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21769     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21770 {
21771 	ipsec_out_t	*io;
21772 	mblk_t		*first_mp;
21773 	boolean_t policy_present;
21774 	ip_stack_t	*ipst;
21775 	ipsec_stack_t	*ipss;
21776 
21777 	ASSERT(ire != NULL);
21778 	ipst = ire->ire_ipst;
21779 	ipss = ipst->ips_netstack->netstack_ipsec;
21780 
21781 	first_mp = mp;
21782 	if (mp->b_datap->db_type == M_CTL) {
21783 		io = (ipsec_out_t *)first_mp->b_rptr;
21784 		/*
21785 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21786 		 *
21787 		 * 1) There is per-socket policy (including cached global
21788 		 *    policy) or a policy on the IP-in-IP tunnel.
21789 		 * 2) There is no per-socket policy, but it is
21790 		 *    a multicast packet that needs to go out
21791 		 *    on a specific interface. This is the case
21792 		 *    where (ip_wput and ip_wput_multicast) attaches
21793 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21794 		 *
21795 		 * In case (2) we check with global policy to
21796 		 * see if there is a match and set the ill_index
21797 		 * appropriately so that we can lookup the ire
21798 		 * properly in ip_wput_ipsec_out.
21799 		 */
21800 
21801 		/*
21802 		 * ipsec_out_use_global_policy is set to B_FALSE
21803 		 * in ipsec_in_to_out(). Refer to that function for
21804 		 * details.
21805 		 */
21806 		if ((io->ipsec_out_latch == NULL) &&
21807 		    (io->ipsec_out_use_global_policy)) {
21808 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21809 			    ire, connp, unspec_src, zoneid));
21810 		}
21811 		if (!io->ipsec_out_secure) {
21812 			/*
21813 			 * If this is not a secure packet, drop
21814 			 * the IPSEC_OUT mp and treat it as a clear
21815 			 * packet. This happens when we are sending
21816 			 * a ICMP reply back to a clear packet. See
21817 			 * ipsec_in_to_out() for details.
21818 			 */
21819 			mp = first_mp->b_cont;
21820 			freeb(first_mp);
21821 		}
21822 		return (mp);
21823 	}
21824 	/*
21825 	 * See whether we need to attach a global policy here. We
21826 	 * don't depend on the conn (as it could be null) for deciding
21827 	 * what policy this datagram should go through because it
21828 	 * should have happened in ip_wput if there was some
21829 	 * policy. This normally happens for connections which are not
21830 	 * fully bound preventing us from caching policies in
21831 	 * ip_bind. Packets coming from the TCP listener/global queue
21832 	 * - which are non-hard_bound - could also be affected by
21833 	 * applying policy here.
21834 	 *
21835 	 * If this packet is coming from tcp global queue or listener,
21836 	 * we will be applying policy here.  This may not be *right*
21837 	 * if these packets are coming from the detached connection as
21838 	 * it could have gone in clear before. This happens only if a
21839 	 * TCP connection started when there is no policy and somebody
21840 	 * added policy before it became detached. Thus packets of the
21841 	 * detached connection could go out secure and the other end
21842 	 * would drop it because it will be expecting in clear. The
21843 	 * converse is not true i.e if somebody starts a TCP
21844 	 * connection and deletes the policy, all the packets will
21845 	 * still go out with the policy that existed before deleting
21846 	 * because ip_unbind sends up policy information which is used
21847 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21848 	 * TCP to attach a dummy IPSEC_OUT and set
21849 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21850 	 * affect performance for normal cases, we are not doing it.
21851 	 * Thus, set policy before starting any TCP connections.
21852 	 *
21853 	 * NOTE - We might apply policy even for a hard bound connection
21854 	 * - for which we cached policy in ip_bind - if somebody added
21855 	 * global policy after we inherited the policy in ip_bind.
21856 	 * This means that the packets that were going out in clear
21857 	 * previously would start going secure and hence get dropped
21858 	 * on the other side. To fix this, TCP attaches a dummy
21859 	 * ipsec_out and make sure that we don't apply global policy.
21860 	 */
21861 	if (ipha != NULL)
21862 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21863 	else
21864 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21865 	if (!policy_present)
21866 		return (mp);
21867 
21868 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21869 	    zoneid));
21870 }
21871 
21872 ire_t *
21873 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21874 {
21875 	ipaddr_t addr;
21876 	ire_t *save_ire;
21877 	irb_t *irb;
21878 	ill_group_t *illgrp;
21879 	int	err;
21880 
21881 	save_ire = ire;
21882 	addr = ire->ire_addr;
21883 
21884 	ASSERT(ire->ire_type == IRE_BROADCAST);
21885 
21886 	illgrp = connp->conn_outgoing_ill->ill_group;
21887 	if (illgrp == NULL) {
21888 		*conn_outgoing_ill = conn_get_held_ill(connp,
21889 		    &connp->conn_outgoing_ill, &err);
21890 		if (err == ILL_LOOKUP_FAILED) {
21891 			ire_refrele(save_ire);
21892 			return (NULL);
21893 		}
21894 		return (save_ire);
21895 	}
21896 	/*
21897 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21898 	 * If it is part of the group, we need to send on the ire
21899 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21900 	 * to this group. This is okay as IP_BOUND_IF really means
21901 	 * any ill in the group. We depend on the fact that the
21902 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21903 	 * if such an ire exists. This is possible only if you have
21904 	 * at least one ill in the group that has not failed.
21905 	 *
21906 	 * First get to the ire that matches the address and group.
21907 	 *
21908 	 * We don't look for an ire with a matching zoneid because a given zone
21909 	 * won't always have broadcast ires on all ills in the group.
21910 	 */
21911 	irb = ire->ire_bucket;
21912 	rw_enter(&irb->irb_lock, RW_READER);
21913 	if (ire->ire_marks & IRE_MARK_NORECV) {
21914 		/*
21915 		 * If the current zone only has an ire broadcast for this
21916 		 * address marked NORECV, the ire we want is ahead in the
21917 		 * bucket, so we look it up deliberately ignoring the zoneid.
21918 		 */
21919 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21920 			if (ire->ire_addr != addr)
21921 				continue;
21922 			/* skip over deleted ires */
21923 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21924 				continue;
21925 		}
21926 	}
21927 	while (ire != NULL) {
21928 		/*
21929 		 * If a new interface is coming up, we could end up
21930 		 * seeing the loopback ire and the non-loopback ire
21931 		 * may not have been added yet. So check for ire_stq
21932 		 */
21933 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21934 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21935 			break;
21936 		}
21937 		ire = ire->ire_next;
21938 	}
21939 	if (ire != NULL && ire->ire_addr == addr &&
21940 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21941 		IRE_REFHOLD(ire);
21942 		rw_exit(&irb->irb_lock);
21943 		ire_refrele(save_ire);
21944 		*conn_outgoing_ill = ire_to_ill(ire);
21945 		/*
21946 		 * Refhold the ill to make the conn_outgoing_ill
21947 		 * independent of the ire. ip_wput_ire goes in a loop
21948 		 * and may refrele the ire. Since we have an ire at this
21949 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21950 		 */
21951 		ill_refhold(*conn_outgoing_ill);
21952 		return (ire);
21953 	}
21954 	rw_exit(&irb->irb_lock);
21955 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21956 	/*
21957 	 * If we can't find a suitable ire, return the original ire.
21958 	 */
21959 	return (save_ire);
21960 }
21961 
21962 /*
21963  * This function does the ire_refrele of the ire passed in as the
21964  * argument. As this function looks up more ires i.e broadcast ires,
21965  * it needs to REFRELE them. Currently, for simplicity we don't
21966  * differentiate the one passed in and looked up here. We always
21967  * REFRELE.
21968  * IPQoS Notes:
21969  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21970  * IPsec packets are done in ipsec_out_process.
21971  *
21972  */
21973 void
21974 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
21975     zoneid_t zoneid)
21976 {
21977 	ipha_t		*ipha;
21978 #define	rptr	((uchar_t *)ipha)
21979 	queue_t		*stq;
21980 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
21981 	uint32_t	v_hlen_tos_len;
21982 	uint32_t	ttl_protocol;
21983 	ipaddr_t	src;
21984 	ipaddr_t	dst;
21985 	uint32_t	cksum;
21986 	ipaddr_t	orig_src;
21987 	ire_t		*ire1;
21988 	mblk_t		*next_mp;
21989 	uint_t		hlen;
21990 	uint16_t	*up;
21991 	uint32_t	max_frag = ire->ire_max_frag;
21992 	ill_t		*ill = ire_to_ill(ire);
21993 	int		clusterwide;
21994 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
21995 	int		ipsec_len;
21996 	mblk_t		*first_mp;
21997 	ipsec_out_t	*io;
21998 	boolean_t	conn_dontroute;		/* conn value for multicast */
21999 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22000 	boolean_t	multicast_forward;	/* Should we forward ? */
22001 	boolean_t	unspec_src;
22002 	ill_t		*conn_outgoing_ill = NULL;
22003 	ill_t		*ire_ill;
22004 	ill_t		*ire1_ill;
22005 	ill_t		*out_ill;
22006 	uint32_t 	ill_index = 0;
22007 	boolean_t	multirt_send = B_FALSE;
22008 	int		err;
22009 	ipxmit_state_t	pktxmit_state;
22010 	ip_stack_t	*ipst = ire->ire_ipst;
22011 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22012 
22013 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22014 	    "ip_wput_ire_start: q %p", q);
22015 
22016 	multicast_forward = B_FALSE;
22017 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22018 
22019 	if (ire->ire_flags & RTF_MULTIRT) {
22020 		/*
22021 		 * Multirouting case. The bucket where ire is stored
22022 		 * probably holds other RTF_MULTIRT flagged ire
22023 		 * to the destination. In this call to ip_wput_ire,
22024 		 * we attempt to send the packet through all
22025 		 * those ires. Thus, we first ensure that ire is the
22026 		 * first RTF_MULTIRT ire in the bucket,
22027 		 * before walking the ire list.
22028 		 */
22029 		ire_t *first_ire;
22030 		irb_t *irb = ire->ire_bucket;
22031 		ASSERT(irb != NULL);
22032 
22033 		/* Make sure we do not omit any multiroute ire. */
22034 		IRB_REFHOLD(irb);
22035 		for (first_ire = irb->irb_ire;
22036 		    first_ire != NULL;
22037 		    first_ire = first_ire->ire_next) {
22038 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22039 			    (first_ire->ire_addr == ire->ire_addr) &&
22040 			    !(first_ire->ire_marks &
22041 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22042 				break;
22043 			}
22044 		}
22045 
22046 		if ((first_ire != NULL) && (first_ire != ire)) {
22047 			IRE_REFHOLD(first_ire);
22048 			ire_refrele(ire);
22049 			ire = first_ire;
22050 			ill = ire_to_ill(ire);
22051 		}
22052 		IRB_REFRELE(irb);
22053 	}
22054 
22055 	/*
22056 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22057 	 * for performance we don't grab the mutexs in the fastpath
22058 	 */
22059 	if ((connp != NULL) &&
22060 	    (ire->ire_type == IRE_BROADCAST) &&
22061 	    ((connp->conn_nofailover_ill != NULL) ||
22062 	    (connp->conn_outgoing_ill != NULL))) {
22063 		/*
22064 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22065 		 * option. So, see if this endpoint is bound to a
22066 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22067 		 * that if the interface is failed, we will still send
22068 		 * the packet on the same ill which is what we want.
22069 		 */
22070 		conn_outgoing_ill = conn_get_held_ill(connp,
22071 		    &connp->conn_nofailover_ill, &err);
22072 		if (err == ILL_LOOKUP_FAILED) {
22073 			ire_refrele(ire);
22074 			freemsg(mp);
22075 			return;
22076 		}
22077 		if (conn_outgoing_ill == NULL) {
22078 			/*
22079 			 * Choose a good ill in the group to send the
22080 			 * packets on.
22081 			 */
22082 			ire = conn_set_outgoing_ill(connp, ire,
22083 			    &conn_outgoing_ill);
22084 			if (ire == NULL) {
22085 				freemsg(mp);
22086 				return;
22087 			}
22088 		}
22089 	}
22090 
22091 	if (mp->b_datap->db_type != M_CTL) {
22092 		ipha = (ipha_t *)mp->b_rptr;
22093 	} else {
22094 		io = (ipsec_out_t *)mp->b_rptr;
22095 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22096 		ASSERT(zoneid == io->ipsec_out_zoneid);
22097 		ASSERT(zoneid != ALL_ZONES);
22098 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22099 		dst = ipha->ipha_dst;
22100 		/*
22101 		 * For the multicast case, ipsec_out carries conn_dontroute and
22102 		 * conn_multicast_loop as conn may not be available here. We
22103 		 * need this for multicast loopback and forwarding which is done
22104 		 * later in the code.
22105 		 */
22106 		if (CLASSD(dst)) {
22107 			conn_dontroute = io->ipsec_out_dontroute;
22108 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22109 			/*
22110 			 * If conn_dontroute is not set or conn_multicast_loop
22111 			 * is set, we need to do forwarding/loopback. For
22112 			 * datagrams from ip_wput_multicast, conn_dontroute is
22113 			 * set to B_TRUE and conn_multicast_loop is set to
22114 			 * B_FALSE so that we neither do forwarding nor
22115 			 * loopback.
22116 			 */
22117 			if (!conn_dontroute || conn_multicast_loop)
22118 				multicast_forward = B_TRUE;
22119 		}
22120 	}
22121 
22122 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22123 	    ire->ire_zoneid != ALL_ZONES) {
22124 		/*
22125 		 * When a zone sends a packet to another zone, we try to deliver
22126 		 * the packet under the same conditions as if the destination
22127 		 * was a real node on the network. To do so, we look for a
22128 		 * matching route in the forwarding table.
22129 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22130 		 * ip_newroute() does.
22131 		 * Note that IRE_LOCAL are special, since they are used
22132 		 * when the zoneid doesn't match in some cases. This means that
22133 		 * we need to handle ipha_src differently since ire_src_addr
22134 		 * belongs to the receiving zone instead of the sending zone.
22135 		 * When ip_restrict_interzone_loopback is set, then
22136 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22137 		 * for loopback between zones when the logical "Ethernet" would
22138 		 * have looped them back.
22139 		 */
22140 		ire_t *src_ire;
22141 
22142 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22143 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22144 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22145 		if (src_ire != NULL &&
22146 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22147 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22148 		    ire_local_same_ill_group(ire, src_ire))) {
22149 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22150 				ipha->ipha_src = src_ire->ire_src_addr;
22151 			ire_refrele(src_ire);
22152 		} else {
22153 			ire_refrele(ire);
22154 			if (conn_outgoing_ill != NULL)
22155 				ill_refrele(conn_outgoing_ill);
22156 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22157 			if (src_ire != NULL) {
22158 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22159 					ire_refrele(src_ire);
22160 					freemsg(mp);
22161 					return;
22162 				}
22163 				ire_refrele(src_ire);
22164 			}
22165 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22166 				/* Failed */
22167 				freemsg(mp);
22168 				return;
22169 			}
22170 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22171 			    ipst);
22172 			return;
22173 		}
22174 	}
22175 
22176 	if (mp->b_datap->db_type == M_CTL ||
22177 	    ipss->ipsec_outbound_v4_policy_present) {
22178 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22179 		    unspec_src, zoneid);
22180 		if (mp == NULL) {
22181 			ire_refrele(ire);
22182 			if (conn_outgoing_ill != NULL)
22183 				ill_refrele(conn_outgoing_ill);
22184 			return;
22185 		}
22186 	}
22187 
22188 	first_mp = mp;
22189 	ipsec_len = 0;
22190 
22191 	if (first_mp->b_datap->db_type == M_CTL) {
22192 		io = (ipsec_out_t *)first_mp->b_rptr;
22193 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22194 		mp = first_mp->b_cont;
22195 		ipsec_len = ipsec_out_extra_length(first_mp);
22196 		ASSERT(ipsec_len >= 0);
22197 		/* We already picked up the zoneid from the M_CTL above */
22198 		ASSERT(zoneid == io->ipsec_out_zoneid);
22199 		ASSERT(zoneid != ALL_ZONES);
22200 
22201 		/*
22202 		 * Drop M_CTL here if IPsec processing is not needed.
22203 		 * (Non-IPsec use of M_CTL extracted any information it
22204 		 * needed above).
22205 		 */
22206 		if (ipsec_len == 0) {
22207 			freeb(first_mp);
22208 			first_mp = mp;
22209 		}
22210 	}
22211 
22212 	/*
22213 	 * Fast path for ip_wput_ire
22214 	 */
22215 
22216 	ipha = (ipha_t *)mp->b_rptr;
22217 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22218 	dst = ipha->ipha_dst;
22219 
22220 	/*
22221 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22222 	 * if the socket is a SOCK_RAW type. The transport checksum should
22223 	 * be provided in the pre-built packet, so we don't need to compute it.
22224 	 * Also, other application set flags, like DF, should not be altered.
22225 	 * Other transport MUST pass down zero.
22226 	 */
22227 	ip_hdr_included = ipha->ipha_ident;
22228 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22229 
22230 	if (CLASSD(dst)) {
22231 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22232 		    ntohl(dst),
22233 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22234 		    ntohl(ire->ire_addr)));
22235 	}
22236 
22237 /* Macros to extract header fields from data already in registers */
22238 #ifdef	_BIG_ENDIAN
22239 #define	V_HLEN	(v_hlen_tos_len >> 24)
22240 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22241 #define	PROTO	(ttl_protocol & 0xFF)
22242 #else
22243 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22244 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22245 #define	PROTO	(ttl_protocol >> 8)
22246 #endif
22247 
22248 
22249 	orig_src = src = ipha->ipha_src;
22250 	/* (The loop back to "another" is explained down below.) */
22251 another:;
22252 	/*
22253 	 * Assign an ident value for this packet.  We assign idents on
22254 	 * a per destination basis out of the IRE.  There could be
22255 	 * other threads targeting the same destination, so we have to
22256 	 * arrange for a atomic increment.  Note that we use a 32-bit
22257 	 * atomic add because it has better performance than its
22258 	 * 16-bit sibling.
22259 	 *
22260 	 * If running in cluster mode and if the source address
22261 	 * belongs to a replicated service then vector through
22262 	 * cl_inet_ipident vector to allocate ip identifier
22263 	 * NOTE: This is a contract private interface with the
22264 	 * clustering group.
22265 	 */
22266 	clusterwide = 0;
22267 	if (cl_inet_ipident) {
22268 		ASSERT(cl_inet_isclusterwide);
22269 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22270 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22271 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22272 			    AF_INET, (uint8_t *)(uintptr_t)src,
22273 			    (uint8_t *)(uintptr_t)dst);
22274 			clusterwide = 1;
22275 		}
22276 	}
22277 	if (!clusterwide) {
22278 		ipha->ipha_ident =
22279 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22280 	}
22281 
22282 #ifndef _BIG_ENDIAN
22283 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22284 #endif
22285 
22286 	/*
22287 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22288 	 * This is needed to obey conn_unspec_src when packets go through
22289 	 * ip_newroute + arp.
22290 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22291 	 */
22292 	if (src == INADDR_ANY && !unspec_src) {
22293 		/*
22294 		 * Assign the appropriate source address from the IRE if none
22295 		 * was specified.
22296 		 */
22297 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22298 
22299 		/*
22300 		 * With IP multipathing, broadcast packets are sent on the ire
22301 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22302 		 * the group. However, this ire might not be in the same zone so
22303 		 * we can't always use its source address. We look for a
22304 		 * broadcast ire in the same group and in the right zone.
22305 		 */
22306 		if (ire->ire_type == IRE_BROADCAST &&
22307 		    ire->ire_zoneid != zoneid) {
22308 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22309 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22310 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22311 			if (src_ire != NULL) {
22312 				src = src_ire->ire_src_addr;
22313 				ire_refrele(src_ire);
22314 			} else {
22315 				ire_refrele(ire);
22316 				if (conn_outgoing_ill != NULL)
22317 					ill_refrele(conn_outgoing_ill);
22318 				freemsg(first_mp);
22319 				if (ill != NULL) {
22320 					BUMP_MIB(ill->ill_ip_mib,
22321 					    ipIfStatsOutDiscards);
22322 				} else {
22323 					BUMP_MIB(&ipst->ips_ip_mib,
22324 					    ipIfStatsOutDiscards);
22325 				}
22326 				return;
22327 			}
22328 		} else {
22329 			src = ire->ire_src_addr;
22330 		}
22331 
22332 		if (connp == NULL) {
22333 			ip1dbg(("ip_wput_ire: no connp and no src "
22334 			    "address for dst 0x%x, using src 0x%x\n",
22335 			    ntohl(dst),
22336 			    ntohl(src)));
22337 		}
22338 		ipha->ipha_src = src;
22339 	}
22340 	stq = ire->ire_stq;
22341 
22342 	/*
22343 	 * We only allow ire chains for broadcasts since there will
22344 	 * be multiple IRE_CACHE entries for the same multicast
22345 	 * address (one per ipif).
22346 	 */
22347 	next_mp = NULL;
22348 
22349 	/* broadcast packet */
22350 	if (ire->ire_type == IRE_BROADCAST)
22351 		goto broadcast;
22352 
22353 	/* loopback ? */
22354 	if (stq == NULL)
22355 		goto nullstq;
22356 
22357 	/* The ill_index for outbound ILL */
22358 	ill_index = Q_TO_INDEX(stq);
22359 
22360 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22361 	ttl_protocol = ((uint16_t *)ipha)[4];
22362 
22363 	/* pseudo checksum (do it in parts for IP header checksum) */
22364 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22365 
22366 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22367 		queue_t *dev_q = stq->q_next;
22368 
22369 		/* flow controlled */
22370 		if ((dev_q->q_next || dev_q->q_first) &&
22371 		    !canput(dev_q))
22372 			goto blocked;
22373 		if ((PROTO == IPPROTO_UDP) &&
22374 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22375 			hlen = (V_HLEN & 0xF) << 2;
22376 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22377 			if (*up != 0) {
22378 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22379 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22380 				/* Software checksum? */
22381 				if (DB_CKSUMFLAGS(mp) == 0) {
22382 					IP_STAT(ipst, ip_out_sw_cksum);
22383 					IP_STAT_UPDATE(ipst,
22384 					    ip_udp_out_sw_cksum_bytes,
22385 					    LENGTH - hlen);
22386 				}
22387 			}
22388 		}
22389 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22390 		hlen = (V_HLEN & 0xF) << 2;
22391 		if (PROTO == IPPROTO_TCP) {
22392 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22393 			/*
22394 			 * The packet header is processed once and for all, even
22395 			 * in the multirouting case. We disable hardware
22396 			 * checksum if the packet is multirouted, as it will be
22397 			 * replicated via several interfaces, and not all of
22398 			 * them may have this capability.
22399 			 */
22400 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22401 			    LENGTH, max_frag, ipsec_len, cksum);
22402 			/* Software checksum? */
22403 			if (DB_CKSUMFLAGS(mp) == 0) {
22404 				IP_STAT(ipst, ip_out_sw_cksum);
22405 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22406 				    LENGTH - hlen);
22407 			}
22408 		} else {
22409 			sctp_hdr_t	*sctph;
22410 
22411 			ASSERT(PROTO == IPPROTO_SCTP);
22412 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22413 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22414 			/*
22415 			 * Zero out the checksum field to ensure proper
22416 			 * checksum calculation.
22417 			 */
22418 			sctph->sh_chksum = 0;
22419 #ifdef	DEBUG
22420 			if (!skip_sctp_cksum)
22421 #endif
22422 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22423 		}
22424 	}
22425 
22426 	/*
22427 	 * If this is a multicast packet and originated from ip_wput
22428 	 * we need to do loopback and forwarding checks. If it comes
22429 	 * from ip_wput_multicast, we SHOULD not do this.
22430 	 */
22431 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22432 
22433 	/* checksum */
22434 	cksum += ttl_protocol;
22435 
22436 	/* fragment the packet */
22437 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22438 		goto fragmentit;
22439 	/*
22440 	 * Don't use frag_flag if packet is pre-built or source
22441 	 * routed or if multicast (since multicast packets do
22442 	 * not solicit ICMP "packet too big" messages).
22443 	 */
22444 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22445 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22446 	    !ip_source_route_included(ipha)) &&
22447 	    !CLASSD(ipha->ipha_dst))
22448 		ipha->ipha_fragment_offset_and_flags |=
22449 		    htons(ire->ire_frag_flag);
22450 
22451 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22452 		/* calculate IP header checksum */
22453 		cksum += ipha->ipha_ident;
22454 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22455 		cksum += ipha->ipha_fragment_offset_and_flags;
22456 
22457 		/* IP options present */
22458 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22459 		if (hlen)
22460 			goto checksumoptions;
22461 
22462 		/* calculate hdr checksum */
22463 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22464 		cksum = ~(cksum + (cksum >> 16));
22465 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22466 	}
22467 	if (ipsec_len != 0) {
22468 		/*
22469 		 * We will do the rest of the processing after
22470 		 * we come back from IPsec in ip_wput_ipsec_out().
22471 		 */
22472 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22473 
22474 		io = (ipsec_out_t *)first_mp->b_rptr;
22475 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22476 		    ill_phyint->phyint_ifindex;
22477 
22478 		ipsec_out_process(q, first_mp, ire, ill_index);
22479 		ire_refrele(ire);
22480 		if (conn_outgoing_ill != NULL)
22481 			ill_refrele(conn_outgoing_ill);
22482 		return;
22483 	}
22484 
22485 	/*
22486 	 * In most cases, the emission loop below is entered only
22487 	 * once. Only in the case where the ire holds the
22488 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22489 	 * flagged ires in the bucket, and send the packet
22490 	 * through all crossed RTF_MULTIRT routes.
22491 	 */
22492 	if (ire->ire_flags & RTF_MULTIRT) {
22493 		multirt_send = B_TRUE;
22494 	}
22495 	do {
22496 		if (multirt_send) {
22497 			irb_t *irb;
22498 			/*
22499 			 * We are in a multiple send case, need to get
22500 			 * the next ire and make a duplicate of the packet.
22501 			 * ire1 holds here the next ire to process in the
22502 			 * bucket. If multirouting is expected,
22503 			 * any non-RTF_MULTIRT ire that has the
22504 			 * right destination address is ignored.
22505 			 */
22506 			irb = ire->ire_bucket;
22507 			ASSERT(irb != NULL);
22508 
22509 			IRB_REFHOLD(irb);
22510 			for (ire1 = ire->ire_next;
22511 			    ire1 != NULL;
22512 			    ire1 = ire1->ire_next) {
22513 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22514 					continue;
22515 				if (ire1->ire_addr != ire->ire_addr)
22516 					continue;
22517 				if (ire1->ire_marks &
22518 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22519 					continue;
22520 
22521 				/* Got one */
22522 				IRE_REFHOLD(ire1);
22523 				break;
22524 			}
22525 			IRB_REFRELE(irb);
22526 
22527 			if (ire1 != NULL) {
22528 				next_mp = copyb(mp);
22529 				if ((next_mp == NULL) ||
22530 				    ((mp->b_cont != NULL) &&
22531 				    ((next_mp->b_cont =
22532 				    dupmsg(mp->b_cont)) == NULL))) {
22533 					freemsg(next_mp);
22534 					next_mp = NULL;
22535 					ire_refrele(ire1);
22536 					ire1 = NULL;
22537 				}
22538 			}
22539 
22540 			/* Last multiroute ire; don't loop anymore. */
22541 			if (ire1 == NULL) {
22542 				multirt_send = B_FALSE;
22543 			}
22544 		}
22545 
22546 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22547 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22548 		    mblk_t *, mp);
22549 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22550 		    ipst->ips_ipv4firewall_physical_out,
22551 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22552 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22553 		if (mp == NULL)
22554 			goto release_ire_and_ill;
22555 
22556 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22557 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22558 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22559 		if ((pktxmit_state == SEND_FAILED) ||
22560 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22561 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22562 			    "- packet dropped\n"));
22563 release_ire_and_ill:
22564 			ire_refrele(ire);
22565 			if (next_mp != NULL) {
22566 				freemsg(next_mp);
22567 				ire_refrele(ire1);
22568 			}
22569 			if (conn_outgoing_ill != NULL)
22570 				ill_refrele(conn_outgoing_ill);
22571 			return;
22572 		}
22573 
22574 		if (CLASSD(dst)) {
22575 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22576 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22577 			    LENGTH);
22578 		}
22579 
22580 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22581 		    "ip_wput_ire_end: q %p (%S)",
22582 		    q, "last copy out");
22583 		IRE_REFRELE(ire);
22584 
22585 		if (multirt_send) {
22586 			ASSERT(ire1);
22587 			/*
22588 			 * Proceed with the next RTF_MULTIRT ire,
22589 			 * Also set up the send-to queue accordingly.
22590 			 */
22591 			ire = ire1;
22592 			ire1 = NULL;
22593 			stq = ire->ire_stq;
22594 			mp = next_mp;
22595 			next_mp = NULL;
22596 			ipha = (ipha_t *)mp->b_rptr;
22597 			ill_index = Q_TO_INDEX(stq);
22598 			ill = (ill_t *)stq->q_ptr;
22599 		}
22600 	} while (multirt_send);
22601 	if (conn_outgoing_ill != NULL)
22602 		ill_refrele(conn_outgoing_ill);
22603 	return;
22604 
22605 	/*
22606 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22607 	 */
22608 broadcast:
22609 	{
22610 		/*
22611 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22612 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22613 		 * can be overridden stack-wide through the ip_broadcast_ttl
22614 		 * ndd tunable, or on a per-connection basis through the
22615 		 * IP_BROADCAST_TTL socket option.
22616 		 *
22617 		 * In the event that we are replying to incoming ICMP packets,
22618 		 * connp could be NULL.
22619 		 */
22620 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22621 		if (connp != NULL) {
22622 			if (connp->conn_dontroute)
22623 				ipha->ipha_ttl = 1;
22624 			else if (connp->conn_broadcast_ttl != 0)
22625 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22626 		}
22627 
22628 		/*
22629 		 * Note that we are not doing a IRB_REFHOLD here.
22630 		 * Actually we don't care if the list changes i.e
22631 		 * if somebody deletes an IRE from the list while
22632 		 * we drop the lock, the next time we come around
22633 		 * ire_next will be NULL and hence we won't send
22634 		 * out multiple copies which is fine.
22635 		 */
22636 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22637 		ire1 = ire->ire_next;
22638 		if (conn_outgoing_ill != NULL) {
22639 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22640 				ASSERT(ire1 == ire->ire_next);
22641 				if (ire1 != NULL && ire1->ire_addr == dst) {
22642 					ire_refrele(ire);
22643 					ire = ire1;
22644 					IRE_REFHOLD(ire);
22645 					ire1 = ire->ire_next;
22646 					continue;
22647 				}
22648 				rw_exit(&ire->ire_bucket->irb_lock);
22649 				/* Did not find a matching ill */
22650 				ip1dbg(("ip_wput_ire: broadcast with no "
22651 				    "matching IP_BOUND_IF ill %s dst %x\n",
22652 				    conn_outgoing_ill->ill_name, dst));
22653 				freemsg(first_mp);
22654 				if (ire != NULL)
22655 					ire_refrele(ire);
22656 				ill_refrele(conn_outgoing_ill);
22657 				return;
22658 			}
22659 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22660 			/*
22661 			 * If the next IRE has the same address and is not one
22662 			 * of the two copies that we need to send, try to see
22663 			 * whether this copy should be sent at all. This
22664 			 * assumes that we insert loopbacks first and then
22665 			 * non-loopbacks. This is acheived by inserting the
22666 			 * loopback always before non-loopback.
22667 			 * This is used to send a single copy of a broadcast
22668 			 * packet out all physical interfaces that have an
22669 			 * matching IRE_BROADCAST while also looping
22670 			 * back one copy (to ip_wput_local) for each
22671 			 * matching physical interface. However, we avoid
22672 			 * sending packets out different logical that match by
22673 			 * having ipif_up/ipif_down supress duplicate
22674 			 * IRE_BROADCASTS.
22675 			 *
22676 			 * This feature is currently used to get broadcasts
22677 			 * sent to multiple interfaces, when the broadcast
22678 			 * address being used applies to multiple interfaces.
22679 			 * For example, a whole net broadcast will be
22680 			 * replicated on every connected subnet of
22681 			 * the target net.
22682 			 *
22683 			 * Each zone has its own set of IRE_BROADCASTs, so that
22684 			 * we're able to distribute inbound packets to multiple
22685 			 * zones who share a broadcast address. We avoid looping
22686 			 * back outbound packets in different zones but on the
22687 			 * same ill, as the application would see duplicates.
22688 			 *
22689 			 * If the interfaces are part of the same group,
22690 			 * we would want to send only one copy out for
22691 			 * whole group.
22692 			 *
22693 			 * This logic assumes that ire_add_v4() groups the
22694 			 * IRE_BROADCAST entries so that those with the same
22695 			 * ire_addr and ill_group are kept together.
22696 			 */
22697 			ire_ill = ire->ire_ipif->ipif_ill;
22698 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22699 				if (ire_ill->ill_group != NULL &&
22700 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22701 					/*
22702 					 * If the current zone only has an ire
22703 					 * broadcast for this address marked
22704 					 * NORECV, the ire we want is ahead in
22705 					 * the bucket, so we look it up
22706 					 * deliberately ignoring the zoneid.
22707 					 */
22708 					for (ire1 = ire->ire_bucket->irb_ire;
22709 					    ire1 != NULL;
22710 					    ire1 = ire1->ire_next) {
22711 						ire1_ill =
22712 						    ire1->ire_ipif->ipif_ill;
22713 						if (ire1->ire_addr != dst)
22714 							continue;
22715 						/* skip over the current ire */
22716 						if (ire1 == ire)
22717 							continue;
22718 						/* skip over deleted ires */
22719 						if (ire1->ire_marks &
22720 						    IRE_MARK_CONDEMNED)
22721 							continue;
22722 						/*
22723 						 * non-loopback ire in our
22724 						 * group: use it for the next
22725 						 * pass in the loop
22726 						 */
22727 						if (ire1->ire_stq != NULL &&
22728 						    ire1_ill->ill_group ==
22729 						    ire_ill->ill_group)
22730 							break;
22731 					}
22732 				}
22733 			} else {
22734 				while (ire1 != NULL && ire1->ire_addr == dst) {
22735 					ire1_ill = ire1->ire_ipif->ipif_ill;
22736 					/*
22737 					 * We can have two broadcast ires on the
22738 					 * same ill in different zones; here
22739 					 * we'll send a copy of the packet on
22740 					 * each ill and the fanout code will
22741 					 * call conn_wantpacket() to check that
22742 					 * the zone has the broadcast address
22743 					 * configured on the ill. If the two
22744 					 * ires are in the same group we only
22745 					 * send one copy up.
22746 					 */
22747 					if (ire1_ill != ire_ill &&
22748 					    (ire1_ill->ill_group == NULL ||
22749 					    ire_ill->ill_group == NULL ||
22750 					    ire1_ill->ill_group !=
22751 					    ire_ill->ill_group)) {
22752 						break;
22753 					}
22754 					ire1 = ire1->ire_next;
22755 				}
22756 			}
22757 		}
22758 		ASSERT(multirt_send == B_FALSE);
22759 		if (ire1 != NULL && ire1->ire_addr == dst) {
22760 			if ((ire->ire_flags & RTF_MULTIRT) &&
22761 			    (ire1->ire_flags & RTF_MULTIRT)) {
22762 				/*
22763 				 * We are in the multirouting case.
22764 				 * The message must be sent at least
22765 				 * on both ires. These ires have been
22766 				 * inserted AFTER the standard ones
22767 				 * in ip_rt_add(). There are thus no
22768 				 * other ire entries for the destination
22769 				 * address in the rest of the bucket
22770 				 * that do not have the RTF_MULTIRT
22771 				 * flag. We don't process a copy
22772 				 * of the message here. This will be
22773 				 * done in the final sending loop.
22774 				 */
22775 				multirt_send = B_TRUE;
22776 			} else {
22777 				next_mp = ip_copymsg(first_mp);
22778 				if (next_mp != NULL)
22779 					IRE_REFHOLD(ire1);
22780 			}
22781 		}
22782 		rw_exit(&ire->ire_bucket->irb_lock);
22783 	}
22784 
22785 	if (stq) {
22786 		/*
22787 		 * A non-NULL send-to queue means this packet is going
22788 		 * out of this machine.
22789 		 */
22790 		out_ill = (ill_t *)stq->q_ptr;
22791 
22792 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22793 		ttl_protocol = ((uint16_t *)ipha)[4];
22794 		/*
22795 		 * We accumulate the pseudo header checksum in cksum.
22796 		 * This is pretty hairy code, so watch close.  One
22797 		 * thing to keep in mind is that UDP and TCP have
22798 		 * stored their respective datagram lengths in their
22799 		 * checksum fields.  This lines things up real nice.
22800 		 */
22801 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22802 		    (src >> 16) + (src & 0xFFFF);
22803 		/*
22804 		 * We assume the udp checksum field contains the
22805 		 * length, so to compute the pseudo header checksum,
22806 		 * all we need is the protocol number and src/dst.
22807 		 */
22808 		/* Provide the checksums for UDP and TCP. */
22809 		if ((PROTO == IPPROTO_TCP) &&
22810 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22811 			/* hlen gets the number of uchar_ts in the IP header */
22812 			hlen = (V_HLEN & 0xF) << 2;
22813 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22814 			IP_STAT(ipst, ip_out_sw_cksum);
22815 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22816 			    LENGTH - hlen);
22817 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22818 		} else if (PROTO == IPPROTO_SCTP &&
22819 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22820 			sctp_hdr_t	*sctph;
22821 
22822 			hlen = (V_HLEN & 0xF) << 2;
22823 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22824 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22825 			sctph->sh_chksum = 0;
22826 #ifdef	DEBUG
22827 			if (!skip_sctp_cksum)
22828 #endif
22829 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22830 		} else {
22831 			queue_t *dev_q = stq->q_next;
22832 
22833 			if ((dev_q->q_next || dev_q->q_first) &&
22834 			    !canput(dev_q)) {
22835 blocked:
22836 				ipha->ipha_ident = ip_hdr_included;
22837 				/*
22838 				 * If we don't have a conn to apply
22839 				 * backpressure, free the message.
22840 				 * In the ire_send path, we don't know
22841 				 * the position to requeue the packet. Rather
22842 				 * than reorder packets, we just drop this
22843 				 * packet.
22844 				 */
22845 				if (ipst->ips_ip_output_queue &&
22846 				    connp != NULL &&
22847 				    caller != IRE_SEND) {
22848 					if (caller == IP_WSRV) {
22849 						connp->conn_did_putbq = 1;
22850 						(void) putbq(connp->conn_wq,
22851 						    first_mp);
22852 						conn_drain_insert(connp);
22853 						/*
22854 						 * This is the service thread,
22855 						 * and the queue is already
22856 						 * noenabled. The check for
22857 						 * canput and the putbq is not
22858 						 * atomic. So we need to check
22859 						 * again.
22860 						 */
22861 						if (canput(stq->q_next))
22862 							connp->conn_did_putbq
22863 							    = 0;
22864 						IP_STAT(ipst, ip_conn_flputbq);
22865 					} else {
22866 						/*
22867 						 * We are not the service proc.
22868 						 * ip_wsrv will be scheduled or
22869 						 * is already running.
22870 						 */
22871 						(void) putq(connp->conn_wq,
22872 						    first_mp);
22873 					}
22874 				} else {
22875 					out_ill = (ill_t *)stq->q_ptr;
22876 					BUMP_MIB(out_ill->ill_ip_mib,
22877 					    ipIfStatsOutDiscards);
22878 					freemsg(first_mp);
22879 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22880 					    "ip_wput_ire_end: q %p (%S)",
22881 					    q, "discard");
22882 				}
22883 				ire_refrele(ire);
22884 				if (next_mp) {
22885 					ire_refrele(ire1);
22886 					freemsg(next_mp);
22887 				}
22888 				if (conn_outgoing_ill != NULL)
22889 					ill_refrele(conn_outgoing_ill);
22890 				return;
22891 			}
22892 			if ((PROTO == IPPROTO_UDP) &&
22893 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22894 				/*
22895 				 * hlen gets the number of uchar_ts in the
22896 				 * IP header
22897 				 */
22898 				hlen = (V_HLEN & 0xF) << 2;
22899 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22900 				max_frag = ire->ire_max_frag;
22901 				if (*up != 0) {
22902 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22903 					    up, PROTO, hlen, LENGTH, max_frag,
22904 					    ipsec_len, cksum);
22905 					/* Software checksum? */
22906 					if (DB_CKSUMFLAGS(mp) == 0) {
22907 						IP_STAT(ipst, ip_out_sw_cksum);
22908 						IP_STAT_UPDATE(ipst,
22909 						    ip_udp_out_sw_cksum_bytes,
22910 						    LENGTH - hlen);
22911 					}
22912 				}
22913 			}
22914 		}
22915 		/*
22916 		 * Need to do this even when fragmenting. The local
22917 		 * loopback can be done without computing checksums
22918 		 * but forwarding out other interface must be done
22919 		 * after the IP checksum (and ULP checksums) have been
22920 		 * computed.
22921 		 *
22922 		 * NOTE : multicast_forward is set only if this packet
22923 		 * originated from ip_wput. For packets originating from
22924 		 * ip_wput_multicast, it is not set.
22925 		 */
22926 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22927 multi_loopback:
22928 			ip2dbg(("ip_wput: multicast, loop %d\n",
22929 			    conn_multicast_loop));
22930 
22931 			/*  Forget header checksum offload */
22932 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22933 
22934 			/*
22935 			 * Local loopback of multicasts?  Check the
22936 			 * ill.
22937 			 *
22938 			 * Note that the loopback function will not come
22939 			 * in through ip_rput - it will only do the
22940 			 * client fanout thus we need to do an mforward
22941 			 * as well.  The is different from the BSD
22942 			 * logic.
22943 			 */
22944 			if (ill != NULL) {
22945 				ilm_t	*ilm;
22946 
22947 				ILM_WALKER_HOLD(ill);
22948 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22949 				    ALL_ZONES);
22950 				ILM_WALKER_RELE(ill);
22951 				if (ilm != NULL) {
22952 					/*
22953 					 * Pass along the virtual output q.
22954 					 * ip_wput_local() will distribute the
22955 					 * packet to all the matching zones,
22956 					 * except the sending zone when
22957 					 * IP_MULTICAST_LOOP is false.
22958 					 */
22959 					ip_multicast_loopback(q, ill, first_mp,
22960 					    conn_multicast_loop ? 0 :
22961 					    IP_FF_NO_MCAST_LOOP, zoneid);
22962 				}
22963 			}
22964 			if (ipha->ipha_ttl == 0) {
22965 				/*
22966 				 * 0 => only to this host i.e. we are
22967 				 * done. We are also done if this was the
22968 				 * loopback interface since it is sufficient
22969 				 * to loopback one copy of a multicast packet.
22970 				 */
22971 				freemsg(first_mp);
22972 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22973 				    "ip_wput_ire_end: q %p (%S)",
22974 				    q, "loopback");
22975 				ire_refrele(ire);
22976 				if (conn_outgoing_ill != NULL)
22977 					ill_refrele(conn_outgoing_ill);
22978 				return;
22979 			}
22980 			/*
22981 			 * ILLF_MULTICAST is checked in ip_newroute
22982 			 * i.e. we don't need to check it here since
22983 			 * all IRE_CACHEs come from ip_newroute.
22984 			 * For multicast traffic, SO_DONTROUTE is interpreted
22985 			 * to mean only send the packet out the interface
22986 			 * (optionally specified with IP_MULTICAST_IF)
22987 			 * and do not forward it out additional interfaces.
22988 			 * RSVP and the rsvp daemon is an example of a
22989 			 * protocol and user level process that
22990 			 * handles it's own routing. Hence, it uses the
22991 			 * SO_DONTROUTE option to accomplish this.
22992 			 */
22993 
22994 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
22995 			    ill != NULL) {
22996 				/* Unconditionally redo the checksum */
22997 				ipha->ipha_hdr_checksum = 0;
22998 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
22999 
23000 				/*
23001 				 * If this needs to go out secure, we need
23002 				 * to wait till we finish the IPsec
23003 				 * processing.
23004 				 */
23005 				if (ipsec_len == 0 &&
23006 				    ip_mforward(ill, ipha, mp)) {
23007 					freemsg(first_mp);
23008 					ip1dbg(("ip_wput: mforward failed\n"));
23009 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23010 					    "ip_wput_ire_end: q %p (%S)",
23011 					    q, "mforward failed");
23012 					ire_refrele(ire);
23013 					if (conn_outgoing_ill != NULL)
23014 						ill_refrele(conn_outgoing_ill);
23015 					return;
23016 				}
23017 			}
23018 		}
23019 		max_frag = ire->ire_max_frag;
23020 		cksum += ttl_protocol;
23021 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23022 			/* No fragmentation required for this one. */
23023 			/*
23024 			 * Don't use frag_flag if packet is pre-built or source
23025 			 * routed or if multicast (since multicast packets do
23026 			 * not solicit ICMP "packet too big" messages).
23027 			 */
23028 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23029 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23030 			    !ip_source_route_included(ipha)) &&
23031 			    !CLASSD(ipha->ipha_dst))
23032 				ipha->ipha_fragment_offset_and_flags |=
23033 				    htons(ire->ire_frag_flag);
23034 
23035 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23036 				/* Complete the IP header checksum. */
23037 				cksum += ipha->ipha_ident;
23038 				cksum += (v_hlen_tos_len >> 16)+
23039 				    (v_hlen_tos_len & 0xFFFF);
23040 				cksum += ipha->ipha_fragment_offset_and_flags;
23041 				hlen = (V_HLEN & 0xF) -
23042 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23043 				if (hlen) {
23044 checksumoptions:
23045 					/*
23046 					 * Account for the IP Options in the IP
23047 					 * header checksum.
23048 					 */
23049 					up = (uint16_t *)(rptr+
23050 					    IP_SIMPLE_HDR_LENGTH);
23051 					do {
23052 						cksum += up[0];
23053 						cksum += up[1];
23054 						up += 2;
23055 					} while (--hlen);
23056 				}
23057 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23058 				cksum = ~(cksum + (cksum >> 16));
23059 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23060 			}
23061 			if (ipsec_len != 0) {
23062 				ipsec_out_process(q, first_mp, ire, ill_index);
23063 				if (!next_mp) {
23064 					ire_refrele(ire);
23065 					if (conn_outgoing_ill != NULL)
23066 						ill_refrele(conn_outgoing_ill);
23067 					return;
23068 				}
23069 				goto next;
23070 			}
23071 
23072 			/*
23073 			 * multirt_send has already been handled
23074 			 * for broadcast, but not yet for multicast
23075 			 * or IP options.
23076 			 */
23077 			if (next_mp == NULL) {
23078 				if (ire->ire_flags & RTF_MULTIRT) {
23079 					multirt_send = B_TRUE;
23080 				}
23081 			}
23082 
23083 			/*
23084 			 * In most cases, the emission loop below is
23085 			 * entered only once. Only in the case where
23086 			 * the ire holds the RTF_MULTIRT flag, do we loop
23087 			 * to process all RTF_MULTIRT ires in the bucket,
23088 			 * and send the packet through all crossed
23089 			 * RTF_MULTIRT routes.
23090 			 */
23091 			do {
23092 				if (multirt_send) {
23093 					irb_t *irb;
23094 
23095 					irb = ire->ire_bucket;
23096 					ASSERT(irb != NULL);
23097 					/*
23098 					 * We are in a multiple send case,
23099 					 * need to get the next IRE and make
23100 					 * a duplicate of the packet.
23101 					 */
23102 					IRB_REFHOLD(irb);
23103 					for (ire1 = ire->ire_next;
23104 					    ire1 != NULL;
23105 					    ire1 = ire1->ire_next) {
23106 						if (!(ire1->ire_flags &
23107 						    RTF_MULTIRT)) {
23108 							continue;
23109 						}
23110 						if (ire1->ire_addr !=
23111 						    ire->ire_addr) {
23112 							continue;
23113 						}
23114 						if (ire1->ire_marks &
23115 						    (IRE_MARK_CONDEMNED|
23116 						    IRE_MARK_HIDDEN)) {
23117 							continue;
23118 						}
23119 
23120 						/* Got one */
23121 						IRE_REFHOLD(ire1);
23122 						break;
23123 					}
23124 					IRB_REFRELE(irb);
23125 
23126 					if (ire1 != NULL) {
23127 						next_mp = copyb(mp);
23128 						if ((next_mp == NULL) ||
23129 						    ((mp->b_cont != NULL) &&
23130 						    ((next_mp->b_cont =
23131 						    dupmsg(mp->b_cont))
23132 						    == NULL))) {
23133 							freemsg(next_mp);
23134 							next_mp = NULL;
23135 							ire_refrele(ire1);
23136 							ire1 = NULL;
23137 						}
23138 					}
23139 
23140 					/*
23141 					 * Last multiroute ire; don't loop
23142 					 * anymore. The emission is over
23143 					 * and next_mp is NULL.
23144 					 */
23145 					if (ire1 == NULL) {
23146 						multirt_send = B_FALSE;
23147 					}
23148 				}
23149 
23150 				out_ill = ire_to_ill(ire);
23151 				DTRACE_PROBE4(ip4__physical__out__start,
23152 				    ill_t *, NULL,
23153 				    ill_t *, out_ill,
23154 				    ipha_t *, ipha, mblk_t *, mp);
23155 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23156 				    ipst->ips_ipv4firewall_physical_out,
23157 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23158 				DTRACE_PROBE1(ip4__physical__out__end,
23159 				    mblk_t *, mp);
23160 				if (mp == NULL)
23161 					goto release_ire_and_ill_2;
23162 
23163 				ASSERT(ipsec_len == 0);
23164 				mp->b_prev =
23165 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23166 				DTRACE_PROBE2(ip__xmit__2,
23167 				    mblk_t *, mp, ire_t *, ire);
23168 				pktxmit_state = ip_xmit_v4(mp, ire,
23169 				    NULL, B_TRUE);
23170 				if ((pktxmit_state == SEND_FAILED) ||
23171 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23172 release_ire_and_ill_2:
23173 					if (next_mp) {
23174 						freemsg(next_mp);
23175 						ire_refrele(ire1);
23176 					}
23177 					ire_refrele(ire);
23178 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23179 					    "ip_wput_ire_end: q %p (%S)",
23180 					    q, "discard MDATA");
23181 					if (conn_outgoing_ill != NULL)
23182 						ill_refrele(conn_outgoing_ill);
23183 					return;
23184 				}
23185 
23186 				if (CLASSD(dst)) {
23187 					BUMP_MIB(out_ill->ill_ip_mib,
23188 					    ipIfStatsHCOutMcastPkts);
23189 					UPDATE_MIB(out_ill->ill_ip_mib,
23190 					    ipIfStatsHCOutMcastOctets,
23191 					    LENGTH);
23192 				} else if (ire->ire_type == IRE_BROADCAST) {
23193 					BUMP_MIB(out_ill->ill_ip_mib,
23194 					    ipIfStatsHCOutBcastPkts);
23195 				}
23196 
23197 				if (multirt_send) {
23198 					/*
23199 					 * We are in a multiple send case,
23200 					 * need to re-enter the sending loop
23201 					 * using the next ire.
23202 					 */
23203 					ire_refrele(ire);
23204 					ire = ire1;
23205 					stq = ire->ire_stq;
23206 					mp = next_mp;
23207 					next_mp = NULL;
23208 					ipha = (ipha_t *)mp->b_rptr;
23209 					ill_index = Q_TO_INDEX(stq);
23210 				}
23211 			} while (multirt_send);
23212 
23213 			if (!next_mp) {
23214 				/*
23215 				 * Last copy going out (the ultra-common
23216 				 * case).  Note that we intentionally replicate
23217 				 * the putnext rather than calling it before
23218 				 * the next_mp check in hopes of a little
23219 				 * tail-call action out of the compiler.
23220 				 */
23221 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23222 				    "ip_wput_ire_end: q %p (%S)",
23223 				    q, "last copy out(1)");
23224 				ire_refrele(ire);
23225 				if (conn_outgoing_ill != NULL)
23226 					ill_refrele(conn_outgoing_ill);
23227 				return;
23228 			}
23229 			/* More copies going out below. */
23230 		} else {
23231 			int offset;
23232 fragmentit:
23233 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23234 			/*
23235 			 * If this would generate a icmp_frag_needed message,
23236 			 * we need to handle it before we do the IPsec
23237 			 * processing. Otherwise, we need to strip the IPsec
23238 			 * headers before we send up the message to the ULPs
23239 			 * which becomes messy and difficult.
23240 			 */
23241 			if (ipsec_len != 0) {
23242 				if ((max_frag < (unsigned int)(LENGTH +
23243 				    ipsec_len)) && (offset & IPH_DF)) {
23244 					out_ill = (ill_t *)stq->q_ptr;
23245 					BUMP_MIB(out_ill->ill_ip_mib,
23246 					    ipIfStatsOutFragFails);
23247 					BUMP_MIB(out_ill->ill_ip_mib,
23248 					    ipIfStatsOutFragReqds);
23249 					ipha->ipha_hdr_checksum = 0;
23250 					ipha->ipha_hdr_checksum =
23251 					    (uint16_t)ip_csum_hdr(ipha);
23252 					icmp_frag_needed(ire->ire_stq, first_mp,
23253 					    max_frag, zoneid, ipst);
23254 					if (!next_mp) {
23255 						ire_refrele(ire);
23256 						if (conn_outgoing_ill != NULL) {
23257 							ill_refrele(
23258 							    conn_outgoing_ill);
23259 						}
23260 						return;
23261 					}
23262 				} else {
23263 					/*
23264 					 * This won't cause a icmp_frag_needed
23265 					 * message. to be generated. Send it on
23266 					 * the wire. Note that this could still
23267 					 * cause fragmentation and all we
23268 					 * do is the generation of the message
23269 					 * to the ULP if needed before IPsec.
23270 					 */
23271 					if (!next_mp) {
23272 						ipsec_out_process(q, first_mp,
23273 						    ire, ill_index);
23274 						TRACE_2(TR_FAC_IP,
23275 						    TR_IP_WPUT_IRE_END,
23276 						    "ip_wput_ire_end: q %p "
23277 						    "(%S)", q,
23278 						    "last ipsec_out_process");
23279 						ire_refrele(ire);
23280 						if (conn_outgoing_ill != NULL) {
23281 							ill_refrele(
23282 							    conn_outgoing_ill);
23283 						}
23284 						return;
23285 					}
23286 					ipsec_out_process(q, first_mp,
23287 					    ire, ill_index);
23288 				}
23289 			} else {
23290 				/*
23291 				 * Initiate IPPF processing. For
23292 				 * fragmentable packets we finish
23293 				 * all QOS packet processing before
23294 				 * calling:
23295 				 * ip_wput_ire_fragmentit->ip_wput_frag
23296 				 */
23297 
23298 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23299 					ip_process(IPP_LOCAL_OUT, &mp,
23300 					    ill_index);
23301 					if (mp == NULL) {
23302 						out_ill = (ill_t *)stq->q_ptr;
23303 						BUMP_MIB(out_ill->ill_ip_mib,
23304 						    ipIfStatsOutDiscards);
23305 						if (next_mp != NULL) {
23306 							freemsg(next_mp);
23307 							ire_refrele(ire1);
23308 						}
23309 						ire_refrele(ire);
23310 						TRACE_2(TR_FAC_IP,
23311 						    TR_IP_WPUT_IRE_END,
23312 						    "ip_wput_ire: q %p (%S)",
23313 						    q, "discard MDATA");
23314 						if (conn_outgoing_ill != NULL) {
23315 							ill_refrele(
23316 							    conn_outgoing_ill);
23317 						}
23318 						return;
23319 					}
23320 				}
23321 				if (!next_mp) {
23322 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23323 					    "ip_wput_ire_end: q %p (%S)",
23324 					    q, "last fragmentation");
23325 					ip_wput_ire_fragmentit(mp, ire,
23326 					    zoneid, ipst);
23327 					ire_refrele(ire);
23328 					if (conn_outgoing_ill != NULL)
23329 						ill_refrele(conn_outgoing_ill);
23330 					return;
23331 				}
23332 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23333 			}
23334 		}
23335 	} else {
23336 nullstq:
23337 		/* A NULL stq means the destination address is local. */
23338 		UPDATE_OB_PKT_COUNT(ire);
23339 		ire->ire_last_used_time = lbolt;
23340 		ASSERT(ire->ire_ipif != NULL);
23341 		if (!next_mp) {
23342 			/*
23343 			 * Is there an "in" and "out" for traffic local
23344 			 * to a host (loopback)?  The code in Solaris doesn't
23345 			 * explicitly draw a line in its code for in vs out,
23346 			 * so we've had to draw a line in the sand: ip_wput_ire
23347 			 * is considered to be the "output" side and
23348 			 * ip_wput_local to be the "input" side.
23349 			 */
23350 			out_ill = ire_to_ill(ire);
23351 
23352 			DTRACE_PROBE4(ip4__loopback__out__start,
23353 			    ill_t *, NULL, ill_t *, out_ill,
23354 			    ipha_t *, ipha, mblk_t *, first_mp);
23355 
23356 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23357 			    ipst->ips_ipv4firewall_loopback_out,
23358 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23359 
23360 			DTRACE_PROBE1(ip4__loopback__out_end,
23361 			    mblk_t *, first_mp);
23362 
23363 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23364 			    "ip_wput_ire_end: q %p (%S)",
23365 			    q, "local address");
23366 
23367 			if (first_mp != NULL)
23368 				ip_wput_local(q, out_ill, ipha,
23369 				    first_mp, ire, 0, ire->ire_zoneid);
23370 			ire_refrele(ire);
23371 			if (conn_outgoing_ill != NULL)
23372 				ill_refrele(conn_outgoing_ill);
23373 			return;
23374 		}
23375 
23376 		out_ill = ire_to_ill(ire);
23377 
23378 		DTRACE_PROBE4(ip4__loopback__out__start,
23379 		    ill_t *, NULL, ill_t *, out_ill,
23380 		    ipha_t *, ipha, mblk_t *, first_mp);
23381 
23382 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23383 		    ipst->ips_ipv4firewall_loopback_out,
23384 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23385 
23386 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23387 
23388 		if (first_mp != NULL)
23389 			ip_wput_local(q, out_ill, ipha,
23390 			    first_mp, ire, 0, ire->ire_zoneid);
23391 	}
23392 next:
23393 	/*
23394 	 * More copies going out to additional interfaces.
23395 	 * ire1 has already been held. We don't need the
23396 	 * "ire" anymore.
23397 	 */
23398 	ire_refrele(ire);
23399 	ire = ire1;
23400 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23401 	mp = next_mp;
23402 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23403 	ill = ire_to_ill(ire);
23404 	first_mp = mp;
23405 	if (ipsec_len != 0) {
23406 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23407 		mp = mp->b_cont;
23408 	}
23409 	dst = ire->ire_addr;
23410 	ipha = (ipha_t *)mp->b_rptr;
23411 	/*
23412 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23413 	 * Restore ipha_ident "no checksum" flag.
23414 	 */
23415 	src = orig_src;
23416 	ipha->ipha_ident = ip_hdr_included;
23417 	goto another;
23418 
23419 #undef	rptr
23420 #undef	Q_TO_INDEX
23421 }
23422 
23423 /*
23424  * Routine to allocate a message that is used to notify the ULP about MDT.
23425  * The caller may provide a pointer to the link-layer MDT capabilities,
23426  * or NULL if MDT is to be disabled on the stream.
23427  */
23428 mblk_t *
23429 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23430 {
23431 	mblk_t *mp;
23432 	ip_mdt_info_t *mdti;
23433 	ill_mdt_capab_t *idst;
23434 
23435 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23436 		DB_TYPE(mp) = M_CTL;
23437 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23438 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23439 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23440 		idst = &(mdti->mdt_capab);
23441 
23442 		/*
23443 		 * If the caller provides us with the capability, copy
23444 		 * it over into our notification message; otherwise
23445 		 * we zero out the capability portion.
23446 		 */
23447 		if (isrc != NULL)
23448 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23449 		else
23450 			bzero((caddr_t)idst, sizeof (*idst));
23451 	}
23452 	return (mp);
23453 }
23454 
23455 /*
23456  * Routine which determines whether MDT can be enabled on the destination
23457  * IRE and IPC combination, and if so, allocates and returns the MDT
23458  * notification mblk that may be used by ULP.  We also check if we need to
23459  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23460  * MDT usage in the past have been lifted.  This gets called during IP
23461  * and ULP binding.
23462  */
23463 mblk_t *
23464 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23465     ill_mdt_capab_t *mdt_cap)
23466 {
23467 	mblk_t *mp;
23468 	boolean_t rc = B_FALSE;
23469 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23470 
23471 	ASSERT(dst_ire != NULL);
23472 	ASSERT(connp != NULL);
23473 	ASSERT(mdt_cap != NULL);
23474 
23475 	/*
23476 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23477 	 * Multidata, which is handled in tcp_multisend().  This
23478 	 * is the reason why we do all these checks here, to ensure
23479 	 * that we don't enable Multidata for the cases which we
23480 	 * can't handle at the moment.
23481 	 */
23482 	do {
23483 		/* Only do TCP at the moment */
23484 		if (connp->conn_ulp != IPPROTO_TCP)
23485 			break;
23486 
23487 		/*
23488 		 * IPsec outbound policy present?  Note that we get here
23489 		 * after calling ipsec_conn_cache_policy() where the global
23490 		 * policy checking is performed.  conn_latch will be
23491 		 * non-NULL as long as there's a policy defined,
23492 		 * i.e. conn_out_enforce_policy may be NULL in such case
23493 		 * when the connection is non-secure, and hence we check
23494 		 * further if the latch refers to an outbound policy.
23495 		 */
23496 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23497 			break;
23498 
23499 		/* CGTP (multiroute) is enabled? */
23500 		if (dst_ire->ire_flags & RTF_MULTIRT)
23501 			break;
23502 
23503 		/* Outbound IPQoS enabled? */
23504 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23505 			/*
23506 			 * In this case, we disable MDT for this and all
23507 			 * future connections going over the interface.
23508 			 */
23509 			mdt_cap->ill_mdt_on = 0;
23510 			break;
23511 		}
23512 
23513 		/* socket option(s) present? */
23514 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23515 			break;
23516 
23517 		rc = B_TRUE;
23518 	/* CONSTCOND */
23519 	} while (0);
23520 
23521 	/* Remember the result */
23522 	connp->conn_mdt_ok = rc;
23523 
23524 	if (!rc)
23525 		return (NULL);
23526 	else if (!mdt_cap->ill_mdt_on) {
23527 		/*
23528 		 * If MDT has been previously turned off in the past, and we
23529 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23530 		 * then enable it for this interface.
23531 		 */
23532 		mdt_cap->ill_mdt_on = 1;
23533 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23534 		    "interface %s\n", ill_name));
23535 	}
23536 
23537 	/* Allocate the MDT info mblk */
23538 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23539 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23540 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23541 		return (NULL);
23542 	}
23543 	return (mp);
23544 }
23545 
23546 /*
23547  * Routine to allocate a message that is used to notify the ULP about LSO.
23548  * The caller may provide a pointer to the link-layer LSO capabilities,
23549  * or NULL if LSO is to be disabled on the stream.
23550  */
23551 mblk_t *
23552 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23553 {
23554 	mblk_t *mp;
23555 	ip_lso_info_t *lsoi;
23556 	ill_lso_capab_t *idst;
23557 
23558 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23559 		DB_TYPE(mp) = M_CTL;
23560 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23561 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23562 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23563 		idst = &(lsoi->lso_capab);
23564 
23565 		/*
23566 		 * If the caller provides us with the capability, copy
23567 		 * it over into our notification message; otherwise
23568 		 * we zero out the capability portion.
23569 		 */
23570 		if (isrc != NULL)
23571 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23572 		else
23573 			bzero((caddr_t)idst, sizeof (*idst));
23574 	}
23575 	return (mp);
23576 }
23577 
23578 /*
23579  * Routine which determines whether LSO can be enabled on the destination
23580  * IRE and IPC combination, and if so, allocates and returns the LSO
23581  * notification mblk that may be used by ULP.  We also check if we need to
23582  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23583  * LSO usage in the past have been lifted.  This gets called during IP
23584  * and ULP binding.
23585  */
23586 mblk_t *
23587 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23588     ill_lso_capab_t *lso_cap)
23589 {
23590 	mblk_t *mp;
23591 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23592 
23593 	ASSERT(dst_ire != NULL);
23594 	ASSERT(connp != NULL);
23595 	ASSERT(lso_cap != NULL);
23596 
23597 	connp->conn_lso_ok = B_TRUE;
23598 
23599 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23600 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23601 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23602 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23603 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23604 		connp->conn_lso_ok = B_FALSE;
23605 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23606 			/*
23607 			 * Disable LSO for this and all future connections going
23608 			 * over the interface.
23609 			 */
23610 			lso_cap->ill_lso_on = 0;
23611 		}
23612 	}
23613 
23614 	if (!connp->conn_lso_ok)
23615 		return (NULL);
23616 	else if (!lso_cap->ill_lso_on) {
23617 		/*
23618 		 * If LSO has been previously turned off in the past, and we
23619 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23620 		 * then enable it for this interface.
23621 		 */
23622 		lso_cap->ill_lso_on = 1;
23623 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23624 		    ill_name));
23625 	}
23626 
23627 	/* Allocate the LSO info mblk */
23628 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23629 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23630 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23631 
23632 	return (mp);
23633 }
23634 
23635 /*
23636  * Create destination address attribute, and fill it with the physical
23637  * destination address and SAP taken from the template DL_UNITDATA_REQ
23638  * message block.
23639  */
23640 boolean_t
23641 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23642 {
23643 	dl_unitdata_req_t *dlurp;
23644 	pattr_t *pa;
23645 	pattrinfo_t pa_info;
23646 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23647 	uint_t das_len, das_off;
23648 
23649 	ASSERT(dlmp != NULL);
23650 
23651 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23652 	das_len = dlurp->dl_dest_addr_length;
23653 	das_off = dlurp->dl_dest_addr_offset;
23654 
23655 	pa_info.type = PATTR_DSTADDRSAP;
23656 	pa_info.len = sizeof (**das) + das_len - 1;
23657 
23658 	/* create and associate the attribute */
23659 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23660 	if (pa != NULL) {
23661 		ASSERT(*das != NULL);
23662 		(*das)->addr_is_group = 0;
23663 		(*das)->addr_len = (uint8_t)das_len;
23664 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23665 	}
23666 
23667 	return (pa != NULL);
23668 }
23669 
23670 /*
23671  * Create hardware checksum attribute and fill it with the values passed.
23672  */
23673 boolean_t
23674 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23675     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23676 {
23677 	pattr_t *pa;
23678 	pattrinfo_t pa_info;
23679 
23680 	ASSERT(mmd != NULL);
23681 
23682 	pa_info.type = PATTR_HCKSUM;
23683 	pa_info.len = sizeof (pattr_hcksum_t);
23684 
23685 	/* create and associate the attribute */
23686 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23687 	if (pa != NULL) {
23688 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23689 
23690 		hck->hcksum_start_offset = start_offset;
23691 		hck->hcksum_stuff_offset = stuff_offset;
23692 		hck->hcksum_end_offset = end_offset;
23693 		hck->hcksum_flags = flags;
23694 	}
23695 	return (pa != NULL);
23696 }
23697 
23698 /*
23699  * Create zerocopy attribute and fill it with the specified flags
23700  */
23701 boolean_t
23702 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23703 {
23704 	pattr_t *pa;
23705 	pattrinfo_t pa_info;
23706 
23707 	ASSERT(mmd != NULL);
23708 	pa_info.type = PATTR_ZCOPY;
23709 	pa_info.len = sizeof (pattr_zcopy_t);
23710 
23711 	/* create and associate the attribute */
23712 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23713 	if (pa != NULL) {
23714 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23715 
23716 		zcopy->zcopy_flags = flags;
23717 	}
23718 	return (pa != NULL);
23719 }
23720 
23721 /*
23722  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23723  * block chain. We could rewrite to handle arbitrary message block chains but
23724  * that would make the code complicated and slow. Right now there three
23725  * restrictions:
23726  *
23727  *   1. The first message block must contain the complete IP header and
23728  *	at least 1 byte of payload data.
23729  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23730  *	so that we can use a single Multidata message.
23731  *   3. No frag must be distributed over two or more message blocks so
23732  *	that we don't need more than two packet descriptors per frag.
23733  *
23734  * The above restrictions allow us to support userland applications (which
23735  * will send down a single message block) and NFS over UDP (which will
23736  * send down a chain of at most three message blocks).
23737  *
23738  * We also don't use MDT for payloads with less than or equal to
23739  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23740  */
23741 boolean_t
23742 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23743 {
23744 	int	blocks;
23745 	ssize_t	total, missing, size;
23746 
23747 	ASSERT(mp != NULL);
23748 	ASSERT(hdr_len > 0);
23749 
23750 	size = MBLKL(mp) - hdr_len;
23751 	if (size <= 0)
23752 		return (B_FALSE);
23753 
23754 	/* The first mblk contains the header and some payload. */
23755 	blocks = 1;
23756 	total = size;
23757 	size %= len;
23758 	missing = (size == 0) ? 0 : (len - size);
23759 	mp = mp->b_cont;
23760 
23761 	while (mp != NULL) {
23762 		/*
23763 		 * Give up if we encounter a zero length message block.
23764 		 * In practice, this should rarely happen and therefore
23765 		 * not worth the trouble of freeing and re-linking the
23766 		 * mblk from the chain to handle such case.
23767 		 */
23768 		if ((size = MBLKL(mp)) == 0)
23769 			return (B_FALSE);
23770 
23771 		/* Too many payload buffers for a single Multidata message? */
23772 		if (++blocks > MULTIDATA_MAX_PBUFS)
23773 			return (B_FALSE);
23774 
23775 		total += size;
23776 		/* Is a frag distributed over two or more message blocks? */
23777 		if (missing > size)
23778 			return (B_FALSE);
23779 		size -= missing;
23780 
23781 		size %= len;
23782 		missing = (size == 0) ? 0 : (len - size);
23783 
23784 		mp = mp->b_cont;
23785 	}
23786 
23787 	return (total > ip_wput_frag_mdt_min);
23788 }
23789 
23790 /*
23791  * Outbound IPv4 fragmentation routine using MDT.
23792  */
23793 static void
23794 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23795     uint32_t frag_flag, int offset)
23796 {
23797 	ipha_t		*ipha_orig;
23798 	int		i1, ip_data_end;
23799 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23800 	mblk_t		*hdr_mp, *md_mp = NULL;
23801 	unsigned char	*hdr_ptr, *pld_ptr;
23802 	multidata_t	*mmd;
23803 	ip_pdescinfo_t	pdi;
23804 	ill_t		*ill;
23805 	ip_stack_t	*ipst = ire->ire_ipst;
23806 
23807 	ASSERT(DB_TYPE(mp) == M_DATA);
23808 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23809 
23810 	ill = ire_to_ill(ire);
23811 	ASSERT(ill != NULL);
23812 
23813 	ipha_orig = (ipha_t *)mp->b_rptr;
23814 	mp->b_rptr += sizeof (ipha_t);
23815 
23816 	/* Calculate how many packets we will send out */
23817 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23818 	pkts = (i1 + len - 1) / len;
23819 	ASSERT(pkts > 1);
23820 
23821 	/* Allocate a message block which will hold all the IP Headers. */
23822 	wroff = ipst->ips_ip_wroff_extra;
23823 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23824 
23825 	i1 = pkts * hdr_chunk_len;
23826 	/*
23827 	 * Create the header buffer, Multidata and destination address
23828 	 * and SAP attribute that should be associated with it.
23829 	 */
23830 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23831 	    ((hdr_mp->b_wptr += i1),
23832 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23833 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23834 		freemsg(mp);
23835 		if (md_mp == NULL) {
23836 			freemsg(hdr_mp);
23837 		} else {
23838 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23839 			freemsg(md_mp);
23840 		}
23841 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23842 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23843 		return;
23844 	}
23845 	IP_STAT(ipst, ip_frag_mdt_allocd);
23846 
23847 	/*
23848 	 * Add a payload buffer to the Multidata; this operation must not
23849 	 * fail, or otherwise our logic in this routine is broken.  There
23850 	 * is no memory allocation done by the routine, so any returned
23851 	 * failure simply tells us that we've done something wrong.
23852 	 *
23853 	 * A failure tells us that either we're adding the same payload
23854 	 * buffer more than once, or we're trying to add more buffers than
23855 	 * allowed.  None of the above cases should happen, and we panic
23856 	 * because either there's horrible heap corruption, and/or
23857 	 * programming mistake.
23858 	 */
23859 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23860 		goto pbuf_panic;
23861 
23862 	hdr_ptr = hdr_mp->b_rptr;
23863 	pld_ptr = mp->b_rptr;
23864 
23865 	/* Establish the ending byte offset, based on the starting offset. */
23866 	offset <<= 3;
23867 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23868 	    IP_SIMPLE_HDR_LENGTH;
23869 
23870 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23871 
23872 	while (pld_ptr < mp->b_wptr) {
23873 		ipha_t		*ipha;
23874 		uint16_t	offset_and_flags;
23875 		uint16_t	ip_len;
23876 		int		error;
23877 
23878 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23879 		ipha = (ipha_t *)(hdr_ptr + wroff);
23880 		ASSERT(OK_32PTR(ipha));
23881 		*ipha = *ipha_orig;
23882 
23883 		if (ip_data_end - offset > len) {
23884 			offset_and_flags = IPH_MF;
23885 		} else {
23886 			/*
23887 			 * Last frag. Set len to the length of this last piece.
23888 			 */
23889 			len = ip_data_end - offset;
23890 			/* A frag of a frag might have IPH_MF non-zero */
23891 			offset_and_flags =
23892 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23893 			    IPH_MF;
23894 		}
23895 		offset_and_flags |= (uint16_t)(offset >> 3);
23896 		offset_and_flags |= (uint16_t)frag_flag;
23897 		/* Store the offset and flags in the IP header. */
23898 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23899 
23900 		/* Store the length in the IP header. */
23901 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23902 		ipha->ipha_length = htons(ip_len);
23903 
23904 		/*
23905 		 * Set the IP header checksum.  Note that mp is just
23906 		 * the header, so this is easy to pass to ip_csum.
23907 		 */
23908 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23909 
23910 		/*
23911 		 * Record offset and size of header and data of the next packet
23912 		 * in the multidata message.
23913 		 */
23914 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23915 		PDESC_PLD_INIT(&pdi);
23916 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23917 		ASSERT(i1 > 0);
23918 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23919 		if (i1 == len) {
23920 			pld_ptr += len;
23921 		} else {
23922 			i1 = len - i1;
23923 			mp = mp->b_cont;
23924 			ASSERT(mp != NULL);
23925 			ASSERT(MBLKL(mp) >= i1);
23926 			/*
23927 			 * Attach the next payload message block to the
23928 			 * multidata message.
23929 			 */
23930 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23931 				goto pbuf_panic;
23932 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23933 			pld_ptr = mp->b_rptr + i1;
23934 		}
23935 
23936 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23937 		    KM_NOSLEEP)) == NULL) {
23938 			/*
23939 			 * Any failure other than ENOMEM indicates that we
23940 			 * have passed in invalid pdesc info or parameters
23941 			 * to mmd_addpdesc, which must not happen.
23942 			 *
23943 			 * EINVAL is a result of failure on boundary checks
23944 			 * against the pdesc info contents.  It should not
23945 			 * happen, and we panic because either there's
23946 			 * horrible heap corruption, and/or programming
23947 			 * mistake.
23948 			 */
23949 			if (error != ENOMEM) {
23950 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23951 				    "pdesc logic error detected for "
23952 				    "mmd %p pinfo %p (%d)\n",
23953 				    (void *)mmd, (void *)&pdi, error);
23954 				/* NOTREACHED */
23955 			}
23956 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23957 			/* Free unattached payload message blocks as well */
23958 			md_mp->b_cont = mp->b_cont;
23959 			goto free_mmd;
23960 		}
23961 
23962 		/* Advance fragment offset. */
23963 		offset += len;
23964 
23965 		/* Advance to location for next header in the buffer. */
23966 		hdr_ptr += hdr_chunk_len;
23967 
23968 		/* Did we reach the next payload message block? */
23969 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
23970 			mp = mp->b_cont;
23971 			/*
23972 			 * Attach the next message block with payload
23973 			 * data to the multidata message.
23974 			 */
23975 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23976 				goto pbuf_panic;
23977 			pld_ptr = mp->b_rptr;
23978 		}
23979 	}
23980 
23981 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
23982 	ASSERT(mp->b_wptr == pld_ptr);
23983 
23984 	/* Update IP statistics */
23985 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
23986 
23987 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
23988 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
23989 
23990 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
23991 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
23992 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
23993 
23994 	if (pkt_type == OB_PKT) {
23995 		ire->ire_ob_pkt_count += pkts;
23996 		if (ire->ire_ipif != NULL)
23997 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
23998 	} else {
23999 		/* The type is IB_PKT in the forwarding path. */
24000 		ire->ire_ib_pkt_count += pkts;
24001 		ASSERT(!IRE_IS_LOCAL(ire));
24002 		if (ire->ire_type & IRE_BROADCAST) {
24003 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24004 		} else {
24005 			UPDATE_MIB(ill->ill_ip_mib,
24006 			    ipIfStatsHCOutForwDatagrams, pkts);
24007 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24008 		}
24009 	}
24010 	ire->ire_last_used_time = lbolt;
24011 	/* Send it down */
24012 	putnext(ire->ire_stq, md_mp);
24013 	return;
24014 
24015 pbuf_panic:
24016 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24017 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24018 	    pbuf_idx);
24019 	/* NOTREACHED */
24020 }
24021 
24022 /*
24023  * Outbound IP fragmentation routine.
24024  *
24025  * NOTE : This routine does not ire_refrele the ire that is passed in
24026  * as the argument.
24027  */
24028 static void
24029 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24030     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24031 {
24032 	int		i1;
24033 	mblk_t		*ll_hdr_mp;
24034 	int 		ll_hdr_len;
24035 	int		hdr_len;
24036 	mblk_t		*hdr_mp;
24037 	ipha_t		*ipha;
24038 	int		ip_data_end;
24039 	int		len;
24040 	mblk_t		*mp = mp_orig, *mp1;
24041 	int		offset;
24042 	queue_t		*q;
24043 	uint32_t	v_hlen_tos_len;
24044 	mblk_t		*first_mp;
24045 	boolean_t	mctl_present;
24046 	ill_t		*ill;
24047 	ill_t		*out_ill;
24048 	mblk_t		*xmit_mp;
24049 	mblk_t		*carve_mp;
24050 	ire_t		*ire1 = NULL;
24051 	ire_t		*save_ire = NULL;
24052 	mblk_t  	*next_mp = NULL;
24053 	boolean_t	last_frag = B_FALSE;
24054 	boolean_t	multirt_send = B_FALSE;
24055 	ire_t		*first_ire = NULL;
24056 	irb_t		*irb = NULL;
24057 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24058 
24059 	ill = ire_to_ill(ire);
24060 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24061 
24062 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24063 
24064 	if (max_frag == 0) {
24065 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24066 		    " -  dropping packet\n"));
24067 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24068 		freemsg(mp);
24069 		return;
24070 	}
24071 
24072 	/*
24073 	 * IPsec does not allow hw accelerated packets to be fragmented
24074 	 * This check is made in ip_wput_ipsec_out prior to coming here
24075 	 * via ip_wput_ire_fragmentit.
24076 	 *
24077 	 * If at this point we have an ire whose ARP request has not
24078 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24079 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24080 	 * This packet and all fragmentable packets for this ire will
24081 	 * continue to get dropped while ire_nce->nce_state remains in
24082 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24083 	 * ND_REACHABLE, all subsquent large packets for this ire will
24084 	 * get fragemented and sent out by this function.
24085 	 */
24086 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24087 		/* If nce_state is ND_INITIAL, trigger ARP query */
24088 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24089 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24090 		    " -  dropping packet\n"));
24091 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24092 		freemsg(mp);
24093 		return;
24094 	}
24095 
24096 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24097 	    "ip_wput_frag_start:");
24098 
24099 	if (mp->b_datap->db_type == M_CTL) {
24100 		first_mp = mp;
24101 		mp_orig = mp = mp->b_cont;
24102 		mctl_present = B_TRUE;
24103 	} else {
24104 		first_mp = mp;
24105 		mctl_present = B_FALSE;
24106 	}
24107 
24108 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24109 	ipha = (ipha_t *)mp->b_rptr;
24110 
24111 	/*
24112 	 * If the Don't Fragment flag is on, generate an ICMP destination
24113 	 * unreachable, fragmentation needed.
24114 	 */
24115 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24116 	if (offset & IPH_DF) {
24117 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24118 		if (is_system_labeled()) {
24119 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24120 			    ire->ire_max_frag - max_frag, AF_INET);
24121 		}
24122 		/*
24123 		 * Need to compute hdr checksum if called from ip_wput_ire.
24124 		 * Note that ip_rput_forward verifies the checksum before
24125 		 * calling this routine so in that case this is a noop.
24126 		 */
24127 		ipha->ipha_hdr_checksum = 0;
24128 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24129 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24130 		    ipst);
24131 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24132 		    "ip_wput_frag_end:(%S)",
24133 		    "don't fragment");
24134 		return;
24135 	}
24136 	/*
24137 	 * Labeled systems adjust max_frag if they add a label
24138 	 * to send the correct path mtu.  We need the real mtu since we
24139 	 * are fragmenting the packet after label adjustment.
24140 	 */
24141 	if (is_system_labeled())
24142 		max_frag = ire->ire_max_frag;
24143 	if (mctl_present)
24144 		freeb(first_mp);
24145 	/*
24146 	 * Establish the starting offset.  May not be zero if we are fragging
24147 	 * a fragment that is being forwarded.
24148 	 */
24149 	offset = offset & IPH_OFFSET;
24150 
24151 	/* TODO why is this test needed? */
24152 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24153 	if (((max_frag - LENGTH) & ~7) < 8) {
24154 		/* TODO: notify ulp somehow */
24155 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24156 		freemsg(mp);
24157 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24158 		    "ip_wput_frag_end:(%S)",
24159 		    "len < 8");
24160 		return;
24161 	}
24162 
24163 	hdr_len = (V_HLEN & 0xF) << 2;
24164 
24165 	ipha->ipha_hdr_checksum = 0;
24166 
24167 	/*
24168 	 * Establish the number of bytes maximum per frag, after putting
24169 	 * in the header.
24170 	 */
24171 	len = (max_frag - hdr_len) & ~7;
24172 
24173 	/* Check if we can use MDT to send out the frags. */
24174 	ASSERT(!IRE_IS_LOCAL(ire));
24175 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24176 	    ipst->ips_ip_multidata_outbound &&
24177 	    !(ire->ire_flags & RTF_MULTIRT) &&
24178 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24179 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24180 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24181 		ASSERT(ill->ill_mdt_capab != NULL);
24182 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24183 			/*
24184 			 * If MDT has been previously turned off in the past,
24185 			 * and we currently can do MDT (due to IPQoS policy
24186 			 * removal, etc.) then enable it for this interface.
24187 			 */
24188 			ill->ill_mdt_capab->ill_mdt_on = 1;
24189 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24190 			    ill->ill_name));
24191 		}
24192 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24193 		    offset);
24194 		return;
24195 	}
24196 
24197 	/* Get a copy of the header for the trailing frags */
24198 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24199 	if (!hdr_mp) {
24200 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24201 		freemsg(mp);
24202 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24203 		    "ip_wput_frag_end:(%S)",
24204 		    "couldn't copy hdr");
24205 		return;
24206 	}
24207 	if (DB_CRED(mp) != NULL)
24208 		mblk_setcred(hdr_mp, DB_CRED(mp));
24209 
24210 	/* Store the starting offset, with the MoreFrags flag. */
24211 	i1 = offset | IPH_MF | frag_flag;
24212 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24213 
24214 	/* Establish the ending byte offset, based on the starting offset. */
24215 	offset <<= 3;
24216 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24217 
24218 	/* Store the length of the first fragment in the IP header. */
24219 	i1 = len + hdr_len;
24220 	ASSERT(i1 <= IP_MAXPACKET);
24221 	ipha->ipha_length = htons((uint16_t)i1);
24222 
24223 	/*
24224 	 * Compute the IP header checksum for the first frag.  We have to
24225 	 * watch out that we stop at the end of the header.
24226 	 */
24227 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24228 
24229 	/*
24230 	 * Now carve off the first frag.  Note that this will include the
24231 	 * original IP header.
24232 	 */
24233 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24234 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24235 		freeb(hdr_mp);
24236 		freemsg(mp_orig);
24237 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24238 		    "ip_wput_frag_end:(%S)",
24239 		    "couldn't carve first");
24240 		return;
24241 	}
24242 
24243 	/*
24244 	 * Multirouting case. Each fragment is replicated
24245 	 * via all non-condemned RTF_MULTIRT routes
24246 	 * currently resolved.
24247 	 * We ensure that first_ire is the first RTF_MULTIRT
24248 	 * ire in the bucket.
24249 	 */
24250 	if (ire->ire_flags & RTF_MULTIRT) {
24251 		irb = ire->ire_bucket;
24252 		ASSERT(irb != NULL);
24253 
24254 		multirt_send = B_TRUE;
24255 
24256 		/* Make sure we do not omit any multiroute ire. */
24257 		IRB_REFHOLD(irb);
24258 		for (first_ire = irb->irb_ire;
24259 		    first_ire != NULL;
24260 		    first_ire = first_ire->ire_next) {
24261 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24262 			    (first_ire->ire_addr == ire->ire_addr) &&
24263 			    !(first_ire->ire_marks &
24264 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24265 				break;
24266 			}
24267 		}
24268 
24269 		if (first_ire != NULL) {
24270 			if (first_ire != ire) {
24271 				IRE_REFHOLD(first_ire);
24272 				/*
24273 				 * Do not release the ire passed in
24274 				 * as the argument.
24275 				 */
24276 				ire = first_ire;
24277 			} else {
24278 				first_ire = NULL;
24279 			}
24280 		}
24281 		IRB_REFRELE(irb);
24282 
24283 		/*
24284 		 * Save the first ire; we will need to restore it
24285 		 * for the trailing frags.
24286 		 * We REFHOLD save_ire, as each iterated ire will be
24287 		 * REFRELEd.
24288 		 */
24289 		save_ire = ire;
24290 		IRE_REFHOLD(save_ire);
24291 	}
24292 
24293 	/*
24294 	 * First fragment emission loop.
24295 	 * In most cases, the emission loop below is entered only
24296 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24297 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24298 	 * bucket, and send the fragment through all crossed
24299 	 * RTF_MULTIRT routes.
24300 	 */
24301 	do {
24302 		if (ire->ire_flags & RTF_MULTIRT) {
24303 			/*
24304 			 * We are in a multiple send case, need to get
24305 			 * the next ire and make a copy of the packet.
24306 			 * ire1 holds here the next ire to process in the
24307 			 * bucket. If multirouting is expected,
24308 			 * any non-RTF_MULTIRT ire that has the
24309 			 * right destination address is ignored.
24310 			 *
24311 			 * We have to take into account the MTU of
24312 			 * each walked ire. max_frag is set by the
24313 			 * the caller and generally refers to
24314 			 * the primary ire entry. Here we ensure that
24315 			 * no route with a lower MTU will be used, as
24316 			 * fragments are carved once for all ires,
24317 			 * then replicated.
24318 			 */
24319 			ASSERT(irb != NULL);
24320 			IRB_REFHOLD(irb);
24321 			for (ire1 = ire->ire_next;
24322 			    ire1 != NULL;
24323 			    ire1 = ire1->ire_next) {
24324 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24325 					continue;
24326 				if (ire1->ire_addr != ire->ire_addr)
24327 					continue;
24328 				if (ire1->ire_marks &
24329 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24330 					continue;
24331 				/*
24332 				 * Ensure we do not exceed the MTU
24333 				 * of the next route.
24334 				 */
24335 				if (ire1->ire_max_frag < max_frag) {
24336 					ip_multirt_bad_mtu(ire1, max_frag);
24337 					continue;
24338 				}
24339 
24340 				/* Got one. */
24341 				IRE_REFHOLD(ire1);
24342 				break;
24343 			}
24344 			IRB_REFRELE(irb);
24345 
24346 			if (ire1 != NULL) {
24347 				next_mp = copyb(mp);
24348 				if ((next_mp == NULL) ||
24349 				    ((mp->b_cont != NULL) &&
24350 				    ((next_mp->b_cont =
24351 				    dupmsg(mp->b_cont)) == NULL))) {
24352 					freemsg(next_mp);
24353 					next_mp = NULL;
24354 					ire_refrele(ire1);
24355 					ire1 = NULL;
24356 				}
24357 			}
24358 
24359 			/* Last multiroute ire; don't loop anymore. */
24360 			if (ire1 == NULL) {
24361 				multirt_send = B_FALSE;
24362 			}
24363 		}
24364 
24365 		ll_hdr_len = 0;
24366 		LOCK_IRE_FP_MP(ire);
24367 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24368 		if (ll_hdr_mp != NULL) {
24369 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24370 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24371 		} else {
24372 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24373 		}
24374 
24375 		/* If there is a transmit header, get a copy for this frag. */
24376 		/*
24377 		 * TODO: should check db_ref before calling ip_carve_mp since
24378 		 * it might give us a dup.
24379 		 */
24380 		if (!ll_hdr_mp) {
24381 			/* No xmit header. */
24382 			xmit_mp = mp;
24383 
24384 		/* We have a link-layer header that can fit in our mblk. */
24385 		} else if (mp->b_datap->db_ref == 1 &&
24386 		    ll_hdr_len != 0 &&
24387 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24388 			/* M_DATA fastpath */
24389 			mp->b_rptr -= ll_hdr_len;
24390 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24391 			xmit_mp = mp;
24392 
24393 		/* Corner case if copyb has failed */
24394 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24395 			UNLOCK_IRE_FP_MP(ire);
24396 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24397 			freeb(hdr_mp);
24398 			freemsg(mp);
24399 			freemsg(mp_orig);
24400 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24401 			    "ip_wput_frag_end:(%S)",
24402 			    "discard");
24403 
24404 			if (multirt_send) {
24405 				ASSERT(ire1);
24406 				ASSERT(next_mp);
24407 
24408 				freemsg(next_mp);
24409 				ire_refrele(ire1);
24410 			}
24411 			if (save_ire != NULL)
24412 				IRE_REFRELE(save_ire);
24413 
24414 			if (first_ire != NULL)
24415 				ire_refrele(first_ire);
24416 			return;
24417 
24418 		/*
24419 		 * Case of res_mp OR the fastpath mp can't fit
24420 		 * in the mblk
24421 		 */
24422 		} else {
24423 			xmit_mp->b_cont = mp;
24424 			if (DB_CRED(mp) != NULL)
24425 				mblk_setcred(xmit_mp, DB_CRED(mp));
24426 			/*
24427 			 * Get priority marking, if any.
24428 			 * We propagate the CoS marking from the
24429 			 * original packet that went to QoS processing
24430 			 * in ip_wput_ire to the newly carved mp.
24431 			 */
24432 			if (DB_TYPE(xmit_mp) == M_DATA)
24433 				xmit_mp->b_band = mp->b_band;
24434 		}
24435 		UNLOCK_IRE_FP_MP(ire);
24436 
24437 		q = ire->ire_stq;
24438 		out_ill = (ill_t *)q->q_ptr;
24439 
24440 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24441 
24442 		DTRACE_PROBE4(ip4__physical__out__start,
24443 		    ill_t *, NULL, ill_t *, out_ill,
24444 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24445 
24446 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24447 		    ipst->ips_ipv4firewall_physical_out,
24448 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24449 
24450 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24451 
24452 		if (xmit_mp != NULL) {
24453 			putnext(q, xmit_mp);
24454 
24455 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24456 			UPDATE_MIB(out_ill->ill_ip_mib,
24457 			    ipIfStatsHCOutOctets, i1);
24458 
24459 			if (pkt_type != OB_PKT) {
24460 				/*
24461 				 * Update the packet count and MIB stats
24462 				 * of trailing RTF_MULTIRT ires.
24463 				 */
24464 				UPDATE_OB_PKT_COUNT(ire);
24465 				BUMP_MIB(out_ill->ill_ip_mib,
24466 				    ipIfStatsOutFragReqds);
24467 			}
24468 		}
24469 
24470 		if (multirt_send) {
24471 			/*
24472 			 * We are in a multiple send case; look for
24473 			 * the next ire and re-enter the loop.
24474 			 */
24475 			ASSERT(ire1);
24476 			ASSERT(next_mp);
24477 			/* REFRELE the current ire before looping */
24478 			ire_refrele(ire);
24479 			ire = ire1;
24480 			ire1 = NULL;
24481 			mp = next_mp;
24482 			next_mp = NULL;
24483 		}
24484 	} while (multirt_send);
24485 
24486 	ASSERT(ire1 == NULL);
24487 
24488 	/* Restore the original ire; we need it for the trailing frags */
24489 	if (save_ire != NULL) {
24490 		/* REFRELE the last iterated ire */
24491 		ire_refrele(ire);
24492 		/* save_ire has been REFHOLDed */
24493 		ire = save_ire;
24494 		save_ire = NULL;
24495 		q = ire->ire_stq;
24496 	}
24497 
24498 	if (pkt_type == OB_PKT) {
24499 		UPDATE_OB_PKT_COUNT(ire);
24500 	} else {
24501 		out_ill = (ill_t *)q->q_ptr;
24502 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24503 		UPDATE_IB_PKT_COUNT(ire);
24504 	}
24505 
24506 	/* Advance the offset to the second frag starting point. */
24507 	offset += len;
24508 	/*
24509 	 * Update hdr_len from the copied header - there might be less options
24510 	 * in the later fragments.
24511 	 */
24512 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24513 	/* Loop until done. */
24514 	for (;;) {
24515 		uint16_t	offset_and_flags;
24516 		uint16_t	ip_len;
24517 
24518 		if (ip_data_end - offset > len) {
24519 			/*
24520 			 * Carve off the appropriate amount from the original
24521 			 * datagram.
24522 			 */
24523 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24524 				mp = NULL;
24525 				break;
24526 			}
24527 			/*
24528 			 * More frags after this one.  Get another copy
24529 			 * of the header.
24530 			 */
24531 			if (carve_mp->b_datap->db_ref == 1 &&
24532 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24533 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24534 				/* Inline IP header */
24535 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24536 				    hdr_mp->b_rptr;
24537 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24538 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24539 				mp = carve_mp;
24540 			} else {
24541 				if (!(mp = copyb(hdr_mp))) {
24542 					freemsg(carve_mp);
24543 					break;
24544 				}
24545 				/* Get priority marking, if any. */
24546 				mp->b_band = carve_mp->b_band;
24547 				mp->b_cont = carve_mp;
24548 			}
24549 			ipha = (ipha_t *)mp->b_rptr;
24550 			offset_and_flags = IPH_MF;
24551 		} else {
24552 			/*
24553 			 * Last frag.  Consume the header. Set len to
24554 			 * the length of this last piece.
24555 			 */
24556 			len = ip_data_end - offset;
24557 
24558 			/*
24559 			 * Carve off the appropriate amount from the original
24560 			 * datagram.
24561 			 */
24562 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24563 				mp = NULL;
24564 				break;
24565 			}
24566 			if (carve_mp->b_datap->db_ref == 1 &&
24567 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24568 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24569 				/* Inline IP header */
24570 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24571 				    hdr_mp->b_rptr;
24572 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24573 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24574 				mp = carve_mp;
24575 				freeb(hdr_mp);
24576 				hdr_mp = mp;
24577 			} else {
24578 				mp = hdr_mp;
24579 				/* Get priority marking, if any. */
24580 				mp->b_band = carve_mp->b_band;
24581 				mp->b_cont = carve_mp;
24582 			}
24583 			ipha = (ipha_t *)mp->b_rptr;
24584 			/* A frag of a frag might have IPH_MF non-zero */
24585 			offset_and_flags =
24586 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24587 			    IPH_MF;
24588 		}
24589 		offset_and_flags |= (uint16_t)(offset >> 3);
24590 		offset_and_flags |= (uint16_t)frag_flag;
24591 		/* Store the offset and flags in the IP header. */
24592 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24593 
24594 		/* Store the length in the IP header. */
24595 		ip_len = (uint16_t)(len + hdr_len);
24596 		ipha->ipha_length = htons(ip_len);
24597 
24598 		/*
24599 		 * Set the IP header checksum.	Note that mp is just
24600 		 * the header, so this is easy to pass to ip_csum.
24601 		 */
24602 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24603 
24604 		/* Attach a transmit header, if any, and ship it. */
24605 		if (pkt_type == OB_PKT) {
24606 			UPDATE_OB_PKT_COUNT(ire);
24607 		} else {
24608 			out_ill = (ill_t *)q->q_ptr;
24609 			BUMP_MIB(out_ill->ill_ip_mib,
24610 			    ipIfStatsHCOutForwDatagrams);
24611 			UPDATE_IB_PKT_COUNT(ire);
24612 		}
24613 
24614 		if (ire->ire_flags & RTF_MULTIRT) {
24615 			irb = ire->ire_bucket;
24616 			ASSERT(irb != NULL);
24617 
24618 			multirt_send = B_TRUE;
24619 
24620 			/*
24621 			 * Save the original ire; we will need to restore it
24622 			 * for the tailing frags.
24623 			 */
24624 			save_ire = ire;
24625 			IRE_REFHOLD(save_ire);
24626 		}
24627 		/*
24628 		 * Emission loop for this fragment, similar
24629 		 * to what is done for the first fragment.
24630 		 */
24631 		do {
24632 			if (multirt_send) {
24633 				/*
24634 				 * We are in a multiple send case, need to get
24635 				 * the next ire and make a copy of the packet.
24636 				 */
24637 				ASSERT(irb != NULL);
24638 				IRB_REFHOLD(irb);
24639 				for (ire1 = ire->ire_next;
24640 				    ire1 != NULL;
24641 				    ire1 = ire1->ire_next) {
24642 					if (!(ire1->ire_flags & RTF_MULTIRT))
24643 						continue;
24644 					if (ire1->ire_addr != ire->ire_addr)
24645 						continue;
24646 					if (ire1->ire_marks &
24647 					    (IRE_MARK_CONDEMNED|
24648 					    IRE_MARK_HIDDEN)) {
24649 						continue;
24650 					}
24651 					/*
24652 					 * Ensure we do not exceed the MTU
24653 					 * of the next route.
24654 					 */
24655 					if (ire1->ire_max_frag < max_frag) {
24656 						ip_multirt_bad_mtu(ire1,
24657 						    max_frag);
24658 						continue;
24659 					}
24660 
24661 					/* Got one. */
24662 					IRE_REFHOLD(ire1);
24663 					break;
24664 				}
24665 				IRB_REFRELE(irb);
24666 
24667 				if (ire1 != NULL) {
24668 					next_mp = copyb(mp);
24669 					if ((next_mp == NULL) ||
24670 					    ((mp->b_cont != NULL) &&
24671 					    ((next_mp->b_cont =
24672 					    dupmsg(mp->b_cont)) == NULL))) {
24673 						freemsg(next_mp);
24674 						next_mp = NULL;
24675 						ire_refrele(ire1);
24676 						ire1 = NULL;
24677 					}
24678 				}
24679 
24680 				/* Last multiroute ire; don't loop anymore. */
24681 				if (ire1 == NULL) {
24682 					multirt_send = B_FALSE;
24683 				}
24684 			}
24685 
24686 			/* Update transmit header */
24687 			ll_hdr_len = 0;
24688 			LOCK_IRE_FP_MP(ire);
24689 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24690 			if (ll_hdr_mp != NULL) {
24691 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24692 				ll_hdr_len = MBLKL(ll_hdr_mp);
24693 			} else {
24694 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24695 			}
24696 
24697 			if (!ll_hdr_mp) {
24698 				xmit_mp = mp;
24699 
24700 			/*
24701 			 * We have link-layer header that can fit in
24702 			 * our mblk.
24703 			 */
24704 			} else if (mp->b_datap->db_ref == 1 &&
24705 			    ll_hdr_len != 0 &&
24706 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24707 				/* M_DATA fastpath */
24708 				mp->b_rptr -= ll_hdr_len;
24709 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24710 				    ll_hdr_len);
24711 				xmit_mp = mp;
24712 
24713 			/*
24714 			 * Case of res_mp OR the fastpath mp can't fit
24715 			 * in the mblk
24716 			 */
24717 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24718 				xmit_mp->b_cont = mp;
24719 				if (DB_CRED(mp) != NULL)
24720 					mblk_setcred(xmit_mp, DB_CRED(mp));
24721 				/* Get priority marking, if any. */
24722 				if (DB_TYPE(xmit_mp) == M_DATA)
24723 					xmit_mp->b_band = mp->b_band;
24724 
24725 			/* Corner case if copyb failed */
24726 			} else {
24727 				/*
24728 				 * Exit both the replication and
24729 				 * fragmentation loops.
24730 				 */
24731 				UNLOCK_IRE_FP_MP(ire);
24732 				goto drop_pkt;
24733 			}
24734 			UNLOCK_IRE_FP_MP(ire);
24735 
24736 			mp1 = mp;
24737 			out_ill = (ill_t *)q->q_ptr;
24738 
24739 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24740 
24741 			DTRACE_PROBE4(ip4__physical__out__start,
24742 			    ill_t *, NULL, ill_t *, out_ill,
24743 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24744 
24745 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24746 			    ipst->ips_ipv4firewall_physical_out,
24747 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24748 
24749 			DTRACE_PROBE1(ip4__physical__out__end,
24750 			    mblk_t *, xmit_mp);
24751 
24752 			if (mp != mp1 && hdr_mp == mp1)
24753 				hdr_mp = mp;
24754 			if (mp != mp1 && mp_orig == mp1)
24755 				mp_orig = mp;
24756 
24757 			if (xmit_mp != NULL) {
24758 				putnext(q, xmit_mp);
24759 
24760 				BUMP_MIB(out_ill->ill_ip_mib,
24761 				    ipIfStatsHCOutTransmits);
24762 				UPDATE_MIB(out_ill->ill_ip_mib,
24763 				    ipIfStatsHCOutOctets, ip_len);
24764 
24765 				if (pkt_type != OB_PKT) {
24766 					/*
24767 					 * Update the packet count of trailing
24768 					 * RTF_MULTIRT ires.
24769 					 */
24770 					UPDATE_OB_PKT_COUNT(ire);
24771 				}
24772 			}
24773 
24774 			/* All done if we just consumed the hdr_mp. */
24775 			if (mp == hdr_mp) {
24776 				last_frag = B_TRUE;
24777 				BUMP_MIB(out_ill->ill_ip_mib,
24778 				    ipIfStatsOutFragOKs);
24779 			}
24780 
24781 			if (multirt_send) {
24782 				/*
24783 				 * We are in a multiple send case; look for
24784 				 * the next ire and re-enter the loop.
24785 				 */
24786 				ASSERT(ire1);
24787 				ASSERT(next_mp);
24788 				/* REFRELE the current ire before looping */
24789 				ire_refrele(ire);
24790 				ire = ire1;
24791 				ire1 = NULL;
24792 				q = ire->ire_stq;
24793 				mp = next_mp;
24794 				next_mp = NULL;
24795 			}
24796 		} while (multirt_send);
24797 		/*
24798 		 * Restore the original ire; we need it for the
24799 		 * trailing frags
24800 		 */
24801 		if (save_ire != NULL) {
24802 			ASSERT(ire1 == NULL);
24803 			/* REFRELE the last iterated ire */
24804 			ire_refrele(ire);
24805 			/* save_ire has been REFHOLDed */
24806 			ire = save_ire;
24807 			q = ire->ire_stq;
24808 			save_ire = NULL;
24809 		}
24810 
24811 		if (last_frag) {
24812 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24813 			    "ip_wput_frag_end:(%S)",
24814 			    "consumed hdr_mp");
24815 
24816 			if (first_ire != NULL)
24817 				ire_refrele(first_ire);
24818 			return;
24819 		}
24820 		/* Otherwise, advance and loop. */
24821 		offset += len;
24822 	}
24823 
24824 drop_pkt:
24825 	/* Clean up following allocation failure. */
24826 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24827 	freemsg(mp);
24828 	if (mp != hdr_mp)
24829 		freeb(hdr_mp);
24830 	if (mp != mp_orig)
24831 		freemsg(mp_orig);
24832 
24833 	if (save_ire != NULL)
24834 		IRE_REFRELE(save_ire);
24835 	if (first_ire != NULL)
24836 		ire_refrele(first_ire);
24837 
24838 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24839 	    "ip_wput_frag_end:(%S)",
24840 	    "end--alloc failure");
24841 }
24842 
24843 /*
24844  * Copy the header plus those options which have the copy bit set
24845  */
24846 static mblk_t *
24847 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24848 {
24849 	mblk_t	*mp;
24850 	uchar_t	*up;
24851 
24852 	/*
24853 	 * Quick check if we need to look for options without the copy bit
24854 	 * set
24855 	 */
24856 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24857 	if (!mp)
24858 		return (mp);
24859 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24860 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24861 		bcopy(rptr, mp->b_rptr, hdr_len);
24862 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24863 		return (mp);
24864 	}
24865 	up  = mp->b_rptr;
24866 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24867 	up += IP_SIMPLE_HDR_LENGTH;
24868 	rptr += IP_SIMPLE_HDR_LENGTH;
24869 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24870 	while (hdr_len > 0) {
24871 		uint32_t optval;
24872 		uint32_t optlen;
24873 
24874 		optval = *rptr;
24875 		if (optval == IPOPT_EOL)
24876 			break;
24877 		if (optval == IPOPT_NOP)
24878 			optlen = 1;
24879 		else
24880 			optlen = rptr[1];
24881 		if (optval & IPOPT_COPY) {
24882 			bcopy(rptr, up, optlen);
24883 			up += optlen;
24884 		}
24885 		rptr += optlen;
24886 		hdr_len -= optlen;
24887 	}
24888 	/*
24889 	 * Make sure that we drop an even number of words by filling
24890 	 * with EOL to the next word boundary.
24891 	 */
24892 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24893 	    hdr_len & 0x3; hdr_len++)
24894 		*up++ = IPOPT_EOL;
24895 	mp->b_wptr = up;
24896 	/* Update header length */
24897 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24898 	return (mp);
24899 }
24900 
24901 /*
24902  * Delivery to local recipients including fanout to multiple recipients.
24903  * Does not do checksumming of UDP/TCP.
24904  * Note: q should be the read side queue for either the ill or conn.
24905  * Note: rq should be the read side q for the lower (ill) stream.
24906  * We don't send packets to IPPF processing, thus the last argument
24907  * to all the fanout calls are B_FALSE.
24908  */
24909 void
24910 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24911     int fanout_flags, zoneid_t zoneid)
24912 {
24913 	uint32_t	protocol;
24914 	mblk_t		*first_mp;
24915 	boolean_t	mctl_present;
24916 	int		ire_type;
24917 #define	rptr	((uchar_t *)ipha)
24918 	ip_stack_t	*ipst = ill->ill_ipst;
24919 
24920 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24921 	    "ip_wput_local_start: q %p", q);
24922 
24923 	if (ire != NULL) {
24924 		ire_type = ire->ire_type;
24925 	} else {
24926 		/*
24927 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24928 		 * packet is not multicast, we can't tell the ire type.
24929 		 */
24930 		ASSERT(CLASSD(ipha->ipha_dst));
24931 		ire_type = IRE_BROADCAST;
24932 	}
24933 
24934 	first_mp = mp;
24935 	if (first_mp->b_datap->db_type == M_CTL) {
24936 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24937 		if (!io->ipsec_out_secure) {
24938 			/*
24939 			 * This ipsec_out_t was allocated in ip_wput
24940 			 * for multicast packets to store the ill_index.
24941 			 * As this is being delivered locally, we don't
24942 			 * need this anymore.
24943 			 */
24944 			mp = first_mp->b_cont;
24945 			freeb(first_mp);
24946 			first_mp = mp;
24947 			mctl_present = B_FALSE;
24948 		} else {
24949 			/*
24950 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24951 			 * security properties for the looped-back packet.
24952 			 */
24953 			mctl_present = B_TRUE;
24954 			mp = first_mp->b_cont;
24955 			ASSERT(mp != NULL);
24956 			ipsec_out_to_in(first_mp);
24957 		}
24958 	} else {
24959 		mctl_present = B_FALSE;
24960 	}
24961 
24962 	DTRACE_PROBE4(ip4__loopback__in__start,
24963 	    ill_t *, ill, ill_t *, NULL,
24964 	    ipha_t *, ipha, mblk_t *, first_mp);
24965 
24966 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
24967 	    ipst->ips_ipv4firewall_loopback_in,
24968 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
24969 
24970 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
24971 
24972 	if (first_mp == NULL)
24973 		return;
24974 
24975 	ipst->ips_loopback_packets++;
24976 
24977 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
24978 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
24979 	if (!IS_SIMPLE_IPH(ipha)) {
24980 		ip_wput_local_options(ipha, ipst);
24981 	}
24982 
24983 	protocol = ipha->ipha_protocol;
24984 	switch (protocol) {
24985 	case IPPROTO_ICMP: {
24986 		ire_t		*ire_zone;
24987 		ilm_t		*ilm;
24988 		mblk_t		*mp1;
24989 		zoneid_t	last_zoneid;
24990 
24991 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
24992 			ASSERT(ire_type == IRE_BROADCAST);
24993 			/*
24994 			 * In the multicast case, applications may have joined
24995 			 * the group from different zones, so we need to deliver
24996 			 * the packet to each of them. Loop through the
24997 			 * multicast memberships structures (ilm) on the receive
24998 			 * ill and send a copy of the packet up each matching
24999 			 * one. However, we don't do this for multicasts sent on
25000 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25001 			 * they must stay in the sender's zone.
25002 			 *
25003 			 * ilm_add_v6() ensures that ilms in the same zone are
25004 			 * contiguous in the ill_ilm list. We use this property
25005 			 * to avoid sending duplicates needed when two
25006 			 * applications in the same zone join the same group on
25007 			 * different logical interfaces: we ignore the ilm if
25008 			 * it's zoneid is the same as the last matching one.
25009 			 * In addition, the sending of the packet for
25010 			 * ire_zoneid is delayed until all of the other ilms
25011 			 * have been exhausted.
25012 			 */
25013 			last_zoneid = -1;
25014 			ILM_WALKER_HOLD(ill);
25015 			for (ilm = ill->ill_ilm; ilm != NULL;
25016 			    ilm = ilm->ilm_next) {
25017 				if ((ilm->ilm_flags & ILM_DELETED) ||
25018 				    ipha->ipha_dst != ilm->ilm_addr ||
25019 				    ilm->ilm_zoneid == last_zoneid ||
25020 				    ilm->ilm_zoneid == zoneid ||
25021 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25022 					continue;
25023 				mp1 = ip_copymsg(first_mp);
25024 				if (mp1 == NULL)
25025 					continue;
25026 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25027 				    mctl_present, B_FALSE, ill,
25028 				    ilm->ilm_zoneid);
25029 				last_zoneid = ilm->ilm_zoneid;
25030 			}
25031 			ILM_WALKER_RELE(ill);
25032 			/*
25033 			 * Loopback case: the sending endpoint has
25034 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25035 			 * dispatch the multicast packet to the sending zone.
25036 			 */
25037 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25038 				freemsg(first_mp);
25039 				return;
25040 			}
25041 		} else if (ire_type == IRE_BROADCAST) {
25042 			/*
25043 			 * In the broadcast case, there may be many zones
25044 			 * which need a copy of the packet delivered to them.
25045 			 * There is one IRE_BROADCAST per broadcast address
25046 			 * and per zone; we walk those using a helper function.
25047 			 * In addition, the sending of the packet for zoneid is
25048 			 * delayed until all of the other ires have been
25049 			 * processed.
25050 			 */
25051 			IRB_REFHOLD(ire->ire_bucket);
25052 			ire_zone = NULL;
25053 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25054 			    ire)) != NULL) {
25055 				mp1 = ip_copymsg(first_mp);
25056 				if (mp1 == NULL)
25057 					continue;
25058 
25059 				UPDATE_IB_PKT_COUNT(ire_zone);
25060 				ire_zone->ire_last_used_time = lbolt;
25061 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25062 				    mctl_present, B_FALSE, ill,
25063 				    ire_zone->ire_zoneid);
25064 			}
25065 			IRB_REFRELE(ire->ire_bucket);
25066 		}
25067 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25068 		    0, mctl_present, B_FALSE, ill, zoneid);
25069 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25070 		    "ip_wput_local_end: q %p (%S)",
25071 		    q, "icmp");
25072 		return;
25073 	}
25074 	case IPPROTO_IGMP:
25075 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25076 			/* Bad packet - discarded by igmp_input */
25077 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25078 			    "ip_wput_local_end: q %p (%S)",
25079 			    q, "igmp_input--bad packet");
25080 			if (mctl_present)
25081 				freeb(first_mp);
25082 			return;
25083 		}
25084 		/*
25085 		 * igmp_input() may have returned the pulled up message.
25086 		 * So first_mp and ipha need to be reinitialized.
25087 		 */
25088 		ipha = (ipha_t *)mp->b_rptr;
25089 		if (mctl_present)
25090 			first_mp->b_cont = mp;
25091 		else
25092 			first_mp = mp;
25093 		/* deliver to local raw users */
25094 		break;
25095 	case IPPROTO_ENCAP:
25096 		/*
25097 		 * This case is covered by either ip_fanout_proto, or by
25098 		 * the above security processing for self-tunneled packets.
25099 		 */
25100 		break;
25101 	case IPPROTO_UDP: {
25102 		uint16_t	*up;
25103 		uint32_t	ports;
25104 
25105 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25106 		    UDP_PORTS_OFFSET);
25107 		/* Force a 'valid' checksum. */
25108 		up[3] = 0;
25109 
25110 		ports = *(uint32_t *)up;
25111 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25112 		    (ire_type == IRE_BROADCAST),
25113 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25114 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25115 		    ill, zoneid);
25116 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25117 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25118 		return;
25119 	}
25120 	case IPPROTO_TCP: {
25121 
25122 		/*
25123 		 * For TCP, discard broadcast packets.
25124 		 */
25125 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25126 			freemsg(first_mp);
25127 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25128 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25129 			return;
25130 		}
25131 
25132 		if (mp->b_datap->db_type == M_DATA) {
25133 			/*
25134 			 * M_DATA mblk, so init mblk (chain) for no struio().
25135 			 */
25136 			mblk_t	*mp1 = mp;
25137 
25138 			do {
25139 				mp1->b_datap->db_struioflag = 0;
25140 			} while ((mp1 = mp1->b_cont) != NULL);
25141 		}
25142 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25143 		    <= mp->b_wptr);
25144 		ip_fanout_tcp(q, first_mp, ill, ipha,
25145 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25146 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25147 		    mctl_present, B_FALSE, zoneid);
25148 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25149 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25150 		return;
25151 	}
25152 	case IPPROTO_SCTP:
25153 	{
25154 		uint32_t	ports;
25155 
25156 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25157 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25158 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25159 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25160 		return;
25161 	}
25162 
25163 	default:
25164 		break;
25165 	}
25166 	/*
25167 	 * Find a client for some other protocol.  We give
25168 	 * copies to multiple clients, if more than one is
25169 	 * bound.
25170 	 */
25171 	ip_fanout_proto(q, first_mp, ill, ipha,
25172 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25173 	    mctl_present, B_FALSE, ill, zoneid);
25174 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25175 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25176 #undef	rptr
25177 }
25178 
25179 /*
25180  * Update any source route, record route, or timestamp options.
25181  * Check that we are at end of strict source route.
25182  * The options have been sanity checked by ip_wput_options().
25183  */
25184 static void
25185 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25186 {
25187 	ipoptp_t	opts;
25188 	uchar_t		*opt;
25189 	uint8_t		optval;
25190 	uint8_t		optlen;
25191 	ipaddr_t	dst;
25192 	uint32_t	ts;
25193 	ire_t		*ire;
25194 	timestruc_t	now;
25195 
25196 	ip2dbg(("ip_wput_local_options\n"));
25197 	for (optval = ipoptp_first(&opts, ipha);
25198 	    optval != IPOPT_EOL;
25199 	    optval = ipoptp_next(&opts)) {
25200 		opt = opts.ipoptp_cur;
25201 		optlen = opts.ipoptp_len;
25202 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25203 		switch (optval) {
25204 			uint32_t off;
25205 		case IPOPT_SSRR:
25206 		case IPOPT_LSRR:
25207 			off = opt[IPOPT_OFFSET];
25208 			off--;
25209 			if (optlen < IP_ADDR_LEN ||
25210 			    off > optlen - IP_ADDR_LEN) {
25211 				/* End of source route */
25212 				break;
25213 			}
25214 			/*
25215 			 * This will only happen if two consecutive entries
25216 			 * in the source route contains our address or if
25217 			 * it is a packet with a loose source route which
25218 			 * reaches us before consuming the whole source route
25219 			 */
25220 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25221 			if (optval == IPOPT_SSRR) {
25222 				return;
25223 			}
25224 			/*
25225 			 * Hack: instead of dropping the packet truncate the
25226 			 * source route to what has been used by filling the
25227 			 * rest with IPOPT_NOP.
25228 			 */
25229 			opt[IPOPT_OLEN] = (uint8_t)off;
25230 			while (off < optlen) {
25231 				opt[off++] = IPOPT_NOP;
25232 			}
25233 			break;
25234 		case IPOPT_RR:
25235 			off = opt[IPOPT_OFFSET];
25236 			off--;
25237 			if (optlen < IP_ADDR_LEN ||
25238 			    off > optlen - IP_ADDR_LEN) {
25239 				/* No more room - ignore */
25240 				ip1dbg((
25241 				    "ip_wput_forward_options: end of RR\n"));
25242 				break;
25243 			}
25244 			dst = htonl(INADDR_LOOPBACK);
25245 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25246 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25247 			break;
25248 		case IPOPT_TS:
25249 			/* Insert timestamp if there is romm */
25250 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25251 			case IPOPT_TS_TSONLY:
25252 				off = IPOPT_TS_TIMELEN;
25253 				break;
25254 			case IPOPT_TS_PRESPEC:
25255 			case IPOPT_TS_PRESPEC_RFC791:
25256 				/* Verify that the address matched */
25257 				off = opt[IPOPT_OFFSET] - 1;
25258 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25259 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25260 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25261 				    ipst);
25262 				if (ire == NULL) {
25263 					/* Not for us */
25264 					break;
25265 				}
25266 				ire_refrele(ire);
25267 				/* FALLTHRU */
25268 			case IPOPT_TS_TSANDADDR:
25269 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25270 				break;
25271 			default:
25272 				/*
25273 				 * ip_*put_options should have already
25274 				 * dropped this packet.
25275 				 */
25276 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25277 				    "unknown IT - bug in ip_wput_options?\n");
25278 				return;	/* Keep "lint" happy */
25279 			}
25280 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25281 				/* Increase overflow counter */
25282 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25283 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25284 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25285 				    (off << 4);
25286 				break;
25287 			}
25288 			off = opt[IPOPT_OFFSET] - 1;
25289 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25290 			case IPOPT_TS_PRESPEC:
25291 			case IPOPT_TS_PRESPEC_RFC791:
25292 			case IPOPT_TS_TSANDADDR:
25293 				dst = htonl(INADDR_LOOPBACK);
25294 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25295 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25296 				/* FALLTHRU */
25297 			case IPOPT_TS_TSONLY:
25298 				off = opt[IPOPT_OFFSET] - 1;
25299 				/* Compute # of milliseconds since midnight */
25300 				gethrestime(&now);
25301 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25302 				    now.tv_nsec / (NANOSEC / MILLISEC);
25303 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25304 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25305 				break;
25306 			}
25307 			break;
25308 		}
25309 	}
25310 }
25311 
25312 /*
25313  * Send out a multicast packet on interface ipif.
25314  * The sender does not have an conn.
25315  * Caller verifies that this isn't a PHYI_LOOPBACK.
25316  */
25317 void
25318 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25319 {
25320 	ipha_t	*ipha;
25321 	ire_t	*ire;
25322 	ipaddr_t	dst;
25323 	mblk_t		*first_mp;
25324 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25325 
25326 	/* igmp_sendpkt always allocates a ipsec_out_t */
25327 	ASSERT(mp->b_datap->db_type == M_CTL);
25328 	ASSERT(!ipif->ipif_isv6);
25329 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25330 
25331 	first_mp = mp;
25332 	mp = first_mp->b_cont;
25333 	ASSERT(mp->b_datap->db_type == M_DATA);
25334 	ipha = (ipha_t *)mp->b_rptr;
25335 
25336 	/*
25337 	 * Find an IRE which matches the destination and the outgoing
25338 	 * queue (i.e. the outgoing interface.)
25339 	 */
25340 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25341 		dst = ipif->ipif_pp_dst_addr;
25342 	else
25343 		dst = ipha->ipha_dst;
25344 	/*
25345 	 * The source address has already been initialized by the
25346 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25347 	 * be sufficient rather than MATCH_IRE_IPIF.
25348 	 *
25349 	 * This function is used for sending IGMP packets. We need
25350 	 * to make sure that we send the packet out of the interface
25351 	 * (ipif->ipif_ill) where we joined the group. This is to
25352 	 * prevent from switches doing IGMP snooping to send us multicast
25353 	 * packets for a given group on the interface we have joined.
25354 	 * If we can't find an ire, igmp_sendpkt has already initialized
25355 	 * ipsec_out_attach_if so that this will not be load spread in
25356 	 * ip_newroute_ipif.
25357 	 */
25358 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25359 	    MATCH_IRE_ILL, ipst);
25360 	if (!ire) {
25361 		/*
25362 		 * Mark this packet to make it be delivered to
25363 		 * ip_wput_ire after the new ire has been
25364 		 * created.
25365 		 */
25366 		mp->b_prev = NULL;
25367 		mp->b_next = NULL;
25368 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25369 		    zoneid, &zero_info);
25370 		return;
25371 	}
25372 
25373 	/*
25374 	 * Honor the RTF_SETSRC flag; this is the only case
25375 	 * where we force this addr whatever the current src addr is,
25376 	 * because this address is set by igmp_sendpkt(), and
25377 	 * cannot be specified by any user.
25378 	 */
25379 	if (ire->ire_flags & RTF_SETSRC) {
25380 		ipha->ipha_src = ire->ire_src_addr;
25381 	}
25382 
25383 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25384 }
25385 
25386 /*
25387  * NOTE : This function does not ire_refrele the ire argument passed in.
25388  *
25389  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25390  * failure. The nce_fp_mp can vanish any time in the case of
25391  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25392  * the ire_lock to access the nce_fp_mp in this case.
25393  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25394  * prepending a fastpath message IPQoS processing must precede it, we also set
25395  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25396  * (IPQoS might have set the b_band for CoS marking).
25397  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25398  * must follow it so that IPQoS can mark the dl_priority field for CoS
25399  * marking, if needed.
25400  */
25401 static mblk_t *
25402 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25403 {
25404 	uint_t	hlen;
25405 	ipha_t *ipha;
25406 	mblk_t *mp1;
25407 	boolean_t qos_done = B_FALSE;
25408 	uchar_t	*ll_hdr;
25409 	ip_stack_t	*ipst = ire->ire_ipst;
25410 
25411 #define	rptr	((uchar_t *)ipha)
25412 
25413 	ipha = (ipha_t *)mp->b_rptr;
25414 	hlen = 0;
25415 	LOCK_IRE_FP_MP(ire);
25416 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25417 		ASSERT(DB_TYPE(mp1) == M_DATA);
25418 		/* Initiate IPPF processing */
25419 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25420 			UNLOCK_IRE_FP_MP(ire);
25421 			ip_process(proc, &mp, ill_index);
25422 			if (mp == NULL)
25423 				return (NULL);
25424 
25425 			ipha = (ipha_t *)mp->b_rptr;
25426 			LOCK_IRE_FP_MP(ire);
25427 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25428 				qos_done = B_TRUE;
25429 				goto no_fp_mp;
25430 			}
25431 			ASSERT(DB_TYPE(mp1) == M_DATA);
25432 		}
25433 		hlen = MBLKL(mp1);
25434 		/*
25435 		 * Check if we have enough room to prepend fastpath
25436 		 * header
25437 		 */
25438 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25439 			ll_hdr = rptr - hlen;
25440 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25441 			/*
25442 			 * Set the b_rptr to the start of the link layer
25443 			 * header
25444 			 */
25445 			mp->b_rptr = ll_hdr;
25446 			mp1 = mp;
25447 		} else {
25448 			mp1 = copyb(mp1);
25449 			if (mp1 == NULL)
25450 				goto unlock_err;
25451 			mp1->b_band = mp->b_band;
25452 			mp1->b_cont = mp;
25453 			/*
25454 			 * certain system generated traffic may not
25455 			 * have cred/label in ip header block. This
25456 			 * is true even for a labeled system. But for
25457 			 * labeled traffic, inherit the label in the
25458 			 * new header.
25459 			 */
25460 			if (DB_CRED(mp) != NULL)
25461 				mblk_setcred(mp1, DB_CRED(mp));
25462 			/*
25463 			 * XXX disable ICK_VALID and compute checksum
25464 			 * here; can happen if nce_fp_mp changes and
25465 			 * it can't be copied now due to insufficient
25466 			 * space. (unlikely, fp mp can change, but it
25467 			 * does not increase in length)
25468 			 */
25469 		}
25470 		UNLOCK_IRE_FP_MP(ire);
25471 	} else {
25472 no_fp_mp:
25473 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25474 		if (mp1 == NULL) {
25475 unlock_err:
25476 			UNLOCK_IRE_FP_MP(ire);
25477 			freemsg(mp);
25478 			return (NULL);
25479 		}
25480 		UNLOCK_IRE_FP_MP(ire);
25481 		mp1->b_cont = mp;
25482 		/*
25483 		 * certain system generated traffic may not
25484 		 * have cred/label in ip header block. This
25485 		 * is true even for a labeled system. But for
25486 		 * labeled traffic, inherit the label in the
25487 		 * new header.
25488 		 */
25489 		if (DB_CRED(mp) != NULL)
25490 			mblk_setcred(mp1, DB_CRED(mp));
25491 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25492 			ip_process(proc, &mp1, ill_index);
25493 			if (mp1 == NULL)
25494 				return (NULL);
25495 		}
25496 	}
25497 	return (mp1);
25498 #undef rptr
25499 }
25500 
25501 /*
25502  * Finish the outbound IPsec processing for an IPv6 packet. This function
25503  * is called from ipsec_out_process() if the IPsec packet was processed
25504  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25505  * asynchronously.
25506  */
25507 void
25508 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25509     ire_t *ire_arg)
25510 {
25511 	in6_addr_t *v6dstp;
25512 	ire_t *ire;
25513 	mblk_t *mp;
25514 	ip6_t *ip6h1;
25515 	uint_t	ill_index;
25516 	ipsec_out_t *io;
25517 	boolean_t attach_if, hwaccel;
25518 	uint32_t flags = IP6_NO_IPPOLICY;
25519 	int match_flags;
25520 	zoneid_t zoneid;
25521 	boolean_t ill_need_rele = B_FALSE;
25522 	boolean_t ire_need_rele = B_FALSE;
25523 	ip_stack_t	*ipst;
25524 
25525 	mp = ipsec_mp->b_cont;
25526 	ip6h1 = (ip6_t *)mp->b_rptr;
25527 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25528 	ASSERT(io->ipsec_out_ns != NULL);
25529 	ipst = io->ipsec_out_ns->netstack_ip;
25530 	ill_index = io->ipsec_out_ill_index;
25531 	if (io->ipsec_out_reachable) {
25532 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25533 	}
25534 	attach_if = io->ipsec_out_attach_if;
25535 	hwaccel = io->ipsec_out_accelerated;
25536 	zoneid = io->ipsec_out_zoneid;
25537 	ASSERT(zoneid != ALL_ZONES);
25538 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25539 	/* Multicast addresses should have non-zero ill_index. */
25540 	v6dstp = &ip6h->ip6_dst;
25541 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25542 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25543 	ASSERT(!attach_if || ill_index != 0);
25544 	if (ill_index != 0) {
25545 		if (ill == NULL) {
25546 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25547 			    B_TRUE, ipst);
25548 
25549 			/* Failure case frees things for us. */
25550 			if (ill == NULL)
25551 				return;
25552 
25553 			ill_need_rele = B_TRUE;
25554 		}
25555 		/*
25556 		 * If this packet needs to go out on a particular interface
25557 		 * honor it.
25558 		 */
25559 		if (attach_if) {
25560 			match_flags = MATCH_IRE_ILL;
25561 
25562 			/*
25563 			 * Check if we need an ire that will not be
25564 			 * looked up by anybody else i.e. HIDDEN.
25565 			 */
25566 			if (ill_is_probeonly(ill)) {
25567 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25568 			}
25569 		}
25570 	}
25571 	ASSERT(mp != NULL);
25572 
25573 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25574 		boolean_t unspec_src;
25575 		ipif_t	*ipif;
25576 
25577 		/*
25578 		 * Use the ill_index to get the right ill.
25579 		 */
25580 		unspec_src = io->ipsec_out_unspec_src;
25581 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25582 		if (ipif == NULL) {
25583 			if (ill_need_rele)
25584 				ill_refrele(ill);
25585 			freemsg(ipsec_mp);
25586 			return;
25587 		}
25588 
25589 		if (ire_arg != NULL) {
25590 			ire = ire_arg;
25591 		} else {
25592 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25593 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25594 			ire_need_rele = B_TRUE;
25595 		}
25596 		if (ire != NULL) {
25597 			ipif_refrele(ipif);
25598 			/*
25599 			 * XXX Do the multicast forwarding now, as the IPsec
25600 			 * processing has been done.
25601 			 */
25602 			goto send;
25603 		}
25604 
25605 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25606 		mp->b_prev = NULL;
25607 		mp->b_next = NULL;
25608 
25609 		/*
25610 		 * If the IPsec packet was processed asynchronously,
25611 		 * drop it now.
25612 		 */
25613 		if (q == NULL) {
25614 			if (ill_need_rele)
25615 				ill_refrele(ill);
25616 			freemsg(ipsec_mp);
25617 			return;
25618 		}
25619 
25620 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25621 		    unspec_src, zoneid);
25622 		ipif_refrele(ipif);
25623 	} else {
25624 		if (attach_if) {
25625 			ipif_t	*ipif;
25626 
25627 			ipif = ipif_get_next_ipif(NULL, ill);
25628 			if (ipif == NULL) {
25629 				if (ill_need_rele)
25630 					ill_refrele(ill);
25631 				freemsg(ipsec_mp);
25632 				return;
25633 			}
25634 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25635 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25636 			ire_need_rele = B_TRUE;
25637 			ipif_refrele(ipif);
25638 		} else {
25639 			if (ire_arg != NULL) {
25640 				ire = ire_arg;
25641 			} else {
25642 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25643 				    ipst);
25644 				ire_need_rele = B_TRUE;
25645 			}
25646 		}
25647 		if (ire != NULL)
25648 			goto send;
25649 		/*
25650 		 * ire disappeared underneath.
25651 		 *
25652 		 * What we need to do here is the ip_newroute
25653 		 * logic to get the ire without doing the IPsec
25654 		 * processing. Follow the same old path. But this
25655 		 * time, ip_wput or ire_add_then_send will call us
25656 		 * directly as all the IPsec operations are done.
25657 		 */
25658 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25659 		mp->b_prev = NULL;
25660 		mp->b_next = NULL;
25661 
25662 		/*
25663 		 * If the IPsec packet was processed asynchronously,
25664 		 * drop it now.
25665 		 */
25666 		if (q == NULL) {
25667 			if (ill_need_rele)
25668 				ill_refrele(ill);
25669 			freemsg(ipsec_mp);
25670 			return;
25671 		}
25672 
25673 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25674 		    zoneid, ipst);
25675 	}
25676 	if (ill != NULL && ill_need_rele)
25677 		ill_refrele(ill);
25678 	return;
25679 send:
25680 	if (ill != NULL && ill_need_rele)
25681 		ill_refrele(ill);
25682 
25683 	/* Local delivery */
25684 	if (ire->ire_stq == NULL) {
25685 		ill_t	*out_ill;
25686 		ASSERT(q != NULL);
25687 
25688 		/* PFHooks: LOOPBACK_OUT */
25689 		out_ill = ire_to_ill(ire);
25690 
25691 		DTRACE_PROBE4(ip6__loopback__out__start,
25692 		    ill_t *, NULL, ill_t *, out_ill,
25693 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25694 
25695 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25696 		    ipst->ips_ipv6firewall_loopback_out,
25697 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25698 
25699 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25700 
25701 		if (ipsec_mp != NULL)
25702 			ip_wput_local_v6(RD(q), out_ill,
25703 			    ip6h, ipsec_mp, ire, 0);
25704 		if (ire_need_rele)
25705 			ire_refrele(ire);
25706 		return;
25707 	}
25708 	/*
25709 	 * Everything is done. Send it out on the wire.
25710 	 * We force the insertion of a fragment header using the
25711 	 * IPH_FRAG_HDR flag in two cases:
25712 	 * - after reception of an ICMPv6 "packet too big" message
25713 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25714 	 * - for multirouted IPv6 packets, so that the receiver can
25715 	 *   discard duplicates according to their fragment identifier
25716 	 */
25717 	/* XXX fix flow control problems. */
25718 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25719 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25720 		if (hwaccel) {
25721 			/*
25722 			 * hardware acceleration does not handle these
25723 			 * "slow path" cases.
25724 			 */
25725 			/* IPsec KSTATS: should bump bean counter here. */
25726 			if (ire_need_rele)
25727 				ire_refrele(ire);
25728 			freemsg(ipsec_mp);
25729 			return;
25730 		}
25731 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25732 		    (mp->b_cont ? msgdsize(mp) :
25733 		    mp->b_wptr - (uchar_t *)ip6h)) {
25734 			/* IPsec KSTATS: should bump bean counter here. */
25735 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25736 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25737 			    msgdsize(mp)));
25738 			if (ire_need_rele)
25739 				ire_refrele(ire);
25740 			freemsg(ipsec_mp);
25741 			return;
25742 		}
25743 		ASSERT(mp->b_prev == NULL);
25744 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25745 		    ntohs(ip6h->ip6_plen) +
25746 		    IPV6_HDR_LEN, ire->ire_max_frag));
25747 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25748 		    ire->ire_max_frag);
25749 	} else {
25750 		UPDATE_OB_PKT_COUNT(ire);
25751 		ire->ire_last_used_time = lbolt;
25752 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25753 	}
25754 	if (ire_need_rele)
25755 		ire_refrele(ire);
25756 	freeb(ipsec_mp);
25757 }
25758 
25759 void
25760 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25761 {
25762 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25763 	da_ipsec_t *hada;	/* data attributes */
25764 	ill_t *ill = (ill_t *)q->q_ptr;
25765 
25766 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25767 
25768 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25769 		/* IPsec KSTATS: Bump lose counter here! */
25770 		freemsg(mp);
25771 		return;
25772 	}
25773 
25774 	/*
25775 	 * It's an IPsec packet that must be
25776 	 * accelerated by the Provider, and the
25777 	 * outbound ill is IPsec acceleration capable.
25778 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25779 	 * to the ill.
25780 	 * IPsec KSTATS: should bump packet counter here.
25781 	 */
25782 
25783 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25784 	if (hada_mp == NULL) {
25785 		/* IPsec KSTATS: should bump packet counter here. */
25786 		freemsg(mp);
25787 		return;
25788 	}
25789 
25790 	hada_mp->b_datap->db_type = M_CTL;
25791 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25792 	hada_mp->b_cont = mp;
25793 
25794 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25795 	bzero(hada, sizeof (da_ipsec_t));
25796 	hada->da_type = IPHADA_M_CTL;
25797 
25798 	putnext(q, hada_mp);
25799 }
25800 
25801 /*
25802  * Finish the outbound IPsec processing. This function is called from
25803  * ipsec_out_process() if the IPsec packet was processed
25804  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25805  * asynchronously.
25806  */
25807 void
25808 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25809     ire_t *ire_arg)
25810 {
25811 	uint32_t v_hlen_tos_len;
25812 	ipaddr_t	dst;
25813 	ipif_t	*ipif = NULL;
25814 	ire_t *ire;
25815 	ire_t *ire1 = NULL;
25816 	mblk_t *next_mp = NULL;
25817 	uint32_t max_frag;
25818 	boolean_t multirt_send = B_FALSE;
25819 	mblk_t *mp;
25820 	ipha_t *ipha1;
25821 	uint_t	ill_index;
25822 	ipsec_out_t *io;
25823 	boolean_t attach_if;
25824 	int match_flags;
25825 	irb_t *irb = NULL;
25826 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25827 	zoneid_t zoneid;
25828 	ipxmit_state_t	pktxmit_state;
25829 	ip_stack_t	*ipst;
25830 
25831 #ifdef	_BIG_ENDIAN
25832 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25833 #else
25834 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25835 #endif
25836 
25837 	mp = ipsec_mp->b_cont;
25838 	ipha1 = (ipha_t *)mp->b_rptr;
25839 	ASSERT(mp != NULL);
25840 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25841 	dst = ipha->ipha_dst;
25842 
25843 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25844 	ill_index = io->ipsec_out_ill_index;
25845 	attach_if = io->ipsec_out_attach_if;
25846 	zoneid = io->ipsec_out_zoneid;
25847 	ASSERT(zoneid != ALL_ZONES);
25848 	ipst = io->ipsec_out_ns->netstack_ip;
25849 	ASSERT(io->ipsec_out_ns != NULL);
25850 
25851 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25852 	if (ill_index != 0) {
25853 		if (ill == NULL) {
25854 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25855 			    ill_index, B_FALSE, ipst);
25856 
25857 			/* Failure case frees things for us. */
25858 			if (ill == NULL)
25859 				return;
25860 
25861 			ill_need_rele = B_TRUE;
25862 		}
25863 		/*
25864 		 * If this packet needs to go out on a particular interface
25865 		 * honor it.
25866 		 */
25867 		if (attach_if) {
25868 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25869 
25870 			/*
25871 			 * Check if we need an ire that will not be
25872 			 * looked up by anybody else i.e. HIDDEN.
25873 			 */
25874 			if (ill_is_probeonly(ill)) {
25875 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25876 			}
25877 		}
25878 	}
25879 
25880 	if (CLASSD(dst)) {
25881 		boolean_t conn_dontroute;
25882 		/*
25883 		 * Use the ill_index to get the right ipif.
25884 		 */
25885 		conn_dontroute = io->ipsec_out_dontroute;
25886 		if (ill_index == 0)
25887 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25888 		else
25889 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25890 		if (ipif == NULL) {
25891 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25892 			    " multicast\n"));
25893 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25894 			freemsg(ipsec_mp);
25895 			goto done;
25896 		}
25897 		/*
25898 		 * ipha_src has already been intialized with the
25899 		 * value of the ipif in ip_wput. All we need now is
25900 		 * an ire to send this downstream.
25901 		 */
25902 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25903 		    MBLK_GETLABEL(mp), match_flags, ipst);
25904 		if (ire != NULL) {
25905 			ill_t *ill1;
25906 			/*
25907 			 * Do the multicast forwarding now, as the IPsec
25908 			 * processing has been done.
25909 			 */
25910 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25911 			    (ill1 = ire_to_ill(ire))) {
25912 				if (ip_mforward(ill1, ipha, mp)) {
25913 					freemsg(ipsec_mp);
25914 					ip1dbg(("ip_wput_ipsec_out: mforward "
25915 					    "failed\n"));
25916 					ire_refrele(ire);
25917 					goto done;
25918 				}
25919 			}
25920 			goto send;
25921 		}
25922 
25923 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25924 		mp->b_prev = NULL;
25925 		mp->b_next = NULL;
25926 
25927 		/*
25928 		 * If the IPsec packet was processed asynchronously,
25929 		 * drop it now.
25930 		 */
25931 		if (q == NULL) {
25932 			freemsg(ipsec_mp);
25933 			goto done;
25934 		}
25935 
25936 		/*
25937 		 * We may be using a wrong ipif to create the ire.
25938 		 * But it is okay as the source address is assigned
25939 		 * for the packet already. Next outbound packet would
25940 		 * create the IRE with the right IPIF in ip_wput.
25941 		 *
25942 		 * Also handle RTF_MULTIRT routes.
25943 		 */
25944 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25945 		    zoneid, &zero_info);
25946 	} else {
25947 		if (attach_if) {
25948 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25949 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25950 		} else {
25951 			if (ire_arg != NULL) {
25952 				ire = ire_arg;
25953 				ire_need_rele = B_FALSE;
25954 			} else {
25955 				ire = ire_cache_lookup(dst, zoneid,
25956 				    MBLK_GETLABEL(mp), ipst);
25957 			}
25958 		}
25959 		if (ire != NULL) {
25960 			goto send;
25961 		}
25962 
25963 		/*
25964 		 * ire disappeared underneath.
25965 		 *
25966 		 * What we need to do here is the ip_newroute
25967 		 * logic to get the ire without doing the IPsec
25968 		 * processing. Follow the same old path. But this
25969 		 * time, ip_wput or ire_add_then_put will call us
25970 		 * directly as all the IPsec operations are done.
25971 		 */
25972 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
25973 		mp->b_prev = NULL;
25974 		mp->b_next = NULL;
25975 
25976 		/*
25977 		 * If the IPsec packet was processed asynchronously,
25978 		 * drop it now.
25979 		 */
25980 		if (q == NULL) {
25981 			freemsg(ipsec_mp);
25982 			goto done;
25983 		}
25984 
25985 		/*
25986 		 * Since we're going through ip_newroute() again, we
25987 		 * need to make sure we don't:
25988 		 *
25989 		 *	1.) Trigger the ASSERT() with the ipha_ident
25990 		 *	    overloading.
25991 		 *	2.) Redo transport-layer checksumming, since we've
25992 		 *	    already done all that to get this far.
25993 		 *
25994 		 * The easiest way not do either of the above is to set
25995 		 * the ipha_ident field to IP_HDR_INCLUDED.
25996 		 */
25997 		ipha->ipha_ident = IP_HDR_INCLUDED;
25998 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
25999 		    zoneid, ipst);
26000 	}
26001 	goto done;
26002 send:
26003 	if (ire->ire_stq == NULL) {
26004 		ill_t	*out_ill;
26005 		/*
26006 		 * Loopbacks go through ip_wput_local except for one case.
26007 		 * We come here if we generate a icmp_frag_needed message
26008 		 * after IPsec processing is over. When this function calls
26009 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26010 		 * icmp_frag_needed. The message generated comes back here
26011 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26012 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26013 		 * source address as it is usually set in ip_wput_ire. As
26014 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26015 		 * and we end up here. We can't enter ip_wput_ire once the
26016 		 * IPsec processing is over and hence we need to do it here.
26017 		 */
26018 		ASSERT(q != NULL);
26019 		UPDATE_OB_PKT_COUNT(ire);
26020 		ire->ire_last_used_time = lbolt;
26021 		if (ipha->ipha_src == 0)
26022 			ipha->ipha_src = ire->ire_src_addr;
26023 
26024 		/* PFHooks: LOOPBACK_OUT */
26025 		out_ill = ire_to_ill(ire);
26026 
26027 		DTRACE_PROBE4(ip4__loopback__out__start,
26028 		    ill_t *, NULL, ill_t *, out_ill,
26029 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26030 
26031 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26032 		    ipst->ips_ipv4firewall_loopback_out,
26033 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26034 
26035 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26036 
26037 		if (ipsec_mp != NULL)
26038 			ip_wput_local(RD(q), out_ill,
26039 			    ipha, ipsec_mp, ire, 0, zoneid);
26040 		if (ire_need_rele)
26041 			ire_refrele(ire);
26042 		goto done;
26043 	}
26044 
26045 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26046 		/*
26047 		 * We are through with IPsec processing.
26048 		 * Fragment this and send it on the wire.
26049 		 */
26050 		if (io->ipsec_out_accelerated) {
26051 			/*
26052 			 * The packet has been accelerated but must
26053 			 * be fragmented. This should not happen
26054 			 * since AH and ESP must not accelerate
26055 			 * packets that need fragmentation, however
26056 			 * the configuration could have changed
26057 			 * since the AH or ESP processing.
26058 			 * Drop packet.
26059 			 * IPsec KSTATS: bump bean counter here.
26060 			 */
26061 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26062 			    "fragmented accelerated packet!\n"));
26063 			freemsg(ipsec_mp);
26064 		} else {
26065 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26066 		}
26067 		if (ire_need_rele)
26068 			ire_refrele(ire);
26069 		goto done;
26070 	}
26071 
26072 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26073 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26074 	    (void *)ire->ire_ipif, (void *)ipif));
26075 
26076 	/*
26077 	 * Multiroute the secured packet, unless IPsec really
26078 	 * requires the packet to go out only through a particular
26079 	 * interface.
26080 	 */
26081 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26082 		ire_t *first_ire;
26083 		irb = ire->ire_bucket;
26084 		ASSERT(irb != NULL);
26085 		/*
26086 		 * This ire has been looked up as the one that
26087 		 * goes through the given ipif;
26088 		 * make sure we do not omit any other multiroute ire
26089 		 * that may be present in the bucket before this one.
26090 		 */
26091 		IRB_REFHOLD(irb);
26092 		for (first_ire = irb->irb_ire;
26093 		    first_ire != NULL;
26094 		    first_ire = first_ire->ire_next) {
26095 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26096 			    (first_ire->ire_addr == ire->ire_addr) &&
26097 			    !(first_ire->ire_marks &
26098 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26099 				break;
26100 			}
26101 		}
26102 
26103 		if ((first_ire != NULL) && (first_ire != ire)) {
26104 			/*
26105 			 * Don't change the ire if the packet must
26106 			 * be fragmented if sent via this new one.
26107 			 */
26108 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26109 				IRE_REFHOLD(first_ire);
26110 				if (ire_need_rele)
26111 					ire_refrele(ire);
26112 				else
26113 					ire_need_rele = B_TRUE;
26114 				ire = first_ire;
26115 			}
26116 		}
26117 		IRB_REFRELE(irb);
26118 
26119 		multirt_send = B_TRUE;
26120 		max_frag = ire->ire_max_frag;
26121 	} else {
26122 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26123 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26124 			    "flag, attach_if %d\n", attach_if));
26125 		}
26126 	}
26127 
26128 	/*
26129 	 * In most cases, the emission loop below is entered only once.
26130 	 * Only in the case where the ire holds the RTF_MULTIRT
26131 	 * flag, we loop to process all RTF_MULTIRT ires in the
26132 	 * bucket, and send the packet through all crossed
26133 	 * RTF_MULTIRT routes.
26134 	 */
26135 	do {
26136 		if (multirt_send) {
26137 			/*
26138 			 * ire1 holds here the next ire to process in the
26139 			 * bucket. If multirouting is expected,
26140 			 * any non-RTF_MULTIRT ire that has the
26141 			 * right destination address is ignored.
26142 			 */
26143 			ASSERT(irb != NULL);
26144 			IRB_REFHOLD(irb);
26145 			for (ire1 = ire->ire_next;
26146 			    ire1 != NULL;
26147 			    ire1 = ire1->ire_next) {
26148 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26149 					continue;
26150 				if (ire1->ire_addr != ire->ire_addr)
26151 					continue;
26152 				if (ire1->ire_marks &
26153 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26154 					continue;
26155 				/* No loopback here */
26156 				if (ire1->ire_stq == NULL)
26157 					continue;
26158 				/*
26159 				 * Ensure we do not exceed the MTU
26160 				 * of the next route.
26161 				 */
26162 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26163 					ip_multirt_bad_mtu(ire1, max_frag);
26164 					continue;
26165 				}
26166 
26167 				IRE_REFHOLD(ire1);
26168 				break;
26169 			}
26170 			IRB_REFRELE(irb);
26171 			if (ire1 != NULL) {
26172 				/*
26173 				 * We are in a multiple send case, need to
26174 				 * make a copy of the packet.
26175 				 */
26176 				next_mp = copymsg(ipsec_mp);
26177 				if (next_mp == NULL) {
26178 					ire_refrele(ire1);
26179 					ire1 = NULL;
26180 				}
26181 			}
26182 		}
26183 		/*
26184 		 * Everything is done. Send it out on the wire
26185 		 *
26186 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26187 		 * either send it on the wire or, in the case of
26188 		 * HW acceleration, call ipsec_hw_putnext.
26189 		 */
26190 		if (ire->ire_nce &&
26191 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26192 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26193 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26194 			/*
26195 			 * If ire's link-layer is unresolved (this
26196 			 * would only happen if the incomplete ire
26197 			 * was added to cachetable via forwarding path)
26198 			 * don't bother going to ip_xmit_v4. Just drop the
26199 			 * packet.
26200 			 * There is a slight risk here, in that, if we
26201 			 * have the forwarding path create an incomplete
26202 			 * IRE, then until the IRE is completed, any
26203 			 * transmitted IPsec packets will be dropped
26204 			 * instead of being queued waiting for resolution.
26205 			 *
26206 			 * But the likelihood of a forwarding packet and a wput
26207 			 * packet sending to the same dst at the same time
26208 			 * and there not yet be an ARP entry for it is small.
26209 			 * Furthermore, if this actually happens, it might
26210 			 * be likely that wput would generate multiple
26211 			 * packets (and forwarding would also have a train
26212 			 * of packets) for that destination. If this is
26213 			 * the case, some of them would have been dropped
26214 			 * anyway, since ARP only queues a few packets while
26215 			 * waiting for resolution
26216 			 *
26217 			 * NOTE: We should really call ip_xmit_v4,
26218 			 * and let it queue the packet and send the
26219 			 * ARP query and have ARP come back thus:
26220 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26221 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26222 			 * hw accel work. But it's too complex to get
26223 			 * the IPsec hw  acceleration approach to fit
26224 			 * well with ip_xmit_v4 doing ARP without
26225 			 * doing IPsec simplification. For now, we just
26226 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26227 			 * that we can continue with the send on the next
26228 			 * attempt.
26229 			 *
26230 			 * XXX THis should be revisited, when
26231 			 * the IPsec/IP interaction is cleaned up
26232 			 */
26233 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26234 			    " - dropping packet\n"));
26235 			freemsg(ipsec_mp);
26236 			/*
26237 			 * Call ip_xmit_v4() to trigger ARP query
26238 			 * in case the nce_state is ND_INITIAL
26239 			 */
26240 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26241 			goto drop_pkt;
26242 		}
26243 
26244 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26245 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26246 		    mblk_t *, ipsec_mp);
26247 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26248 		    ipst->ips_ipv4firewall_physical_out, NULL,
26249 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26250 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26251 		if (ipsec_mp == NULL)
26252 			goto drop_pkt;
26253 
26254 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26255 		pktxmit_state = ip_xmit_v4(mp, ire,
26256 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26257 
26258 		if ((pktxmit_state ==  SEND_FAILED) ||
26259 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26260 
26261 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26262 drop_pkt:
26263 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26264 			    ipIfStatsOutDiscards);
26265 			if (ire_need_rele)
26266 				ire_refrele(ire);
26267 			if (ire1 != NULL) {
26268 				ire_refrele(ire1);
26269 				freemsg(next_mp);
26270 			}
26271 			goto done;
26272 		}
26273 
26274 		freeb(ipsec_mp);
26275 		if (ire_need_rele)
26276 			ire_refrele(ire);
26277 
26278 		if (ire1 != NULL) {
26279 			ire = ire1;
26280 			ire_need_rele = B_TRUE;
26281 			ASSERT(next_mp);
26282 			ipsec_mp = next_mp;
26283 			mp = ipsec_mp->b_cont;
26284 			ire1 = NULL;
26285 			next_mp = NULL;
26286 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26287 		} else {
26288 			multirt_send = B_FALSE;
26289 		}
26290 	} while (multirt_send);
26291 done:
26292 	if (ill != NULL && ill_need_rele)
26293 		ill_refrele(ill);
26294 	if (ipif != NULL)
26295 		ipif_refrele(ipif);
26296 }
26297 
26298 /*
26299  * Get the ill corresponding to the specified ire, and compare its
26300  * capabilities with the protocol and algorithms specified by the
26301  * the SA obtained from ipsec_out. If they match, annotate the
26302  * ipsec_out structure to indicate that the packet needs acceleration.
26303  *
26304  *
26305  * A packet is eligible for outbound hardware acceleration if the
26306  * following conditions are satisfied:
26307  *
26308  * 1. the packet will not be fragmented
26309  * 2. the provider supports the algorithm
26310  * 3. there is no pending control message being exchanged
26311  * 4. snoop is not attached
26312  * 5. the destination address is not a broadcast or multicast address.
26313  *
26314  * Rationale:
26315  *	- Hardware drivers do not support fragmentation with
26316  *	  the current interface.
26317  *	- snoop, multicast, and broadcast may result in exposure of
26318  *	  a cleartext datagram.
26319  * We check all five of these conditions here.
26320  *
26321  * XXX would like to nuke "ire_t *" parameter here; problem is that
26322  * IRE is only way to figure out if a v4 address is a broadcast and
26323  * thus ineligible for acceleration...
26324  */
26325 static void
26326 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26327 {
26328 	ipsec_out_t *io;
26329 	mblk_t *data_mp;
26330 	uint_t plen, overhead;
26331 	ip_stack_t	*ipst;
26332 
26333 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26334 		return;
26335 
26336 	if (ill == NULL)
26337 		return;
26338 	ipst = ill->ill_ipst;
26339 	/*
26340 	 * Destination address is a broadcast or multicast.  Punt.
26341 	 */
26342 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26343 	    IRE_LOCAL)))
26344 		return;
26345 
26346 	data_mp = ipsec_mp->b_cont;
26347 
26348 	if (ill->ill_isv6) {
26349 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26350 
26351 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26352 			return;
26353 
26354 		plen = ip6h->ip6_plen;
26355 	} else {
26356 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26357 
26358 		if (CLASSD(ipha->ipha_dst))
26359 			return;
26360 
26361 		plen = ipha->ipha_length;
26362 	}
26363 	/*
26364 	 * Is there a pending DLPI control message being exchanged
26365 	 * between IP/IPsec and the DLS Provider? If there is, it
26366 	 * could be a SADB update, and the state of the DLS Provider
26367 	 * SADB might not be in sync with the SADB maintained by
26368 	 * IPsec. To avoid dropping packets or using the wrong keying
26369 	 * material, we do not accelerate this packet.
26370 	 */
26371 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26372 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26373 		    "ill_dlpi_pending! don't accelerate packet\n"));
26374 		return;
26375 	}
26376 
26377 	/*
26378 	 * Is the Provider in promiscous mode? If it does, we don't
26379 	 * accelerate the packet since it will bounce back up to the
26380 	 * listeners in the clear.
26381 	 */
26382 	if (ill->ill_promisc_on_phys) {
26383 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26384 		    "ill in promiscous mode, don't accelerate packet\n"));
26385 		return;
26386 	}
26387 
26388 	/*
26389 	 * Will the packet require fragmentation?
26390 	 */
26391 
26392 	/*
26393 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26394 	 * as is used elsewhere.
26395 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26396 	 *	+ 2-byte trailer
26397 	 */
26398 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26399 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26400 
26401 	if ((plen + overhead) > ill->ill_max_mtu)
26402 		return;
26403 
26404 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26405 
26406 	/*
26407 	 * Can the ill accelerate this IPsec protocol and algorithm
26408 	 * specified by the SA?
26409 	 */
26410 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26411 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26412 		return;
26413 	}
26414 
26415 	/*
26416 	 * Tell AH or ESP that the outbound ill is capable of
26417 	 * accelerating this packet.
26418 	 */
26419 	io->ipsec_out_is_capab_ill = B_TRUE;
26420 }
26421 
26422 /*
26423  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26424  *
26425  * If this function returns B_TRUE, the requested SA's have been filled
26426  * into the ipsec_out_*_sa pointers.
26427  *
26428  * If the function returns B_FALSE, the packet has been "consumed", most
26429  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26430  *
26431  * The SA references created by the protocol-specific "select"
26432  * function will be released when the ipsec_mp is freed, thanks to the
26433  * ipsec_out_free destructor -- see spd.c.
26434  */
26435 static boolean_t
26436 ipsec_out_select_sa(mblk_t *ipsec_mp)
26437 {
26438 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26439 	ipsec_out_t *io;
26440 	ipsec_policy_t *pp;
26441 	ipsec_action_t *ap;
26442 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26443 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26444 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26445 
26446 	if (!io->ipsec_out_secure) {
26447 		/*
26448 		 * We came here by mistake.
26449 		 * Don't bother with ipsec processing
26450 		 * We should "discourage" this path in the future.
26451 		 */
26452 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26453 		return (B_FALSE);
26454 	}
26455 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26456 	ASSERT((io->ipsec_out_policy != NULL) ||
26457 	    (io->ipsec_out_act != NULL));
26458 
26459 	ASSERT(io->ipsec_out_failed == B_FALSE);
26460 
26461 	/*
26462 	 * IPsec processing has started.
26463 	 */
26464 	io->ipsec_out_proc_begin = B_TRUE;
26465 	ap = io->ipsec_out_act;
26466 	if (ap == NULL) {
26467 		pp = io->ipsec_out_policy;
26468 		ASSERT(pp != NULL);
26469 		ap = pp->ipsp_act;
26470 		ASSERT(ap != NULL);
26471 	}
26472 
26473 	/*
26474 	 * We have an action.  now, let's select SA's.
26475 	 * (In the future, we can cache this in the conn_t..)
26476 	 */
26477 	if (ap->ipa_want_esp) {
26478 		if (io->ipsec_out_esp_sa == NULL) {
26479 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26480 			    IPPROTO_ESP);
26481 		}
26482 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26483 	}
26484 
26485 	if (ap->ipa_want_ah) {
26486 		if (io->ipsec_out_ah_sa == NULL) {
26487 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26488 			    IPPROTO_AH);
26489 		}
26490 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26491 		/*
26492 		 * The ESP and AH processing order needs to be preserved
26493 		 * when both protocols are required (ESP should be applied
26494 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26495 		 * when both ESP and AH are required, and an AH ACQUIRE
26496 		 * is needed.
26497 		 */
26498 		if (ap->ipa_want_esp && need_ah_acquire)
26499 			need_esp_acquire = B_TRUE;
26500 	}
26501 
26502 	/*
26503 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26504 	 * Release SAs that got referenced, but will not be used until we
26505 	 * acquire _all_ of the SAs we need.
26506 	 */
26507 	if (need_ah_acquire || need_esp_acquire) {
26508 		if (io->ipsec_out_ah_sa != NULL) {
26509 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26510 			io->ipsec_out_ah_sa = NULL;
26511 		}
26512 		if (io->ipsec_out_esp_sa != NULL) {
26513 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26514 			io->ipsec_out_esp_sa = NULL;
26515 		}
26516 
26517 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26518 		return (B_FALSE);
26519 	}
26520 
26521 	return (B_TRUE);
26522 }
26523 
26524 /*
26525  * Process an IPSEC_OUT message and see what you can
26526  * do with it.
26527  * IPQoS Notes:
26528  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26529  * IPsec.
26530  * XXX would like to nuke ire_t.
26531  * XXX ill_index better be "real"
26532  */
26533 void
26534 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26535 {
26536 	ipsec_out_t *io;
26537 	ipsec_policy_t *pp;
26538 	ipsec_action_t *ap;
26539 	ipha_t *ipha;
26540 	ip6_t *ip6h;
26541 	mblk_t *mp;
26542 	ill_t *ill;
26543 	zoneid_t zoneid;
26544 	ipsec_status_t ipsec_rc;
26545 	boolean_t ill_need_rele = B_FALSE;
26546 	ip_stack_t	*ipst;
26547 	ipsec_stack_t	*ipss;
26548 
26549 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26550 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26551 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26552 	ipst = io->ipsec_out_ns->netstack_ip;
26553 	mp = ipsec_mp->b_cont;
26554 
26555 	/*
26556 	 * Initiate IPPF processing. We do it here to account for packets
26557 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26558 	 * We can check for ipsec_out_proc_begin even for such packets, as
26559 	 * they will always be false (asserted below).
26560 	 */
26561 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26562 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26563 		    io->ipsec_out_ill_index : ill_index);
26564 		if (mp == NULL) {
26565 			ip2dbg(("ipsec_out_process: packet dropped "\
26566 			    "during IPPF processing\n"));
26567 			freeb(ipsec_mp);
26568 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26569 			return;
26570 		}
26571 	}
26572 
26573 	if (!io->ipsec_out_secure) {
26574 		/*
26575 		 * We came here by mistake.
26576 		 * Don't bother with ipsec processing
26577 		 * Should "discourage" this path in the future.
26578 		 */
26579 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26580 		goto done;
26581 	}
26582 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26583 	ASSERT((io->ipsec_out_policy != NULL) ||
26584 	    (io->ipsec_out_act != NULL));
26585 	ASSERT(io->ipsec_out_failed == B_FALSE);
26586 
26587 	ipss = ipst->ips_netstack->netstack_ipsec;
26588 	if (!ipsec_loaded(ipss)) {
26589 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26590 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26591 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26592 		} else {
26593 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26594 		}
26595 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26596 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26597 		    &ipss->ipsec_dropper);
26598 		return;
26599 	}
26600 
26601 	/*
26602 	 * IPsec processing has started.
26603 	 */
26604 	io->ipsec_out_proc_begin = B_TRUE;
26605 	ap = io->ipsec_out_act;
26606 	if (ap == NULL) {
26607 		pp = io->ipsec_out_policy;
26608 		ASSERT(pp != NULL);
26609 		ap = pp->ipsp_act;
26610 		ASSERT(ap != NULL);
26611 	}
26612 
26613 	/*
26614 	 * Save the outbound ill index. When the packet comes back
26615 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26616 	 * before sending it the accelerated packet.
26617 	 */
26618 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26619 		int ifindex;
26620 		ill = ire_to_ill(ire);
26621 		ifindex = ill->ill_phyint->phyint_ifindex;
26622 		io->ipsec_out_capab_ill_index = ifindex;
26623 	}
26624 
26625 	/*
26626 	 * The order of processing is first insert a IP header if needed.
26627 	 * Then insert the ESP header and then the AH header.
26628 	 */
26629 	if ((io->ipsec_out_se_done == B_FALSE) &&
26630 	    (ap->ipa_want_se)) {
26631 		/*
26632 		 * First get the outer IP header before sending
26633 		 * it to ESP.
26634 		 */
26635 		ipha_t *oipha, *iipha;
26636 		mblk_t *outer_mp, *inner_mp;
26637 
26638 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26639 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26640 			    "ipsec_out_process: "
26641 			    "Self-Encapsulation failed: Out of memory\n");
26642 			freemsg(ipsec_mp);
26643 			if (ill != NULL) {
26644 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26645 			} else {
26646 				BUMP_MIB(&ipst->ips_ip_mib,
26647 				    ipIfStatsOutDiscards);
26648 			}
26649 			return;
26650 		}
26651 		inner_mp = ipsec_mp->b_cont;
26652 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26653 		oipha = (ipha_t *)outer_mp->b_rptr;
26654 		iipha = (ipha_t *)inner_mp->b_rptr;
26655 		*oipha = *iipha;
26656 		outer_mp->b_wptr += sizeof (ipha_t);
26657 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26658 		    sizeof (ipha_t));
26659 		oipha->ipha_protocol = IPPROTO_ENCAP;
26660 		oipha->ipha_version_and_hdr_length =
26661 		    IP_SIMPLE_HDR_VERSION;
26662 		oipha->ipha_hdr_checksum = 0;
26663 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26664 		outer_mp->b_cont = inner_mp;
26665 		ipsec_mp->b_cont = outer_mp;
26666 
26667 		io->ipsec_out_se_done = B_TRUE;
26668 		io->ipsec_out_tunnel = B_TRUE;
26669 	}
26670 
26671 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26672 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26673 	    !ipsec_out_select_sa(ipsec_mp))
26674 		return;
26675 
26676 	/*
26677 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26678 	 * to do the heavy lifting.
26679 	 */
26680 	zoneid = io->ipsec_out_zoneid;
26681 	ASSERT(zoneid != ALL_ZONES);
26682 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26683 		ASSERT(io->ipsec_out_esp_sa != NULL);
26684 		io->ipsec_out_esp_done = B_TRUE;
26685 		/*
26686 		 * Note that since hw accel can only apply one transform,
26687 		 * not two, we skip hw accel for ESP if we also have AH
26688 		 * This is an design limitation of the interface
26689 		 * which should be revisited.
26690 		 */
26691 		ASSERT(ire != NULL);
26692 		if (io->ipsec_out_ah_sa == NULL) {
26693 			ill = (ill_t *)ire->ire_stq->q_ptr;
26694 			ipsec_out_is_accelerated(ipsec_mp,
26695 			    io->ipsec_out_esp_sa, ill, ire);
26696 		}
26697 
26698 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26699 		switch (ipsec_rc) {
26700 		case IPSEC_STATUS_SUCCESS:
26701 			break;
26702 		case IPSEC_STATUS_FAILED:
26703 			if (ill != NULL) {
26704 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26705 			} else {
26706 				BUMP_MIB(&ipst->ips_ip_mib,
26707 				    ipIfStatsOutDiscards);
26708 			}
26709 			/* FALLTHRU */
26710 		case IPSEC_STATUS_PENDING:
26711 			return;
26712 		}
26713 	}
26714 
26715 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26716 		ASSERT(io->ipsec_out_ah_sa != NULL);
26717 		io->ipsec_out_ah_done = B_TRUE;
26718 		if (ire == NULL) {
26719 			int idx = io->ipsec_out_capab_ill_index;
26720 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26721 			    NULL, NULL, NULL, NULL, ipst);
26722 			ill_need_rele = B_TRUE;
26723 		} else {
26724 			ill = (ill_t *)ire->ire_stq->q_ptr;
26725 		}
26726 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26727 		    ire);
26728 
26729 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26730 		switch (ipsec_rc) {
26731 		case IPSEC_STATUS_SUCCESS:
26732 			break;
26733 		case IPSEC_STATUS_FAILED:
26734 			if (ill != NULL) {
26735 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26736 			} else {
26737 				BUMP_MIB(&ipst->ips_ip_mib,
26738 				    ipIfStatsOutDiscards);
26739 			}
26740 			/* FALLTHRU */
26741 		case IPSEC_STATUS_PENDING:
26742 			if (ill != NULL && ill_need_rele)
26743 				ill_refrele(ill);
26744 			return;
26745 		}
26746 	}
26747 	/*
26748 	 * We are done with IPsec processing. Send it over
26749 	 * the wire.
26750 	 */
26751 done:
26752 	mp = ipsec_mp->b_cont;
26753 	ipha = (ipha_t *)mp->b_rptr;
26754 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26755 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26756 	} else {
26757 		ip6h = (ip6_t *)ipha;
26758 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26759 	}
26760 	if (ill != NULL && ill_need_rele)
26761 		ill_refrele(ill);
26762 }
26763 
26764 /* ARGSUSED */
26765 void
26766 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26767 {
26768 	opt_restart_t	*or;
26769 	int	err;
26770 	conn_t	*connp;
26771 
26772 	ASSERT(CONN_Q(q));
26773 	connp = Q_TO_CONN(q);
26774 
26775 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26776 	or = (opt_restart_t *)first_mp->b_rptr;
26777 	/*
26778 	 * We don't need to pass any credentials here since this is just
26779 	 * a restart. The credentials are passed in when svr4_optcom_req
26780 	 * is called the first time (from ip_wput_nondata).
26781 	 */
26782 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26783 		err = svr4_optcom_req(q, first_mp, NULL,
26784 		    &ip_opt_obj, B_FALSE);
26785 	} else {
26786 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26787 		err = tpi_optcom_req(q, first_mp, NULL,
26788 		    &ip_opt_obj, B_FALSE);
26789 	}
26790 	if (err != EINPROGRESS) {
26791 		/* operation is done */
26792 		CONN_OPER_PENDING_DONE(connp);
26793 	}
26794 }
26795 
26796 /*
26797  * ioctls that go through a down/up sequence may need to wait for the down
26798  * to complete. This involves waiting for the ire and ipif refcnts to go down
26799  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26800  */
26801 /* ARGSUSED */
26802 void
26803 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26804 {
26805 	struct iocblk *iocp;
26806 	mblk_t *mp1;
26807 	ip_ioctl_cmd_t *ipip;
26808 	int err;
26809 	sin_t	*sin;
26810 	struct lifreq *lifr;
26811 	struct ifreq *ifr;
26812 
26813 	iocp = (struct iocblk *)mp->b_rptr;
26814 	ASSERT(ipsq != NULL);
26815 	/* Existence of mp1 verified in ip_wput_nondata */
26816 	mp1 = mp->b_cont->b_cont;
26817 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26818 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26819 		/*
26820 		 * Special case where ipsq_current_ipif is not set:
26821 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26822 		 * ill could also have become part of a ipmp group in the
26823 		 * process, we are here as were not able to complete the
26824 		 * operation in ipif_set_values because we could not become
26825 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26826 		 * will not be set so we need to set it.
26827 		 */
26828 		ill_t *ill = q->q_ptr;
26829 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26830 	}
26831 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26832 
26833 	if (ipip->ipi_cmd_type == IF_CMD) {
26834 		/* This a old style SIOC[GS]IF* command */
26835 		ifr = (struct ifreq *)mp1->b_rptr;
26836 		sin = (sin_t *)&ifr->ifr_addr;
26837 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26838 		/* This a new style SIOC[GS]LIF* command */
26839 		lifr = (struct lifreq *)mp1->b_rptr;
26840 		sin = (sin_t *)&lifr->lifr_addr;
26841 	} else {
26842 		sin = NULL;
26843 	}
26844 
26845 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26846 	    ipip, mp1->b_rptr);
26847 
26848 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26849 }
26850 
26851 /*
26852  * ioctl processing
26853  *
26854  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26855  * the ioctl command in the ioctl tables, determines the copyin data size
26856  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26857  *
26858  * ioctl processing then continues when the M_IOCDATA makes its way down to
26859  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26860  * associated 'conn' is refheld till the end of the ioctl and the general
26861  * ioctl processing function ip_process_ioctl() is called to extract the
26862  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26863  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26864  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26865  * is used to extract the ioctl's arguments.
26866  *
26867  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26868  * so goes thru the serialization primitive ipsq_try_enter. Then the
26869  * appropriate function to handle the ioctl is called based on the entry in
26870  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26871  * which also refreleases the 'conn' that was refheld at the start of the
26872  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26873  *
26874  * Many exclusive ioctls go thru an internal down up sequence as part of
26875  * the operation. For example an attempt to change the IP address of an
26876  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26877  * does all the cleanup such as deleting all ires that use this address.
26878  * Then we need to wait till all references to the interface go away.
26879  */
26880 void
26881 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26882 {
26883 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26884 	ip_ioctl_cmd_t *ipip = arg;
26885 	ip_extract_func_t *extract_funcp;
26886 	cmd_info_t ci;
26887 	int err;
26888 	boolean_t entered_ipsq = B_FALSE;
26889 
26890 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26891 
26892 	if (ipip == NULL)
26893 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26894 
26895 	/*
26896 	 * SIOCLIFADDIF needs to go thru a special path since the
26897 	 * ill may not exist yet. This happens in the case of lo0
26898 	 * which is created using this ioctl.
26899 	 */
26900 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26901 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26902 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26903 		return;
26904 	}
26905 
26906 	ci.ci_ipif = NULL;
26907 	if (ipip->ipi_cmd_type == MISC_CMD) {
26908 		/*
26909 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26910 		 */
26911 		if (ipip->ipi_cmd == IF_UNITSEL) {
26912 			/* ioctl comes down the ill */
26913 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26914 			ipif_refhold(ci.ci_ipif);
26915 		}
26916 		err = 0;
26917 		ci.ci_sin = NULL;
26918 		ci.ci_sin6 = NULL;
26919 		ci.ci_lifr = NULL;
26920 	} else {
26921 		switch (ipip->ipi_cmd_type) {
26922 		case IF_CMD:
26923 		case LIF_CMD:
26924 			extract_funcp = ip_extract_lifreq;
26925 			break;
26926 
26927 		case ARP_CMD:
26928 		case XARP_CMD:
26929 			extract_funcp = ip_extract_arpreq;
26930 			break;
26931 
26932 		case TUN_CMD:
26933 			extract_funcp = ip_extract_tunreq;
26934 			break;
26935 
26936 		case MSFILT_CMD:
26937 			extract_funcp = ip_extract_msfilter;
26938 			break;
26939 
26940 		default:
26941 			ASSERT(0);
26942 		}
26943 
26944 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26945 		if (err != 0) {
26946 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26947 			return;
26948 		}
26949 
26950 		/*
26951 		 * All of the extraction functions return a refheld ipif.
26952 		 */
26953 		ASSERT(ci.ci_ipif != NULL);
26954 	}
26955 
26956 	/*
26957 	 * If ipsq is non-null, we are already being called exclusively
26958 	 */
26959 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26960 	if (!(ipip->ipi_flags & IPI_WR)) {
26961 		/*
26962 		 * A return value of EINPROGRESS means the ioctl is
26963 		 * either queued and waiting for some reason or has
26964 		 * already completed.
26965 		 */
26966 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
26967 		    ci.ci_lifr);
26968 		if (ci.ci_ipif != NULL)
26969 			ipif_refrele(ci.ci_ipif);
26970 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26971 		return;
26972 	}
26973 
26974 	ASSERT(ci.ci_ipif != NULL);
26975 
26976 	if (ipsq == NULL) {
26977 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
26978 		    ip_process_ioctl, NEW_OP, B_TRUE);
26979 		entered_ipsq = B_TRUE;
26980 	}
26981 	/*
26982 	 * Release the ipif so that ipif_down and friends that wait for
26983 	 * references to go away are not misled about the current ipif_refcnt
26984 	 * values. We are writer so we can access the ipif even after releasing
26985 	 * the ipif.
26986 	 */
26987 	ipif_refrele(ci.ci_ipif);
26988 	if (ipsq == NULL)
26989 		return;
26990 
26991 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
26992 
26993 	/*
26994 	 * For most set ioctls that come here, this serves as a single point
26995 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
26996 	 * be any new references to the ipif. This helps functions that go
26997 	 * through this path and end up trying to wait for the refcnts
26998 	 * associated with the ipif to go down to zero. Some exceptions are
26999 	 * Failover, Failback, and Groupname commands that operate on more than
27000 	 * just the ci.ci_ipif. These commands internally determine the
27001 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27002 	 * flags on that set. Another exception is the Removeif command that
27003 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27004 	 * ipif to operate on.
27005 	 */
27006 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27007 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27008 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27009 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27010 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27011 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27012 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27013 
27014 	/*
27015 	 * A return value of EINPROGRESS means the ioctl is
27016 	 * either queued and waiting for some reason or has
27017 	 * already completed.
27018 	 */
27019 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27020 
27021 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27022 
27023 	if (entered_ipsq)
27024 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27025 }
27026 
27027 /*
27028  * Complete the ioctl. Typically ioctls use the mi package and need to
27029  * do mi_copyout/mi_copy_done.
27030  */
27031 void
27032 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27033 {
27034 	conn_t	*connp = NULL;
27035 
27036 	if (err == EINPROGRESS)
27037 		return;
27038 
27039 	if (CONN_Q(q)) {
27040 		connp = Q_TO_CONN(q);
27041 		ASSERT(connp->conn_ref >= 2);
27042 	}
27043 
27044 	switch (mode) {
27045 	case COPYOUT:
27046 		if (err == 0)
27047 			mi_copyout(q, mp);
27048 		else
27049 			mi_copy_done(q, mp, err);
27050 		break;
27051 
27052 	case NO_COPYOUT:
27053 		mi_copy_done(q, mp, err);
27054 		break;
27055 
27056 	default:
27057 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27058 		break;
27059 	}
27060 
27061 	/*
27062 	 * The refhold placed at the start of the ioctl is released here.
27063 	 */
27064 	if (connp != NULL)
27065 		CONN_OPER_PENDING_DONE(connp);
27066 
27067 	if (ipsq != NULL)
27068 		ipsq_current_finish(ipsq);
27069 }
27070 
27071 /*
27072  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27073  */
27074 /* ARGSUSED */
27075 void
27076 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27077 {
27078 	conn_t *connp = arg;
27079 	tcp_t	*tcp;
27080 
27081 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27082 	tcp = connp->conn_tcp;
27083 
27084 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27085 		freemsg(mp);
27086 	else
27087 		tcp_rput_other(tcp, mp);
27088 	CONN_OPER_PENDING_DONE(connp);
27089 }
27090 
27091 /* Called from ip_wput for all non data messages */
27092 /* ARGSUSED */
27093 void
27094 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27095 {
27096 	mblk_t		*mp1;
27097 	ire_t		*ire, *fake_ire;
27098 	ill_t		*ill;
27099 	struct iocblk	*iocp;
27100 	ip_ioctl_cmd_t	*ipip;
27101 	cred_t		*cr;
27102 	conn_t		*connp;
27103 	int		err;
27104 	nce_t		*nce;
27105 	ipif_t		*ipif;
27106 	ip_stack_t	*ipst;
27107 	char		*proto_str;
27108 
27109 	if (CONN_Q(q)) {
27110 		connp = Q_TO_CONN(q);
27111 		ipst = connp->conn_netstack->netstack_ip;
27112 	} else {
27113 		connp = NULL;
27114 		ipst = ILLQ_TO_IPST(q);
27115 	}
27116 
27117 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27118 
27119 	switch (DB_TYPE(mp)) {
27120 	case M_IOCTL:
27121 		/*
27122 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27123 		 * will arrange to copy in associated control structures.
27124 		 */
27125 		ip_sioctl_copyin_setup(q, mp);
27126 		return;
27127 	case M_IOCDATA:
27128 		/*
27129 		 * Ensure that this is associated with one of our trans-
27130 		 * parent ioctls.  If it's not ours, discard it if we're
27131 		 * running as a driver, or pass it on if we're a module.
27132 		 */
27133 		iocp = (struct iocblk *)mp->b_rptr;
27134 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27135 		if (ipip == NULL) {
27136 			if (q->q_next == NULL) {
27137 				goto nak;
27138 			} else {
27139 				putnext(q, mp);
27140 			}
27141 			return;
27142 		}
27143 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27144 			/*
27145 			 * the ioctl is one we recognise, but is not
27146 			 * consumed by IP as a module, pass M_IOCDATA
27147 			 * for processing downstream, but only for
27148 			 * common Streams ioctls.
27149 			 */
27150 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27151 				putnext(q, mp);
27152 				return;
27153 			} else {
27154 				goto nak;
27155 			}
27156 		}
27157 
27158 		/* IOCTL continuation following copyin or copyout. */
27159 		if (mi_copy_state(q, mp, NULL) == -1) {
27160 			/*
27161 			 * The copy operation failed.  mi_copy_state already
27162 			 * cleaned up, so we're out of here.
27163 			 */
27164 			return;
27165 		}
27166 		/*
27167 		 * If we just completed a copy in, we become writer and
27168 		 * continue processing in ip_sioctl_copyin_done.  If it
27169 		 * was a copy out, we call mi_copyout again.  If there is
27170 		 * nothing more to copy out, it will complete the IOCTL.
27171 		 */
27172 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27173 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27174 				mi_copy_done(q, mp, EPROTO);
27175 				return;
27176 			}
27177 			/*
27178 			 * Check for cases that need more copying.  A return
27179 			 * value of 0 means a second copyin has been started,
27180 			 * so we return; a return value of 1 means no more
27181 			 * copying is needed, so we continue.
27182 			 */
27183 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27184 			    MI_COPY_COUNT(mp) == 1) {
27185 				if (ip_copyin_msfilter(q, mp) == 0)
27186 					return;
27187 			}
27188 			/*
27189 			 * Refhold the conn, till the ioctl completes. This is
27190 			 * needed in case the ioctl ends up in the pending mp
27191 			 * list. Every mp in the ill_pending_mp list and
27192 			 * the ipsq_pending_mp must have a refhold on the conn
27193 			 * to resume processing. The refhold is released when
27194 			 * the ioctl completes. (normally or abnormally)
27195 			 * In all cases ip_ioctl_finish is called to finish
27196 			 * the ioctl.
27197 			 */
27198 			if (connp != NULL) {
27199 				/* This is not a reentry */
27200 				ASSERT(ipsq == NULL);
27201 				CONN_INC_REF(connp);
27202 			} else {
27203 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27204 					mi_copy_done(q, mp, EINVAL);
27205 					return;
27206 				}
27207 			}
27208 
27209 			ip_process_ioctl(ipsq, q, mp, ipip);
27210 
27211 		} else {
27212 			mi_copyout(q, mp);
27213 		}
27214 		return;
27215 nak:
27216 		iocp->ioc_error = EINVAL;
27217 		mp->b_datap->db_type = M_IOCNAK;
27218 		iocp->ioc_count = 0;
27219 		qreply(q, mp);
27220 		return;
27221 
27222 	case M_IOCNAK:
27223 		/*
27224 		 * The only way we could get here is if a resolver didn't like
27225 		 * an IOCTL we sent it.	 This shouldn't happen.
27226 		 */
27227 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27228 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27229 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27230 		freemsg(mp);
27231 		return;
27232 	case M_IOCACK:
27233 		/* /dev/ip shouldn't see this */
27234 		if (CONN_Q(q))
27235 			goto nak;
27236 
27237 		/* Finish socket ioctls passed through to ARP. */
27238 		ip_sioctl_iocack(q, mp);
27239 		return;
27240 	case M_FLUSH:
27241 		if (*mp->b_rptr & FLUSHW)
27242 			flushq(q, FLUSHALL);
27243 		if (q->q_next) {
27244 			putnext(q, mp);
27245 			return;
27246 		}
27247 		if (*mp->b_rptr & FLUSHR) {
27248 			*mp->b_rptr &= ~FLUSHW;
27249 			qreply(q, mp);
27250 			return;
27251 		}
27252 		freemsg(mp);
27253 		return;
27254 	case IRE_DB_REQ_TYPE:
27255 		if (connp == NULL) {
27256 			proto_str = "IRE_DB_REQ_TYPE";
27257 			goto protonak;
27258 		}
27259 		/* An Upper Level Protocol wants a copy of an IRE. */
27260 		ip_ire_req(q, mp);
27261 		return;
27262 	case M_CTL:
27263 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27264 			break;
27265 
27266 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27267 		    TUN_HELLO) {
27268 			ASSERT(connp != NULL);
27269 			connp->conn_flags |= IPCL_IPTUN;
27270 			freeb(mp);
27271 			return;
27272 		}
27273 
27274 		/* M_CTL messages are used by ARP to tell us things. */
27275 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27276 			break;
27277 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27278 		case AR_ENTRY_SQUERY:
27279 			ip_wput_ctl(q, mp);
27280 			return;
27281 		case AR_CLIENT_NOTIFY:
27282 			ip_arp_news(q, mp);
27283 			return;
27284 		case AR_DLPIOP_DONE:
27285 			ASSERT(q->q_next != NULL);
27286 			ill = (ill_t *)q->q_ptr;
27287 			/* qwriter_ip releases the refhold */
27288 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27289 			ill_refhold(ill);
27290 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27291 			return;
27292 		case AR_ARP_CLOSING:
27293 			/*
27294 			 * ARP (above us) is closing. If no ARP bringup is
27295 			 * currently pending, ack the message so that ARP
27296 			 * can complete its close. Also mark ill_arp_closing
27297 			 * so that new ARP bringups will fail. If any
27298 			 * ARP bringup is currently in progress, we will
27299 			 * ack this when the current ARP bringup completes.
27300 			 */
27301 			ASSERT(q->q_next != NULL);
27302 			ill = (ill_t *)q->q_ptr;
27303 			mutex_enter(&ill->ill_lock);
27304 			ill->ill_arp_closing = 1;
27305 			if (!ill->ill_arp_bringup_pending) {
27306 				mutex_exit(&ill->ill_lock);
27307 				qreply(q, mp);
27308 			} else {
27309 				mutex_exit(&ill->ill_lock);
27310 				freemsg(mp);
27311 			}
27312 			return;
27313 		case AR_ARP_EXTEND:
27314 			/*
27315 			 * The ARP module above us is capable of duplicate
27316 			 * address detection.  Old ATM drivers will not send
27317 			 * this message.
27318 			 */
27319 			ASSERT(q->q_next != NULL);
27320 			ill = (ill_t *)q->q_ptr;
27321 			ill->ill_arp_extend = B_TRUE;
27322 			freemsg(mp);
27323 			return;
27324 		default:
27325 			break;
27326 		}
27327 		break;
27328 	case M_PROTO:
27329 	case M_PCPROTO:
27330 		/*
27331 		 * The only PROTO messages we expect are ULP binds and
27332 		 * copies of option negotiation acknowledgements.
27333 		 */
27334 		switch (((union T_primitives *)mp->b_rptr)->type) {
27335 		case O_T_BIND_REQ:
27336 		case T_BIND_REQ: {
27337 			/* Request can get queued in bind */
27338 			if (connp == NULL) {
27339 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27340 				goto protonak;
27341 			}
27342 			/*
27343 			 * The transports except SCTP call ip_bind_{v4,v6}()
27344 			 * directly instead of a a putnext. SCTP doesn't
27345 			 * generate any T_BIND_REQ since it has its own
27346 			 * fanout data structures. However, ESP and AH
27347 			 * come in for regular binds; all other cases are
27348 			 * bind retries.
27349 			 */
27350 			ASSERT(!IPCL_IS_SCTP(connp));
27351 
27352 			/* Don't increment refcnt if this is a re-entry */
27353 			if (ipsq == NULL)
27354 				CONN_INC_REF(connp);
27355 
27356 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27357 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27358 			if (mp == NULL)
27359 				return;
27360 			if (IPCL_IS_TCP(connp)) {
27361 				/*
27362 				 * In the case of TCP endpoint we
27363 				 * come here only for bind retries
27364 				 */
27365 				ASSERT(ipsq != NULL);
27366 				CONN_INC_REF(connp);
27367 				squeue_fill(connp->conn_sqp, mp,
27368 				    ip_resume_tcp_bind, connp,
27369 				    SQTAG_BIND_RETRY);
27370 			} else if (IPCL_IS_UDP(connp)) {
27371 				/*
27372 				 * In the case of UDP endpoint we
27373 				 * come here only for bind retries
27374 				 */
27375 				ASSERT(ipsq != NULL);
27376 				udp_resume_bind(connp, mp);
27377 			} else if (IPCL_IS_RAWIP(connp)) {
27378 				/*
27379 				 * In the case of RAWIP endpoint we
27380 				 * come here only for bind retries
27381 				 */
27382 				ASSERT(ipsq != NULL);
27383 				rawip_resume_bind(connp, mp);
27384 			} else {
27385 				/* The case of AH and ESP */
27386 				qreply(q, mp);
27387 				CONN_OPER_PENDING_DONE(connp);
27388 			}
27389 			return;
27390 		}
27391 		case T_SVR4_OPTMGMT_REQ:
27392 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27393 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27394 
27395 			if (connp == NULL) {
27396 				proto_str = "T_SVR4_OPTMGMT_REQ";
27397 				goto protonak;
27398 			}
27399 
27400 			if (!snmpcom_req(q, mp, ip_snmp_set,
27401 			    ip_snmp_get, cr)) {
27402 				/*
27403 				 * Call svr4_optcom_req so that it can
27404 				 * generate the ack. We don't come here
27405 				 * if this operation is being restarted.
27406 				 * ip_restart_optmgmt will drop the conn ref.
27407 				 * In the case of ipsec option after the ipsec
27408 				 * load is complete conn_restart_ipsec_waiter
27409 				 * drops the conn ref.
27410 				 */
27411 				ASSERT(ipsq == NULL);
27412 				CONN_INC_REF(connp);
27413 				if (ip_check_for_ipsec_opt(q, mp))
27414 					return;
27415 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27416 				    B_FALSE);
27417 				if (err != EINPROGRESS) {
27418 					/* Operation is done */
27419 					CONN_OPER_PENDING_DONE(connp);
27420 				}
27421 			}
27422 			return;
27423 		case T_OPTMGMT_REQ:
27424 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27425 			/*
27426 			 * Note: No snmpcom_req support through new
27427 			 * T_OPTMGMT_REQ.
27428 			 * Call tpi_optcom_req so that it can
27429 			 * generate the ack.
27430 			 */
27431 			if (connp == NULL) {
27432 				proto_str = "T_OPTMGMT_REQ";
27433 				goto protonak;
27434 			}
27435 
27436 			ASSERT(ipsq == NULL);
27437 			/*
27438 			 * We don't come here for restart. ip_restart_optmgmt
27439 			 * will drop the conn ref. In the case of ipsec option
27440 			 * after the ipsec load is complete
27441 			 * conn_restart_ipsec_waiter drops the conn ref.
27442 			 */
27443 			CONN_INC_REF(connp);
27444 			if (ip_check_for_ipsec_opt(q, mp))
27445 				return;
27446 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27447 			if (err != EINPROGRESS) {
27448 				/* Operation is done */
27449 				CONN_OPER_PENDING_DONE(connp);
27450 			}
27451 			return;
27452 		case T_UNBIND_REQ:
27453 			if (connp == NULL) {
27454 				proto_str = "T_UNBIND_REQ";
27455 				goto protonak;
27456 			}
27457 			mp = ip_unbind(q, mp);
27458 			qreply(q, mp);
27459 			return;
27460 		default:
27461 			/*
27462 			 * Have to drop any DLPI messages coming down from
27463 			 * arp (such as an info_req which would cause ip
27464 			 * to receive an extra info_ack if it was passed
27465 			 * through.
27466 			 */
27467 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27468 			    (int)*(uint_t *)mp->b_rptr));
27469 			freemsg(mp);
27470 			return;
27471 		}
27472 		/* NOTREACHED */
27473 	case IRE_DB_TYPE: {
27474 		nce_t		*nce;
27475 		ill_t		*ill;
27476 		in6_addr_t	gw_addr_v6;
27477 
27478 
27479 		/*
27480 		 * This is a response back from a resolver.  It
27481 		 * consists of a message chain containing:
27482 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27483 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27484 		 * The LL_HDR_MBLK is the DLPI header to use to get
27485 		 * the attached packet, and subsequent ones for the
27486 		 * same destination, transmitted.
27487 		 */
27488 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27489 			break;
27490 		/*
27491 		 * First, check to make sure the resolution succeeded.
27492 		 * If it failed, the second mblk will be empty.
27493 		 * If it is, free the chain, dropping the packet.
27494 		 * (We must ire_delete the ire; that frees the ire mblk)
27495 		 * We're doing this now to support PVCs for ATM; it's
27496 		 * a partial xresolv implementation. When we fully implement
27497 		 * xresolv interfaces, instead of freeing everything here
27498 		 * we'll initiate neighbor discovery.
27499 		 *
27500 		 * For v4 (ARP and other external resolvers) the resolver
27501 		 * frees the message, so no check is needed. This check
27502 		 * is required, though, for a full xresolve implementation.
27503 		 * Including this code here now both shows how external
27504 		 * resolvers can NACK a resolution request using an
27505 		 * existing design that has no specific provisions for NACKs,
27506 		 * and also takes into account that the current non-ARP
27507 		 * external resolver has been coded to use this method of
27508 		 * NACKing for all IPv6 (xresolv) cases,
27509 		 * whether our xresolv implementation is complete or not.
27510 		 *
27511 		 */
27512 		ire = (ire_t *)mp->b_rptr;
27513 		ill = ire_to_ill(ire);
27514 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27515 		if (mp1->b_rptr == mp1->b_wptr) {
27516 			if (ire->ire_ipversion == IPV6_VERSION) {
27517 				/*
27518 				 * XRESOLV interface.
27519 				 */
27520 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27521 				mutex_enter(&ire->ire_lock);
27522 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27523 				mutex_exit(&ire->ire_lock);
27524 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27525 					nce = ndp_lookup_v6(ill,
27526 					    &ire->ire_addr_v6, B_FALSE);
27527 				} else {
27528 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27529 					    B_FALSE);
27530 				}
27531 				if (nce != NULL) {
27532 					nce_resolv_failed(nce);
27533 					ndp_delete(nce);
27534 					NCE_REFRELE(nce);
27535 				}
27536 			}
27537 			mp->b_cont = NULL;
27538 			freemsg(mp1);		/* frees the pkt as well */
27539 			ASSERT(ire->ire_nce == NULL);
27540 			ire_delete((ire_t *)mp->b_rptr);
27541 			return;
27542 		}
27543 
27544 		/*
27545 		 * Split them into IRE_MBLK and pkt and feed it into
27546 		 * ire_add_then_send. Then in ire_add_then_send
27547 		 * the IRE will be added, and then the packet will be
27548 		 * run back through ip_wput. This time it will make
27549 		 * it to the wire.
27550 		 */
27551 		mp->b_cont = NULL;
27552 		mp = mp1->b_cont;		/* now, mp points to pkt */
27553 		mp1->b_cont = NULL;
27554 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27555 		if (ire->ire_ipversion == IPV6_VERSION) {
27556 			/*
27557 			 * XRESOLV interface. Find the nce and put a copy
27558 			 * of the dl_unitdata_req in nce_res_mp
27559 			 */
27560 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27561 			mutex_enter(&ire->ire_lock);
27562 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27563 			mutex_exit(&ire->ire_lock);
27564 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27565 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27566 				    B_FALSE);
27567 			} else {
27568 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27569 			}
27570 			if (nce != NULL) {
27571 				/*
27572 				 * We have to protect nce_res_mp here
27573 				 * from being accessed by other threads
27574 				 * while we change the mblk pointer.
27575 				 * Other functions will also lock the nce when
27576 				 * accessing nce_res_mp.
27577 				 *
27578 				 * The reason we change the mblk pointer
27579 				 * here rather than copying the resolved address
27580 				 * into the template is that, unlike with
27581 				 * ethernet, we have no guarantee that the
27582 				 * resolved address length will be
27583 				 * smaller than or equal to the lla length
27584 				 * with which the template was allocated,
27585 				 * (for ethernet, they're equal)
27586 				 * so we have to use the actual resolved
27587 				 * address mblk - which holds the real
27588 				 * dl_unitdata_req with the resolved address.
27589 				 *
27590 				 * Doing this is the same behavior as was
27591 				 * previously used in the v4 ARP case.
27592 				 */
27593 				mutex_enter(&nce->nce_lock);
27594 				if (nce->nce_res_mp != NULL)
27595 					freemsg(nce->nce_res_mp);
27596 				nce->nce_res_mp = mp1;
27597 				mutex_exit(&nce->nce_lock);
27598 				/*
27599 				 * We do a fastpath probe here because
27600 				 * we have resolved the address without
27601 				 * using Neighbor Discovery.
27602 				 * In the non-XRESOLV v6 case, the fastpath
27603 				 * probe is done right after neighbor
27604 				 * discovery completes.
27605 				 */
27606 				if (nce->nce_res_mp != NULL) {
27607 					int res;
27608 					nce_fastpath_list_add(nce);
27609 					res = ill_fastpath_probe(ill,
27610 					    nce->nce_res_mp);
27611 					if (res != 0 && res != EAGAIN)
27612 						nce_fastpath_list_delete(nce);
27613 				}
27614 
27615 				ire_add_then_send(q, ire, mp);
27616 				/*
27617 				 * Now we have to clean out any packets
27618 				 * that may have been queued on the nce
27619 				 * while it was waiting for address resolution
27620 				 * to complete.
27621 				 */
27622 				mutex_enter(&nce->nce_lock);
27623 				mp1 = nce->nce_qd_mp;
27624 				nce->nce_qd_mp = NULL;
27625 				mutex_exit(&nce->nce_lock);
27626 				while (mp1 != NULL) {
27627 					mblk_t *nxt_mp;
27628 					queue_t *fwdq = NULL;
27629 					ill_t   *inbound_ill;
27630 					uint_t ifindex;
27631 
27632 					nxt_mp = mp1->b_next;
27633 					mp1->b_next = NULL;
27634 					/*
27635 					 * Retrieve ifindex stored in
27636 					 * ip_rput_data_v6()
27637 					 */
27638 					ifindex =
27639 					    (uint_t)(uintptr_t)mp1->b_prev;
27640 					inbound_ill =
27641 					    ill_lookup_on_ifindex(ifindex,
27642 					    B_TRUE, NULL, NULL, NULL,
27643 					    NULL, ipst);
27644 					mp1->b_prev = NULL;
27645 					if (inbound_ill != NULL)
27646 						fwdq = inbound_ill->ill_rq;
27647 
27648 					if (fwdq != NULL) {
27649 						put(fwdq, mp1);
27650 						ill_refrele(inbound_ill);
27651 					} else
27652 						put(WR(ill->ill_rq), mp1);
27653 					mp1 = nxt_mp;
27654 				}
27655 				NCE_REFRELE(nce);
27656 			} else {	/* nce is NULL; clean up */
27657 				ire_delete(ire);
27658 				freemsg(mp);
27659 				freemsg(mp1);
27660 				return;
27661 			}
27662 		} else {
27663 			nce_t *arpce;
27664 			/*
27665 			 * Link layer resolution succeeded. Recompute the
27666 			 * ire_nce.
27667 			 */
27668 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27669 			if ((arpce = ndp_lookup_v4(ill,
27670 			    (ire->ire_gateway_addr != INADDR_ANY ?
27671 			    &ire->ire_gateway_addr : &ire->ire_addr),
27672 			    B_FALSE)) == NULL) {
27673 				freeb(ire->ire_mp);
27674 				freeb(mp1);
27675 				freemsg(mp);
27676 				return;
27677 			}
27678 			mutex_enter(&arpce->nce_lock);
27679 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27680 			if (arpce->nce_state == ND_REACHABLE) {
27681 				/*
27682 				 * Someone resolved this before us;
27683 				 * cleanup the res_mp. Since ire has
27684 				 * not been added yet, the call to ire_add_v4
27685 				 * from ire_add_then_send (when a dup is
27686 				 * detected) will clean up the ire.
27687 				 */
27688 				freeb(mp1);
27689 			} else {
27690 				ASSERT(arpce->nce_res_mp == NULL);
27691 				arpce->nce_res_mp = mp1;
27692 				arpce->nce_state = ND_REACHABLE;
27693 			}
27694 			mutex_exit(&arpce->nce_lock);
27695 			if (ire->ire_marks & IRE_MARK_NOADD) {
27696 				/*
27697 				 * this ire will not be added to the ire
27698 				 * cache table, so we can set the ire_nce
27699 				 * here, as there are no atomicity constraints.
27700 				 */
27701 				ire->ire_nce = arpce;
27702 				/*
27703 				 * We are associating this nce with the ire
27704 				 * so change the nce ref taken in
27705 				 * ndp_lookup_v4() from
27706 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27707 				 */
27708 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27709 			} else {
27710 				NCE_REFRELE(arpce);
27711 			}
27712 			ire_add_then_send(q, ire, mp);
27713 		}
27714 		return;	/* All is well, the packet has been sent. */
27715 	}
27716 	case IRE_ARPRESOLVE_TYPE: {
27717 
27718 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27719 			break;
27720 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27721 		mp->b_cont = NULL;
27722 		/*
27723 		 * First, check to make sure the resolution succeeded.
27724 		 * If it failed, the second mblk will be empty.
27725 		 */
27726 		if (mp1->b_rptr == mp1->b_wptr) {
27727 			/* cleanup  the incomplete ire, free queued packets */
27728 			freemsg(mp); /* fake ire */
27729 			freeb(mp1);  /* dl_unitdata response */
27730 			return;
27731 		}
27732 
27733 		/*
27734 		 * update any incomplete nce_t found. we lookup the ctable
27735 		 * and find the nce from the ire->ire_nce because we need
27736 		 * to pass the ire to ip_xmit_v4 later, and can find both
27737 		 * ire and nce in one lookup from the ctable.
27738 		 */
27739 		fake_ire = (ire_t *)mp->b_rptr;
27740 		/*
27741 		 * By the time we come back here from ARP
27742 		 * the logical outgoing interface  of the incomplete ire
27743 		 * we added in ire_forward could have disappeared,
27744 		 * causing the incomplete ire to also have
27745 		 * dissapeared. So we need to retreive the
27746 		 * proper ipif for the ire  before looking
27747 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27748 		 */
27749 		ill = q->q_ptr;
27750 
27751 		/* Get the outgoing ipif */
27752 		mutex_enter(&ill->ill_lock);
27753 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27754 			mutex_exit(&ill->ill_lock);
27755 			freemsg(mp); /* fake ire */
27756 			freeb(mp1);  /* dl_unitdata response */
27757 			return;
27758 		}
27759 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27760 
27761 		if (ipif == NULL) {
27762 			mutex_exit(&ill->ill_lock);
27763 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27764 			freemsg(mp);
27765 			freeb(mp1);
27766 			return;
27767 		}
27768 		ipif_refhold_locked(ipif);
27769 		mutex_exit(&ill->ill_lock);
27770 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27771 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27772 		    ipif, fake_ire->ire_zoneid, NULL,
27773 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27774 		ipif_refrele(ipif);
27775 		if (ire == NULL) {
27776 			/*
27777 			 * no ire was found; check if there is an nce
27778 			 * for this lookup; if it has no ire's pointing at it
27779 			 * cleanup.
27780 			 */
27781 			if ((nce = ndp_lookup_v4(ill,
27782 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27783 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27784 			    B_FALSE)) != NULL) {
27785 				/*
27786 				 * cleanup:
27787 				 * We check for refcnt 2 (one for the nce
27788 				 * hash list + 1 for the ref taken by
27789 				 * ndp_lookup_v4) to check that there are
27790 				 * no ire's pointing at the nce.
27791 				 */
27792 				if (nce->nce_refcnt == 2)
27793 					ndp_delete(nce);
27794 				NCE_REFRELE(nce);
27795 			}
27796 			freeb(mp1);  /* dl_unitdata response */
27797 			freemsg(mp); /* fake ire */
27798 			return;
27799 		}
27800 		nce = ire->ire_nce;
27801 		DTRACE_PROBE2(ire__arpresolve__type,
27802 		    ire_t *, ire, nce_t *, nce);
27803 		ASSERT(nce->nce_state != ND_INITIAL);
27804 		mutex_enter(&nce->nce_lock);
27805 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27806 		if (nce->nce_state == ND_REACHABLE) {
27807 			/*
27808 			 * Someone resolved this before us;
27809 			 * our response is not needed any more.
27810 			 */
27811 			mutex_exit(&nce->nce_lock);
27812 			freeb(mp1);  /* dl_unitdata response */
27813 		} else {
27814 			ASSERT(nce->nce_res_mp == NULL);
27815 			nce->nce_res_mp = mp1;
27816 			nce->nce_state = ND_REACHABLE;
27817 			mutex_exit(&nce->nce_lock);
27818 			nce_fastpath(nce);
27819 		}
27820 		/*
27821 		 * The cached nce_t has been updated to be reachable;
27822 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27823 		 */
27824 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27825 		freemsg(mp);
27826 		/*
27827 		 * send out queued packets.
27828 		 */
27829 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27830 
27831 		IRE_REFRELE(ire);
27832 		return;
27833 	}
27834 	default:
27835 		break;
27836 	}
27837 	if (q->q_next) {
27838 		putnext(q, mp);
27839 	} else
27840 		freemsg(mp);
27841 	return;
27842 
27843 protonak:
27844 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27845 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27846 		qreply(q, mp);
27847 }
27848 
27849 /*
27850  * Process IP options in an outbound packet.  Modify the destination if there
27851  * is a source route option.
27852  * Returns non-zero if something fails in which case an ICMP error has been
27853  * sent and mp freed.
27854  */
27855 static int
27856 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27857     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27858 {
27859 	ipoptp_t	opts;
27860 	uchar_t		*opt;
27861 	uint8_t		optval;
27862 	uint8_t		optlen;
27863 	ipaddr_t	dst;
27864 	intptr_t	code = 0;
27865 	mblk_t		*mp;
27866 	ire_t		*ire = NULL;
27867 
27868 	ip2dbg(("ip_wput_options\n"));
27869 	mp = ipsec_mp;
27870 	if (mctl_present) {
27871 		mp = ipsec_mp->b_cont;
27872 	}
27873 
27874 	dst = ipha->ipha_dst;
27875 	for (optval = ipoptp_first(&opts, ipha);
27876 	    optval != IPOPT_EOL;
27877 	    optval = ipoptp_next(&opts)) {
27878 		opt = opts.ipoptp_cur;
27879 		optlen = opts.ipoptp_len;
27880 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27881 		    optval, optlen));
27882 		switch (optval) {
27883 			uint32_t off;
27884 		case IPOPT_SSRR:
27885 		case IPOPT_LSRR:
27886 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27887 				ip1dbg((
27888 				    "ip_wput_options: bad option offset\n"));
27889 				code = (char *)&opt[IPOPT_OLEN] -
27890 				    (char *)ipha;
27891 				goto param_prob;
27892 			}
27893 			off = opt[IPOPT_OFFSET];
27894 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27895 			    ntohl(dst)));
27896 			/*
27897 			 * For strict: verify that dst is directly
27898 			 * reachable.
27899 			 */
27900 			if (optval == IPOPT_SSRR) {
27901 				ire = ire_ftable_lookup(dst, 0, 0,
27902 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27903 				    MBLK_GETLABEL(mp),
27904 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27905 				if (ire == NULL) {
27906 					ip1dbg(("ip_wput_options: SSRR not"
27907 					    " directly reachable: 0x%x\n",
27908 					    ntohl(dst)));
27909 					goto bad_src_route;
27910 				}
27911 				ire_refrele(ire);
27912 			}
27913 			break;
27914 		case IPOPT_RR:
27915 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27916 				ip1dbg((
27917 				    "ip_wput_options: bad option offset\n"));
27918 				code = (char *)&opt[IPOPT_OLEN] -
27919 				    (char *)ipha;
27920 				goto param_prob;
27921 			}
27922 			break;
27923 		case IPOPT_TS:
27924 			/*
27925 			 * Verify that length >=5 and that there is either
27926 			 * room for another timestamp or that the overflow
27927 			 * counter is not maxed out.
27928 			 */
27929 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27930 			if (optlen < IPOPT_MINLEN_IT) {
27931 				goto param_prob;
27932 			}
27933 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27934 				ip1dbg((
27935 				    "ip_wput_options: bad option offset\n"));
27936 				code = (char *)&opt[IPOPT_OFFSET] -
27937 				    (char *)ipha;
27938 				goto param_prob;
27939 			}
27940 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27941 			case IPOPT_TS_TSONLY:
27942 				off = IPOPT_TS_TIMELEN;
27943 				break;
27944 			case IPOPT_TS_TSANDADDR:
27945 			case IPOPT_TS_PRESPEC:
27946 			case IPOPT_TS_PRESPEC_RFC791:
27947 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27948 				break;
27949 			default:
27950 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27951 				    (char *)ipha;
27952 				goto param_prob;
27953 			}
27954 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27955 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27956 				/*
27957 				 * No room and the overflow counter is 15
27958 				 * already.
27959 				 */
27960 				goto param_prob;
27961 			}
27962 			break;
27963 		}
27964 	}
27965 
27966 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
27967 		return (0);
27968 
27969 	ip1dbg(("ip_wput_options: error processing IP options."));
27970 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
27971 
27972 param_prob:
27973 	/*
27974 	 * Since ip_wput() isn't close to finished, we fill
27975 	 * in enough of the header for credible error reporting.
27976 	 */
27977 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27978 		/* Failed */
27979 		freemsg(ipsec_mp);
27980 		return (-1);
27981 	}
27982 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
27983 	return (-1);
27984 
27985 bad_src_route:
27986 	/*
27987 	 * Since ip_wput() isn't close to finished, we fill
27988 	 * in enough of the header for credible error reporting.
27989 	 */
27990 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
27991 		/* Failed */
27992 		freemsg(ipsec_mp);
27993 		return (-1);
27994 	}
27995 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
27996 	return (-1);
27997 }
27998 
27999 /*
28000  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28001  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28002  * thru /etc/system.
28003  */
28004 #define	CONN_MAXDRAINCNT	64
28005 
28006 static void
28007 conn_drain_init(ip_stack_t *ipst)
28008 {
28009 	int i;
28010 
28011 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28012 
28013 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28014 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28015 		/*
28016 		 * Default value of the number of drainers is the
28017 		 * number of cpus, subject to maximum of 8 drainers.
28018 		 */
28019 		if (boot_max_ncpus != -1)
28020 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28021 		else
28022 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28023 	}
28024 
28025 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28026 	    sizeof (idl_t), KM_SLEEP);
28027 
28028 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28029 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28030 		    MUTEX_DEFAULT, NULL);
28031 	}
28032 }
28033 
28034 static void
28035 conn_drain_fini(ip_stack_t *ipst)
28036 {
28037 	int i;
28038 
28039 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28040 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28041 	kmem_free(ipst->ips_conn_drain_list,
28042 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28043 	ipst->ips_conn_drain_list = NULL;
28044 }
28045 
28046 /*
28047  * Note: For an overview of how flowcontrol is handled in IP please see the
28048  * IP Flowcontrol notes at the top of this file.
28049  *
28050  * Flow control has blocked us from proceeding. Insert the given conn in one
28051  * of the conn drain lists. These conn wq's will be qenabled later on when
28052  * STREAMS flow control does a backenable. conn_walk_drain will enable
28053  * the first conn in each of these drain lists. Each of these qenabled conns
28054  * in turn enables the next in the list, after it runs, or when it closes,
28055  * thus sustaining the drain process.
28056  *
28057  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28058  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28059  * running at any time, on a given conn, since there can be only 1 service proc
28060  * running on a queue at any time.
28061  */
28062 void
28063 conn_drain_insert(conn_t *connp)
28064 {
28065 	idl_t	*idl;
28066 	uint_t	index;
28067 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28068 
28069 	mutex_enter(&connp->conn_lock);
28070 	if (connp->conn_state_flags & CONN_CLOSING) {
28071 		/*
28072 		 * The conn is closing as a result of which CONN_CLOSING
28073 		 * is set. Return.
28074 		 */
28075 		mutex_exit(&connp->conn_lock);
28076 		return;
28077 	} else if (connp->conn_idl == NULL) {
28078 		/*
28079 		 * Assign the next drain list round robin. We dont' use
28080 		 * a lock, and thus it may not be strictly round robin.
28081 		 * Atomicity of load/stores is enough to make sure that
28082 		 * conn_drain_list_index is always within bounds.
28083 		 */
28084 		index = ipst->ips_conn_drain_list_index;
28085 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28086 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28087 		index++;
28088 		if (index == ipst->ips_conn_drain_list_cnt)
28089 			index = 0;
28090 		ipst->ips_conn_drain_list_index = index;
28091 	}
28092 	mutex_exit(&connp->conn_lock);
28093 
28094 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28095 	if ((connp->conn_drain_prev != NULL) ||
28096 	    (connp->conn_state_flags & CONN_CLOSING)) {
28097 		/*
28098 		 * The conn is already in the drain list, OR
28099 		 * the conn is closing. We need to check again for
28100 		 * the closing case again since close can happen
28101 		 * after we drop the conn_lock, and before we
28102 		 * acquire the CONN_DRAIN_LIST_LOCK.
28103 		 */
28104 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28105 		return;
28106 	} else {
28107 		idl = connp->conn_idl;
28108 	}
28109 
28110 	/*
28111 	 * The conn is not in the drain list. Insert it at the
28112 	 * tail of the drain list. The drain list is circular
28113 	 * and doubly linked. idl_conn points to the 1st element
28114 	 * in the list.
28115 	 */
28116 	if (idl->idl_conn == NULL) {
28117 		idl->idl_conn = connp;
28118 		connp->conn_drain_next = connp;
28119 		connp->conn_drain_prev = connp;
28120 	} else {
28121 		conn_t *head = idl->idl_conn;
28122 
28123 		connp->conn_drain_next = head;
28124 		connp->conn_drain_prev = head->conn_drain_prev;
28125 		head->conn_drain_prev->conn_drain_next = connp;
28126 		head->conn_drain_prev = connp;
28127 	}
28128 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28129 }
28130 
28131 /*
28132  * This conn is closing, and we are called from ip_close. OR
28133  * This conn has been serviced by ip_wsrv, and we need to do the tail
28134  * processing.
28135  * If this conn is part of the drain list, we may need to sustain the drain
28136  * process by qenabling the next conn in the drain list. We may also need to
28137  * remove this conn from the list, if it is done.
28138  */
28139 static void
28140 conn_drain_tail(conn_t *connp, boolean_t closing)
28141 {
28142 	idl_t *idl;
28143 
28144 	/*
28145 	 * connp->conn_idl is stable at this point, and no lock is needed
28146 	 * to check it. If we are called from ip_close, close has already
28147 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28148 	 * called us only because conn_idl is non-null. If we are called thru
28149 	 * service, conn_idl could be null, but it cannot change because
28150 	 * service is single-threaded per queue, and there cannot be another
28151 	 * instance of service trying to call conn_drain_insert on this conn
28152 	 * now.
28153 	 */
28154 	ASSERT(!closing || (connp->conn_idl != NULL));
28155 
28156 	/*
28157 	 * If connp->conn_idl is null, the conn has not been inserted into any
28158 	 * drain list even once since creation of the conn. Just return.
28159 	 */
28160 	if (connp->conn_idl == NULL)
28161 		return;
28162 
28163 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28164 
28165 	if (connp->conn_drain_prev == NULL) {
28166 		/* This conn is currently not in the drain list.  */
28167 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28168 		return;
28169 	}
28170 	idl = connp->conn_idl;
28171 	if (idl->idl_conn_draining == connp) {
28172 		/*
28173 		 * This conn is the current drainer. If this is the last conn
28174 		 * in the drain list, we need to do more checks, in the 'if'
28175 		 * below. Otherwwise we need to just qenable the next conn,
28176 		 * to sustain the draining, and is handled in the 'else'
28177 		 * below.
28178 		 */
28179 		if (connp->conn_drain_next == idl->idl_conn) {
28180 			/*
28181 			 * This conn is the last in this list. This round
28182 			 * of draining is complete. If idl_repeat is set,
28183 			 * it means another flow enabling has happened from
28184 			 * the driver/streams and we need to another round
28185 			 * of draining.
28186 			 * If there are more than 2 conns in the drain list,
28187 			 * do a left rotate by 1, so that all conns except the
28188 			 * conn at the head move towards the head by 1, and the
28189 			 * the conn at the head goes to the tail. This attempts
28190 			 * a more even share for all queues that are being
28191 			 * drained.
28192 			 */
28193 			if ((connp->conn_drain_next != connp) &&
28194 			    (idl->idl_conn->conn_drain_next != connp)) {
28195 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28196 			}
28197 			if (idl->idl_repeat) {
28198 				qenable(idl->idl_conn->conn_wq);
28199 				idl->idl_conn_draining = idl->idl_conn;
28200 				idl->idl_repeat = 0;
28201 			} else {
28202 				idl->idl_conn_draining = NULL;
28203 			}
28204 		} else {
28205 			/*
28206 			 * If the next queue that we are now qenable'ing,
28207 			 * is closing, it will remove itself from this list
28208 			 * and qenable the subsequent queue in ip_close().
28209 			 * Serialization is acheived thru idl_lock.
28210 			 */
28211 			qenable(connp->conn_drain_next->conn_wq);
28212 			idl->idl_conn_draining = connp->conn_drain_next;
28213 		}
28214 	}
28215 	if (!connp->conn_did_putbq || closing) {
28216 		/*
28217 		 * Remove ourself from the drain list, if we did not do
28218 		 * a putbq, or if the conn is closing.
28219 		 * Note: It is possible that q->q_first is non-null. It means
28220 		 * that these messages landed after we did a enableok() in
28221 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28222 		 * service them.
28223 		 */
28224 		if (connp->conn_drain_next == connp) {
28225 			/* Singleton in the list */
28226 			ASSERT(connp->conn_drain_prev == connp);
28227 			idl->idl_conn = NULL;
28228 			idl->idl_conn_draining = NULL;
28229 		} else {
28230 			connp->conn_drain_prev->conn_drain_next =
28231 			    connp->conn_drain_next;
28232 			connp->conn_drain_next->conn_drain_prev =
28233 			    connp->conn_drain_prev;
28234 			if (idl->idl_conn == connp)
28235 				idl->idl_conn = connp->conn_drain_next;
28236 			ASSERT(idl->idl_conn_draining != connp);
28237 
28238 		}
28239 		connp->conn_drain_next = NULL;
28240 		connp->conn_drain_prev = NULL;
28241 	}
28242 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28243 }
28244 
28245 /*
28246  * Write service routine. Shared perimeter entry point.
28247  * ip_wsrv can be called in any of the following ways.
28248  * 1. The device queue's messages has fallen below the low water mark
28249  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28250  *    the drain lists and backenable the first conn in each list.
28251  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28252  *    qenabled non-tcp upper layers. We start dequeing messages and call
28253  *    ip_wput for each message.
28254  */
28255 
28256 void
28257 ip_wsrv(queue_t *q)
28258 {
28259 	conn_t	*connp;
28260 	ill_t	*ill;
28261 	mblk_t	*mp;
28262 
28263 	if (q->q_next) {
28264 		ill = (ill_t *)q->q_ptr;
28265 		if (ill->ill_state_flags == 0) {
28266 			/*
28267 			 * The device flow control has opened up.
28268 			 * Walk through conn drain lists and qenable the
28269 			 * first conn in each list. This makes sense only
28270 			 * if the stream is fully plumbed and setup.
28271 			 * Hence the if check above.
28272 			 */
28273 			ip1dbg(("ip_wsrv: walking\n"));
28274 			conn_walk_drain(ill->ill_ipst);
28275 		}
28276 		return;
28277 	}
28278 
28279 	connp = Q_TO_CONN(q);
28280 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28281 
28282 	/*
28283 	 * 1. Set conn_draining flag to signal that service is active.
28284 	 *
28285 	 * 2. ip_output determines whether it has been called from service,
28286 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28287 	 *    has been called from service.
28288 	 *
28289 	 * 3. Message ordering is preserved by the following logic.
28290 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28291 	 *    the message at the tail, if conn_draining is set (i.e. service
28292 	 *    is running) or if q->q_first is non-null.
28293 	 *
28294 	 *    ii. If ip_output is called from service, and if ip_output cannot
28295 	 *    putnext due to flow control, it does a putbq.
28296 	 *
28297 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28298 	 *    (causing an infinite loop).
28299 	 */
28300 	ASSERT(!connp->conn_did_putbq);
28301 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28302 		connp->conn_draining = 1;
28303 		noenable(q);
28304 		while ((mp = getq(q)) != NULL) {
28305 			ASSERT(CONN_Q(q));
28306 
28307 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28308 			if (connp->conn_did_putbq) {
28309 				/* ip_wput did a putbq */
28310 				break;
28311 			}
28312 		}
28313 		/*
28314 		 * At this point, a thread coming down from top, calling
28315 		 * ip_wput, may end up queueing the message. We have not yet
28316 		 * enabled the queue, so ip_wsrv won't be called again.
28317 		 * To avoid this race, check q->q_first again (in the loop)
28318 		 * If the other thread queued the message before we call
28319 		 * enableok(), we will catch it in the q->q_first check.
28320 		 * If the other thread queues the message after we call
28321 		 * enableok(), ip_wsrv will be called again by STREAMS.
28322 		 */
28323 		connp->conn_draining = 0;
28324 		enableok(q);
28325 	}
28326 
28327 	/* Enable the next conn for draining */
28328 	conn_drain_tail(connp, B_FALSE);
28329 
28330 	connp->conn_did_putbq = 0;
28331 }
28332 
28333 /*
28334  * Walk the list of all conn's calling the function provided with the
28335  * specified argument for each.	 Note that this only walks conn's that
28336  * have been bound.
28337  * Applies to both IPv4 and IPv6.
28338  */
28339 static void
28340 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28341 {
28342 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28343 	    ipst->ips_ipcl_udp_fanout_size,
28344 	    func, arg, zoneid);
28345 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28346 	    ipst->ips_ipcl_conn_fanout_size,
28347 	    func, arg, zoneid);
28348 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28349 	    ipst->ips_ipcl_bind_fanout_size,
28350 	    func, arg, zoneid);
28351 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28352 	    IPPROTO_MAX, func, arg, zoneid);
28353 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28354 	    IPPROTO_MAX, func, arg, zoneid);
28355 }
28356 
28357 /*
28358  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28359  * of conns that need to be drained, check if drain is already in progress.
28360  * If so set the idl_repeat bit, indicating that the last conn in the list
28361  * needs to reinitiate the drain once again, for the list. If drain is not
28362  * in progress for the list, initiate the draining, by qenabling the 1st
28363  * conn in the list. The drain is self-sustaining, each qenabled conn will
28364  * in turn qenable the next conn, when it is done/blocked/closing.
28365  */
28366 static void
28367 conn_walk_drain(ip_stack_t *ipst)
28368 {
28369 	int i;
28370 	idl_t *idl;
28371 
28372 	IP_STAT(ipst, ip_conn_walk_drain);
28373 
28374 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28375 		idl = &ipst->ips_conn_drain_list[i];
28376 		mutex_enter(&idl->idl_lock);
28377 		if (idl->idl_conn == NULL) {
28378 			mutex_exit(&idl->idl_lock);
28379 			continue;
28380 		}
28381 		/*
28382 		 * If this list is not being drained currently by
28383 		 * an ip_wsrv thread, start the process.
28384 		 */
28385 		if (idl->idl_conn_draining == NULL) {
28386 			ASSERT(idl->idl_repeat == 0);
28387 			qenable(idl->idl_conn->conn_wq);
28388 			idl->idl_conn_draining = idl->idl_conn;
28389 		} else {
28390 			idl->idl_repeat = 1;
28391 		}
28392 		mutex_exit(&idl->idl_lock);
28393 	}
28394 }
28395 
28396 /*
28397  * Walk an conn hash table of `count' buckets, calling func for each entry.
28398  */
28399 static void
28400 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28401     zoneid_t zoneid)
28402 {
28403 	conn_t	*connp;
28404 
28405 	while (count-- > 0) {
28406 		mutex_enter(&connfp->connf_lock);
28407 		for (connp = connfp->connf_head; connp != NULL;
28408 		    connp = connp->conn_next) {
28409 			if (zoneid == GLOBAL_ZONEID ||
28410 			    zoneid == connp->conn_zoneid) {
28411 				CONN_INC_REF(connp);
28412 				mutex_exit(&connfp->connf_lock);
28413 				(*func)(connp, arg);
28414 				mutex_enter(&connfp->connf_lock);
28415 				CONN_DEC_REF(connp);
28416 			}
28417 		}
28418 		mutex_exit(&connfp->connf_lock);
28419 		connfp++;
28420 	}
28421 }
28422 
28423 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28424 static void
28425 conn_report1(conn_t *connp, void *mp)
28426 {
28427 	char	buf1[INET6_ADDRSTRLEN];
28428 	char	buf2[INET6_ADDRSTRLEN];
28429 	uint_t	print_len, buf_len;
28430 
28431 	ASSERT(connp != NULL);
28432 
28433 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28434 	if (buf_len <= 0)
28435 		return;
28436 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28437 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28438 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28439 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28440 	    "%5d %s/%05d %s/%05d\n",
28441 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28442 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28443 	    buf1, connp->conn_lport,
28444 	    buf2, connp->conn_fport);
28445 	if (print_len < buf_len) {
28446 		((mblk_t *)mp)->b_wptr += print_len;
28447 	} else {
28448 		((mblk_t *)mp)->b_wptr += buf_len;
28449 	}
28450 }
28451 
28452 /*
28453  * Named Dispatch routine to produce a formatted report on all conns
28454  * that are listed in one of the fanout tables.
28455  * This report is accessed by using the ndd utility to "get" ND variable
28456  * "ip_conn_status".
28457  */
28458 /* ARGSUSED */
28459 static int
28460 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28461 {
28462 	conn_t *connp = Q_TO_CONN(q);
28463 
28464 	(void) mi_mpprintf(mp,
28465 	    "CONN      " MI_COL_HDRPAD_STR
28466 	    "rfq      " MI_COL_HDRPAD_STR
28467 	    "stq      " MI_COL_HDRPAD_STR
28468 	    " zone local                 remote");
28469 
28470 	/*
28471 	 * Because of the ndd constraint, at most we can have 64K buffer
28472 	 * to put in all conn info.  So to be more efficient, just
28473 	 * allocate a 64K buffer here, assuming we need that large buffer.
28474 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28475 	 */
28476 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28477 		/* The following may work even if we cannot get a large buf. */
28478 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28479 		return (0);
28480 	}
28481 
28482 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28483 	    connp->conn_netstack->netstack_ip);
28484 	return (0);
28485 }
28486 
28487 /*
28488  * Determine if the ill and multicast aspects of that packets
28489  * "matches" the conn.
28490  */
28491 boolean_t
28492 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28493     zoneid_t zoneid)
28494 {
28495 	ill_t *in_ill;
28496 	boolean_t found;
28497 	ipif_t *ipif;
28498 	ire_t *ire;
28499 	ipaddr_t dst, src;
28500 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28501 
28502 	dst = ipha->ipha_dst;
28503 	src = ipha->ipha_src;
28504 
28505 	/*
28506 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28507 	 * unicast, broadcast and multicast reception to
28508 	 * conn_incoming_ill. conn_wantpacket itself is called
28509 	 * only for BROADCAST and multicast.
28510 	 *
28511 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28512 	 *    is part of a group. Hence, we should be receiving
28513 	 *    just one copy of broadcast for the whole group.
28514 	 *    Thus, if it is part of the group the packet could
28515 	 *    come on any ill of the group and hence we need a
28516 	 *    match on the group. Otherwise, match on ill should
28517 	 *    be sufficient.
28518 	 *
28519 	 * 2) ip_rput does not suppress duplicate multicast packets.
28520 	 *    If there are two interfaces in a ill group and we have
28521 	 *    2 applications (conns) joined a multicast group G on
28522 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28523 	 *    will give us two packets because we join G on both the
28524 	 *    interfaces rather than nominating just one interface
28525 	 *    for receiving multicast like broadcast above. So,
28526 	 *    we have to call ilg_lookup_ill to filter out duplicate
28527 	 *    copies, if ill is part of a group.
28528 	 */
28529 	in_ill = connp->conn_incoming_ill;
28530 	if (in_ill != NULL) {
28531 		if (in_ill->ill_group == NULL) {
28532 			if (in_ill != ill)
28533 				return (B_FALSE);
28534 		} else if (in_ill->ill_group != ill->ill_group) {
28535 			return (B_FALSE);
28536 		}
28537 	}
28538 
28539 	if (!CLASSD(dst)) {
28540 		if (IPCL_ZONE_MATCH(connp, zoneid))
28541 			return (B_TRUE);
28542 		/*
28543 		 * The conn is in a different zone; we need to check that this
28544 		 * broadcast address is configured in the application's zone and
28545 		 * on one ill in the group.
28546 		 */
28547 		ipif = ipif_get_next_ipif(NULL, ill);
28548 		if (ipif == NULL)
28549 			return (B_FALSE);
28550 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28551 		    connp->conn_zoneid, NULL,
28552 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28553 		ipif_refrele(ipif);
28554 		if (ire != NULL) {
28555 			ire_refrele(ire);
28556 			return (B_TRUE);
28557 		} else {
28558 			return (B_FALSE);
28559 		}
28560 	}
28561 
28562 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28563 	    connp->conn_zoneid == zoneid) {
28564 		/*
28565 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28566 		 * disabled, therefore we don't dispatch the multicast packet to
28567 		 * the sending zone.
28568 		 */
28569 		return (B_FALSE);
28570 	}
28571 
28572 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28573 		/*
28574 		 * Multicast packet on the loopback interface: we only match
28575 		 * conns who joined the group in the specified zone.
28576 		 */
28577 		return (B_FALSE);
28578 	}
28579 
28580 	if (connp->conn_multi_router) {
28581 		/* multicast packet and multicast router socket: send up */
28582 		return (B_TRUE);
28583 	}
28584 
28585 	mutex_enter(&connp->conn_lock);
28586 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28587 	mutex_exit(&connp->conn_lock);
28588 	return (found);
28589 }
28590 
28591 /*
28592  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28593  */
28594 /* ARGSUSED */
28595 static void
28596 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28597 {
28598 	ill_t *ill = (ill_t *)q->q_ptr;
28599 	mblk_t	*mp1, *mp2;
28600 	ipif_t  *ipif;
28601 	int err = 0;
28602 	conn_t *connp = NULL;
28603 	ipsq_t	*ipsq;
28604 	arc_t	*arc;
28605 
28606 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28607 
28608 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28609 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28610 
28611 	ASSERT(IAM_WRITER_ILL(ill));
28612 	mp2 = mp->b_cont;
28613 	mp->b_cont = NULL;
28614 
28615 	/*
28616 	 * We have now received the arp bringup completion message
28617 	 * from ARP. Mark the arp bringup as done. Also if the arp
28618 	 * stream has already started closing, send up the AR_ARP_CLOSING
28619 	 * ack now since ARP is waiting in close for this ack.
28620 	 */
28621 	mutex_enter(&ill->ill_lock);
28622 	ill->ill_arp_bringup_pending = 0;
28623 	if (ill->ill_arp_closing) {
28624 		mutex_exit(&ill->ill_lock);
28625 		/* Let's reuse the mp for sending the ack */
28626 		arc = (arc_t *)mp->b_rptr;
28627 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28628 		arc->arc_cmd = AR_ARP_CLOSING;
28629 		qreply(q, mp);
28630 	} else {
28631 		mutex_exit(&ill->ill_lock);
28632 		freeb(mp);
28633 	}
28634 
28635 	ipsq = ill->ill_phyint->phyint_ipsq;
28636 	ipif = ipsq->ipsq_pending_ipif;
28637 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28638 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28639 	if (mp1 == NULL) {
28640 		/* bringup was aborted by the user */
28641 		freemsg(mp2);
28642 		return;
28643 	}
28644 
28645 	/*
28646 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28647 	 * must have an associated conn_t.  Otherwise, we're bringing this
28648 	 * interface back up as part of handling an asynchronous event (e.g.,
28649 	 * physical address change).
28650 	 */
28651 	if (ipsq->ipsq_current_ioctl != 0) {
28652 		ASSERT(connp != NULL);
28653 		q = CONNP_TO_WQ(connp);
28654 	} else {
28655 		ASSERT(connp == NULL);
28656 		q = ill->ill_rq;
28657 	}
28658 
28659 	/*
28660 	 * If the DL_BIND_REQ fails, it is noted
28661 	 * in arc_name_offset.
28662 	 */
28663 	err = *((int *)mp2->b_rptr);
28664 	if (err == 0) {
28665 		if (ipif->ipif_isv6) {
28666 			if ((err = ipif_up_done_v6(ipif)) != 0)
28667 				ip0dbg(("ip_arp_done: init failed\n"));
28668 		} else {
28669 			if ((err = ipif_up_done(ipif)) != 0)
28670 				ip0dbg(("ip_arp_done: init failed\n"));
28671 		}
28672 	} else {
28673 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28674 	}
28675 
28676 	freemsg(mp2);
28677 
28678 	if ((err == 0) && (ill->ill_up_ipifs)) {
28679 		err = ill_up_ipifs(ill, q, mp1);
28680 		if (err == EINPROGRESS)
28681 			return;
28682 	}
28683 
28684 	if (ill->ill_up_ipifs)
28685 		ill_group_cleanup(ill);
28686 
28687 	/*
28688 	 * The operation must complete without EINPROGRESS since
28689 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28690 	 * Otherwise, the operation will be stuck forever in the ipsq.
28691 	 */
28692 	ASSERT(err != EINPROGRESS);
28693 	if (ipsq->ipsq_current_ioctl != 0)
28694 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28695 	else
28696 		ipsq_current_finish(ipsq);
28697 }
28698 
28699 /* Allocate the private structure */
28700 static int
28701 ip_priv_alloc(void **bufp)
28702 {
28703 	void	*buf;
28704 
28705 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28706 		return (ENOMEM);
28707 
28708 	*bufp = buf;
28709 	return (0);
28710 }
28711 
28712 /* Function to delete the private structure */
28713 void
28714 ip_priv_free(void *buf)
28715 {
28716 	ASSERT(buf != NULL);
28717 	kmem_free(buf, sizeof (ip_priv_t));
28718 }
28719 
28720 /*
28721  * The entry point for IPPF processing.
28722  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28723  * routine just returns.
28724  *
28725  * When called, ip_process generates an ipp_packet_t structure
28726  * which holds the state information for this packet and invokes the
28727  * the classifier (via ipp_packet_process). The classification, depending on
28728  * configured filters, results in a list of actions for this packet. Invoking
28729  * an action may cause the packet to be dropped, in which case the resulting
28730  * mblk (*mpp) is NULL. proc indicates the callout position for
28731  * this packet and ill_index is the interface this packet on or will leave
28732  * on (inbound and outbound resp.).
28733  */
28734 void
28735 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28736 {
28737 	mblk_t		*mp;
28738 	ip_priv_t	*priv;
28739 	ipp_action_id_t	aid;
28740 	int		rc = 0;
28741 	ipp_packet_t	*pp;
28742 #define	IP_CLASS	"ip"
28743 
28744 	/* If the classifier is not loaded, return  */
28745 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28746 		return;
28747 	}
28748 
28749 	mp = *mpp;
28750 	ASSERT(mp != NULL);
28751 
28752 	/* Allocate the packet structure */
28753 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28754 	if (rc != 0) {
28755 		*mpp = NULL;
28756 		freemsg(mp);
28757 		return;
28758 	}
28759 
28760 	/* Allocate the private structure */
28761 	rc = ip_priv_alloc((void **)&priv);
28762 	if (rc != 0) {
28763 		*mpp = NULL;
28764 		freemsg(mp);
28765 		ipp_packet_free(pp);
28766 		return;
28767 	}
28768 	priv->proc = proc;
28769 	priv->ill_index = ill_index;
28770 	ipp_packet_set_private(pp, priv, ip_priv_free);
28771 	ipp_packet_set_data(pp, mp);
28772 
28773 	/* Invoke the classifier */
28774 	rc = ipp_packet_process(&pp);
28775 	if (pp != NULL) {
28776 		mp = ipp_packet_get_data(pp);
28777 		ipp_packet_free(pp);
28778 		if (rc != 0) {
28779 			freemsg(mp);
28780 			*mpp = NULL;
28781 		}
28782 	} else {
28783 		*mpp = NULL;
28784 	}
28785 #undef	IP_CLASS
28786 }
28787 
28788 /*
28789  * Propagate a multicast group membership operation (add/drop) on
28790  * all the interfaces crossed by the related multirt routes.
28791  * The call is considered successful if the operation succeeds
28792  * on at least one interface.
28793  */
28794 static int
28795 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28796     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28797     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28798     mblk_t *first_mp)
28799 {
28800 	ire_t		*ire_gw;
28801 	irb_t		*irb;
28802 	int		error = 0;
28803 	opt_restart_t	*or;
28804 	ip_stack_t	*ipst = ire->ire_ipst;
28805 
28806 	irb = ire->ire_bucket;
28807 	ASSERT(irb != NULL);
28808 
28809 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28810 
28811 	or = (opt_restart_t *)first_mp->b_rptr;
28812 	IRB_REFHOLD(irb);
28813 	for (; ire != NULL; ire = ire->ire_next) {
28814 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28815 			continue;
28816 		if (ire->ire_addr != group)
28817 			continue;
28818 
28819 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28820 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28821 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28822 		/* No resolver exists for the gateway; skip this ire. */
28823 		if (ire_gw == NULL)
28824 			continue;
28825 
28826 		/*
28827 		 * This function can return EINPROGRESS. If so the operation
28828 		 * will be restarted from ip_restart_optmgmt which will
28829 		 * call ip_opt_set and option processing will restart for
28830 		 * this option. So we may end up calling 'fn' more than once.
28831 		 * This requires that 'fn' is idempotent except for the
28832 		 * return value. The operation is considered a success if
28833 		 * it succeeds at least once on any one interface.
28834 		 */
28835 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28836 		    NULL, fmode, src, first_mp);
28837 		if (error == 0)
28838 			or->or_private = CGTP_MCAST_SUCCESS;
28839 
28840 		if (ip_debug > 0) {
28841 			ulong_t	off;
28842 			char	*ksym;
28843 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28844 			ip2dbg(("ip_multirt_apply_membership: "
28845 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28846 			    "error %d [success %u]\n",
28847 			    ksym ? ksym : "?",
28848 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28849 			    error, or->or_private));
28850 		}
28851 
28852 		ire_refrele(ire_gw);
28853 		if (error == EINPROGRESS) {
28854 			IRB_REFRELE(irb);
28855 			return (error);
28856 		}
28857 	}
28858 	IRB_REFRELE(irb);
28859 	/*
28860 	 * Consider the call as successful if we succeeded on at least
28861 	 * one interface. Otherwise, return the last encountered error.
28862 	 */
28863 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28864 }
28865 
28866 
28867 /*
28868  * Issue a warning regarding a route crossing an interface with an
28869  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28870  * amount of time is logged.
28871  */
28872 static void
28873 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28874 {
28875 	hrtime_t	current = gethrtime();
28876 	char		buf[INET_ADDRSTRLEN];
28877 	ip_stack_t	*ipst = ire->ire_ipst;
28878 
28879 	/* Convert interval in ms to hrtime in ns */
28880 	if (ipst->ips_multirt_bad_mtu_last_time +
28881 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28882 	    current) {
28883 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28884 		    "to %s, incorrect MTU %u (expected %u)\n",
28885 		    ip_dot_addr(ire->ire_addr, buf),
28886 		    ire->ire_max_frag, max_frag);
28887 
28888 		ipst->ips_multirt_bad_mtu_last_time = current;
28889 	}
28890 }
28891 
28892 
28893 /*
28894  * Get the CGTP (multirouting) filtering status.
28895  * If 0, the CGTP hooks are transparent.
28896  */
28897 /* ARGSUSED */
28898 static int
28899 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28900 {
28901 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28902 
28903 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28904 	return (0);
28905 }
28906 
28907 
28908 /*
28909  * Set the CGTP (multirouting) filtering status.
28910  * If the status is changed from active to transparent
28911  * or from transparent to active, forward the new status
28912  * to the filtering module (if loaded).
28913  */
28914 /* ARGSUSED */
28915 static int
28916 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28917     cred_t *ioc_cr)
28918 {
28919 	long		new_value;
28920 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28921 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28922 
28923 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28924 		return (EPERM);
28925 
28926 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28927 	    new_value < 0 || new_value > 1) {
28928 		return (EINVAL);
28929 	}
28930 
28931 	if ((!*ip_cgtp_filter_value) && new_value) {
28932 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28933 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28934 		    " (module not loaded)" : "");
28935 	}
28936 	if (*ip_cgtp_filter_value && (!new_value)) {
28937 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28938 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28939 		    " (module not loaded)" : "");
28940 	}
28941 
28942 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28943 		int	res;
28944 		netstackid_t stackid;
28945 
28946 		stackid = ipst->ips_netstack->netstack_stackid;
28947 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28948 		    new_value);
28949 		if (res)
28950 			return (res);
28951 	}
28952 
28953 	*ip_cgtp_filter_value = (boolean_t)new_value;
28954 
28955 	return (0);
28956 }
28957 
28958 
28959 /*
28960  * Return the expected CGTP hooks version number.
28961  */
28962 int
28963 ip_cgtp_filter_supported(void)
28964 {
28965 	return (ip_cgtp_filter_rev);
28966 }
28967 
28968 
28969 /*
28970  * CGTP hooks can be registered by invoking this function.
28971  * Checks that the version number matches.
28972  */
28973 int
28974 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
28975 {
28976 	netstack_t *ns;
28977 	ip_stack_t *ipst;
28978 
28979 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
28980 		return (ENOTSUP);
28981 
28982 	ns = netstack_find_by_stackid(stackid);
28983 	if (ns == NULL)
28984 		return (EINVAL);
28985 	ipst = ns->netstack_ip;
28986 	ASSERT(ipst != NULL);
28987 
28988 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28989 		netstack_rele(ns);
28990 		return (EALREADY);
28991 	}
28992 
28993 	ipst->ips_ip_cgtp_filter_ops = ops;
28994 	netstack_rele(ns);
28995 	return (0);
28996 }
28997 
28998 /*
28999  * CGTP hooks can be unregistered by invoking this function.
29000  * Returns ENXIO if there was no registration.
29001  * Returns EBUSY if the ndd variable has not been turned off.
29002  */
29003 int
29004 ip_cgtp_filter_unregister(netstackid_t stackid)
29005 {
29006 	netstack_t *ns;
29007 	ip_stack_t *ipst;
29008 
29009 	ns = netstack_find_by_stackid(stackid);
29010 	if (ns == NULL)
29011 		return (EINVAL);
29012 	ipst = ns->netstack_ip;
29013 	ASSERT(ipst != NULL);
29014 
29015 	if (ipst->ips_ip_cgtp_filter) {
29016 		netstack_rele(ns);
29017 		return (EBUSY);
29018 	}
29019 
29020 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29021 		netstack_rele(ns);
29022 		return (ENXIO);
29023 	}
29024 	ipst->ips_ip_cgtp_filter_ops = NULL;
29025 	netstack_rele(ns);
29026 	return (0);
29027 }
29028 
29029 /*
29030  * Check whether there is a CGTP filter registration.
29031  * Returns non-zero if there is a registration, otherwise returns zero.
29032  * Note: returns zero if bad stackid.
29033  */
29034 int
29035 ip_cgtp_filter_is_registered(netstackid_t stackid)
29036 {
29037 	netstack_t *ns;
29038 	ip_stack_t *ipst;
29039 	int ret;
29040 
29041 	ns = netstack_find_by_stackid(stackid);
29042 	if (ns == NULL)
29043 		return (0);
29044 	ipst = ns->netstack_ip;
29045 	ASSERT(ipst != NULL);
29046 
29047 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29048 		ret = 1;
29049 	else
29050 		ret = 0;
29051 
29052 	netstack_rele(ns);
29053 	return (ret);
29054 }
29055 
29056 static squeue_func_t
29057 ip_squeue_switch(int val)
29058 {
29059 	squeue_func_t rval = squeue_fill;
29060 
29061 	switch (val) {
29062 	case IP_SQUEUE_ENTER_NODRAIN:
29063 		rval = squeue_enter_nodrain;
29064 		break;
29065 	case IP_SQUEUE_ENTER:
29066 		rval = squeue_enter;
29067 		break;
29068 	default:
29069 		break;
29070 	}
29071 	return (rval);
29072 }
29073 
29074 /* ARGSUSED */
29075 static int
29076 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29077     caddr_t addr, cred_t *cr)
29078 {
29079 	int *v = (int *)addr;
29080 	long new_value;
29081 
29082 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29083 		return (EPERM);
29084 
29085 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29086 		return (EINVAL);
29087 
29088 	ip_input_proc = ip_squeue_switch(new_value);
29089 	*v = new_value;
29090 	return (0);
29091 }
29092 
29093 /*
29094  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29095  * ip_debug.
29096  */
29097 /* ARGSUSED */
29098 static int
29099 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29100     caddr_t addr, cred_t *cr)
29101 {
29102 	int *v = (int *)addr;
29103 	long new_value;
29104 
29105 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29106 		return (EPERM);
29107 
29108 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29109 		return (EINVAL);
29110 
29111 	*v = new_value;
29112 	return (0);
29113 }
29114 
29115 /*
29116  * Handle changes to ipmp_hook_emulation ndd variable.
29117  * Need to update phyint_hook_ifindex.
29118  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29119  */
29120 static void
29121 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29122 {
29123 	phyint_t *phyi;
29124 	phyint_t *phyi_tmp;
29125 	char *groupname;
29126 	int namelen;
29127 	ill_t	*ill;
29128 	boolean_t new_group;
29129 
29130 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29131 	/*
29132 	 * Group indicies are stored in the phyint - a common structure
29133 	 * to both IPv4 and IPv6.
29134 	 */
29135 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29136 	for (; phyi != NULL;
29137 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29138 	    phyi, AVL_AFTER)) {
29139 		/* Ignore the ones that do not have a group */
29140 		if (phyi->phyint_groupname_len == 0)
29141 			continue;
29142 
29143 		/*
29144 		 * Look for other phyint in group.
29145 		 * Clear name/namelen so the lookup doesn't find ourselves.
29146 		 */
29147 		namelen = phyi->phyint_groupname_len;
29148 		groupname = phyi->phyint_groupname;
29149 		phyi->phyint_groupname_len = 0;
29150 		phyi->phyint_groupname = NULL;
29151 
29152 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29153 		/* Restore */
29154 		phyi->phyint_groupname_len = namelen;
29155 		phyi->phyint_groupname = groupname;
29156 
29157 		new_group = B_FALSE;
29158 		if (ipst->ips_ipmp_hook_emulation) {
29159 			/*
29160 			 * If the group already exists and has already
29161 			 * been assigned a group ifindex, we use the existing
29162 			 * group_ifindex, otherwise we pick a new group_ifindex
29163 			 * here.
29164 			 */
29165 			if (phyi_tmp != NULL &&
29166 			    phyi_tmp->phyint_group_ifindex != 0) {
29167 				phyi->phyint_group_ifindex =
29168 				    phyi_tmp->phyint_group_ifindex;
29169 			} else {
29170 				/* XXX We need a recovery strategy here. */
29171 				if (!ip_assign_ifindex(
29172 				    &phyi->phyint_group_ifindex, ipst))
29173 					cmn_err(CE_PANIC,
29174 					    "ip_assign_ifindex() failed");
29175 				new_group = B_TRUE;
29176 			}
29177 		} else {
29178 			phyi->phyint_group_ifindex = 0;
29179 		}
29180 		if (ipst->ips_ipmp_hook_emulation)
29181 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29182 		else
29183 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29184 
29185 		/*
29186 		 * For IP Filter to find out the relationship between
29187 		 * names and interface indicies, we need to generate
29188 		 * a NE_PLUMB event when a new group can appear.
29189 		 * We always generate events when a new interface appears
29190 		 * (even when ipmp_hook_emulation is set) so there
29191 		 * is no need to generate NE_PLUMB events when
29192 		 * ipmp_hook_emulation is turned off.
29193 		 * And since it isn't critical for IP Filter to get
29194 		 * the NE_UNPLUMB events we skip those here.
29195 		 */
29196 		if (new_group) {
29197 			/*
29198 			 * First phyint in group - generate group PLUMB event.
29199 			 * Since we are not running inside the ipsq we do
29200 			 * the dispatch immediately.
29201 			 */
29202 			if (phyi->phyint_illv4 != NULL)
29203 				ill = phyi->phyint_illv4;
29204 			else
29205 				ill = phyi->phyint_illv6;
29206 
29207 			if (ill != NULL) {
29208 				mutex_enter(&ill->ill_lock);
29209 				ill_nic_info_plumb(ill, B_TRUE);
29210 				ill_nic_info_dispatch(ill);
29211 				mutex_exit(&ill->ill_lock);
29212 			}
29213 		}
29214 	}
29215 	rw_exit(&ipst->ips_ill_g_lock);
29216 }
29217 
29218 /* ARGSUSED */
29219 static int
29220 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29221     caddr_t addr, cred_t *cr)
29222 {
29223 	int *v = (int *)addr;
29224 	long new_value;
29225 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29226 
29227 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29228 		return (EINVAL);
29229 
29230 	if (*v != new_value) {
29231 		*v = new_value;
29232 		ipmp_hook_emulation_changed(ipst);
29233 	}
29234 	return (0);
29235 }
29236 
29237 static void *
29238 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29239 {
29240 	kstat_t *ksp;
29241 
29242 	ip_stat_t template = {
29243 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29244 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29245 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29246 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29247 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29248 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29249 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29250 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29251 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29252 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29253 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29254 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29255 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29256 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29257 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29258 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29259 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29260 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29261 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29262 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29263 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29264 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29265 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29266 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29267 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29268 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29269 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29270 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29271 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29272 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29273 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29274 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29275 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29276 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29277 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29278 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29279 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29280 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29281 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29282 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29284 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29285 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29286 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29287 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29288 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29289 	};
29290 
29291 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29292 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29293 	    KSTAT_FLAG_VIRTUAL, stackid);
29294 
29295 	if (ksp == NULL)
29296 		return (NULL);
29297 
29298 	bcopy(&template, ip_statisticsp, sizeof (template));
29299 	ksp->ks_data = (void *)ip_statisticsp;
29300 	ksp->ks_private = (void *)(uintptr_t)stackid;
29301 
29302 	kstat_install(ksp);
29303 	return (ksp);
29304 }
29305 
29306 static void
29307 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29308 {
29309 	if (ksp != NULL) {
29310 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29311 		kstat_delete_netstack(ksp, stackid);
29312 	}
29313 }
29314 
29315 static void *
29316 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29317 {
29318 	kstat_t	*ksp;
29319 
29320 	ip_named_kstat_t template = {
29321 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29322 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29323 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29324 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29325 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29326 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29327 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29328 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29329 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29330 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29331 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29332 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29333 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29334 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29335 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29336 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29337 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29338 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29339 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29340 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29341 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29342 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29343 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29344 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29345 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29346 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29347 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29348 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29349 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29350 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29351 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29352 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29353 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29354 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29355 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29356 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29357 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29358 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29359 	};
29360 
29361 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29362 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29363 	if (ksp == NULL || ksp->ks_data == NULL)
29364 		return (NULL);
29365 
29366 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29367 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29368 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29369 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29370 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29371 
29372 	template.netToMediaEntrySize.value.i32 =
29373 	    sizeof (mib2_ipNetToMediaEntry_t);
29374 
29375 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29376 
29377 	bcopy(&template, ksp->ks_data, sizeof (template));
29378 	ksp->ks_update = ip_kstat_update;
29379 	ksp->ks_private = (void *)(uintptr_t)stackid;
29380 
29381 	kstat_install(ksp);
29382 	return (ksp);
29383 }
29384 
29385 static void
29386 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29387 {
29388 	if (ksp != NULL) {
29389 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29390 		kstat_delete_netstack(ksp, stackid);
29391 	}
29392 }
29393 
29394 static int
29395 ip_kstat_update(kstat_t *kp, int rw)
29396 {
29397 	ip_named_kstat_t *ipkp;
29398 	mib2_ipIfStatsEntry_t ipmib;
29399 	ill_walk_context_t ctx;
29400 	ill_t *ill;
29401 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29402 	netstack_t	*ns;
29403 	ip_stack_t	*ipst;
29404 
29405 	if (kp == NULL || kp->ks_data == NULL)
29406 		return (EIO);
29407 
29408 	if (rw == KSTAT_WRITE)
29409 		return (EACCES);
29410 
29411 	ns = netstack_find_by_stackid(stackid);
29412 	if (ns == NULL)
29413 		return (-1);
29414 	ipst = ns->netstack_ip;
29415 	if (ipst == NULL) {
29416 		netstack_rele(ns);
29417 		return (-1);
29418 	}
29419 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29420 
29421 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29422 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29423 	ill = ILL_START_WALK_V4(&ctx, ipst);
29424 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29425 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29426 	rw_exit(&ipst->ips_ill_g_lock);
29427 
29428 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29429 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29430 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29431 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29432 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29433 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29434 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29435 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29436 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29437 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29438 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29439 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29440 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29441 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29442 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29443 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29444 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29445 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29446 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29447 
29448 	ipkp->routingDiscards.value.ui32 =	0;
29449 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29450 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29451 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29452 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29453 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29454 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29455 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29456 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29457 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29458 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29459 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29460 
29461 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29462 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29463 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29464 
29465 	netstack_rele(ns);
29466 
29467 	return (0);
29468 }
29469 
29470 static void *
29471 icmp_kstat_init(netstackid_t stackid)
29472 {
29473 	kstat_t	*ksp;
29474 
29475 	icmp_named_kstat_t template = {
29476 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29477 		{ "inErrors",		KSTAT_DATA_UINT32 },
29478 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29479 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29480 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29481 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29482 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29483 		{ "inEchos",		KSTAT_DATA_UINT32 },
29484 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29485 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29486 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29487 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29488 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29489 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29490 		{ "outErrors",		KSTAT_DATA_UINT32 },
29491 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29492 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29493 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29494 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29495 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29496 		{ "outEchos",		KSTAT_DATA_UINT32 },
29497 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29498 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29499 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29500 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29501 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29502 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29503 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29504 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29505 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29506 		{ "outDrops",		KSTAT_DATA_UINT32 },
29507 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29508 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29509 	};
29510 
29511 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29512 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29513 	if (ksp == NULL || ksp->ks_data == NULL)
29514 		return (NULL);
29515 
29516 	bcopy(&template, ksp->ks_data, sizeof (template));
29517 
29518 	ksp->ks_update = icmp_kstat_update;
29519 	ksp->ks_private = (void *)(uintptr_t)stackid;
29520 
29521 	kstat_install(ksp);
29522 	return (ksp);
29523 }
29524 
29525 static void
29526 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29527 {
29528 	if (ksp != NULL) {
29529 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29530 		kstat_delete_netstack(ksp, stackid);
29531 	}
29532 }
29533 
29534 static int
29535 icmp_kstat_update(kstat_t *kp, int rw)
29536 {
29537 	icmp_named_kstat_t *icmpkp;
29538 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29539 	netstack_t	*ns;
29540 	ip_stack_t	*ipst;
29541 
29542 	if ((kp == NULL) || (kp->ks_data == NULL))
29543 		return (EIO);
29544 
29545 	if (rw == KSTAT_WRITE)
29546 		return (EACCES);
29547 
29548 	ns = netstack_find_by_stackid(stackid);
29549 	if (ns == NULL)
29550 		return (-1);
29551 	ipst = ns->netstack_ip;
29552 	if (ipst == NULL) {
29553 		netstack_rele(ns);
29554 		return (-1);
29555 	}
29556 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29557 
29558 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29559 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29560 	icmpkp->inDestUnreachs.value.ui32 =
29561 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29562 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29563 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29564 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29565 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29566 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29567 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29568 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29569 	icmpkp->inTimestampReps.value.ui32 =
29570 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29571 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29572 	icmpkp->inAddrMaskReps.value.ui32 =
29573 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29574 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29575 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29576 	icmpkp->outDestUnreachs.value.ui32 =
29577 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29578 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29579 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29580 	icmpkp->outSrcQuenchs.value.ui32 =
29581 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29582 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29583 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29584 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29585 	icmpkp->outTimestamps.value.ui32 =
29586 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29587 	icmpkp->outTimestampReps.value.ui32 =
29588 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29589 	icmpkp->outAddrMasks.value.ui32 =
29590 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29591 	icmpkp->outAddrMaskReps.value.ui32 =
29592 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29593 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29594 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29595 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29596 	icmpkp->outFragNeeded.value.ui32 =
29597 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29598 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29599 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29600 	icmpkp->inBadRedirects.value.ui32 =
29601 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29602 
29603 	netstack_rele(ns);
29604 	return (0);
29605 }
29606 
29607 /*
29608  * This is the fanout function for raw socket opened for SCTP.  Note
29609  * that it is called after SCTP checks that there is no socket which
29610  * wants a packet.  Then before SCTP handles this out of the blue packet,
29611  * this function is called to see if there is any raw socket for SCTP.
29612  * If there is and it is bound to the correct address, the packet will
29613  * be sent to that socket.  Note that only one raw socket can be bound to
29614  * a port.  This is assured in ipcl_sctp_hash_insert();
29615  */
29616 void
29617 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29618     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29619     zoneid_t zoneid)
29620 {
29621 	conn_t		*connp;
29622 	queue_t		*rq;
29623 	mblk_t		*first_mp;
29624 	boolean_t	secure;
29625 	ip6_t		*ip6h;
29626 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29627 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29628 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29629 	boolean_t	sctp_csum_err = B_FALSE;
29630 
29631 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29632 		sctp_csum_err = B_TRUE;
29633 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29634 	}
29635 
29636 	first_mp = mp;
29637 	if (mctl_present) {
29638 		mp = first_mp->b_cont;
29639 		secure = ipsec_in_is_secure(first_mp);
29640 		ASSERT(mp != NULL);
29641 	} else {
29642 		secure = B_FALSE;
29643 	}
29644 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29645 
29646 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29647 	if (connp == NULL) {
29648 		/*
29649 		 * Although raw sctp is not summed, OOB chunks must be.
29650 		 * Drop the packet here if the sctp checksum failed.
29651 		 */
29652 		if (sctp_csum_err) {
29653 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29654 			freemsg(first_mp);
29655 			return;
29656 		}
29657 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29658 		return;
29659 	}
29660 	rq = connp->conn_rq;
29661 	if (!canputnext(rq)) {
29662 		CONN_DEC_REF(connp);
29663 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29664 		freemsg(first_mp);
29665 		return;
29666 	}
29667 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29668 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29669 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29670 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29671 		if (first_mp == NULL) {
29672 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29673 			CONN_DEC_REF(connp);
29674 			return;
29675 		}
29676 	}
29677 	/*
29678 	 * We probably should not send M_CTL message up to
29679 	 * raw socket.
29680 	 */
29681 	if (mctl_present)
29682 		freeb(first_mp);
29683 
29684 	/* Initiate IPPF processing here if needed. */
29685 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29686 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29687 		ip_process(IPP_LOCAL_IN, &mp,
29688 		    recv_ill->ill_phyint->phyint_ifindex);
29689 		if (mp == NULL) {
29690 			CONN_DEC_REF(connp);
29691 			return;
29692 		}
29693 	}
29694 
29695 	if (connp->conn_recvif || connp->conn_recvslla ||
29696 	    ((connp->conn_ip_recvpktinfo ||
29697 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29698 	    (flags & IP_FF_IPINFO))) {
29699 		int in_flags = 0;
29700 
29701 		/*
29702 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29703 		 * IPF_RECVIF.
29704 		 */
29705 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29706 			in_flags = IPF_RECVIF;
29707 		}
29708 		if (connp->conn_recvslla) {
29709 			in_flags |= IPF_RECVSLLA;
29710 		}
29711 		if (isv4) {
29712 			mp = ip_add_info(mp, recv_ill, in_flags,
29713 			    IPCL_ZONEID(connp), ipst);
29714 		} else {
29715 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29716 			if (mp == NULL) {
29717 				BUMP_MIB(recv_ill->ill_ip_mib,
29718 				    ipIfStatsInDiscards);
29719 				CONN_DEC_REF(connp);
29720 				return;
29721 			}
29722 		}
29723 	}
29724 
29725 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29726 	/*
29727 	 * We are sending the IPSEC_IN message also up. Refer
29728 	 * to comments above this function.
29729 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29730 	 */
29731 	(connp->conn_recv)(connp, mp, NULL);
29732 	CONN_DEC_REF(connp);
29733 }
29734 
29735 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29736 {									\
29737 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29738 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29739 }
29740 /*
29741  * This function should be called only if all packet processing
29742  * including fragmentation is complete. Callers of this function
29743  * must set mp->b_prev to one of these values:
29744  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29745  * prior to handing over the mp as first argument to this function.
29746  *
29747  * If the ire passed by caller is incomplete, this function
29748  * queues the packet and if necessary, sends ARP request and bails.
29749  * If the ire passed is fully resolved, we simply prepend
29750  * the link-layer header to the packet, do ipsec hw acceleration
29751  * work if necessary, and send the packet out on the wire.
29752  *
29753  * NOTE: IPsec will only call this function with fully resolved
29754  * ires if hw acceleration is involved.
29755  * TODO list :
29756  * 	a Handle M_MULTIDATA so that
29757  *	  tcp_multisend->tcp_multisend_data can
29758  *	  call ip_xmit_v4 directly
29759  *	b Handle post-ARP work for fragments so that
29760  *	  ip_wput_frag can call this function.
29761  */
29762 ipxmit_state_t
29763 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29764 {
29765 	nce_t		*arpce;
29766 	queue_t		*q;
29767 	int		ill_index;
29768 	mblk_t		*nxt_mp, *first_mp;
29769 	boolean_t	xmit_drop = B_FALSE;
29770 	ip_proc_t	proc;
29771 	ill_t		*out_ill;
29772 	int		pkt_len;
29773 
29774 	arpce = ire->ire_nce;
29775 	ASSERT(arpce != NULL);
29776 
29777 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29778 
29779 	mutex_enter(&arpce->nce_lock);
29780 	switch (arpce->nce_state) {
29781 	case ND_REACHABLE:
29782 		/* If there are other queued packets, queue this packet */
29783 		if (arpce->nce_qd_mp != NULL) {
29784 			if (mp != NULL)
29785 				nce_queue_mp_common(arpce, mp, B_FALSE);
29786 			mp = arpce->nce_qd_mp;
29787 		}
29788 		arpce->nce_qd_mp = NULL;
29789 		mutex_exit(&arpce->nce_lock);
29790 
29791 		/*
29792 		 * Flush the queue.  In the common case, where the
29793 		 * ARP is already resolved,  it will go through the
29794 		 * while loop only once.
29795 		 */
29796 		while (mp != NULL) {
29797 
29798 			nxt_mp = mp->b_next;
29799 			mp->b_next = NULL;
29800 			ASSERT(mp->b_datap->db_type != M_CTL);
29801 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29802 			/*
29803 			 * This info is needed for IPQOS to do COS marking
29804 			 * in ip_wput_attach_llhdr->ip_process.
29805 			 */
29806 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29807 			mp->b_prev = NULL;
29808 
29809 			/* set up ill index for outbound qos processing */
29810 			out_ill = ire_to_ill(ire);
29811 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29812 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29813 			    ill_index);
29814 			if (first_mp == NULL) {
29815 				xmit_drop = B_TRUE;
29816 				BUMP_MIB(out_ill->ill_ip_mib,
29817 				    ipIfStatsOutDiscards);
29818 				goto next_mp;
29819 			}
29820 			/* non-ipsec hw accel case */
29821 			if (io == NULL || !io->ipsec_out_accelerated) {
29822 				/* send it */
29823 				q = ire->ire_stq;
29824 				if (proc == IPP_FWD_OUT) {
29825 					UPDATE_IB_PKT_COUNT(ire);
29826 				} else {
29827 					UPDATE_OB_PKT_COUNT(ire);
29828 				}
29829 				ire->ire_last_used_time = lbolt;
29830 
29831 				if (flow_ctl_enabled || canputnext(q)) {
29832 					if (proc == IPP_FWD_OUT) {
29833 
29834 					BUMP_MIB(out_ill->ill_ip_mib,
29835 					    ipIfStatsHCOutForwDatagrams);
29836 
29837 					}
29838 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29839 					    pkt_len);
29840 
29841 					putnext(q, first_mp);
29842 				} else {
29843 					BUMP_MIB(out_ill->ill_ip_mib,
29844 					    ipIfStatsOutDiscards);
29845 					xmit_drop = B_TRUE;
29846 					freemsg(first_mp);
29847 				}
29848 			} else {
29849 				/*
29850 				 * Safety Pup says: make sure this
29851 				 *  is going to the right interface!
29852 				 */
29853 				ill_t *ill1 =
29854 				    (ill_t *)ire->ire_stq->q_ptr;
29855 				int ifindex =
29856 				    ill1->ill_phyint->phyint_ifindex;
29857 				if (ifindex !=
29858 				    io->ipsec_out_capab_ill_index) {
29859 					xmit_drop = B_TRUE;
29860 					freemsg(mp);
29861 				} else {
29862 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29863 					    pkt_len);
29864 					ipsec_hw_putnext(ire->ire_stq, mp);
29865 				}
29866 			}
29867 next_mp:
29868 			mp = nxt_mp;
29869 		} /* while (mp != NULL) */
29870 		if (xmit_drop)
29871 			return (SEND_FAILED);
29872 		else
29873 			return (SEND_PASSED);
29874 
29875 	case ND_INITIAL:
29876 	case ND_INCOMPLETE:
29877 
29878 		/*
29879 		 * While we do send off packets to dests that
29880 		 * use fully-resolved CGTP routes, we do not
29881 		 * handle unresolved CGTP routes.
29882 		 */
29883 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29884 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29885 
29886 		if (mp != NULL) {
29887 			/* queue the packet */
29888 			nce_queue_mp_common(arpce, mp, B_FALSE);
29889 		}
29890 
29891 		if (arpce->nce_state == ND_INCOMPLETE) {
29892 			mutex_exit(&arpce->nce_lock);
29893 			DTRACE_PROBE3(ip__xmit__incomplete,
29894 			    (ire_t *), ire, (mblk_t *), mp,
29895 			    (ipsec_out_t *), io);
29896 			return (LOOKUP_IN_PROGRESS);
29897 		}
29898 
29899 		arpce->nce_state = ND_INCOMPLETE;
29900 		mutex_exit(&arpce->nce_lock);
29901 		/*
29902 		 * Note that ire_add() (called from ire_forward())
29903 		 * holds a ref on the ire until ARP is completed.
29904 		 */
29905 
29906 		ire_arpresolve(ire, ire_to_ill(ire));
29907 		return (LOOKUP_IN_PROGRESS);
29908 	default:
29909 		ASSERT(0);
29910 		mutex_exit(&arpce->nce_lock);
29911 		return (LLHDR_RESLV_FAILED);
29912 	}
29913 }
29914 
29915 #undef	UPDATE_IP_MIB_OB_COUNTERS
29916 
29917 /*
29918  * Return B_TRUE if the buffers differ in length or content.
29919  * This is used for comparing extension header buffers.
29920  * Note that an extension header would be declared different
29921  * even if all that changed was the next header value in that header i.e.
29922  * what really changed is the next extension header.
29923  */
29924 boolean_t
29925 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29926     uint_t blen)
29927 {
29928 	if (!b_valid)
29929 		blen = 0;
29930 
29931 	if (alen != blen)
29932 		return (B_TRUE);
29933 	if (alen == 0)
29934 		return (B_FALSE);	/* Both zero length */
29935 	return (bcmp(abuf, bbuf, alen));
29936 }
29937 
29938 /*
29939  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29940  * Return B_FALSE if memory allocation fails - don't change any state!
29941  */
29942 boolean_t
29943 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29944     const void *src, uint_t srclen)
29945 {
29946 	void *dst;
29947 
29948 	if (!src_valid)
29949 		srclen = 0;
29950 
29951 	ASSERT(*dstlenp == 0);
29952 	if (src != NULL && srclen != 0) {
29953 		dst = mi_alloc(srclen, BPRI_MED);
29954 		if (dst == NULL)
29955 			return (B_FALSE);
29956 	} else {
29957 		dst = NULL;
29958 	}
29959 	if (*dstp != NULL)
29960 		mi_free(*dstp);
29961 	*dstp = dst;
29962 	*dstlenp = dst == NULL ? 0 : srclen;
29963 	return (B_TRUE);
29964 }
29965 
29966 /*
29967  * Replace what is in *dst, *dstlen with the source.
29968  * Assumes ip_allocbuf has already been called.
29969  */
29970 void
29971 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29972     const void *src, uint_t srclen)
29973 {
29974 	if (!src_valid)
29975 		srclen = 0;
29976 
29977 	ASSERT(*dstlenp == srclen);
29978 	if (src != NULL && srclen != 0)
29979 		bcopy(src, *dstp, srclen);
29980 }
29981 
29982 /*
29983  * Free the storage pointed to by the members of an ip6_pkt_t.
29984  */
29985 void
29986 ip6_pkt_free(ip6_pkt_t *ipp)
29987 {
29988 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
29989 
29990 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
29991 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
29992 		ipp->ipp_hopopts = NULL;
29993 		ipp->ipp_hopoptslen = 0;
29994 	}
29995 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
29996 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
29997 		ipp->ipp_rtdstopts = NULL;
29998 		ipp->ipp_rtdstoptslen = 0;
29999 	}
30000 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30001 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30002 		ipp->ipp_dstopts = NULL;
30003 		ipp->ipp_dstoptslen = 0;
30004 	}
30005 	if (ipp->ipp_fields & IPPF_RTHDR) {
30006 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30007 		ipp->ipp_rthdr = NULL;
30008 		ipp->ipp_rthdrlen = 0;
30009 	}
30010 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30011 	    IPPF_RTHDR);
30012 }
30013