xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision b9ccdc5a)
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 		    ipha_t **);
610 
611 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
612 		    ip_stack_t *);
613 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
614 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
615 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
616 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
617 		    mblk_t *, int, ip_stack_t *);
618 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
619 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
620 		    ill_t *, zoneid_t);
621 static void	icmp_options_update(ipha_t *);
622 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
623 		    ip_stack_t *);
624 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
625 		    zoneid_t zoneid, ip_stack_t *);
626 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
627 static void	icmp_redirect(ill_t *, mblk_t *);
628 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
629 		    ip_stack_t *);
630 
631 static void	ip_arp_news(queue_t *, mblk_t *);
632 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
633 		    ip_stack_t *);
634 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
635 char		*ip_dot_addr(ipaddr_t, char *);
636 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
637 int		ip_close(queue_t *, int);
638 static char	*ip_dot_saddr(uchar_t *, char *);
639 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
640 		    boolean_t, boolean_t, ill_t *, zoneid_t);
641 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
642 		    boolean_t, boolean_t, zoneid_t);
643 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
644 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
645 static void	ip_lrput(queue_t *, mblk_t *);
646 ipaddr_t	ip_net_mask(ipaddr_t);
647 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
648 		    ip_stack_t *);
649 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
650 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
651 char		*ip_nv_lookup(nv_t *, int);
652 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
653 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
654 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
655 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
656     ipndp_t *, size_t);
657 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
658 void	ip_rput(queue_t *, mblk_t *);
659 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
660 		    void *dummy_arg);
661 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
662 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
663     ip_stack_t *);
664 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
665 			    ire_t *, ip_stack_t *);
666 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
667 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
668 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
669     ip_stack_t *);
670 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
671 		    uint16_t *);
672 int		ip_snmp_get(queue_t *, mblk_t *, int);
673 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
674 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
675 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
676 		    ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
678 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
682 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
683 		    ip_stack_t *ipst);
684 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
685 		    ip_stack_t *ipst);
686 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
687 		    ip_stack_t *ipst);
688 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
689 		    ip_stack_t *ipst);
690 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
691 		    ip_stack_t *ipst);
692 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
693 		    ip_stack_t *ipst);
694 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
695 		    ip_stack_t *ipst);
696 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
697 		    ip_stack_t *ipst);
698 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
699 		    ip_stack_t *ipst);
700 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
701 		    ip_stack_t *ipst);
702 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
703 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
704 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
705 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
706 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
707 static boolean_t	ip_source_route_included(ipha_t *);
708 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
709 
710 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
711 		    zoneid_t, ip_stack_t *);
712 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
713 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
714 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
715 		    zoneid_t, ip_stack_t *);
716 
717 static void	conn_drain_init(ip_stack_t *);
718 static void	conn_drain_fini(ip_stack_t *);
719 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
720 
721 static void	conn_walk_drain(ip_stack_t *);
722 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
723     zoneid_t);
724 
725 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
726 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
727 static void	ip_stack_fini(netstackid_t stackid, void *arg);
728 
729 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
730     zoneid_t);
731 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
732     void *dummy_arg);
733 
734 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
735 
736 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
737     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
738     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
739 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
740 
741 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
742 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
743     caddr_t, cred_t *);
744 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
745     caddr_t cp, cred_t *cr);
746 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
747     cred_t *);
748 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
749     caddr_t cp, cred_t *cr);
750 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
751     cred_t *);
752 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
753     cred_t *);
754 static squeue_func_t ip_squeue_switch(int);
755 
756 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
757 static void	ip_kstat_fini(netstackid_t, kstat_t *);
758 static int	ip_kstat_update(kstat_t *kp, int rw);
759 static void	*icmp_kstat_init(netstackid_t);
760 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
761 static int	icmp_kstat_update(kstat_t *kp, int rw);
762 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
763 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
764 
765 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
766 
767 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
768     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
769 
770 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
771     ipha_t *, ill_t *, boolean_t);
772 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
773 
774 /* How long, in seconds, we allow frags to hang around. */
775 #define	IP_FRAG_TIMEOUT	60
776 
777 /*
778  * Threshold which determines whether MDT should be used when
779  * generating IP fragments; payload size must be greater than
780  * this threshold for MDT to take place.
781  */
782 #define	IP_WPUT_FRAG_MDT_MIN	32768
783 
784 /* Setable in /etc/system only */
785 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
786 
787 static long ip_rput_pullups;
788 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
789 
790 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
791 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
792 
793 int	ip_debug;
794 
795 #ifdef DEBUG
796 uint32_t ipsechw_debug = 0;
797 #endif
798 
799 /*
800  * Multirouting/CGTP stuff
801  */
802 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
803 
804 /*
805  * XXX following really should only be in a header. Would need more
806  * header and .c clean up first.
807  */
808 extern optdb_obj_t	ip_opt_obj;
809 
810 ulong_t ip_squeue_enter_unbound = 0;
811 
812 /*
813  * Named Dispatch Parameter Table.
814  * All of these are alterable, within the min/max values given, at run time.
815  */
816 static ipparam_t	lcl_param_arr[] = {
817 	/* min	max	value	name */
818 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
819 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
820 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
821 	{  0,	1,	0,	"ip_respond_to_timestamp"},
822 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
823 	{  0,	1,	1,	"ip_send_redirects"},
824 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
825 	{  0,	10,	0,	"ip_mrtdebug"},
826 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
827 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
828 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
829 	{  1,	255,	255,	"ip_def_ttl" },
830 	{  0,	1,	0,	"ip_forward_src_routed"},
831 	{  0,	256,	32,	"ip_wroff_extra" },
832 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
833 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
834 	{  0,	1,	1,	"ip_path_mtu_discovery" },
835 	{  0,	240,	30,	"ip_ignore_delete_time" },
836 	{  0,	1,	0,	"ip_ignore_redirect" },
837 	{  0,	1,	1,	"ip_output_queue" },
838 	{  1,	254,	1,	"ip_broadcast_ttl" },
839 	{  0,	99999,	100,	"ip_icmp_err_interval" },
840 	{  1,	99999,	10,	"ip_icmp_err_burst" },
841 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
842 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
843 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
844 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
845 	{  0,	1,	1,	"icmp_accept_clear_messages" },
846 	{  0,	1,	1,	"igmp_accept_clear_messages" },
847 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
848 				"ip_ndp_delay_first_probe_time"},
849 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
850 				"ip_ndp_max_unicast_solicit"},
851 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
852 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
853 	{  0,	1,	0,	"ip6_forward_src_routed"},
854 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
855 	{  0,	1,	1,	"ip6_send_redirects"},
856 	{  0,	1,	0,	"ip6_ignore_redirect" },
857 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
858 
859 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
860 
861 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
862 
863 	{  0,	1,	1,	"pim_accept_clear_messages" },
864 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
865 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
866 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
867 	{  0,	15,	0,	"ip_policy_mask" },
868 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
869 	{  0,	255,	1,	"ip_multirt_ttl" },
870 	{  0,	1,	1,	"ip_multidata_outbound" },
871 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
872 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
873 	{  0,	1000,	1,	"ip_max_temp_defend" },
874 	{  0,	1000,	3,	"ip_max_defend" },
875 	{  0,	999999,	30,	"ip_defend_interval" },
876 	{  0,	3600000, 300000, "ip_dup_recovery" },
877 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
878 	{  0,	1,	1,	"ip_lso_outbound" },
879 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
880 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
881 #ifdef DEBUG
882 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
883 #else
884 	{  0,	0,	0,	"" },
885 #endif
886 };
887 
888 /*
889  * Extended NDP table
890  * The addresses for the first two are filled in to be ips_ip_g_forward
891  * and ips_ipv6_forward at init time.
892  */
893 static ipndp_t	lcl_ndp_arr[] = {
894 	/* getf			setf		data			name */
895 #define	IPNDP_IP_FORWARDING_OFFSET	0
896 	{  ip_param_generic_get,	ip_forward_set,	NULL,
897 	    "ip_forwarding" },
898 #define	IPNDP_IP6_FORWARDING_OFFSET	1
899 	{  ip_param_generic_get,	ip_forward_set,	NULL,
900 	    "ip6_forwarding" },
901 	{  ip_ill_report,	NULL,		NULL,
902 	    "ip_ill_status" },
903 	{  ip_ipif_report,	NULL,		NULL,
904 	    "ip_ipif_status" },
905 	{  ip_conn_report,	NULL,		NULL,
906 	    "ip_conn_status" },
907 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
908 	    "ip_rput_pullups" },
909 	{  ip_srcid_report,	NULL,		NULL,
910 	    "ip_srcid_status" },
911 	{ ip_param_generic_get, ip_squeue_profile_set,
912 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
913 	{ ip_param_generic_get, ip_squeue_bind_set,
914 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
915 	{ ip_param_generic_get, ip_input_proc_set,
916 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
917 	{ ip_param_generic_get, ip_int_set,
918 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
919 #define	IPNDP_CGTP_FILTER_OFFSET	11
920 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
921 	    "ip_cgtp_filter" },
922 	{ ip_param_generic_get, ip_int_set,
923 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
924 #define	IPNDP_IPMP_HOOK_OFFSET	13
925 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
926 	    "ipmp_hook_emulation" },
927 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
928 	    "ip_debug" },
929 };
930 
931 /*
932  * Table of IP ioctls encoding the various properties of the ioctl and
933  * indexed based on the last byte of the ioctl command. Occasionally there
934  * is a clash, and there is more than 1 ioctl with the same last byte.
935  * In such a case 1 ioctl is encoded in the ndx table and the remaining
936  * ioctls are encoded in the misc table. An entry in the ndx table is
937  * retrieved by indexing on the last byte of the ioctl command and comparing
938  * the ioctl command with the value in the ndx table. In the event of a
939  * mismatch the misc table is then searched sequentially for the desired
940  * ioctl command.
941  *
942  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
943  */
944 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
945 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 
956 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
957 			MISC_CMD, ip_siocaddrt, NULL },
958 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
959 			MISC_CMD, ip_siocdelrt, NULL },
960 
961 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
962 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
963 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
964 			IF_CMD, ip_sioctl_get_addr, NULL },
965 
966 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
967 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
968 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
969 			IPI_GET_CMD | IPI_REPL,
970 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
971 
972 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
973 			IPI_PRIV | IPI_WR | IPI_REPL,
974 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
975 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
976 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
977 			IF_CMD, ip_sioctl_get_flags, NULL },
978 
979 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
981 
982 	/* copyin size cannot be coded for SIOCGIFCONF */
983 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
984 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
985 
986 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
987 			IF_CMD, ip_sioctl_mtu, NULL },
988 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
989 			IF_CMD, ip_sioctl_get_mtu, NULL },
990 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
991 			IPI_GET_CMD | IPI_REPL,
992 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
993 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
994 			IF_CMD, ip_sioctl_brdaddr, NULL },
995 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
996 			IPI_GET_CMD | IPI_REPL,
997 			IF_CMD, ip_sioctl_get_netmask, NULL },
998 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
999 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1000 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_metric, NULL },
1003 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1004 			IF_CMD, ip_sioctl_metric, NULL },
1005 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1006 
1007 	/* See 166-168 below for extended SIOC*XARP ioctls */
1008 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1009 			ARP_CMD, ip_sioctl_arp, NULL },
1010 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1011 			ARP_CMD, ip_sioctl_arp, NULL },
1012 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1013 			ARP_CMD, ip_sioctl_arp, NULL },
1014 
1015 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 
1037 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1038 			MISC_CMD, if_unitsel, if_unitsel_restart },
1039 
1040 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 
1059 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1060 			IPI_PRIV | IPI_WR | IPI_MODOK,
1061 			IF_CMD, ip_sioctl_sifname, NULL },
1062 
1063 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 
1077 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1078 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1079 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1080 			IF_CMD, ip_sioctl_get_muxid, NULL },
1081 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1082 			IPI_PRIV | IPI_WR | IPI_REPL,
1083 			IF_CMD, ip_sioctl_muxid, NULL },
1084 
1085 	/* Both if and lif variants share same func */
1086 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1087 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1088 	/* Both if and lif variants share same func */
1089 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1090 			IPI_PRIV | IPI_WR | IPI_REPL,
1091 			IF_CMD, ip_sioctl_slifindex, NULL },
1092 
1093 	/* copyin size cannot be coded for SIOCGIFCONF */
1094 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1095 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1096 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 
1114 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1115 			IPI_PRIV | IPI_WR | IPI_REPL,
1116 			LIF_CMD, ip_sioctl_removeif,
1117 			ip_sioctl_removeif_restart },
1118 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1119 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1120 			LIF_CMD, ip_sioctl_addif, NULL },
1121 #define	SIOCLIFADDR_NDX 112
1122 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1123 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1124 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1125 			IPI_GET_CMD | IPI_REPL,
1126 			LIF_CMD, ip_sioctl_get_addr, NULL },
1127 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1128 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1129 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1130 			IPI_GET_CMD | IPI_REPL,
1131 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1132 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1133 			IPI_PRIV | IPI_WR | IPI_REPL,
1134 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1135 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1136 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1137 			LIF_CMD, ip_sioctl_get_flags, NULL },
1138 
1139 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1141 
1142 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1143 			ip_sioctl_get_lifconf, NULL },
1144 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1145 			LIF_CMD, ip_sioctl_mtu, NULL },
1146 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1147 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1148 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1149 			IPI_GET_CMD | IPI_REPL,
1150 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1151 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1152 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1153 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1154 			IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1156 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1157 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1158 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_metric, NULL },
1161 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_metric, NULL },
1163 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1164 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_slifname,
1166 			ip_sioctl_slifname_restart },
1167 
1168 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1169 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1170 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1171 			IPI_GET_CMD | IPI_REPL,
1172 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1173 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1174 			IPI_PRIV | IPI_WR | IPI_REPL,
1175 			LIF_CMD, ip_sioctl_muxid, NULL },
1176 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1177 			IPI_GET_CMD | IPI_REPL,
1178 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1179 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1180 			IPI_PRIV | IPI_WR | IPI_REPL,
1181 			LIF_CMD, ip_sioctl_slifindex, 0 },
1182 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1183 			LIF_CMD, ip_sioctl_token, NULL },
1184 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1185 			IPI_GET_CMD | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_get_token, NULL },
1187 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1188 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1189 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1190 			IPI_GET_CMD | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1192 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1194 
1195 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1196 			IPI_GET_CMD | IPI_REPL,
1197 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1198 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1199 			LIF_CMD, ip_siocdelndp_v6, NULL },
1200 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1201 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1202 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1203 			LIF_CMD, ip_siocsetndp_v6, NULL },
1204 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1205 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1206 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1207 			MISC_CMD, ip_sioctl_tonlink, NULL },
1208 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1209 			MISC_CMD, ip_sioctl_tmysite, NULL },
1210 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1211 			TUN_CMD, ip_sioctl_tunparam, NULL },
1212 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1213 			IPI_PRIV | IPI_WR,
1214 			TUN_CMD, ip_sioctl_tunparam, NULL },
1215 
1216 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1217 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1218 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1221 
1222 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1223 			IPI_PRIV | IPI_WR | IPI_REPL,
1224 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1225 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1226 			IPI_PRIV | IPI_WR | IPI_REPL,
1227 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1228 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1229 			IPI_PRIV | IPI_WR,
1230 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1231 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1232 			IPI_GET_CMD | IPI_REPL,
1233 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1234 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1235 			IPI_GET_CMD | IPI_REPL,
1236 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1237 
1238 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1239 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1242 
1243 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1244 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1245 
1246 	/* These are handled in ip_sioctl_copyin_setup itself */
1247 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1248 			MISC_CMD, NULL, NULL },
1249 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1250 			MISC_CMD, NULL, NULL },
1251 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1252 
1253 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1254 			ip_sioctl_get_lifconf, NULL },
1255 
1256 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1257 			XARP_CMD, ip_sioctl_arp, NULL },
1258 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1259 			XARP_CMD, ip_sioctl_arp, NULL },
1260 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1261 			XARP_CMD, ip_sioctl_arp, NULL },
1262 
1263 	/* SIOCPOPSOCKFS is not handled by IP */
1264 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1265 
1266 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1267 			IPI_GET_CMD | IPI_REPL,
1268 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1269 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1270 			IPI_PRIV | IPI_WR | IPI_REPL,
1271 			LIF_CMD, ip_sioctl_slifzone,
1272 			ip_sioctl_slifzone_restart },
1273 	/* 172-174 are SCTP ioctls and not handled by IP */
1274 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1275 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1276 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1277 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1278 			IPI_GET_CMD, LIF_CMD,
1279 			ip_sioctl_get_lifusesrc, 0 },
1280 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1281 			IPI_PRIV | IPI_WR,
1282 			LIF_CMD, ip_sioctl_slifusesrc,
1283 			NULL },
1284 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1285 			ip_sioctl_get_lifsrcof, NULL },
1286 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1287 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1288 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1289 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1290 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1291 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1292 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1293 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1294 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1295 			ip_sioctl_set_ipmpfailback, NULL },
1296 	/* SIOCSENABLESDP is handled by SDP */
1297 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1298 };
1299 
1300 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1301 
1302 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1303 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1304 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1305 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1306 		TUN_CMD, ip_sioctl_tunparam, NULL },
1307 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1314 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1315 		MISC_CMD, mrt_ioctl},
1316 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1317 		MISC_CMD, mrt_ioctl},
1318 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1319 		MISC_CMD, mrt_ioctl}
1320 };
1321 
1322 int ip_misc_ioctl_count =
1323     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1324 
1325 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1326 					/* Settable in /etc/system */
1327 /* Defined in ip_ire.c */
1328 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1329 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1330 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1331 
1332 static nv_t	ire_nv_arr[] = {
1333 	{ IRE_BROADCAST, "BROADCAST" },
1334 	{ IRE_LOCAL, "LOCAL" },
1335 	{ IRE_LOOPBACK, "LOOPBACK" },
1336 	{ IRE_CACHE, "CACHE" },
1337 	{ IRE_DEFAULT, "DEFAULT" },
1338 	{ IRE_PREFIX, "PREFIX" },
1339 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1340 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1341 	{ IRE_HOST, "HOST" },
1342 	{ 0 }
1343 };
1344 
1345 nv_t	*ire_nv_tbl = ire_nv_arr;
1346 
1347 /* Simple ICMP IP Header Template */
1348 static ipha_t icmp_ipha = {
1349 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1350 };
1351 
1352 struct module_info ip_mod_info = {
1353 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1354 };
1355 
1356 /*
1357  * Duplicate static symbols within a module confuses mdb; so we avoid the
1358  * problem by making the symbols here distinct from those in udp.c.
1359  */
1360 
1361 /*
1362  * Entry points for IP as a device and as a module.
1363  * FIXME: down the road we might want a separate module and driver qinit.
1364  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1365  */
1366 static struct qinit iprinitv4 = {
1367 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1368 	&ip_mod_info
1369 };
1370 
1371 struct qinit iprinitv6 = {
1372 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1373 	&ip_mod_info
1374 };
1375 
1376 static struct qinit ipwinitv4 = {
1377 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1378 	&ip_mod_info
1379 };
1380 
1381 struct qinit ipwinitv6 = {
1382 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1383 	&ip_mod_info
1384 };
1385 
1386 static struct qinit iplrinit = {
1387 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1388 	&ip_mod_info
1389 };
1390 
1391 static struct qinit iplwinit = {
1392 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1393 	&ip_mod_info
1394 };
1395 
1396 /* For AF_INET aka /dev/ip */
1397 struct streamtab ipinfov4 = {
1398 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1399 };
1400 
1401 /* For AF_INET6 aka /dev/ip6 */
1402 struct streamtab ipinfov6 = {
1403 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1404 };
1405 
1406 #ifdef	DEBUG
1407 static boolean_t skip_sctp_cksum = B_FALSE;
1408 #endif
1409 
1410 /*
1411  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1412  * ip_rput_v6(), ip_output(), etc.  If the message
1413  * block already has a M_CTL at the front of it, then simply set the zoneid
1414  * appropriately.
1415  */
1416 mblk_t *
1417 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1418 {
1419 	mblk_t		*first_mp;
1420 	ipsec_out_t	*io;
1421 
1422 	ASSERT(zoneid != ALL_ZONES);
1423 	if (mp->b_datap->db_type == M_CTL) {
1424 		io = (ipsec_out_t *)mp->b_rptr;
1425 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1426 		io->ipsec_out_zoneid = zoneid;
1427 		return (mp);
1428 	}
1429 
1430 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1431 	if (first_mp == NULL)
1432 		return (NULL);
1433 	io = (ipsec_out_t *)first_mp->b_rptr;
1434 	/* This is not a secure packet */
1435 	io->ipsec_out_secure = B_FALSE;
1436 	io->ipsec_out_zoneid = zoneid;
1437 	first_mp->b_cont = mp;
1438 	return (first_mp);
1439 }
1440 
1441 /*
1442  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1443  */
1444 mblk_t *
1445 ip_copymsg(mblk_t *mp)
1446 {
1447 	mblk_t *nmp;
1448 	ipsec_info_t *in;
1449 
1450 	if (mp->b_datap->db_type != M_CTL)
1451 		return (copymsg(mp));
1452 
1453 	in = (ipsec_info_t *)mp->b_rptr;
1454 
1455 	/*
1456 	 * Note that M_CTL is also used for delivering ICMP error messages
1457 	 * upstream to transport layers.
1458 	 */
1459 	if (in->ipsec_info_type != IPSEC_OUT &&
1460 	    in->ipsec_info_type != IPSEC_IN)
1461 		return (copymsg(mp));
1462 
1463 	nmp = copymsg(mp->b_cont);
1464 
1465 	if (in->ipsec_info_type == IPSEC_OUT) {
1466 		return (ipsec_out_tag(mp, nmp,
1467 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1468 	} else {
1469 		return (ipsec_in_tag(mp, nmp,
1470 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1471 	}
1472 }
1473 
1474 /* Generate an ICMP fragmentation needed message. */
1475 static void
1476 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1477     ip_stack_t *ipst)
1478 {
1479 	icmph_t	icmph;
1480 	mblk_t *first_mp;
1481 	boolean_t mctl_present;
1482 
1483 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1484 
1485 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1486 		if (mctl_present)
1487 			freeb(first_mp);
1488 		return;
1489 	}
1490 
1491 	bzero(&icmph, sizeof (icmph_t));
1492 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1493 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1494 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1495 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1496 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1497 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1498 	    ipst);
1499 }
1500 
1501 /*
1502  * icmp_inbound deals with ICMP messages in the following ways.
1503  *
1504  * 1) It needs to send a reply back and possibly delivering it
1505  *    to the "interested" upper clients.
1506  * 2) It needs to send it to the upper clients only.
1507  * 3) It needs to change some values in IP only.
1508  * 4) It needs to change some values in IP and upper layers e.g TCP.
1509  *
1510  * We need to accomodate icmp messages coming in clear until we get
1511  * everything secure from the wire. If icmp_accept_clear_messages
1512  * is zero we check with the global policy and act accordingly. If
1513  * it is non-zero, we accept the message without any checks. But
1514  * *this does not mean* that this will be delivered to the upper
1515  * clients. By accepting we might send replies back, change our MTU
1516  * value etc. but delivery to the ULP/clients depends on their policy
1517  * dispositions.
1518  *
1519  * We handle the above 4 cases in the context of IPsec in the
1520  * following way :
1521  *
1522  * 1) Send the reply back in the same way as the request came in.
1523  *    If it came in encrypted, it goes out encrypted. If it came in
1524  *    clear, it goes out in clear. Thus, this will prevent chosen
1525  *    plain text attack.
1526  * 2) The client may or may not expect things to come in secure.
1527  *    If it comes in secure, the policy constraints are checked
1528  *    before delivering it to the upper layers. If it comes in
1529  *    clear, ipsec_inbound_accept_clear will decide whether to
1530  *    accept this in clear or not. In both the cases, if the returned
1531  *    message (IP header + 8 bytes) that caused the icmp message has
1532  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1533  *    sending up. If there are only 8 bytes of returned message, then
1534  *    upper client will not be notified.
1535  * 3) Check with global policy to see whether it matches the constaints.
1536  *    But this will be done only if icmp_accept_messages_in_clear is
1537  *    zero.
1538  * 4) If we need to change both in IP and ULP, then the decision taken
1539  *    while affecting the values in IP and while delivering up to TCP
1540  *    should be the same.
1541  *
1542  * 	There are two cases.
1543  *
1544  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1545  *	   failed), we will not deliver it to the ULP, even though they
1546  *	   are *willing* to accept in *clear*. This is fine as our global
1547  *	   disposition to icmp messages asks us reject the datagram.
1548  *
1549  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1550  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1551  *	   to deliver it to ULP (policy failed), it can lead to
1552  *	   consistency problems. The cases known at this time are
1553  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1554  *	   values :
1555  *
1556  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1557  *	     and Upper layer rejects. Then the communication will
1558  *	     come to a stop. This is solved by making similar decisions
1559  *	     at both levels. Currently, when we are unable to deliver
1560  *	     to the Upper Layer (due to policy failures) while IP has
1561  *	     adjusted ire_max_frag, the next outbound datagram would
1562  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1563  *	     will be with the right level of protection. Thus the right
1564  *	     value will be communicated even if we are not able to
1565  *	     communicate when we get from the wire initially. But this
1566  *	     assumes there would be at least one outbound datagram after
1567  *	     IP has adjusted its ire_max_frag value. To make things
1568  *	     simpler, we accept in clear after the validation of
1569  *	     AH/ESP headers.
1570  *
1571  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1572  *	     upper layer depending on the level of protection the upper
1573  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1574  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1575  *	     should be accepted in clear when the Upper layer expects secure.
1576  *	     Thus the communication may get aborted by some bad ICMP
1577  *	     packets.
1578  *
1579  * IPQoS Notes:
1580  * The only instance when a packet is sent for processing is when there
1581  * isn't an ICMP client and if we are interested in it.
1582  * If there is a client, IPPF processing will take place in the
1583  * ip_fanout_proto routine.
1584  *
1585  * Zones notes:
1586  * The packet is only processed in the context of the specified zone: typically
1587  * only this zone will reply to an echo request, and only interested clients in
1588  * this zone will receive a copy of the packet. This means that the caller must
1589  * call icmp_inbound() for each relevant zone.
1590  */
1591 static void
1592 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1593     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1594     ill_t *recv_ill, zoneid_t zoneid)
1595 {
1596 	icmph_t	*icmph;
1597 	ipha_t	*ipha;
1598 	int	iph_hdr_length;
1599 	int	hdr_length;
1600 	boolean_t	interested;
1601 	uint32_t	ts;
1602 	uchar_t	*wptr;
1603 	ipif_t	*ipif;
1604 	mblk_t *first_mp;
1605 	ipsec_in_t *ii;
1606 	ire_t *src_ire;
1607 	boolean_t onlink;
1608 	timestruc_t now;
1609 	uint32_t ill_index;
1610 	ip_stack_t *ipst;
1611 
1612 	ASSERT(ill != NULL);
1613 	ipst = ill->ill_ipst;
1614 
1615 	first_mp = mp;
1616 	if (mctl_present) {
1617 		mp = first_mp->b_cont;
1618 		ASSERT(mp != NULL);
1619 	}
1620 
1621 	ipha = (ipha_t *)mp->b_rptr;
1622 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1623 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1624 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1625 		if (first_mp == NULL)
1626 			return;
1627 	}
1628 
1629 	/*
1630 	 * On a labeled system, we have to check whether the zone itself is
1631 	 * permitted to receive raw traffic.
1632 	 */
1633 	if (is_system_labeled()) {
1634 		if (zoneid == ALL_ZONES)
1635 			zoneid = tsol_packet_to_zoneid(mp);
1636 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1637 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1638 			    zoneid));
1639 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1640 			freemsg(first_mp);
1641 			return;
1642 		}
1643 	}
1644 
1645 	/*
1646 	 * We have accepted the ICMP message. It means that we will
1647 	 * respond to the packet if needed. It may not be delivered
1648 	 * to the upper client depending on the policy constraints
1649 	 * and the disposition in ipsec_inbound_accept_clear.
1650 	 */
1651 
1652 	ASSERT(ill != NULL);
1653 
1654 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1655 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1656 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1657 		/* Last chance to get real. */
1658 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1659 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1660 			freemsg(first_mp);
1661 			return;
1662 		}
1663 		/* Refresh iph following the pullup. */
1664 		ipha = (ipha_t *)mp->b_rptr;
1665 	}
1666 	/* ICMP header checksum, including checksum field, should be zero. */
1667 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1668 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1669 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1670 		freemsg(first_mp);
1671 		return;
1672 	}
1673 	/* The IP header will always be a multiple of four bytes */
1674 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1675 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1676 	    icmph->icmph_code));
1677 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1678 	/* We will set "interested" to "true" if we want a copy */
1679 	interested = B_FALSE;
1680 	switch (icmph->icmph_type) {
1681 	case ICMP_ECHO_REPLY:
1682 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1683 		break;
1684 	case ICMP_DEST_UNREACHABLE:
1685 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1686 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1687 		interested = B_TRUE;	/* Pass up to transport */
1688 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1689 		break;
1690 	case ICMP_SOURCE_QUENCH:
1691 		interested = B_TRUE;	/* Pass up to transport */
1692 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1693 		break;
1694 	case ICMP_REDIRECT:
1695 		if (!ipst->ips_ip_ignore_redirect)
1696 			interested = B_TRUE;
1697 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1698 		break;
1699 	case ICMP_ECHO_REQUEST:
1700 		/*
1701 		 * Whether to respond to echo requests that come in as IP
1702 		 * broadcasts or as IP multicast is subject to debate
1703 		 * (what isn't?).  We aim to please, you pick it.
1704 		 * Default is do it.
1705 		 */
1706 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1707 			/* unicast: always respond */
1708 			interested = B_TRUE;
1709 		} else if (CLASSD(ipha->ipha_dst)) {
1710 			/* multicast: respond based on tunable */
1711 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1712 		} else if (broadcast) {
1713 			/* broadcast: respond based on tunable */
1714 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1715 		}
1716 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1717 		break;
1718 	case ICMP_ROUTER_ADVERTISEMENT:
1719 	case ICMP_ROUTER_SOLICITATION:
1720 		break;
1721 	case ICMP_TIME_EXCEEDED:
1722 		interested = B_TRUE;	/* Pass up to transport */
1723 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1724 		break;
1725 	case ICMP_PARAM_PROBLEM:
1726 		interested = B_TRUE;	/* Pass up to transport */
1727 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1728 		break;
1729 	case ICMP_TIME_STAMP_REQUEST:
1730 		/* Response to Time Stamp Requests is local policy. */
1731 		if (ipst->ips_ip_g_resp_to_timestamp &&
1732 		    /* So is whether to respond if it was an IP broadcast. */
1733 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1734 			int tstamp_len = 3 * sizeof (uint32_t);
1735 
1736 			if (wptr +  tstamp_len > mp->b_wptr) {
1737 				if (!pullupmsg(mp, wptr + tstamp_len -
1738 				    mp->b_rptr)) {
1739 					BUMP_MIB(ill->ill_ip_mib,
1740 					    ipIfStatsInDiscards);
1741 					freemsg(first_mp);
1742 					return;
1743 				}
1744 				/* Refresh ipha following the pullup. */
1745 				ipha = (ipha_t *)mp->b_rptr;
1746 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1747 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1748 			}
1749 			interested = B_TRUE;
1750 		}
1751 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1752 		break;
1753 	case ICMP_TIME_STAMP_REPLY:
1754 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1755 		break;
1756 	case ICMP_INFO_REQUEST:
1757 		/* Per RFC 1122 3.2.2.7, ignore this. */
1758 	case ICMP_INFO_REPLY:
1759 		break;
1760 	case ICMP_ADDRESS_MASK_REQUEST:
1761 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1762 		    !broadcast) &&
1763 		    /* TODO m_pullup of complete header? */
1764 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1765 			interested = B_TRUE;
1766 		}
1767 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1768 		break;
1769 	case ICMP_ADDRESS_MASK_REPLY:
1770 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1771 		break;
1772 	default:
1773 		interested = B_TRUE;	/* Pass up to transport */
1774 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1775 		break;
1776 	}
1777 	/* See if there is an ICMP client. */
1778 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1779 		/* If there is an ICMP client and we want one too, copy it. */
1780 		mblk_t *first_mp1;
1781 
1782 		if (!interested) {
1783 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1784 			    ip_policy, recv_ill, zoneid);
1785 			return;
1786 		}
1787 		first_mp1 = ip_copymsg(first_mp);
1788 		if (first_mp1 != NULL) {
1789 			ip_fanout_proto(q, first_mp1, ill, ipha,
1790 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1791 		}
1792 	} else if (!interested) {
1793 		freemsg(first_mp);
1794 		return;
1795 	} else {
1796 		/*
1797 		 * Initiate policy processing for this packet if ip_policy
1798 		 * is true.
1799 		 */
1800 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1801 			ill_index = ill->ill_phyint->phyint_ifindex;
1802 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1803 			if (mp == NULL) {
1804 				if (mctl_present) {
1805 					freeb(first_mp);
1806 				}
1807 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1808 				return;
1809 			}
1810 		}
1811 	}
1812 	/* We want to do something with it. */
1813 	/* Check db_ref to make sure we can modify the packet. */
1814 	if (mp->b_datap->db_ref > 1) {
1815 		mblk_t	*first_mp1;
1816 
1817 		first_mp1 = ip_copymsg(first_mp);
1818 		freemsg(first_mp);
1819 		if (!first_mp1) {
1820 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1821 			return;
1822 		}
1823 		first_mp = first_mp1;
1824 		if (mctl_present) {
1825 			mp = first_mp->b_cont;
1826 			ASSERT(mp != NULL);
1827 		} else {
1828 			mp = first_mp;
1829 		}
1830 		ipha = (ipha_t *)mp->b_rptr;
1831 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1832 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1833 	}
1834 	switch (icmph->icmph_type) {
1835 	case ICMP_ADDRESS_MASK_REQUEST:
1836 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1837 		if (ipif == NULL) {
1838 			freemsg(first_mp);
1839 			return;
1840 		}
1841 		/*
1842 		 * outging interface must be IPv4
1843 		 */
1844 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1845 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1846 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1847 		ipif_refrele(ipif);
1848 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1849 		break;
1850 	case ICMP_ECHO_REQUEST:
1851 		icmph->icmph_type = ICMP_ECHO_REPLY;
1852 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1853 		break;
1854 	case ICMP_TIME_STAMP_REQUEST: {
1855 		uint32_t *tsp;
1856 
1857 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1858 		tsp = (uint32_t *)wptr;
1859 		tsp++;		/* Skip past 'originate time' */
1860 		/* Compute # of milliseconds since midnight */
1861 		gethrestime(&now);
1862 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1863 		    now.tv_nsec / (NANOSEC / MILLISEC);
1864 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1865 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1866 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1867 		break;
1868 	}
1869 	default:
1870 		ipha = (ipha_t *)&icmph[1];
1871 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1872 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1873 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1874 				freemsg(first_mp);
1875 				return;
1876 			}
1877 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1878 			ipha = (ipha_t *)&icmph[1];
1879 		}
1880 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1881 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1882 			freemsg(first_mp);
1883 			return;
1884 		}
1885 		hdr_length = IPH_HDR_LENGTH(ipha);
1886 		if (hdr_length < sizeof (ipha_t)) {
1887 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1888 			freemsg(first_mp);
1889 			return;
1890 		}
1891 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1892 			if (!pullupmsg(mp,
1893 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1894 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1895 				freemsg(first_mp);
1896 				return;
1897 			}
1898 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1899 			ipha = (ipha_t *)&icmph[1];
1900 		}
1901 		switch (icmph->icmph_type) {
1902 		case ICMP_REDIRECT:
1903 			/*
1904 			 * As there is no upper client to deliver, we don't
1905 			 * need the first_mp any more.
1906 			 */
1907 			if (mctl_present) {
1908 				freeb(first_mp);
1909 			}
1910 			icmp_redirect(ill, mp);
1911 			return;
1912 		case ICMP_DEST_UNREACHABLE:
1913 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1914 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1915 				    zoneid, mp, iph_hdr_length, ipst)) {
1916 					freemsg(first_mp);
1917 					return;
1918 				}
1919 				/*
1920 				 * icmp_inbound_too_big() may alter mp.
1921 				 * Resynch ipha and icmph accordingly.
1922 				 */
1923 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1924 				ipha = (ipha_t *)&icmph[1];
1925 			}
1926 			/* FALLTHRU */
1927 		default :
1928 			/*
1929 			 * IPQoS notes: Since we have already done IPQoS
1930 			 * processing we don't want to do it again in
1931 			 * the fanout routines called by
1932 			 * icmp_inbound_error_fanout, hence the last
1933 			 * argument, ip_policy, is B_FALSE.
1934 			 */
1935 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1936 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1937 			    B_FALSE, recv_ill, zoneid);
1938 		}
1939 		return;
1940 	}
1941 	/* Send out an ICMP packet */
1942 	icmph->icmph_checksum = 0;
1943 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1944 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1945 		ipif_t	*ipif_chosen;
1946 		/*
1947 		 * Make it look like it was directed to us, so we don't look
1948 		 * like a fool with a broadcast or multicast source address.
1949 		 */
1950 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1951 		/*
1952 		 * Make sure that we haven't grabbed an interface that's DOWN.
1953 		 */
1954 		if (ipif != NULL) {
1955 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1956 			    ipha->ipha_src, zoneid);
1957 			if (ipif_chosen != NULL) {
1958 				ipif_refrele(ipif);
1959 				ipif = ipif_chosen;
1960 			}
1961 		}
1962 		if (ipif == NULL) {
1963 			ip0dbg(("icmp_inbound: "
1964 			    "No source for broadcast/multicast:\n"
1965 			    "\tsrc 0x%x dst 0x%x ill %p "
1966 			    "ipif_lcl_addr 0x%x\n",
1967 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1968 			    (void *)ill,
1969 			    ill->ill_ipif->ipif_lcl_addr));
1970 			freemsg(first_mp);
1971 			return;
1972 		}
1973 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1974 		ipha->ipha_dst = ipif->ipif_src_addr;
1975 		ipif_refrele(ipif);
1976 	}
1977 	/* Reset time to live. */
1978 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1979 	{
1980 		/* Swap source and destination addresses */
1981 		ipaddr_t tmp;
1982 
1983 		tmp = ipha->ipha_src;
1984 		ipha->ipha_src = ipha->ipha_dst;
1985 		ipha->ipha_dst = tmp;
1986 	}
1987 	ipha->ipha_ident = 0;
1988 	if (!IS_SIMPLE_IPH(ipha))
1989 		icmp_options_update(ipha);
1990 
1991 	/*
1992 	 * ICMP echo replies should go out on the same interface
1993 	 * the request came on as probes used by in.mpathd for detecting
1994 	 * NIC failures are ECHO packets. We turn-off load spreading
1995 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1996 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1997 	 * function. This is in turn handled by ip_wput and ip_newroute
1998 	 * to make sure that the packet goes out on the interface it came
1999 	 * in on. If we don't turnoff load spreading, the packets might get
2000 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2001 	 * to go out and in.mpathd would wrongly detect a failure or
2002 	 * mis-detect a NIC failure for link failure. As load spreading
2003 	 * can happen only if ill_group is not NULL, we do only for
2004 	 * that case and this does not affect the normal case.
2005 	 *
2006 	 * We turn off load spreading only on echo packets that came from
2007 	 * on-link hosts. If the interface route has been deleted, this will
2008 	 * not be enforced as we can't do much. For off-link hosts, as the
2009 	 * default routes in IPv4 does not typically have an ire_ipif
2010 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2011 	 * Moreover, expecting a default route through this interface may
2012 	 * not be correct. We use ipha_dst because of the swap above.
2013 	 */
2014 	onlink = B_FALSE;
2015 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2016 		/*
2017 		 * First, we need to make sure that it is not one of our
2018 		 * local addresses. If we set onlink when it is one of
2019 		 * our local addresses, we will end up creating IRE_CACHES
2020 		 * for one of our local addresses. Then, we will never
2021 		 * accept packets for them afterwards.
2022 		 */
2023 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2024 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2025 		if (src_ire == NULL) {
2026 			ipif = ipif_get_next_ipif(NULL, ill);
2027 			if (ipif == NULL) {
2028 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2029 				freemsg(mp);
2030 				return;
2031 			}
2032 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2033 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2034 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2035 			ipif_refrele(ipif);
2036 			if (src_ire != NULL) {
2037 				onlink = B_TRUE;
2038 				ire_refrele(src_ire);
2039 			}
2040 		} else {
2041 			ire_refrele(src_ire);
2042 		}
2043 	}
2044 	if (!mctl_present) {
2045 		/*
2046 		 * This packet should go out the same way as it
2047 		 * came in i.e in clear. To make sure that global
2048 		 * policy will not be applied to this in ip_wput_ire,
2049 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2050 		 */
2051 		ASSERT(first_mp == mp);
2052 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2053 		if (first_mp == NULL) {
2054 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2055 			freemsg(mp);
2056 			return;
2057 		}
2058 		ii = (ipsec_in_t *)first_mp->b_rptr;
2059 
2060 		/* This is not a secure packet */
2061 		ii->ipsec_in_secure = B_FALSE;
2062 		if (onlink) {
2063 			ii->ipsec_in_attach_if = B_TRUE;
2064 			ii->ipsec_in_ill_index =
2065 			    ill->ill_phyint->phyint_ifindex;
2066 			ii->ipsec_in_rill_index =
2067 			    recv_ill->ill_phyint->phyint_ifindex;
2068 		}
2069 		first_mp->b_cont = mp;
2070 	} else if (onlink) {
2071 		ii = (ipsec_in_t *)first_mp->b_rptr;
2072 		ii->ipsec_in_attach_if = B_TRUE;
2073 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2074 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2075 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2076 	} else {
2077 		ii = (ipsec_in_t *)first_mp->b_rptr;
2078 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2079 	}
2080 	ii->ipsec_in_zoneid = zoneid;
2081 	ASSERT(zoneid != ALL_ZONES);
2082 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2084 		return;
2085 	}
2086 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2087 	put(WR(q), first_mp);
2088 }
2089 
2090 static ipaddr_t
2091 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2092 {
2093 	conn_t *connp;
2094 	connf_t *connfp;
2095 	ipaddr_t nexthop_addr = INADDR_ANY;
2096 	int hdr_length = IPH_HDR_LENGTH(ipha);
2097 	uint16_t *up;
2098 	uint32_t ports;
2099 	ip_stack_t *ipst = ill->ill_ipst;
2100 
2101 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2102 	switch (ipha->ipha_protocol) {
2103 		case IPPROTO_TCP:
2104 		{
2105 			tcph_t *tcph;
2106 
2107 			/* do a reverse lookup */
2108 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2109 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2110 			    TCPS_LISTEN, ipst);
2111 			break;
2112 		}
2113 		case IPPROTO_UDP:
2114 		{
2115 			uint32_t dstport, srcport;
2116 
2117 			((uint16_t *)&ports)[0] = up[1];
2118 			((uint16_t *)&ports)[1] = up[0];
2119 
2120 			/* Extract ports in net byte order */
2121 			dstport = htons(ntohl(ports) & 0xFFFF);
2122 			srcport = htons(ntohl(ports) >> 16);
2123 
2124 			connfp = &ipst->ips_ipcl_udp_fanout[
2125 			    IPCL_UDP_HASH(dstport, ipst)];
2126 			mutex_enter(&connfp->connf_lock);
2127 			connp = connfp->connf_head;
2128 
2129 			/* do a reverse lookup */
2130 			while ((connp != NULL) &&
2131 			    (!IPCL_UDP_MATCH(connp, dstport,
2132 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2133 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2134 				connp = connp->conn_next;
2135 			}
2136 			if (connp != NULL)
2137 				CONN_INC_REF(connp);
2138 			mutex_exit(&connfp->connf_lock);
2139 			break;
2140 		}
2141 		case IPPROTO_SCTP:
2142 		{
2143 			in6_addr_t map_src, map_dst;
2144 
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2146 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2147 			((uint16_t *)&ports)[0] = up[1];
2148 			((uint16_t *)&ports)[1] = up[0];
2149 
2150 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2151 			    zoneid, ipst->ips_netstack->netstack_sctp);
2152 			if (connp == NULL) {
2153 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2154 				    zoneid, ports, ipha, ipst);
2155 			} else {
2156 				CONN_INC_REF(connp);
2157 				SCTP_REFRELE(CONN2SCTP(connp));
2158 			}
2159 			break;
2160 		}
2161 		default:
2162 		{
2163 			ipha_t ripha;
2164 
2165 			ripha.ipha_src = ipha->ipha_dst;
2166 			ripha.ipha_dst = ipha->ipha_src;
2167 			ripha.ipha_protocol = ipha->ipha_protocol;
2168 
2169 			connfp = &ipst->ips_ipcl_proto_fanout[
2170 			    ipha->ipha_protocol];
2171 			mutex_enter(&connfp->connf_lock);
2172 			connp = connfp->connf_head;
2173 			for (connp = connfp->connf_head; connp != NULL;
2174 			    connp = connp->conn_next) {
2175 				if (IPCL_PROTO_MATCH(connp,
2176 				    ipha->ipha_protocol, &ripha, ill,
2177 				    0, zoneid)) {
2178 					CONN_INC_REF(connp);
2179 					break;
2180 				}
2181 			}
2182 			mutex_exit(&connfp->connf_lock);
2183 		}
2184 	}
2185 	if (connp != NULL) {
2186 		if (connp->conn_nexthop_set)
2187 			nexthop_addr = connp->conn_nexthop_v4;
2188 		CONN_DEC_REF(connp);
2189 	}
2190 	return (nexthop_addr);
2191 }
2192 
2193 /* Table from RFC 1191 */
2194 static int icmp_frag_size_table[] =
2195 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2196 
2197 /*
2198  * Process received ICMP Packet too big.
2199  * After updating any IRE it does the fanout to any matching transport streams.
2200  * Assumes the message has been pulled up till the IP header that caused
2201  * the error.
2202  *
2203  * Returns B_FALSE on failure and B_TRUE on success.
2204  */
2205 static boolean_t
2206 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2207     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2208     ip_stack_t *ipst)
2209 {
2210 	ire_t	*ire, *first_ire;
2211 	int	mtu;
2212 	int	hdr_length;
2213 	ipaddr_t nexthop_addr;
2214 
2215 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2216 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2217 	ASSERT(ill != NULL);
2218 
2219 	hdr_length = IPH_HDR_LENGTH(ipha);
2220 
2221 	/* Drop if the original packet contained a source route */
2222 	if (ip_source_route_included(ipha)) {
2223 		return (B_FALSE);
2224 	}
2225 	/*
2226 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2227 	 * header.
2228 	 */
2229 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2230 	    mp->b_wptr) {
2231 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2232 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2233 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2234 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2235 			return (B_FALSE);
2236 		}
2237 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2238 		ipha = (ipha_t *)&icmph[1];
2239 	}
2240 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2241 	if (nexthop_addr != INADDR_ANY) {
2242 		/* nexthop set */
2243 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2244 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2245 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2246 	} else {
2247 		/* nexthop not set */
2248 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2249 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2250 	}
2251 
2252 	if (!first_ire) {
2253 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2254 		    ntohl(ipha->ipha_dst)));
2255 		return (B_FALSE);
2256 	}
2257 	/* Check for MTU discovery advice as described in RFC 1191 */
2258 	mtu = ntohs(icmph->icmph_du_mtu);
2259 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2260 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2261 	    ire = ire->ire_next) {
2262 		/*
2263 		 * Look for the connection to which this ICMP message is
2264 		 * directed. If it has the IP_NEXTHOP option set, then the
2265 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2266 		 * option. Else the search is limited to regular IREs.
2267 		 */
2268 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2269 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2270 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2271 		    (nexthop_addr != INADDR_ANY)))
2272 			continue;
2273 
2274 		mutex_enter(&ire->ire_lock);
2275 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2276 			/* Reduce the IRE max frag value as advised. */
2277 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2278 			    mtu, ire->ire_max_frag));
2279 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2280 		} else {
2281 			uint32_t length;
2282 			int	i;
2283 
2284 			/*
2285 			 * Use the table from RFC 1191 to figure out
2286 			 * the next "plateau" based on the length in
2287 			 * the original IP packet.
2288 			 */
2289 			length = ntohs(ipha->ipha_length);
2290 			if (ire->ire_max_frag <= length &&
2291 			    ire->ire_max_frag >= length - hdr_length) {
2292 				/*
2293 				 * Handle broken BSD 4.2 systems that
2294 				 * return the wrong iph_length in ICMP
2295 				 * errors.
2296 				 */
2297 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2298 				    length, ire->ire_max_frag));
2299 				length -= hdr_length;
2300 			}
2301 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2302 				if (length > icmp_frag_size_table[i])
2303 					break;
2304 			}
2305 			if (i == A_CNT(icmp_frag_size_table)) {
2306 				/* Smaller than 68! */
2307 				ip1dbg(("Too big for packet size %d\n",
2308 				    length));
2309 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2310 				ire->ire_frag_flag = 0;
2311 			} else {
2312 				mtu = icmp_frag_size_table[i];
2313 				ip1dbg(("Calculated mtu %d, packet size %d, "
2314 				    "before %d", mtu, length,
2315 				    ire->ire_max_frag));
2316 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2317 				ip1dbg((", after %d\n", ire->ire_max_frag));
2318 			}
2319 			/* Record the new max frag size for the ULP. */
2320 			icmph->icmph_du_zero = 0;
2321 			icmph->icmph_du_mtu =
2322 			    htons((uint16_t)ire->ire_max_frag);
2323 		}
2324 		mutex_exit(&ire->ire_lock);
2325 	}
2326 	rw_exit(&first_ire->ire_bucket->irb_lock);
2327 	ire_refrele(first_ire);
2328 	return (B_TRUE);
2329 }
2330 
2331 /*
2332  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2333  * calls this function.
2334  */
2335 static mblk_t *
2336 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2337 {
2338 	ipha_t *ipha;
2339 	icmph_t *icmph;
2340 	ipha_t *in_ipha;
2341 	int length;
2342 
2343 	ASSERT(mp->b_datap->db_type == M_DATA);
2344 
2345 	/*
2346 	 * For Self-encapsulated packets, we added an extra IP header
2347 	 * without the options. Inner IP header is the one from which
2348 	 * the outer IP header was formed. Thus, we need to remove the
2349 	 * outer IP header. To do this, we pullup the whole message
2350 	 * and overlay whatever follows the outer IP header over the
2351 	 * outer IP header.
2352 	 */
2353 
2354 	if (!pullupmsg(mp, -1))
2355 		return (NULL);
2356 
2357 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2358 	ipha = (ipha_t *)&icmph[1];
2359 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2360 
2361 	/*
2362 	 * The length that we want to overlay is following the inner
2363 	 * IP header. Subtracting the IP header + icmp header + outer
2364 	 * IP header's length should give us the length that we want to
2365 	 * overlay.
2366 	 */
2367 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2368 	    hdr_length;
2369 	/*
2370 	 * Overlay whatever follows the inner header over the
2371 	 * outer header.
2372 	 */
2373 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2374 
2375 	/* Set the wptr to account for the outer header */
2376 	mp->b_wptr -= hdr_length;
2377 	return (mp);
2378 }
2379 
2380 /*
2381  * Try to pass the ICMP message upstream in case the ULP cares.
2382  *
2383  * If the packet that caused the ICMP error is secure, we send
2384  * it to AH/ESP to make sure that the attached packet has a
2385  * valid association. ipha in the code below points to the
2386  * IP header of the packet that caused the error.
2387  *
2388  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2389  * in the context of IPsec. Normally we tell the upper layer
2390  * whenever we send the ire (including ip_bind), the IPsec header
2391  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2392  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2393  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2394  * same thing. As TCP has the IPsec options size that needs to be
2395  * adjusted, we just pass the MTU unchanged.
2396  *
2397  * IFN could have been generated locally or by some router.
2398  *
2399  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2400  *	    This happens because IP adjusted its value of MTU on an
2401  *	    earlier IFN message and could not tell the upper layer,
2402  *	    the new adjusted value of MTU e.g. Packet was encrypted
2403  *	    or there was not enough information to fanout to upper
2404  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2405  *	    generates the IFN, where IPsec processing has *not* been
2406  *	    done.
2407  *
2408  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2409  *	    could have generated this. This happens because ire_max_frag
2410  *	    value in IP was set to a new value, while the IPsec processing
2411  *	    was being done and after we made the fragmentation check in
2412  *	    ip_wput_ire. Thus on return from IPsec processing,
2413  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2414  *	    and generates the IFN. As IPsec processing is over, we fanout
2415  *	    to AH/ESP to remove the header.
2416  *
2417  *	    In both these cases, ipsec_in_loopback will be set indicating
2418  *	    that IFN was generated locally.
2419  *
2420  * ROUTER : IFN could be secure or non-secure.
2421  *
2422  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2423  *	      packet in error has AH/ESP headers to validate the AH/ESP
2424  *	      headers. AH/ESP will verify whether there is a valid SA or
2425  *	      not and send it back. We will fanout again if we have more
2426  *	      data in the packet.
2427  *
2428  *	      If the packet in error does not have AH/ESP, we handle it
2429  *	      like any other case.
2430  *
2431  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2432  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2433  *	      for validation. AH/ESP will verify whether there is a
2434  *	      valid SA or not and send it back. We will fanout again if
2435  *	      we have more data in the packet.
2436  *
2437  *	      If the packet in error does not have AH/ESP, we handle it
2438  *	      like any other case.
2439  */
2440 static void
2441 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2442     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2443     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2444     zoneid_t zoneid)
2445 {
2446 	uint16_t *up;	/* Pointer to ports in ULP header */
2447 	uint32_t ports;	/* reversed ports for fanout */
2448 	ipha_t ripha;	/* With reversed addresses */
2449 	mblk_t *first_mp;
2450 	ipsec_in_t *ii;
2451 	tcph_t	*tcph;
2452 	conn_t	*connp;
2453 	ip_stack_t *ipst;
2454 
2455 	ASSERT(ill != NULL);
2456 
2457 	ASSERT(recv_ill != NULL);
2458 	ipst = recv_ill->ill_ipst;
2459 
2460 	first_mp = mp;
2461 	if (mctl_present) {
2462 		mp = first_mp->b_cont;
2463 		ASSERT(mp != NULL);
2464 
2465 		ii = (ipsec_in_t *)first_mp->b_rptr;
2466 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2467 	} else {
2468 		ii = NULL;
2469 	}
2470 
2471 	switch (ipha->ipha_protocol) {
2472 	case IPPROTO_UDP:
2473 		/*
2474 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2475 		 * transport header.
2476 		 */
2477 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2478 		    mp->b_wptr) {
2479 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2480 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2481 				goto discard_pkt;
2482 			}
2483 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2484 			ipha = (ipha_t *)&icmph[1];
2485 		}
2486 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2487 
2488 		/*
2489 		 * Attempt to find a client stream based on port.
2490 		 * Note that we do a reverse lookup since the header is
2491 		 * in the form we sent it out.
2492 		 * The ripha header is only used for the IP_UDP_MATCH and we
2493 		 * only set the src and dst addresses and protocol.
2494 		 */
2495 		ripha.ipha_src = ipha->ipha_dst;
2496 		ripha.ipha_dst = ipha->ipha_src;
2497 		ripha.ipha_protocol = ipha->ipha_protocol;
2498 		((uint16_t *)&ports)[0] = up[1];
2499 		((uint16_t *)&ports)[1] = up[0];
2500 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2501 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2502 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2503 		    icmph->icmph_type, icmph->icmph_code));
2504 
2505 		/* Have to change db_type after any pullupmsg */
2506 		DB_TYPE(mp) = M_CTL;
2507 
2508 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2509 		    mctl_present, ip_policy, recv_ill, zoneid);
2510 		return;
2511 
2512 	case IPPROTO_TCP:
2513 		/*
2514 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2515 		 * transport header.
2516 		 */
2517 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2518 		    mp->b_wptr) {
2519 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2520 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2521 				goto discard_pkt;
2522 			}
2523 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2524 			ipha = (ipha_t *)&icmph[1];
2525 		}
2526 		/*
2527 		 * Find a TCP client stream for this packet.
2528 		 * Note that we do a reverse lookup since the header is
2529 		 * in the form we sent it out.
2530 		 */
2531 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2532 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2533 		    ipst);
2534 		if (connp == NULL)
2535 			goto discard_pkt;
2536 
2537 		/* Have to change db_type after any pullupmsg */
2538 		DB_TYPE(mp) = M_CTL;
2539 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2540 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2541 		return;
2542 
2543 	case IPPROTO_SCTP:
2544 		/*
2545 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2546 		 * transport header.
2547 		 */
2548 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2549 		    mp->b_wptr) {
2550 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2551 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2552 				goto discard_pkt;
2553 			}
2554 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2555 			ipha = (ipha_t *)&icmph[1];
2556 		}
2557 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2558 		/*
2559 		 * Find a SCTP client stream for this packet.
2560 		 * Note that we do a reverse lookup since the header is
2561 		 * in the form we sent it out.
2562 		 * The ripha header is only used for the matching and we
2563 		 * only set the src and dst addresses, protocol, and version.
2564 		 */
2565 		ripha.ipha_src = ipha->ipha_dst;
2566 		ripha.ipha_dst = ipha->ipha_src;
2567 		ripha.ipha_protocol = ipha->ipha_protocol;
2568 		ripha.ipha_version_and_hdr_length =
2569 		    ipha->ipha_version_and_hdr_length;
2570 		((uint16_t *)&ports)[0] = up[1];
2571 		((uint16_t *)&ports)[1] = up[0];
2572 
2573 		/* Have to change db_type after any pullupmsg */
2574 		DB_TYPE(mp) = M_CTL;
2575 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2576 		    mctl_present, ip_policy, zoneid);
2577 		return;
2578 
2579 	case IPPROTO_ESP:
2580 	case IPPROTO_AH: {
2581 		int ipsec_rc;
2582 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2583 
2584 		/*
2585 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2586 		 * We will re-use the IPSEC_IN if it is already present as
2587 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2588 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2589 		 * one and attach it in the front.
2590 		 */
2591 		if (ii != NULL) {
2592 			/*
2593 			 * ip_fanout_proto_again converts the ICMP errors
2594 			 * that come back from AH/ESP to M_DATA so that
2595 			 * if it is non-AH/ESP and we do a pullupmsg in
2596 			 * this function, it would work. Convert it back
2597 			 * to M_CTL before we send up as this is a ICMP
2598 			 * error. This could have been generated locally or
2599 			 * by some router. Validate the inner IPsec
2600 			 * headers.
2601 			 *
2602 			 * NOTE : ill_index is used by ip_fanout_proto_again
2603 			 * to locate the ill.
2604 			 */
2605 			ASSERT(ill != NULL);
2606 			ii->ipsec_in_ill_index =
2607 			    ill->ill_phyint->phyint_ifindex;
2608 			ii->ipsec_in_rill_index =
2609 			    recv_ill->ill_phyint->phyint_ifindex;
2610 			DB_TYPE(first_mp->b_cont) = M_CTL;
2611 		} else {
2612 			/*
2613 			 * IPSEC_IN is not present. We attach a ipsec_in
2614 			 * message and send up to IPsec for validating
2615 			 * and removing the IPsec headers. Clear
2616 			 * ipsec_in_secure so that when we return
2617 			 * from IPsec, we don't mistakenly think that this
2618 			 * is a secure packet came from the network.
2619 			 *
2620 			 * NOTE : ill_index is used by ip_fanout_proto_again
2621 			 * to locate the ill.
2622 			 */
2623 			ASSERT(first_mp == mp);
2624 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2625 			if (first_mp == NULL) {
2626 				freemsg(mp);
2627 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2628 				return;
2629 			}
2630 			ii = (ipsec_in_t *)first_mp->b_rptr;
2631 
2632 			/* This is not a secure packet */
2633 			ii->ipsec_in_secure = B_FALSE;
2634 			first_mp->b_cont = mp;
2635 			DB_TYPE(mp) = M_CTL;
2636 			ASSERT(ill != NULL);
2637 			ii->ipsec_in_ill_index =
2638 			    ill->ill_phyint->phyint_ifindex;
2639 			ii->ipsec_in_rill_index =
2640 			    recv_ill->ill_phyint->phyint_ifindex;
2641 		}
2642 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2643 
2644 		if (!ipsec_loaded(ipss)) {
2645 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2646 			return;
2647 		}
2648 
2649 		if (ipha->ipha_protocol == IPPROTO_ESP)
2650 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2651 		else
2652 			ipsec_rc = ipsecah_icmp_error(first_mp);
2653 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2654 			return;
2655 
2656 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2657 		return;
2658 	}
2659 	default:
2660 		/*
2661 		 * The ripha header is only used for the lookup and we
2662 		 * only set the src and dst addresses and protocol.
2663 		 */
2664 		ripha.ipha_src = ipha->ipha_dst;
2665 		ripha.ipha_dst = ipha->ipha_src;
2666 		ripha.ipha_protocol = ipha->ipha_protocol;
2667 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2668 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2669 		    ntohl(ipha->ipha_dst),
2670 		    icmph->icmph_type, icmph->icmph_code));
2671 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2672 			ipha_t *in_ipha;
2673 
2674 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2675 			    mp->b_wptr) {
2676 				if (!pullupmsg(mp, (uchar_t *)ipha +
2677 				    hdr_length + sizeof (ipha_t) -
2678 				    mp->b_rptr)) {
2679 					goto discard_pkt;
2680 				}
2681 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2682 				ipha = (ipha_t *)&icmph[1];
2683 			}
2684 			/*
2685 			 * Caller has verified that length has to be
2686 			 * at least the size of IP header.
2687 			 */
2688 			ASSERT(hdr_length >= sizeof (ipha_t));
2689 			/*
2690 			 * Check the sanity of the inner IP header like
2691 			 * we did for the outer header.
2692 			 */
2693 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2694 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2695 				goto discard_pkt;
2696 			}
2697 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2698 				goto discard_pkt;
2699 			}
2700 			/* Check for Self-encapsulated tunnels */
2701 			if (in_ipha->ipha_src == ipha->ipha_src &&
2702 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2703 
2704 				mp = icmp_inbound_self_encap_error(mp,
2705 				    iph_hdr_length, hdr_length);
2706 				if (mp == NULL)
2707 					goto discard_pkt;
2708 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2709 				ipha = (ipha_t *)&icmph[1];
2710 				hdr_length = IPH_HDR_LENGTH(ipha);
2711 				/*
2712 				 * The packet in error is self-encapsualted.
2713 				 * And we are finding it further encapsulated
2714 				 * which we could not have possibly generated.
2715 				 */
2716 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2717 					goto discard_pkt;
2718 				}
2719 				icmp_inbound_error_fanout(q, ill, first_mp,
2720 				    icmph, ipha, iph_hdr_length, hdr_length,
2721 				    mctl_present, ip_policy, recv_ill, zoneid);
2722 				return;
2723 			}
2724 		}
2725 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2726 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2727 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2728 		    ii != NULL &&
2729 		    ii->ipsec_in_loopback &&
2730 		    ii->ipsec_in_secure) {
2731 			/*
2732 			 * For IP tunnels that get a looped-back
2733 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2734 			 * reported new MTU to take into account the IPsec
2735 			 * headers protecting this configured tunnel.
2736 			 *
2737 			 * This allows the tunnel module (tun.c) to blindly
2738 			 * accept the MTU reported in an ICMP "too big"
2739 			 * message.
2740 			 *
2741 			 * Non-looped back ICMP messages will just be
2742 			 * handled by the security protocols (if needed),
2743 			 * and the first subsequent packet will hit this
2744 			 * path.
2745 			 */
2746 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2747 			    ipsec_in_extra_length(first_mp));
2748 		}
2749 		/* Have to change db_type after any pullupmsg */
2750 		DB_TYPE(mp) = M_CTL;
2751 
2752 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2753 		    ip_policy, recv_ill, zoneid);
2754 		return;
2755 	}
2756 	/* NOTREACHED */
2757 discard_pkt:
2758 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2759 drop_pkt:;
2760 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2761 	freemsg(first_mp);
2762 }
2763 
2764 /*
2765  * Common IP options parser.
2766  *
2767  * Setup routine: fill in *optp with options-parsing state, then
2768  * tail-call ipoptp_next to return the first option.
2769  */
2770 uint8_t
2771 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2772 {
2773 	uint32_t totallen; /* total length of all options */
2774 
2775 	totallen = ipha->ipha_version_and_hdr_length -
2776 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2777 	totallen <<= 2;
2778 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2779 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2780 	optp->ipoptp_flags = 0;
2781 	return (ipoptp_next(optp));
2782 }
2783 
2784 /*
2785  * Common IP options parser: extract next option.
2786  */
2787 uint8_t
2788 ipoptp_next(ipoptp_t *optp)
2789 {
2790 	uint8_t *end = optp->ipoptp_end;
2791 	uint8_t *cur = optp->ipoptp_next;
2792 	uint8_t opt, len, pointer;
2793 
2794 	/*
2795 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2796 	 * has been corrupted.
2797 	 */
2798 	ASSERT(cur <= end);
2799 
2800 	if (cur == end)
2801 		return (IPOPT_EOL);
2802 
2803 	opt = cur[IPOPT_OPTVAL];
2804 
2805 	/*
2806 	 * Skip any NOP options.
2807 	 */
2808 	while (opt == IPOPT_NOP) {
2809 		cur++;
2810 		if (cur == end)
2811 			return (IPOPT_EOL);
2812 		opt = cur[IPOPT_OPTVAL];
2813 	}
2814 
2815 	if (opt == IPOPT_EOL)
2816 		return (IPOPT_EOL);
2817 
2818 	/*
2819 	 * Option requiring a length.
2820 	 */
2821 	if ((cur + 1) >= end) {
2822 		optp->ipoptp_flags |= IPOPTP_ERROR;
2823 		return (IPOPT_EOL);
2824 	}
2825 	len = cur[IPOPT_OLEN];
2826 	if (len < 2) {
2827 		optp->ipoptp_flags |= IPOPTP_ERROR;
2828 		return (IPOPT_EOL);
2829 	}
2830 	optp->ipoptp_cur = cur;
2831 	optp->ipoptp_len = len;
2832 	optp->ipoptp_next = cur + len;
2833 	if (cur + len > end) {
2834 		optp->ipoptp_flags |= IPOPTP_ERROR;
2835 		return (IPOPT_EOL);
2836 	}
2837 
2838 	/*
2839 	 * For the options which require a pointer field, make sure
2840 	 * its there, and make sure it points to either something
2841 	 * inside this option, or the end of the option.
2842 	 */
2843 	switch (opt) {
2844 	case IPOPT_RR:
2845 	case IPOPT_TS:
2846 	case IPOPT_LSRR:
2847 	case IPOPT_SSRR:
2848 		if (len <= IPOPT_OFFSET) {
2849 			optp->ipoptp_flags |= IPOPTP_ERROR;
2850 			return (opt);
2851 		}
2852 		pointer = cur[IPOPT_OFFSET];
2853 		if (pointer - 1 > len) {
2854 			optp->ipoptp_flags |= IPOPTP_ERROR;
2855 			return (opt);
2856 		}
2857 		break;
2858 	}
2859 
2860 	/*
2861 	 * Sanity check the pointer field based on the type of the
2862 	 * option.
2863 	 */
2864 	switch (opt) {
2865 	case IPOPT_RR:
2866 	case IPOPT_SSRR:
2867 	case IPOPT_LSRR:
2868 		if (pointer < IPOPT_MINOFF_SR)
2869 			optp->ipoptp_flags |= IPOPTP_ERROR;
2870 		break;
2871 	case IPOPT_TS:
2872 		if (pointer < IPOPT_MINOFF_IT)
2873 			optp->ipoptp_flags |= IPOPTP_ERROR;
2874 		/*
2875 		 * Note that the Internet Timestamp option also
2876 		 * contains two four bit fields (the Overflow field,
2877 		 * and the Flag field), which follow the pointer
2878 		 * field.  We don't need to check that these fields
2879 		 * fall within the length of the option because this
2880 		 * was implicitely done above.  We've checked that the
2881 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2882 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2883 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2884 		 */
2885 		ASSERT(len > IPOPT_POS_OV_FLG);
2886 		break;
2887 	}
2888 
2889 	return (opt);
2890 }
2891 
2892 /*
2893  * Use the outgoing IP header to create an IP_OPTIONS option the way
2894  * it was passed down from the application.
2895  */
2896 int
2897 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2898 {
2899 	ipoptp_t	opts;
2900 	const uchar_t	*opt;
2901 	uint8_t		optval;
2902 	uint8_t		optlen;
2903 	uint32_t	len = 0;
2904 	uchar_t	*buf1 = buf;
2905 
2906 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2907 	len += IP_ADDR_LEN;
2908 	bzero(buf1, IP_ADDR_LEN);
2909 
2910 	/*
2911 	 * OK to cast away const here, as we don't store through the returned
2912 	 * opts.ipoptp_cur pointer.
2913 	 */
2914 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2915 	    optval != IPOPT_EOL;
2916 	    optval = ipoptp_next(&opts)) {
2917 		int	off;
2918 
2919 		opt = opts.ipoptp_cur;
2920 		optlen = opts.ipoptp_len;
2921 		switch (optval) {
2922 		case IPOPT_SSRR:
2923 		case IPOPT_LSRR:
2924 
2925 			/*
2926 			 * Insert ipha_dst as the first entry in the source
2927 			 * route and move down the entries on step.
2928 			 * The last entry gets placed at buf1.
2929 			 */
2930 			buf[IPOPT_OPTVAL] = optval;
2931 			buf[IPOPT_OLEN] = optlen;
2932 			buf[IPOPT_OFFSET] = optlen;
2933 
2934 			off = optlen - IP_ADDR_LEN;
2935 			if (off < 0) {
2936 				/* No entries in source route */
2937 				break;
2938 			}
2939 			/* Last entry in source route */
2940 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2941 			off -= IP_ADDR_LEN;
2942 
2943 			while (off > 0) {
2944 				bcopy(opt + off,
2945 				    buf + off + IP_ADDR_LEN,
2946 				    IP_ADDR_LEN);
2947 				off -= IP_ADDR_LEN;
2948 			}
2949 			/* ipha_dst into first slot */
2950 			bcopy(&ipha->ipha_dst,
2951 			    buf + off + IP_ADDR_LEN,
2952 			    IP_ADDR_LEN);
2953 			buf += optlen;
2954 			len += optlen;
2955 			break;
2956 
2957 		case IPOPT_COMSEC:
2958 		case IPOPT_SECURITY:
2959 			/* if passing up a label is not ok, then remove */
2960 			if (is_system_labeled())
2961 				break;
2962 			/* FALLTHROUGH */
2963 		default:
2964 			bcopy(opt, buf, optlen);
2965 			buf += optlen;
2966 			len += optlen;
2967 			break;
2968 		}
2969 	}
2970 done:
2971 	/* Pad the resulting options */
2972 	while (len & 0x3) {
2973 		*buf++ = IPOPT_EOL;
2974 		len++;
2975 	}
2976 	return (len);
2977 }
2978 
2979 /*
2980  * Update any record route or timestamp options to include this host.
2981  * Reverse any source route option.
2982  * This routine assumes that the options are well formed i.e. that they
2983  * have already been checked.
2984  */
2985 static void
2986 icmp_options_update(ipha_t *ipha)
2987 {
2988 	ipoptp_t	opts;
2989 	uchar_t		*opt;
2990 	uint8_t		optval;
2991 	ipaddr_t	src;		/* Our local address */
2992 	ipaddr_t	dst;
2993 
2994 	ip2dbg(("icmp_options_update\n"));
2995 	src = ipha->ipha_src;
2996 	dst = ipha->ipha_dst;
2997 
2998 	for (optval = ipoptp_first(&opts, ipha);
2999 	    optval != IPOPT_EOL;
3000 	    optval = ipoptp_next(&opts)) {
3001 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3002 		opt = opts.ipoptp_cur;
3003 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3004 		    optval, opts.ipoptp_len));
3005 		switch (optval) {
3006 			int off1, off2;
3007 		case IPOPT_SSRR:
3008 		case IPOPT_LSRR:
3009 			/*
3010 			 * Reverse the source route.  The first entry
3011 			 * should be the next to last one in the current
3012 			 * source route (the last entry is our address).
3013 			 * The last entry should be the final destination.
3014 			 */
3015 			off1 = IPOPT_MINOFF_SR - 1;
3016 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3017 			if (off2 < 0) {
3018 				/* No entries in source route */
3019 				ip1dbg((
3020 				    "icmp_options_update: bad src route\n"));
3021 				break;
3022 			}
3023 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3024 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3025 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3026 			off2 -= IP_ADDR_LEN;
3027 
3028 			while (off1 < off2) {
3029 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3030 				bcopy((char *)opt + off2, (char *)opt + off1,
3031 				    IP_ADDR_LEN);
3032 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3033 				off1 += IP_ADDR_LEN;
3034 				off2 -= IP_ADDR_LEN;
3035 			}
3036 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3037 			break;
3038 		}
3039 	}
3040 }
3041 
3042 /*
3043  * Process received ICMP Redirect messages.
3044  */
3045 static void
3046 icmp_redirect(ill_t *ill, mblk_t *mp)
3047 {
3048 	ipha_t	*ipha;
3049 	int	iph_hdr_length;
3050 	icmph_t	*icmph;
3051 	ipha_t	*ipha_err;
3052 	ire_t	*ire;
3053 	ire_t	*prev_ire;
3054 	ire_t	*save_ire;
3055 	ipaddr_t  src, dst, gateway;
3056 	iulp_t	ulp_info = { 0 };
3057 	int	error;
3058 	ip_stack_t *ipst;
3059 
3060 	ASSERT(ill != NULL);
3061 	ipst = ill->ill_ipst;
3062 
3063 	ipha = (ipha_t *)mp->b_rptr;
3064 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3065 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3066 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3067 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3068 		freemsg(mp);
3069 		return;
3070 	}
3071 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3072 	ipha_err = (ipha_t *)&icmph[1];
3073 	src = ipha->ipha_src;
3074 	dst = ipha_err->ipha_dst;
3075 	gateway = icmph->icmph_rd_gateway;
3076 	/* Make sure the new gateway is reachable somehow. */
3077 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3078 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3079 	/*
3080 	 * Make sure we had a route for the dest in question and that
3081 	 * that route was pointing to the old gateway (the source of the
3082 	 * redirect packet.)
3083 	 */
3084 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3085 	    NULL, MATCH_IRE_GW, ipst);
3086 	/*
3087 	 * Check that
3088 	 *	the redirect was not from ourselves
3089 	 *	the new gateway and the old gateway are directly reachable
3090 	 */
3091 	if (!prev_ire ||
3092 	    !ire ||
3093 	    ire->ire_type == IRE_LOCAL) {
3094 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3095 		freemsg(mp);
3096 		if (ire != NULL)
3097 			ire_refrele(ire);
3098 		if (prev_ire != NULL)
3099 			ire_refrele(prev_ire);
3100 		return;
3101 	}
3102 
3103 	/*
3104 	 * Should we use the old ULP info to create the new gateway?  From
3105 	 * a user's perspective, we should inherit the info so that it
3106 	 * is a "smooth" transition.  If we do not do that, then new
3107 	 * connections going thru the new gateway will have no route metrics,
3108 	 * which is counter-intuitive to user.  From a network point of
3109 	 * view, this may or may not make sense even though the new gateway
3110 	 * is still directly connected to us so the route metrics should not
3111 	 * change much.
3112 	 *
3113 	 * But if the old ire_uinfo is not initialized, we do another
3114 	 * recursive lookup on the dest using the new gateway.  There may
3115 	 * be a route to that.  If so, use it to initialize the redirect
3116 	 * route.
3117 	 */
3118 	if (prev_ire->ire_uinfo.iulp_set) {
3119 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3120 	} else {
3121 		ire_t *tmp_ire;
3122 		ire_t *sire;
3123 
3124 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3125 		    ALL_ZONES, 0, NULL,
3126 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3127 		    ipst);
3128 		if (sire != NULL) {
3129 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3130 			/*
3131 			 * If sire != NULL, ire_ftable_lookup() should not
3132 			 * return a NULL value.
3133 			 */
3134 			ASSERT(tmp_ire != NULL);
3135 			ire_refrele(tmp_ire);
3136 			ire_refrele(sire);
3137 		} else if (tmp_ire != NULL) {
3138 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3139 			    sizeof (iulp_t));
3140 			ire_refrele(tmp_ire);
3141 		}
3142 	}
3143 	if (prev_ire->ire_type == IRE_CACHE)
3144 		ire_delete(prev_ire);
3145 	ire_refrele(prev_ire);
3146 	/*
3147 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3148 	 * require TOS routing
3149 	 */
3150 	switch (icmph->icmph_code) {
3151 	case 0:
3152 	case 1:
3153 		/* TODO: TOS specificity for cases 2 and 3 */
3154 	case 2:
3155 	case 3:
3156 		break;
3157 	default:
3158 		freemsg(mp);
3159 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3160 		ire_refrele(ire);
3161 		return;
3162 	}
3163 	/*
3164 	 * Create a Route Association.  This will allow us to remember that
3165 	 * someone we believe told us to use the particular gateway.
3166 	 */
3167 	save_ire = ire;
3168 	ire = ire_create(
3169 	    (uchar_t *)&dst,			/* dest addr */
3170 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3171 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3172 	    (uchar_t *)&gateway,		/* gateway addr */
3173 	    &save_ire->ire_max_frag,		/* max frag */
3174 	    NULL,				/* no src nce */
3175 	    NULL,				/* no rfq */
3176 	    NULL,				/* no stq */
3177 	    IRE_HOST,
3178 	    NULL,				/* ipif */
3179 	    0,					/* cmask */
3180 	    0,					/* phandle */
3181 	    0,					/* ihandle */
3182 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3183 	    &ulp_info,
3184 	    NULL,				/* tsol_gc_t */
3185 	    NULL,				/* gcgrp */
3186 	    ipst);
3187 
3188 	if (ire == NULL) {
3189 		freemsg(mp);
3190 		ire_refrele(save_ire);
3191 		return;
3192 	}
3193 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3194 	ire_refrele(save_ire);
3195 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3196 
3197 	if (error == 0) {
3198 		ire_refrele(ire);		/* Held in ire_add_v4 */
3199 		/* tell routing sockets that we received a redirect */
3200 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3201 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3202 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3203 	}
3204 
3205 	/*
3206 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3207 	 * This together with the added IRE has the effect of
3208 	 * modifying an existing redirect.
3209 	 */
3210 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3211 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3212 	if (prev_ire != NULL) {
3213 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3214 			ire_delete(prev_ire);
3215 		ire_refrele(prev_ire);
3216 	}
3217 
3218 	freemsg(mp);
3219 }
3220 
3221 /*
3222  * Generate an ICMP parameter problem message.
3223  */
3224 static void
3225 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3226 	ip_stack_t *ipst)
3227 {
3228 	icmph_t	icmph;
3229 	boolean_t mctl_present;
3230 	mblk_t *first_mp;
3231 
3232 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3233 
3234 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3235 		if (mctl_present)
3236 			freeb(first_mp);
3237 		return;
3238 	}
3239 
3240 	bzero(&icmph, sizeof (icmph_t));
3241 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3242 	icmph.icmph_pp_ptr = ptr;
3243 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3244 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3245 	    ipst);
3246 }
3247 
3248 /*
3249  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3250  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3251  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3252  * an icmp error packet can be sent.
3253  * Assigns an appropriate source address to the packet. If ipha_dst is
3254  * one of our addresses use it for source. Otherwise pick a source based
3255  * on a route lookup back to ipha_src.
3256  * Note that ipha_src must be set here since the
3257  * packet is likely to arrive on an ill queue in ip_wput() which will
3258  * not set a source address.
3259  */
3260 static void
3261 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3262     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3263 {
3264 	ipaddr_t dst;
3265 	icmph_t	*icmph;
3266 	ipha_t	*ipha;
3267 	uint_t	len_needed;
3268 	size_t	msg_len;
3269 	mblk_t	*mp1;
3270 	ipaddr_t src;
3271 	ire_t	*ire;
3272 	mblk_t *ipsec_mp;
3273 	ipsec_out_t	*io = NULL;
3274 
3275 	if (mctl_present) {
3276 		/*
3277 		 * If it is :
3278 		 *
3279 		 * 1) a IPSEC_OUT, then this is caused by outbound
3280 		 *    datagram originating on this host. IPsec processing
3281 		 *    may or may not have been done. Refer to comments above
3282 		 *    icmp_inbound_error_fanout for details.
3283 		 *
3284 		 * 2) a IPSEC_IN if we are generating a icmp_message
3285 		 *    for an incoming datagram destined for us i.e called
3286 		 *    from ip_fanout_send_icmp.
3287 		 */
3288 		ipsec_info_t *in;
3289 		ipsec_mp = mp;
3290 		mp = ipsec_mp->b_cont;
3291 
3292 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3293 		ipha = (ipha_t *)mp->b_rptr;
3294 
3295 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3296 		    in->ipsec_info_type == IPSEC_IN);
3297 
3298 		if (in->ipsec_info_type == IPSEC_IN) {
3299 			/*
3300 			 * Convert the IPSEC_IN to IPSEC_OUT.
3301 			 */
3302 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3303 				BUMP_MIB(&ipst->ips_ip_mib,
3304 				    ipIfStatsOutDiscards);
3305 				return;
3306 			}
3307 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3308 		} else {
3309 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3310 			io = (ipsec_out_t *)in;
3311 			/*
3312 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3313 			 * ire lookup.
3314 			 */
3315 			io->ipsec_out_proc_begin = B_FALSE;
3316 		}
3317 		ASSERT(zoneid == io->ipsec_out_zoneid);
3318 		ASSERT(zoneid != ALL_ZONES);
3319 	} else {
3320 		/*
3321 		 * This is in clear. The icmp message we are building
3322 		 * here should go out in clear.
3323 		 *
3324 		 * Pardon the convolution of it all, but it's easier to
3325 		 * allocate a "use cleartext" IPSEC_IN message and convert
3326 		 * it than it is to allocate a new one.
3327 		 */
3328 		ipsec_in_t *ii;
3329 		ASSERT(DB_TYPE(mp) == M_DATA);
3330 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3331 		if (ipsec_mp == NULL) {
3332 			freemsg(mp);
3333 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3334 			return;
3335 		}
3336 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3337 
3338 		/* This is not a secure packet */
3339 		ii->ipsec_in_secure = B_FALSE;
3340 		/*
3341 		 * For trusted extensions using a shared IP address we can
3342 		 * send using any zoneid.
3343 		 */
3344 		if (zoneid == ALL_ZONES)
3345 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3346 		else
3347 			ii->ipsec_in_zoneid = zoneid;
3348 		ipsec_mp->b_cont = mp;
3349 		ipha = (ipha_t *)mp->b_rptr;
3350 		/*
3351 		 * Convert the IPSEC_IN to IPSEC_OUT.
3352 		 */
3353 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3354 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3355 			return;
3356 		}
3357 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3358 	}
3359 
3360 	/* Remember our eventual destination */
3361 	dst = ipha->ipha_src;
3362 
3363 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3364 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3365 	if (ire != NULL &&
3366 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3367 		src = ipha->ipha_dst;
3368 	} else {
3369 		if (ire != NULL)
3370 			ire_refrele(ire);
3371 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3372 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3373 		    ipst);
3374 		if (ire == NULL) {
3375 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3376 			freemsg(ipsec_mp);
3377 			return;
3378 		}
3379 		src = ire->ire_src_addr;
3380 	}
3381 
3382 	if (ire != NULL)
3383 		ire_refrele(ire);
3384 
3385 	/*
3386 	 * Check if we can send back more then 8 bytes in addition to
3387 	 * the IP header.  We try to send 64 bytes of data and the internal
3388 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3389 	 */
3390 	len_needed = IPH_HDR_LENGTH(ipha);
3391 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3392 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3393 
3394 		if (!pullupmsg(mp, -1)) {
3395 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3396 			freemsg(ipsec_mp);
3397 			return;
3398 		}
3399 		ipha = (ipha_t *)mp->b_rptr;
3400 
3401 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3402 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3403 			    len_needed));
3404 		} else {
3405 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3406 
3407 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3408 			len_needed += ip_hdr_length_v6(mp, ip6h);
3409 		}
3410 	}
3411 	len_needed += ipst->ips_ip_icmp_return;
3412 	msg_len = msgdsize(mp);
3413 	if (msg_len > len_needed) {
3414 		(void) adjmsg(mp, len_needed - msg_len);
3415 		msg_len = len_needed;
3416 	}
3417 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3418 	if (mp1 == NULL) {
3419 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3420 		freemsg(ipsec_mp);
3421 		return;
3422 	}
3423 	mp1->b_cont = mp;
3424 	mp = mp1;
3425 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3426 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3427 	    io->ipsec_out_type == IPSEC_OUT);
3428 	ipsec_mp->b_cont = mp;
3429 
3430 	/*
3431 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3432 	 * node generates be accepted in peace by all on-host destinations.
3433 	 * If we do NOT assume that all on-host destinations trust
3434 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3435 	 * (Look for ipsec_out_icmp_loopback).
3436 	 */
3437 	io->ipsec_out_icmp_loopback = B_TRUE;
3438 
3439 	ipha = (ipha_t *)mp->b_rptr;
3440 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3441 	*ipha = icmp_ipha;
3442 	ipha->ipha_src = src;
3443 	ipha->ipha_dst = dst;
3444 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3445 	msg_len += sizeof (icmp_ipha) + len;
3446 	if (msg_len > IP_MAXPACKET) {
3447 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3448 		msg_len = IP_MAXPACKET;
3449 	}
3450 	ipha->ipha_length = htons((uint16_t)msg_len);
3451 	icmph = (icmph_t *)&ipha[1];
3452 	bcopy(stuff, icmph, len);
3453 	icmph->icmph_checksum = 0;
3454 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3455 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3456 	put(q, ipsec_mp);
3457 }
3458 
3459 /*
3460  * Determine if an ICMP error packet can be sent given the rate limit.
3461  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3462  * in milliseconds) and a burst size. Burst size number of packets can
3463  * be sent arbitrarely closely spaced.
3464  * The state is tracked using two variables to implement an approximate
3465  * token bucket filter:
3466  *	icmp_pkt_err_last - lbolt value when the last burst started
3467  *	icmp_pkt_err_sent - number of packets sent in current burst
3468  */
3469 boolean_t
3470 icmp_err_rate_limit(ip_stack_t *ipst)
3471 {
3472 	clock_t now = TICK_TO_MSEC(lbolt);
3473 	uint_t refilled; /* Number of packets refilled in tbf since last */
3474 	/* Guard against changes by loading into local variable */
3475 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3476 
3477 	if (err_interval == 0)
3478 		return (B_FALSE);
3479 
3480 	if (ipst->ips_icmp_pkt_err_last > now) {
3481 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3482 		ipst->ips_icmp_pkt_err_last = 0;
3483 		ipst->ips_icmp_pkt_err_sent = 0;
3484 	}
3485 	/*
3486 	 * If we are in a burst update the token bucket filter.
3487 	 * Update the "last" time to be close to "now" but make sure
3488 	 * we don't loose precision.
3489 	 */
3490 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3491 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3492 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3493 			ipst->ips_icmp_pkt_err_sent = 0;
3494 		} else {
3495 			ipst->ips_icmp_pkt_err_sent -= refilled;
3496 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3497 		}
3498 	}
3499 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3500 		/* Start of new burst */
3501 		ipst->ips_icmp_pkt_err_last = now;
3502 	}
3503 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3504 		ipst->ips_icmp_pkt_err_sent++;
3505 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3506 		    ipst->ips_icmp_pkt_err_sent));
3507 		return (B_FALSE);
3508 	}
3509 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3510 	return (B_TRUE);
3511 }
3512 
3513 /*
3514  * Check if it is ok to send an IPv4 ICMP error packet in
3515  * response to the IPv4 packet in mp.
3516  * Free the message and return null if no
3517  * ICMP error packet should be sent.
3518  */
3519 static mblk_t *
3520 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3521 {
3522 	icmph_t	*icmph;
3523 	ipha_t	*ipha;
3524 	uint_t	len_needed;
3525 	ire_t	*src_ire;
3526 	ire_t	*dst_ire;
3527 
3528 	if (!mp)
3529 		return (NULL);
3530 	ipha = (ipha_t *)mp->b_rptr;
3531 	if (ip_csum_hdr(ipha)) {
3532 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3533 		freemsg(mp);
3534 		return (NULL);
3535 	}
3536 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3537 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3538 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3539 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3540 	if (src_ire != NULL || dst_ire != NULL ||
3541 	    CLASSD(ipha->ipha_dst) ||
3542 	    CLASSD(ipha->ipha_src) ||
3543 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3544 		/* Note: only errors to the fragment with offset 0 */
3545 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3546 		freemsg(mp);
3547 		if (src_ire != NULL)
3548 			ire_refrele(src_ire);
3549 		if (dst_ire != NULL)
3550 			ire_refrele(dst_ire);
3551 		return (NULL);
3552 	}
3553 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3554 		/*
3555 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3556 		 * errors in response to any ICMP errors.
3557 		 */
3558 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3559 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3560 			if (!pullupmsg(mp, len_needed)) {
3561 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3562 				freemsg(mp);
3563 				return (NULL);
3564 			}
3565 			ipha = (ipha_t *)mp->b_rptr;
3566 		}
3567 		icmph = (icmph_t *)
3568 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3569 		switch (icmph->icmph_type) {
3570 		case ICMP_DEST_UNREACHABLE:
3571 		case ICMP_SOURCE_QUENCH:
3572 		case ICMP_TIME_EXCEEDED:
3573 		case ICMP_PARAM_PROBLEM:
3574 		case ICMP_REDIRECT:
3575 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3576 			freemsg(mp);
3577 			return (NULL);
3578 		default:
3579 			break;
3580 		}
3581 	}
3582 	/*
3583 	 * If this is a labeled system, then check to see if we're allowed to
3584 	 * send a response to this particular sender.  If not, then just drop.
3585 	 */
3586 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3587 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3588 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3589 		freemsg(mp);
3590 		return (NULL);
3591 	}
3592 	if (icmp_err_rate_limit(ipst)) {
3593 		/*
3594 		 * Only send ICMP error packets every so often.
3595 		 * This should be done on a per port/source basis,
3596 		 * but for now this will suffice.
3597 		 */
3598 		freemsg(mp);
3599 		return (NULL);
3600 	}
3601 	return (mp);
3602 }
3603 
3604 /*
3605  * Generate an ICMP redirect message.
3606  */
3607 static void
3608 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3609 {
3610 	icmph_t	icmph;
3611 
3612 	/*
3613 	 * We are called from ip_rput where we could
3614 	 * not have attached an IPSEC_IN.
3615 	 */
3616 	ASSERT(mp->b_datap->db_type == M_DATA);
3617 
3618 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3619 		return;
3620 	}
3621 
3622 	bzero(&icmph, sizeof (icmph_t));
3623 	icmph.icmph_type = ICMP_REDIRECT;
3624 	icmph.icmph_code = 1;
3625 	icmph.icmph_rd_gateway = gateway;
3626 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3627 	/* Redirects sent by router, and router is global zone */
3628 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3629 }
3630 
3631 /*
3632  * Generate an ICMP time exceeded message.
3633  */
3634 void
3635 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3636     ip_stack_t *ipst)
3637 {
3638 	icmph_t	icmph;
3639 	boolean_t mctl_present;
3640 	mblk_t *first_mp;
3641 
3642 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3643 
3644 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3645 		if (mctl_present)
3646 			freeb(first_mp);
3647 		return;
3648 	}
3649 
3650 	bzero(&icmph, sizeof (icmph_t));
3651 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3652 	icmph.icmph_code = code;
3653 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3654 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3655 	    ipst);
3656 }
3657 
3658 /*
3659  * Generate an ICMP unreachable message.
3660  */
3661 void
3662 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3663     ip_stack_t *ipst)
3664 {
3665 	icmph_t	icmph;
3666 	mblk_t *first_mp;
3667 	boolean_t mctl_present;
3668 
3669 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3670 
3671 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3672 		if (mctl_present)
3673 			freeb(first_mp);
3674 		return;
3675 	}
3676 
3677 	bzero(&icmph, sizeof (icmph_t));
3678 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3679 	icmph.icmph_code = code;
3680 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3681 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3682 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3683 	    zoneid, ipst);
3684 }
3685 
3686 /*
3687  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3688  * duplicate.  As long as someone else holds the address, the interface will
3689  * stay down.  When that conflict goes away, the interface is brought back up.
3690  * This is done so that accidental shutdowns of addresses aren't made
3691  * permanent.  Your server will recover from a failure.
3692  *
3693  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3694  * user space process (dhcpagent).
3695  *
3696  * Recovery completes if ARP reports that the address is now ours (via
3697  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3698  *
3699  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3700  */
3701 static void
3702 ipif_dup_recovery(void *arg)
3703 {
3704 	ipif_t *ipif = arg;
3705 	ill_t *ill = ipif->ipif_ill;
3706 	mblk_t *arp_add_mp;
3707 	mblk_t *arp_del_mp;
3708 	area_t *area;
3709 	ip_stack_t *ipst = ill->ill_ipst;
3710 
3711 	ipif->ipif_recovery_id = 0;
3712 
3713 	/*
3714 	 * No lock needed for moving or condemned check, as this is just an
3715 	 * optimization.
3716 	 */
3717 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3718 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3719 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3720 		/* No reason to try to bring this address back. */
3721 		return;
3722 	}
3723 
3724 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3725 		goto alloc_fail;
3726 
3727 	if (ipif->ipif_arp_del_mp == NULL) {
3728 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3729 			goto alloc_fail;
3730 		ipif->ipif_arp_del_mp = arp_del_mp;
3731 	}
3732 
3733 	/* Setting the 'unverified' flag restarts DAD */
3734 	area = (area_t *)arp_add_mp->b_rptr;
3735 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3736 	    ACE_F_UNVERIFIED;
3737 	putnext(ill->ill_rq, arp_add_mp);
3738 	return;
3739 
3740 alloc_fail:
3741 	/*
3742 	 * On allocation failure, just restart the timer.  Note that the ipif
3743 	 * is down here, so no other thread could be trying to start a recovery
3744 	 * timer.  The ill_lock protects the condemned flag and the recovery
3745 	 * timer ID.
3746 	 */
3747 	freemsg(arp_add_mp);
3748 	mutex_enter(&ill->ill_lock);
3749 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3750 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3751 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3752 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3753 	}
3754 	mutex_exit(&ill->ill_lock);
3755 }
3756 
3757 /*
3758  * This is for exclusive changes due to ARP.  Either tear down an interface due
3759  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3760  */
3761 /* ARGSUSED */
3762 static void
3763 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3764 {
3765 	ill_t	*ill = rq->q_ptr;
3766 	arh_t *arh;
3767 	ipaddr_t src;
3768 	ipif_t	*ipif;
3769 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3770 	char hbuf[MAC_STR_LEN];
3771 	char sbuf[INET_ADDRSTRLEN];
3772 	const char *failtype;
3773 	boolean_t bring_up;
3774 	ip_stack_t *ipst = ill->ill_ipst;
3775 
3776 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3777 	case AR_CN_READY:
3778 		failtype = NULL;
3779 		bring_up = B_TRUE;
3780 		break;
3781 	case AR_CN_FAILED:
3782 		failtype = "in use";
3783 		bring_up = B_FALSE;
3784 		break;
3785 	default:
3786 		failtype = "claimed";
3787 		bring_up = B_FALSE;
3788 		break;
3789 	}
3790 
3791 	arh = (arh_t *)mp->b_cont->b_rptr;
3792 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3793 
3794 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3795 	    sizeof (hbuf));
3796 	(void) ip_dot_addr(src, sbuf);
3797 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3798 
3799 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3800 		    ipif->ipif_lcl_addr != src) {
3801 			continue;
3802 		}
3803 
3804 		/*
3805 		 * If we failed on a recovery probe, then restart the timer to
3806 		 * try again later.
3807 		 */
3808 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3809 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3810 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3811 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3812 		    ipst->ips_ip_dup_recovery > 0 &&
3813 		    ipif->ipif_recovery_id == 0) {
3814 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3815 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3816 			continue;
3817 		}
3818 
3819 		/*
3820 		 * If what we're trying to do has already been done, then do
3821 		 * nothing.
3822 		 */
3823 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3824 			continue;
3825 
3826 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3827 
3828 		if (failtype == NULL) {
3829 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3830 			    ibuf);
3831 		} else {
3832 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3833 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3834 		}
3835 
3836 		if (bring_up) {
3837 			ASSERT(ill->ill_dl_up);
3838 			/*
3839 			 * Free up the ARP delete message so we can allocate
3840 			 * a fresh one through the normal path.
3841 			 */
3842 			freemsg(ipif->ipif_arp_del_mp);
3843 			ipif->ipif_arp_del_mp = NULL;
3844 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3845 			    EINPROGRESS) {
3846 				ipif->ipif_addr_ready = 1;
3847 				(void) ipif_up_done(ipif);
3848 			}
3849 			continue;
3850 		}
3851 
3852 		mutex_enter(&ill->ill_lock);
3853 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3854 		ipif->ipif_flags |= IPIF_DUPLICATE;
3855 		ill->ill_ipif_dup_count++;
3856 		mutex_exit(&ill->ill_lock);
3857 		/*
3858 		 * Already exclusive on the ill; no need to handle deferred
3859 		 * processing here.
3860 		 */
3861 		(void) ipif_down(ipif, NULL, NULL);
3862 		ipif_down_tail(ipif);
3863 		mutex_enter(&ill->ill_lock);
3864 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3865 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3866 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3867 		    ipst->ips_ip_dup_recovery > 0) {
3868 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3869 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3870 		}
3871 		mutex_exit(&ill->ill_lock);
3872 	}
3873 	freemsg(mp);
3874 }
3875 
3876 /* ARGSUSED */
3877 static void
3878 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3879 {
3880 	ill_t	*ill = rq->q_ptr;
3881 	arh_t *arh;
3882 	ipaddr_t src;
3883 	ipif_t	*ipif;
3884 
3885 	arh = (arh_t *)mp->b_cont->b_rptr;
3886 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3887 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3888 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3889 			(void) ipif_resolver_up(ipif, Res_act_defend);
3890 	}
3891 	freemsg(mp);
3892 }
3893 
3894 /*
3895  * News from ARP.  ARP sends notification of interesting events down
3896  * to its clients using M_CTL messages with the interesting ARP packet
3897  * attached via b_cont.
3898  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3899  * queue as opposed to ARP sending the message to all the clients, i.e. all
3900  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3901  * table if a cache IRE is found to delete all the entries for the address in
3902  * the packet.
3903  */
3904 static void
3905 ip_arp_news(queue_t *q, mblk_t *mp)
3906 {
3907 	arcn_t		*arcn;
3908 	arh_t		*arh;
3909 	ire_t		*ire = NULL;
3910 	char		hbuf[MAC_STR_LEN];
3911 	char		sbuf[INET_ADDRSTRLEN];
3912 	ipaddr_t	src;
3913 	in6_addr_t	v6src;
3914 	boolean_t	isv6 = B_FALSE;
3915 	ipif_t		*ipif;
3916 	ill_t		*ill;
3917 	ip_stack_t	*ipst;
3918 
3919 	if (CONN_Q(q)) {
3920 		conn_t *connp = Q_TO_CONN(q);
3921 
3922 		ipst = connp->conn_netstack->netstack_ip;
3923 	} else {
3924 		ill_t *ill = (ill_t *)q->q_ptr;
3925 
3926 		ipst = ill->ill_ipst;
3927 	}
3928 
3929 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3930 		if (q->q_next) {
3931 			putnext(q, mp);
3932 		} else
3933 			freemsg(mp);
3934 		return;
3935 	}
3936 	arh = (arh_t *)mp->b_cont->b_rptr;
3937 	/* Is it one we are interested in? */
3938 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3939 		isv6 = B_TRUE;
3940 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3941 		    IPV6_ADDR_LEN);
3942 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3943 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3944 		    IP_ADDR_LEN);
3945 	} else {
3946 		freemsg(mp);
3947 		return;
3948 	}
3949 
3950 	ill = q->q_ptr;
3951 
3952 	arcn = (arcn_t *)mp->b_rptr;
3953 	switch (arcn->arcn_code) {
3954 	case AR_CN_BOGON:
3955 		/*
3956 		 * Someone is sending ARP packets with a source protocol
3957 		 * address that we have published and for which we believe our
3958 		 * entry is authoritative and (when ill_arp_extend is set)
3959 		 * verified to be unique on the network.
3960 		 *
3961 		 * The ARP module internally handles the cases where the sender
3962 		 * is just probing (for DAD) and where the hardware address of
3963 		 * a non-authoritative entry has changed.  Thus, these are the
3964 		 * real conflicts, and we have to do resolution.
3965 		 *
3966 		 * We back away quickly from the address if it's from DHCP or
3967 		 * otherwise temporary and hasn't been used recently (or at
3968 		 * all).  We'd like to include "deprecated" addresses here as
3969 		 * well (as there's no real reason to defend something we're
3970 		 * discarding), but IPMP "reuses" this flag to mean something
3971 		 * other than the standard meaning.
3972 		 *
3973 		 * If the ARP module above is not extended (meaning that it
3974 		 * doesn't know how to defend the address), then we just log
3975 		 * the problem as we always did and continue on.  It's not
3976 		 * right, but there's little else we can do, and those old ATM
3977 		 * users are going away anyway.
3978 		 */
3979 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3980 		    hbuf, sizeof (hbuf));
3981 		(void) ip_dot_addr(src, sbuf);
3982 		if (isv6) {
3983 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3984 			    ipst);
3985 		} else {
3986 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3987 		}
3988 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3989 			uint32_t now;
3990 			uint32_t maxage;
3991 			clock_t lused;
3992 			uint_t maxdefense;
3993 			uint_t defs;
3994 
3995 			/*
3996 			 * First, figure out if this address hasn't been used
3997 			 * in a while.  If it hasn't, then it's a better
3998 			 * candidate for abandoning.
3999 			 */
4000 			ipif = ire->ire_ipif;
4001 			ASSERT(ipif != NULL);
4002 			now = gethrestime_sec();
4003 			maxage = now - ire->ire_create_time;
4004 			if (maxage > ipst->ips_ip_max_temp_idle)
4005 				maxage = ipst->ips_ip_max_temp_idle;
4006 			lused = drv_hztousec(ddi_get_lbolt() -
4007 			    ire->ire_last_used_time) / MICROSEC + 1;
4008 			if (lused >= maxage && (ipif->ipif_flags &
4009 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4010 				maxdefense = ipst->ips_ip_max_temp_defend;
4011 			else
4012 				maxdefense = ipst->ips_ip_max_defend;
4013 
4014 			/*
4015 			 * Now figure out how many times we've defended
4016 			 * ourselves.  Ignore defenses that happened long in
4017 			 * the past.
4018 			 */
4019 			mutex_enter(&ire->ire_lock);
4020 			if ((defs = ire->ire_defense_count) > 0 &&
4021 			    now - ire->ire_defense_time >
4022 			    ipst->ips_ip_defend_interval) {
4023 				ire->ire_defense_count = defs = 0;
4024 			}
4025 			ire->ire_defense_count++;
4026 			ire->ire_defense_time = now;
4027 			mutex_exit(&ire->ire_lock);
4028 			ill_refhold(ill);
4029 			ire_refrele(ire);
4030 
4031 			/*
4032 			 * If we've defended ourselves too many times already,
4033 			 * then give up and tear down the interface(s) using
4034 			 * this address.  Otherwise, defend by sending out a
4035 			 * gratuitous ARP.
4036 			 */
4037 			if (defs >= maxdefense && ill->ill_arp_extend) {
4038 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4039 				    B_FALSE);
4040 			} else {
4041 				cmn_err(CE_WARN,
4042 				    "node %s is using our IP address %s on %s",
4043 				    hbuf, sbuf, ill->ill_name);
4044 				/*
4045 				 * If this is an old (ATM) ARP module, then
4046 				 * don't try to defend the address.  Remain
4047 				 * compatible with the old behavior.  Defend
4048 				 * only with new ARP.
4049 				 */
4050 				if (ill->ill_arp_extend) {
4051 					qwriter_ip(ill, q, mp, ip_arp_defend,
4052 					    NEW_OP, B_FALSE);
4053 				} else {
4054 					ill_refrele(ill);
4055 				}
4056 			}
4057 			return;
4058 		}
4059 		cmn_err(CE_WARN,
4060 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4061 		    hbuf, sbuf, ill->ill_name);
4062 		if (ire != NULL)
4063 			ire_refrele(ire);
4064 		break;
4065 	case AR_CN_ANNOUNCE:
4066 		if (isv6) {
4067 			/*
4068 			 * For XRESOLV interfaces.
4069 			 * Delete the IRE cache entry and NCE for this
4070 			 * v6 address
4071 			 */
4072 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4073 			/*
4074 			 * If v6src is a non-zero, it's a router address
4075 			 * as below. Do the same sort of thing to clean
4076 			 * out off-net IRE_CACHE entries that go through
4077 			 * the router.
4078 			 */
4079 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4080 				ire_walk_v6(ire_delete_cache_gw_v6,
4081 				    (char *)&v6src, ALL_ZONES, ipst);
4082 			}
4083 		} else {
4084 			nce_hw_map_t hwm;
4085 
4086 			/*
4087 			 * ARP gives us a copy of any packet where it thinks
4088 			 * the address has changed, so that we can update our
4089 			 * caches.  We're responsible for caching known answers
4090 			 * in the current design.  We check whether the
4091 			 * hardware address really has changed in all of our
4092 			 * entries that have cached this mapping, and if so, we
4093 			 * blow them away.  This way we will immediately pick
4094 			 * up the rare case of a host changing hardware
4095 			 * address.
4096 			 */
4097 			if (src == 0)
4098 				break;
4099 			hwm.hwm_addr = src;
4100 			hwm.hwm_hwlen = arh->arh_hlen;
4101 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4102 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4103 			ndp_walk_common(ipst->ips_ndp4, NULL,
4104 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4105 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4106 		}
4107 		break;
4108 	case AR_CN_READY:
4109 		/* No external v6 resolver has a contract to use this */
4110 		if (isv6)
4111 			break;
4112 		/* If the link is down, we'll retry this later */
4113 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4114 			break;
4115 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4116 		    NULL, NULL, ipst);
4117 		if (ipif != NULL) {
4118 			/*
4119 			 * If this is a duplicate recovery, then we now need to
4120 			 * go exclusive to bring this thing back up.
4121 			 */
4122 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4123 			    IPIF_DUPLICATE) {
4124 				ipif_refrele(ipif);
4125 				ill_refhold(ill);
4126 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4127 				    B_FALSE);
4128 				return;
4129 			}
4130 			/*
4131 			 * If this is the first notice that this address is
4132 			 * ready, then let the user know now.
4133 			 */
4134 			if ((ipif->ipif_flags & IPIF_UP) &&
4135 			    !ipif->ipif_addr_ready) {
4136 				ipif_mask_reply(ipif);
4137 				ip_rts_ifmsg(ipif);
4138 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4139 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4140 			}
4141 			ipif->ipif_addr_ready = 1;
4142 			ipif_refrele(ipif);
4143 		}
4144 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4145 		if (ire != NULL) {
4146 			ire->ire_defense_count = 0;
4147 			ire_refrele(ire);
4148 		}
4149 		break;
4150 	case AR_CN_FAILED:
4151 		/* No external v6 resolver has a contract to use this */
4152 		if (isv6)
4153 			break;
4154 		ill_refhold(ill);
4155 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4156 		return;
4157 	}
4158 	freemsg(mp);
4159 }
4160 
4161 /*
4162  * Create a mblk suitable for carrying the interface index and/or source link
4163  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4164  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4165  * application.
4166  */
4167 mblk_t *
4168 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4169     ip_stack_t *ipst)
4170 {
4171 	mblk_t		*mp;
4172 	ip_pktinfo_t	*pinfo;
4173 	ipha_t *ipha;
4174 	struct ether_header *pether;
4175 
4176 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4177 	if (mp == NULL) {
4178 		ip1dbg(("ip_add_info: allocation failure.\n"));
4179 		return (data_mp);
4180 	}
4181 
4182 	ipha	= (ipha_t *)data_mp->b_rptr;
4183 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4184 	bzero(pinfo, sizeof (ip_pktinfo_t));
4185 	pinfo->ip_pkt_flags = (uchar_t)flags;
4186 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4187 
4188 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4189 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4190 	if (flags & IPF_RECVADDR) {
4191 		ipif_t	*ipif;
4192 		ire_t	*ire;
4193 
4194 		/*
4195 		 * Only valid for V4
4196 		 */
4197 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4198 		    (IPV4_VERSION << 4));
4199 
4200 		ipif = ipif_get_next_ipif(NULL, ill);
4201 		if (ipif != NULL) {
4202 			/*
4203 			 * Since a decision has already been made to deliver the
4204 			 * packet, there is no need to test for SECATTR and
4205 			 * ZONEONLY.
4206 			 * When a multicast packet is transmitted
4207 			 * a cache entry is created for the multicast address.
4208 			 * When delivering a copy of the packet or when new
4209 			 * packets are received we do not want to match on the
4210 			 * cached entry so explicitly match on
4211 			 * IRE_LOCAL and IRE_LOOPBACK
4212 			 */
4213 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4214 			    IRE_LOCAL | IRE_LOOPBACK,
4215 			    ipif, zoneid, NULL,
4216 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4217 			if (ire == NULL) {
4218 				/*
4219 				 * packet must have come on a different
4220 				 * interface.
4221 				 * Since a decision has already been made to
4222 				 * deliver the packet, there is no need to test
4223 				 * for SECATTR and ZONEONLY.
4224 				 * Only match on local and broadcast ire's.
4225 				 * See detailed comment above.
4226 				 */
4227 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4228 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4229 				    NULL, MATCH_IRE_TYPE, ipst);
4230 			}
4231 
4232 			if (ire == NULL) {
4233 				/*
4234 				 * This is either a multicast packet or
4235 				 * the address has been removed since
4236 				 * the packet was received.
4237 				 * Return INADDR_ANY so that normal source
4238 				 * selection occurs for the response.
4239 				 */
4240 
4241 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4242 			} else {
4243 				pinfo->ip_pkt_match_addr.s_addr =
4244 				    ire->ire_src_addr;
4245 				ire_refrele(ire);
4246 			}
4247 			ipif_refrele(ipif);
4248 		} else {
4249 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4250 		}
4251 	}
4252 
4253 	pether = (struct ether_header *)((char *)ipha
4254 	    - sizeof (struct ether_header));
4255 	/*
4256 	 * Make sure the interface is an ethernet type, since this option
4257 	 * is currently supported only on this type of interface. Also make
4258 	 * sure we are pointing correctly above db_base.
4259 	 */
4260 
4261 	if ((flags & IPF_RECVSLLA) &&
4262 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4263 	    (ill->ill_type == IFT_ETHER) &&
4264 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4265 
4266 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4267 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4268 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4269 	} else {
4270 		/*
4271 		 * Clear the bit. Indicate to upper layer that IP is not
4272 		 * sending this ancillary info.
4273 		 */
4274 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4275 	}
4276 
4277 	mp->b_datap->db_type = M_CTL;
4278 	mp->b_wptr += sizeof (ip_pktinfo_t);
4279 	mp->b_cont = data_mp;
4280 
4281 	return (mp);
4282 }
4283 
4284 /*
4285  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4286  * part of the bind request.
4287  */
4288 
4289 boolean_t
4290 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4291 {
4292 	ipsec_in_t *ii;
4293 
4294 	ASSERT(policy_mp != NULL);
4295 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4296 
4297 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4298 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4299 
4300 	connp->conn_policy = ii->ipsec_in_policy;
4301 	ii->ipsec_in_policy = NULL;
4302 
4303 	if (ii->ipsec_in_action != NULL) {
4304 		if (connp->conn_latch == NULL) {
4305 			connp->conn_latch = iplatch_create();
4306 			if (connp->conn_latch == NULL)
4307 				return (B_FALSE);
4308 		}
4309 		ipsec_latch_inbound(connp->conn_latch, ii);
4310 	}
4311 	return (B_TRUE);
4312 }
4313 
4314 /*
4315  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4316  * and to arrange for power-fanout assist.  The ULP is identified by
4317  * adding a single byte at the end of the original bind message.
4318  * A ULP other than UDP or TCP that wishes to be recognized passes
4319  * down a bind with a zero length address.
4320  *
4321  * The binding works as follows:
4322  * - A zero byte address means just bind to the protocol.
4323  * - A four byte address is treated as a request to validate
4324  *   that the address is a valid local address, appropriate for
4325  *   an application to bind to. This does not affect any fanout
4326  *   information in IP.
4327  * - A sizeof sin_t byte address is used to bind to only the local address
4328  *   and port.
4329  * - A sizeof ipa_conn_t byte address contains complete fanout information
4330  *   consisting of local and remote addresses and ports.  In
4331  *   this case, the addresses are both validated as appropriate
4332  *   for this operation, and, if so, the information is retained
4333  *   for use in the inbound fanout.
4334  *
4335  * The ULP (except in the zero-length bind) can append an
4336  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4337  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4338  * a copy of the source or destination IRE (source for local bind;
4339  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4340  * policy information contained should be copied on to the conn.
4341  *
4342  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4343  */
4344 mblk_t *
4345 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4346 {
4347 	ssize_t		len;
4348 	struct T_bind_req	*tbr;
4349 	sin_t		*sin;
4350 	ipa_conn_t	*ac;
4351 	uchar_t		*ucp;
4352 	mblk_t		*mp1;
4353 	boolean_t	ire_requested;
4354 	boolean_t	ipsec_policy_set = B_FALSE;
4355 	int		error = 0;
4356 	int		protocol;
4357 	ipa_conn_x_t	*acx;
4358 
4359 	ASSERT(!connp->conn_af_isv6);
4360 	connp->conn_pkt_isv6 = B_FALSE;
4361 
4362 	len = MBLKL(mp);
4363 	if (len < (sizeof (*tbr) + 1)) {
4364 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4365 		    "ip_bind: bogus msg, len %ld", len);
4366 		/* XXX: Need to return something better */
4367 		goto bad_addr;
4368 	}
4369 	/* Back up and extract the protocol identifier. */
4370 	mp->b_wptr--;
4371 	protocol = *mp->b_wptr & 0xFF;
4372 	tbr = (struct T_bind_req *)mp->b_rptr;
4373 	/* Reset the message type in preparation for shipping it back. */
4374 	DB_TYPE(mp) = M_PCPROTO;
4375 
4376 	connp->conn_ulp = (uint8_t)protocol;
4377 
4378 	/*
4379 	 * Check for a zero length address.  This is from a protocol that
4380 	 * wants to register to receive all packets of its type.
4381 	 */
4382 	if (tbr->ADDR_length == 0) {
4383 		/*
4384 		 * These protocols are now intercepted in ip_bind_v6().
4385 		 * Reject protocol-level binds here for now.
4386 		 *
4387 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4388 		 * so that the protocol type cannot be SCTP.
4389 		 */
4390 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4391 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4392 			goto bad_addr;
4393 		}
4394 
4395 		/*
4396 		 *
4397 		 * The udp module never sends down a zero-length address,
4398 		 * and allowing this on a labeled system will break MLP
4399 		 * functionality.
4400 		 */
4401 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4402 			goto bad_addr;
4403 
4404 		if (connp->conn_mac_exempt)
4405 			goto bad_addr;
4406 
4407 		/* No hash here really.  The table is big enough. */
4408 		connp->conn_srcv6 = ipv6_all_zeros;
4409 
4410 		ipcl_proto_insert(connp, protocol);
4411 
4412 		tbr->PRIM_type = T_BIND_ACK;
4413 		return (mp);
4414 	}
4415 
4416 	/* Extract the address pointer from the message. */
4417 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4418 	    tbr->ADDR_length);
4419 	if (ucp == NULL) {
4420 		ip1dbg(("ip_bind: no address\n"));
4421 		goto bad_addr;
4422 	}
4423 	if (!OK_32PTR(ucp)) {
4424 		ip1dbg(("ip_bind: unaligned address\n"));
4425 		goto bad_addr;
4426 	}
4427 	/*
4428 	 * Check for trailing mps.
4429 	 */
4430 
4431 	mp1 = mp->b_cont;
4432 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4433 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4434 
4435 	switch (tbr->ADDR_length) {
4436 	default:
4437 		ip1dbg(("ip_bind: bad address length %d\n",
4438 		    (int)tbr->ADDR_length));
4439 		goto bad_addr;
4440 
4441 	case IP_ADDR_LEN:
4442 		/* Verification of local address only */
4443 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4444 		    ire_requested, ipsec_policy_set, B_FALSE);
4445 		break;
4446 
4447 	case sizeof (sin_t):
4448 		sin = (sin_t *)ucp;
4449 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4450 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4451 		break;
4452 
4453 	case sizeof (ipa_conn_t):
4454 		ac = (ipa_conn_t *)ucp;
4455 		/* For raw socket, the local port is not set. */
4456 		if (ac->ac_lport == 0)
4457 			ac->ac_lport = connp->conn_lport;
4458 		/* Always verify destination reachability. */
4459 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4460 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4461 		    ipsec_policy_set, B_TRUE, B_TRUE);
4462 		break;
4463 
4464 	case sizeof (ipa_conn_x_t):
4465 		acx = (ipa_conn_x_t *)ucp;
4466 		/*
4467 		 * Whether or not to verify destination reachability depends
4468 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4469 		 */
4470 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4471 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4472 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4473 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4474 		break;
4475 	}
4476 	if (error == EINPROGRESS)
4477 		return (NULL);
4478 	else if (error != 0)
4479 		goto bad_addr;
4480 	/*
4481 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4482 	 * We can't do this in ip_bind_insert_ire because the policy
4483 	 * may not have been inherited at that point in time and hence
4484 	 * conn_out_enforce_policy may not be set.
4485 	 */
4486 	mp1 = mp->b_cont;
4487 	if (ire_requested && connp->conn_out_enforce_policy &&
4488 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4489 		ire_t *ire = (ire_t *)mp1->b_rptr;
4490 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4491 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4492 	}
4493 
4494 	/* Send it home. */
4495 	mp->b_datap->db_type = M_PCPROTO;
4496 	tbr->PRIM_type = T_BIND_ACK;
4497 	return (mp);
4498 
4499 bad_addr:
4500 	/*
4501 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4502 	 * a unix errno.
4503 	 */
4504 	if (error > 0)
4505 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4506 	else
4507 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4508 	return (mp);
4509 }
4510 
4511 /*
4512  * Here address is verified to be a valid local address.
4513  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4514  * address is also considered a valid local address.
4515  * In the case of a broadcast/multicast address, however, the
4516  * upper protocol is expected to reset the src address
4517  * to 0 if it sees a IRE_BROADCAST type returned so that
4518  * no packets are emitted with broadcast/multicast address as
4519  * source address (that violates hosts requirements RFC1122)
4520  * The addresses valid for bind are:
4521  *	(1) - INADDR_ANY (0)
4522  *	(2) - IP address of an UP interface
4523  *	(3) - IP address of a DOWN interface
4524  *	(4) - valid local IP broadcast addresses. In this case
4525  *	the conn will only receive packets destined to
4526  *	the specified broadcast address.
4527  *	(5) - a multicast address. In this case
4528  *	the conn will only receive packets destined to
4529  *	the specified multicast address. Note: the
4530  *	application still has to issue an
4531  *	IP_ADD_MEMBERSHIP socket option.
4532  *
4533  * On error, return -1 for TBADADDR otherwise pass the
4534  * errno with TSYSERR reply.
4535  *
4536  * In all the above cases, the bound address must be valid in the current zone.
4537  * When the address is loopback, multicast or broadcast, there might be many
4538  * matching IREs so bind has to look up based on the zone.
4539  *
4540  * Note: lport is in network byte order.
4541  */
4542 int
4543 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4544     boolean_t ire_requested, boolean_t ipsec_policy_set,
4545     boolean_t fanout_insert)
4546 {
4547 	int		error = 0;
4548 	ire_t		*src_ire;
4549 	mblk_t		*policy_mp;
4550 	ipif_t		*ipif;
4551 	zoneid_t	zoneid;
4552 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4553 
4554 	if (ipsec_policy_set) {
4555 		policy_mp = mp->b_cont;
4556 	}
4557 
4558 	/*
4559 	 * If it was previously connected, conn_fully_bound would have
4560 	 * been set.
4561 	 */
4562 	connp->conn_fully_bound = B_FALSE;
4563 
4564 	src_ire = NULL;
4565 	ipif = NULL;
4566 
4567 	zoneid = IPCL_ZONEID(connp);
4568 
4569 	if (src_addr) {
4570 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4571 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4572 		/*
4573 		 * If an address other than 0.0.0.0 is requested,
4574 		 * we verify that it is a valid address for bind
4575 		 * Note: Following code is in if-else-if form for
4576 		 * readability compared to a condition check.
4577 		 */
4578 		/* LINTED - statement has no consequent */
4579 		if (IRE_IS_LOCAL(src_ire)) {
4580 			/*
4581 			 * (2) Bind to address of local UP interface
4582 			 */
4583 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4584 			/*
4585 			 * (4) Bind to broadcast address
4586 			 * Note: permitted only from transports that
4587 			 * request IRE
4588 			 */
4589 			if (!ire_requested)
4590 				error = EADDRNOTAVAIL;
4591 		} else {
4592 			/*
4593 			 * (3) Bind to address of local DOWN interface
4594 			 * (ipif_lookup_addr() looks up all interfaces
4595 			 * but we do not get here for UP interfaces
4596 			 * - case (2) above)
4597 			 * We put the protocol byte back into the mblk
4598 			 * since we may come back via ip_wput_nondata()
4599 			 * later with this mblk if ipif_lookup_addr chooses
4600 			 * to defer processing.
4601 			 */
4602 			*mp->b_wptr++ = (char)connp->conn_ulp;
4603 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4604 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4605 			    &error, ipst)) != NULL) {
4606 				ipif_refrele(ipif);
4607 			} else if (error == EINPROGRESS) {
4608 				if (src_ire != NULL)
4609 					ire_refrele(src_ire);
4610 				return (EINPROGRESS);
4611 			} else if (CLASSD(src_addr)) {
4612 				error = 0;
4613 				if (src_ire != NULL)
4614 					ire_refrele(src_ire);
4615 				/*
4616 				 * (5) bind to multicast address.
4617 				 * Fake out the IRE returned to upper
4618 				 * layer to be a broadcast IRE.
4619 				 */
4620 				src_ire = ire_ctable_lookup(
4621 				    INADDR_BROADCAST, INADDR_ANY,
4622 				    IRE_BROADCAST, NULL, zoneid, NULL,
4623 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4624 				    ipst);
4625 				if (src_ire == NULL || !ire_requested)
4626 					error = EADDRNOTAVAIL;
4627 			} else {
4628 				/*
4629 				 * Not a valid address for bind
4630 				 */
4631 				error = EADDRNOTAVAIL;
4632 			}
4633 			/*
4634 			 * Just to keep it consistent with the processing in
4635 			 * ip_bind_v4()
4636 			 */
4637 			mp->b_wptr--;
4638 		}
4639 		if (error) {
4640 			/* Red Alert!  Attempting to be a bogon! */
4641 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4642 			    ntohl(src_addr)));
4643 			goto bad_addr;
4644 		}
4645 	}
4646 
4647 	/*
4648 	 * Allow setting new policies. For example, disconnects come
4649 	 * down as ipa_t bind. As we would have set conn_policy_cached
4650 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4651 	 * can change after the disconnect.
4652 	 */
4653 	connp->conn_policy_cached = B_FALSE;
4654 
4655 	/*
4656 	 * If not fanout_insert this was just an address verification
4657 	 */
4658 	if (fanout_insert) {
4659 		/*
4660 		 * The addresses have been verified. Time to insert in
4661 		 * the correct fanout list.
4662 		 */
4663 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4664 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4665 		connp->conn_lport = lport;
4666 		connp->conn_fport = 0;
4667 		/*
4668 		 * Do we need to add a check to reject Multicast packets
4669 		 */
4670 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4671 	}
4672 
4673 	if (error == 0) {
4674 		if (ire_requested) {
4675 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4676 				error = -1;
4677 				/* Falls through to bad_addr */
4678 			}
4679 		} else if (ipsec_policy_set) {
4680 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4681 				error = -1;
4682 				/* Falls through to bad_addr */
4683 			}
4684 		}
4685 	}
4686 bad_addr:
4687 	if (error != 0) {
4688 		if (connp->conn_anon_port) {
4689 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4690 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4691 			    B_FALSE);
4692 		}
4693 		connp->conn_mlp_type = mlptSingle;
4694 	}
4695 	if (src_ire != NULL)
4696 		IRE_REFRELE(src_ire);
4697 	if (ipsec_policy_set) {
4698 		ASSERT(policy_mp == mp->b_cont);
4699 		ASSERT(policy_mp != NULL);
4700 		freeb(policy_mp);
4701 		/*
4702 		 * As of now assume that nothing else accompanies
4703 		 * IPSEC_POLICY_SET.
4704 		 */
4705 		mp->b_cont = NULL;
4706 	}
4707 	return (error);
4708 }
4709 
4710 /*
4711  * Verify that both the source and destination addresses
4712  * are valid.  If verify_dst is false, then the destination address may be
4713  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4714  * destination reachability, while tunnels do not.
4715  * Note that we allow connect to broadcast and multicast
4716  * addresses when ire_requested is set. Thus the ULP
4717  * has to check for IRE_BROADCAST and multicast.
4718  *
4719  * Returns zero if ok.
4720  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4721  * (for use with TSYSERR reply).
4722  *
4723  * Note: lport and fport are in network byte order.
4724  */
4725 int
4726 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4727     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4728     boolean_t ire_requested, boolean_t ipsec_policy_set,
4729     boolean_t fanout_insert, boolean_t verify_dst)
4730 {
4731 	ire_t		*src_ire;
4732 	ire_t		*dst_ire;
4733 	int		error = 0;
4734 	int 		protocol;
4735 	mblk_t		*policy_mp;
4736 	ire_t		*sire = NULL;
4737 	ire_t		*md_dst_ire = NULL;
4738 	ire_t		*lso_dst_ire = NULL;
4739 	ill_t		*ill = NULL;
4740 	zoneid_t	zoneid;
4741 	ipaddr_t	src_addr = *src_addrp;
4742 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4743 
4744 	src_ire = dst_ire = NULL;
4745 	protocol = *mp->b_wptr & 0xFF;
4746 
4747 	/*
4748 	 * If we never got a disconnect before, clear it now.
4749 	 */
4750 	connp->conn_fully_bound = B_FALSE;
4751 
4752 	if (ipsec_policy_set) {
4753 		policy_mp = mp->b_cont;
4754 	}
4755 
4756 	zoneid = IPCL_ZONEID(connp);
4757 
4758 	if (CLASSD(dst_addr)) {
4759 		/* Pick up an IRE_BROADCAST */
4760 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4761 		    NULL, zoneid, MBLK_GETLABEL(mp),
4762 		    (MATCH_IRE_RECURSIVE |
4763 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4764 		    MATCH_IRE_SECATTR), ipst);
4765 	} else {
4766 		/*
4767 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4768 		 * and onlink ipif is not found set ENETUNREACH error.
4769 		 */
4770 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4771 			ipif_t *ipif;
4772 
4773 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4774 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4775 			if (ipif == NULL) {
4776 				error = ENETUNREACH;
4777 				goto bad_addr;
4778 			}
4779 			ipif_refrele(ipif);
4780 		}
4781 
4782 		if (connp->conn_nexthop_set) {
4783 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4784 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4785 			    MATCH_IRE_SECATTR, ipst);
4786 		} else {
4787 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4788 			    &sire, zoneid, MBLK_GETLABEL(mp),
4789 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4790 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4791 			    MATCH_IRE_SECATTR), ipst);
4792 		}
4793 	}
4794 	/*
4795 	 * dst_ire can't be a broadcast when not ire_requested.
4796 	 * We also prevent ire's with src address INADDR_ANY to
4797 	 * be used, which are created temporarily for
4798 	 * sending out packets from endpoints that have
4799 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4800 	 * reachable.  If verify_dst is false, the destination needn't be
4801 	 * reachable.
4802 	 *
4803 	 * If we match on a reject or black hole, then we've got a
4804 	 * local failure.  May as well fail out the connect() attempt,
4805 	 * since it's never going to succeed.
4806 	 */
4807 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4808 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4809 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4810 		/*
4811 		 * If we're verifying destination reachability, we always want
4812 		 * to complain here.
4813 		 *
4814 		 * If we're not verifying destination reachability but the
4815 		 * destination has a route, we still want to fail on the
4816 		 * temporary address and broadcast address tests.
4817 		 */
4818 		if (verify_dst || (dst_ire != NULL)) {
4819 			if (ip_debug > 2) {
4820 				pr_addr_dbg("ip_bind_connected: bad connected "
4821 				    "dst %s\n", AF_INET, &dst_addr);
4822 			}
4823 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4824 				error = ENETUNREACH;
4825 			else
4826 				error = EHOSTUNREACH;
4827 			goto bad_addr;
4828 		}
4829 	}
4830 
4831 	/*
4832 	 * We now know that routing will allow us to reach the destination.
4833 	 * Check whether Trusted Solaris policy allows communication with this
4834 	 * host, and pretend that the destination is unreachable if not.
4835 	 *
4836 	 * This is never a problem for TCP, since that transport is known to
4837 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4838 	 * handling.  If the remote is unreachable, it will be detected at that
4839 	 * point, so there's no reason to check it here.
4840 	 *
4841 	 * Note that for sendto (and other datagram-oriented friends), this
4842 	 * check is done as part of the data path label computation instead.
4843 	 * The check here is just to make non-TCP connect() report the right
4844 	 * error.
4845 	 */
4846 	if (dst_ire != NULL && is_system_labeled() &&
4847 	    !IPCL_IS_TCP(connp) &&
4848 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4849 	    connp->conn_mac_exempt, ipst) != 0) {
4850 		error = EHOSTUNREACH;
4851 		if (ip_debug > 2) {
4852 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4853 			    AF_INET, &dst_addr);
4854 		}
4855 		goto bad_addr;
4856 	}
4857 
4858 	/*
4859 	 * If the app does a connect(), it means that it will most likely
4860 	 * send more than 1 packet to the destination.  It makes sense
4861 	 * to clear the temporary flag.
4862 	 */
4863 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4864 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4865 		irb_t *irb = dst_ire->ire_bucket;
4866 
4867 		rw_enter(&irb->irb_lock, RW_WRITER);
4868 		/*
4869 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4870 		 * the lock to guarantee irb_tmp_ire_cnt.
4871 		 */
4872 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4873 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4874 			irb->irb_tmp_ire_cnt--;
4875 		}
4876 		rw_exit(&irb->irb_lock);
4877 	}
4878 
4879 	/*
4880 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4881 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4882 	 * eligibility tests for passive connects are handled separately
4883 	 * through tcp_adapt_ire().  We do this before the source address
4884 	 * selection, because dst_ire may change after a call to
4885 	 * ipif_select_source().  This is a best-effort check, as the
4886 	 * packet for this connection may not actually go through
4887 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4888 	 * calling ip_newroute().  This is why we further check on the
4889 	 * IRE during LSO/Multidata packet transmission in
4890 	 * tcp_lsosend()/tcp_multisend().
4891 	 */
4892 	if (!ipsec_policy_set && dst_ire != NULL &&
4893 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4894 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4895 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4896 			lso_dst_ire = dst_ire;
4897 			IRE_REFHOLD(lso_dst_ire);
4898 		} else if (ipst->ips_ip_multidata_outbound &&
4899 		    ILL_MDT_CAPABLE(ill)) {
4900 			md_dst_ire = dst_ire;
4901 			IRE_REFHOLD(md_dst_ire);
4902 		}
4903 	}
4904 
4905 	if (dst_ire != NULL &&
4906 	    dst_ire->ire_type == IRE_LOCAL &&
4907 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4908 		/*
4909 		 * If the IRE belongs to a different zone, look for a matching
4910 		 * route in the forwarding table and use the source address from
4911 		 * that route.
4912 		 */
4913 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4914 		    zoneid, 0, NULL,
4915 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4916 		    MATCH_IRE_RJ_BHOLE, ipst);
4917 		if (src_ire == NULL) {
4918 			error = EHOSTUNREACH;
4919 			goto bad_addr;
4920 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4921 			if (!(src_ire->ire_type & IRE_HOST))
4922 				error = ENETUNREACH;
4923 			else
4924 				error = EHOSTUNREACH;
4925 			goto bad_addr;
4926 		}
4927 		if (src_addr == INADDR_ANY)
4928 			src_addr = src_ire->ire_src_addr;
4929 		ire_refrele(src_ire);
4930 		src_ire = NULL;
4931 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4932 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4933 			src_addr = sire->ire_src_addr;
4934 			ire_refrele(dst_ire);
4935 			dst_ire = sire;
4936 			sire = NULL;
4937 		} else {
4938 			/*
4939 			 * Pick a source address so that a proper inbound
4940 			 * load spreading would happen.
4941 			 */
4942 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4943 			ipif_t *src_ipif = NULL;
4944 			ire_t *ipif_ire;
4945 
4946 			/*
4947 			 * Supply a local source address such that inbound
4948 			 * load spreading happens.
4949 			 *
4950 			 * Determine the best source address on this ill for
4951 			 * the destination.
4952 			 *
4953 			 * 1) For broadcast, we should return a broadcast ire
4954 			 *    found above so that upper layers know that the
4955 			 *    destination address is a broadcast address.
4956 			 *
4957 			 * 2) If this is part of a group, select a better
4958 			 *    source address so that better inbound load
4959 			 *    balancing happens. Do the same if the ipif
4960 			 *    is DEPRECATED.
4961 			 *
4962 			 * 3) If the outgoing interface is part of a usesrc
4963 			 *    group, then try selecting a source address from
4964 			 *    the usesrc ILL.
4965 			 */
4966 			if ((dst_ire->ire_zoneid != zoneid &&
4967 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4968 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4969 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4970 			    ((dst_ill->ill_group != NULL) ||
4971 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4972 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4973 				/*
4974 				 * If the destination is reachable via a
4975 				 * given gateway, the selected source address
4976 				 * should be in the same subnet as the gateway.
4977 				 * Otherwise, the destination is not reachable.
4978 				 *
4979 				 * If there are no interfaces on the same subnet
4980 				 * as the destination, ipif_select_source gives
4981 				 * first non-deprecated interface which might be
4982 				 * on a different subnet than the gateway.
4983 				 * This is not desirable. Hence pass the dst_ire
4984 				 * source address to ipif_select_source.
4985 				 * It is sure that the destination is reachable
4986 				 * with the dst_ire source address subnet.
4987 				 * So passing dst_ire source address to
4988 				 * ipif_select_source will make sure that the
4989 				 * selected source will be on the same subnet
4990 				 * as dst_ire source address.
4991 				 */
4992 				ipaddr_t saddr =
4993 				    dst_ire->ire_ipif->ipif_src_addr;
4994 				src_ipif = ipif_select_source(dst_ill,
4995 				    saddr, zoneid);
4996 				if (src_ipif != NULL) {
4997 					if (IS_VNI(src_ipif->ipif_ill)) {
4998 						/*
4999 						 * For VNI there is no
5000 						 * interface route
5001 						 */
5002 						src_addr =
5003 						    src_ipif->ipif_src_addr;
5004 					} else {
5005 						ipif_ire =
5006 						    ipif_to_ire(src_ipif);
5007 						if (ipif_ire != NULL) {
5008 							IRE_REFRELE(dst_ire);
5009 							dst_ire = ipif_ire;
5010 						}
5011 						src_addr =
5012 						    dst_ire->ire_src_addr;
5013 					}
5014 					ipif_refrele(src_ipif);
5015 				} else {
5016 					src_addr = dst_ire->ire_src_addr;
5017 				}
5018 			} else {
5019 				src_addr = dst_ire->ire_src_addr;
5020 			}
5021 		}
5022 	}
5023 
5024 	/*
5025 	 * We do ire_route_lookup() here (and not
5026 	 * interface lookup as we assert that
5027 	 * src_addr should only come from an
5028 	 * UP interface for hard binding.
5029 	 */
5030 	ASSERT(src_ire == NULL);
5031 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5032 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5033 	/* src_ire must be a local|loopback */
5034 	if (!IRE_IS_LOCAL(src_ire)) {
5035 		if (ip_debug > 2) {
5036 			pr_addr_dbg("ip_bind_connected: bad connected "
5037 			    "src %s\n", AF_INET, &src_addr);
5038 		}
5039 		error = EADDRNOTAVAIL;
5040 		goto bad_addr;
5041 	}
5042 
5043 	/*
5044 	 * If the source address is a loopback address, the
5045 	 * destination had best be local or multicast.
5046 	 * The transports that can't handle multicast will reject
5047 	 * those addresses.
5048 	 */
5049 	if (src_ire->ire_type == IRE_LOOPBACK &&
5050 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5051 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5052 		error = -1;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * Allow setting new policies. For example, disconnects come
5058 	 * down as ipa_t bind. As we would have set conn_policy_cached
5059 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5060 	 * can change after the disconnect.
5061 	 */
5062 	connp->conn_policy_cached = B_FALSE;
5063 
5064 	/*
5065 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5066 	 * can handle their passed-in conn's.
5067 	 */
5068 
5069 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5070 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5071 	connp->conn_lport = lport;
5072 	connp->conn_fport = fport;
5073 	*src_addrp = src_addr;
5074 
5075 	ASSERT(!(ipsec_policy_set && ire_requested));
5076 	if (ire_requested) {
5077 		iulp_t *ulp_info = NULL;
5078 
5079 		/*
5080 		 * Note that sire will not be NULL if this is an off-link
5081 		 * connection and there is not cache for that dest yet.
5082 		 *
5083 		 * XXX Because of an existing bug, if there are multiple
5084 		 * default routes, the IRE returned now may not be the actual
5085 		 * default route used (default routes are chosen in a
5086 		 * round robin fashion).  So if the metrics for different
5087 		 * default routes are different, we may return the wrong
5088 		 * metrics.  This will not be a problem if the existing
5089 		 * bug is fixed.
5090 		 */
5091 		if (sire != NULL) {
5092 			ulp_info = &(sire->ire_uinfo);
5093 		}
5094 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5095 			error = -1;
5096 			goto bad_addr;
5097 		}
5098 	} else if (ipsec_policy_set) {
5099 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5100 			error = -1;
5101 			goto bad_addr;
5102 		}
5103 	}
5104 
5105 	/*
5106 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5107 	 * we'll cache that.  If we don't, we'll inherit global policy.
5108 	 *
5109 	 * We can't insert until the conn reflects the policy. Note that
5110 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5111 	 * connections where we don't have a policy. This is to prevent
5112 	 * global policy lookups in the inbound path.
5113 	 *
5114 	 * If we insert before we set conn_policy_cached,
5115 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5116 	 * because global policy cound be non-empty. We normally call
5117 	 * ipsec_check_policy() for conn_policy_cached connections only if
5118 	 * ipc_in_enforce_policy is set. But in this case,
5119 	 * conn_policy_cached can get set anytime since we made the
5120 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5121 	 * called, which will make the above assumption false.  Thus, we
5122 	 * need to insert after we set conn_policy_cached.
5123 	 */
5124 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5125 		goto bad_addr;
5126 
5127 	if (fanout_insert) {
5128 		/*
5129 		 * The addresses have been verified. Time to insert in
5130 		 * the correct fanout list.
5131 		 */
5132 		error = ipcl_conn_insert(connp, protocol, src_addr,
5133 		    dst_addr, connp->conn_ports);
5134 	}
5135 
5136 	if (error == 0) {
5137 		connp->conn_fully_bound = B_TRUE;
5138 		/*
5139 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5140 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5141 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5142 		 * ip_xxinfo_return(), which performs further checks
5143 		 * against them and upon success, returns the LSO/MDT info
5144 		 * mblk which we will attach to the bind acknowledgment.
5145 		 */
5146 		if (lso_dst_ire != NULL) {
5147 			mblk_t *lsoinfo_mp;
5148 
5149 			ASSERT(ill->ill_lso_capab != NULL);
5150 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5151 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5152 				linkb(mp, lsoinfo_mp);
5153 		} else if (md_dst_ire != NULL) {
5154 			mblk_t *mdinfo_mp;
5155 
5156 			ASSERT(ill->ill_mdt_capab != NULL);
5157 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5158 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5159 				linkb(mp, mdinfo_mp);
5160 		}
5161 	}
5162 bad_addr:
5163 	if (ipsec_policy_set) {
5164 		ASSERT(policy_mp == mp->b_cont);
5165 		ASSERT(policy_mp != NULL);
5166 		freeb(policy_mp);
5167 		/*
5168 		 * As of now assume that nothing else accompanies
5169 		 * IPSEC_POLICY_SET.
5170 		 */
5171 		mp->b_cont = NULL;
5172 	}
5173 	if (src_ire != NULL)
5174 		IRE_REFRELE(src_ire);
5175 	if (dst_ire != NULL)
5176 		IRE_REFRELE(dst_ire);
5177 	if (sire != NULL)
5178 		IRE_REFRELE(sire);
5179 	if (md_dst_ire != NULL)
5180 		IRE_REFRELE(md_dst_ire);
5181 	if (lso_dst_ire != NULL)
5182 		IRE_REFRELE(lso_dst_ire);
5183 	return (error);
5184 }
5185 
5186 /*
5187  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5188  * Prefers dst_ire over src_ire.
5189  */
5190 static boolean_t
5191 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5192 {
5193 	mblk_t	*mp1;
5194 	ire_t *ret_ire = NULL;
5195 
5196 	mp1 = mp->b_cont;
5197 	ASSERT(mp1 != NULL);
5198 
5199 	if (ire != NULL) {
5200 		/*
5201 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5202 		 * appended mblk. Its <upper protocol>'s
5203 		 * job to make sure there is room.
5204 		 */
5205 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5206 			return (0);
5207 
5208 		mp1->b_datap->db_type = IRE_DB_TYPE;
5209 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5210 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5211 		ret_ire = (ire_t *)mp1->b_rptr;
5212 		/*
5213 		 * Pass the latest setting of the ip_path_mtu_discovery and
5214 		 * copy the ulp info if any.
5215 		 */
5216 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5217 		    IPH_DF : 0;
5218 		if (ulp_info != NULL) {
5219 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5220 			    sizeof (iulp_t));
5221 		}
5222 		ret_ire->ire_mp = mp1;
5223 	} else {
5224 		/*
5225 		 * No IRE was found. Remove IRE mblk.
5226 		 */
5227 		mp->b_cont = mp1->b_cont;
5228 		freeb(mp1);
5229 	}
5230 
5231 	return (1);
5232 }
5233 
5234 /*
5235  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5236  * the final piece where we don't.  Return a pointer to the first mblk in the
5237  * result, and update the pointer to the next mblk to chew on.  If anything
5238  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5239  * NULL pointer.
5240  */
5241 mblk_t *
5242 ip_carve_mp(mblk_t **mpp, ssize_t len)
5243 {
5244 	mblk_t	*mp0;
5245 	mblk_t	*mp1;
5246 	mblk_t	*mp2;
5247 
5248 	if (!len || !mpp || !(mp0 = *mpp))
5249 		return (NULL);
5250 	/* If we aren't going to consume the first mblk, we need a dup. */
5251 	if (mp0->b_wptr - mp0->b_rptr > len) {
5252 		mp1 = dupb(mp0);
5253 		if (mp1) {
5254 			/* Partition the data between the two mblks. */
5255 			mp1->b_wptr = mp1->b_rptr + len;
5256 			mp0->b_rptr = mp1->b_wptr;
5257 			/*
5258 			 * after adjustments if mblk not consumed is now
5259 			 * unaligned, try to align it. If this fails free
5260 			 * all messages and let upper layer recover.
5261 			 */
5262 			if (!OK_32PTR(mp0->b_rptr)) {
5263 				if (!pullupmsg(mp0, -1)) {
5264 					freemsg(mp0);
5265 					freemsg(mp1);
5266 					*mpp = NULL;
5267 					return (NULL);
5268 				}
5269 			}
5270 		}
5271 		return (mp1);
5272 	}
5273 	/* Eat through as many mblks as we need to get len bytes. */
5274 	len -= mp0->b_wptr - mp0->b_rptr;
5275 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5276 		if (mp2->b_wptr - mp2->b_rptr > len) {
5277 			/*
5278 			 * We won't consume the entire last mblk.  Like
5279 			 * above, dup and partition it.
5280 			 */
5281 			mp1->b_cont = dupb(mp2);
5282 			mp1 = mp1->b_cont;
5283 			if (!mp1) {
5284 				/*
5285 				 * Trouble.  Rather than go to a lot of
5286 				 * trouble to clean up, we free the messages.
5287 				 * This won't be any worse than losing it on
5288 				 * the wire.
5289 				 */
5290 				freemsg(mp0);
5291 				freemsg(mp2);
5292 				*mpp = NULL;
5293 				return (NULL);
5294 			}
5295 			mp1->b_wptr = mp1->b_rptr + len;
5296 			mp2->b_rptr = mp1->b_wptr;
5297 			/*
5298 			 * after adjustments if mblk not consumed is now
5299 			 * unaligned, try to align it. If this fails free
5300 			 * all messages and let upper layer recover.
5301 			 */
5302 			if (!OK_32PTR(mp2->b_rptr)) {
5303 				if (!pullupmsg(mp2, -1)) {
5304 					freemsg(mp0);
5305 					freemsg(mp2);
5306 					*mpp = NULL;
5307 					return (NULL);
5308 				}
5309 			}
5310 			*mpp = mp2;
5311 			return (mp0);
5312 		}
5313 		/* Decrement len by the amount we just got. */
5314 		len -= mp2->b_wptr - mp2->b_rptr;
5315 	}
5316 	/*
5317 	 * len should be reduced to zero now.  If not our caller has
5318 	 * screwed up.
5319 	 */
5320 	if (len) {
5321 		/* Shouldn't happen! */
5322 		freemsg(mp0);
5323 		*mpp = NULL;
5324 		return (NULL);
5325 	}
5326 	/*
5327 	 * We consumed up to exactly the end of an mblk.  Detach the part
5328 	 * we are returning from the rest of the chain.
5329 	 */
5330 	mp1->b_cont = NULL;
5331 	*mpp = mp2;
5332 	return (mp0);
5333 }
5334 
5335 /* The ill stream is being unplumbed. Called from ip_close */
5336 int
5337 ip_modclose(ill_t *ill)
5338 {
5339 	boolean_t success;
5340 	ipsq_t	*ipsq;
5341 	ipif_t	*ipif;
5342 	queue_t	*q = ill->ill_rq;
5343 	ip_stack_t	*ipst = ill->ill_ipst;
5344 	clock_t timeout;
5345 
5346 	/*
5347 	 * Wait for the ACKs of all deferred control messages to be processed.
5348 	 * In particular, we wait for a potential capability reset initiated
5349 	 * in ip_sioctl_plink() to complete before proceeding.
5350 	 *
5351 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5352 	 * in case the driver never replies.
5353 	 */
5354 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5355 	mutex_enter(&ill->ill_lock);
5356 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5357 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5358 			/* Timeout */
5359 			break;
5360 		}
5361 	}
5362 	mutex_exit(&ill->ill_lock);
5363 
5364 	/*
5365 	 * Forcibly enter the ipsq after some delay. This is to take
5366 	 * care of the case when some ioctl does not complete because
5367 	 * we sent a control message to the driver and it did not
5368 	 * send us a reply. We want to be able to at least unplumb
5369 	 * and replumb rather than force the user to reboot the system.
5370 	 */
5371 	success = ipsq_enter(ill, B_FALSE);
5372 
5373 	/*
5374 	 * Open/close/push/pop is guaranteed to be single threaded
5375 	 * per stream by STREAMS. FS guarantees that all references
5376 	 * from top are gone before close is called. So there can't
5377 	 * be another close thread that has set CONDEMNED on this ill.
5378 	 * and cause ipsq_enter to return failure.
5379 	 */
5380 	ASSERT(success);
5381 	ipsq = ill->ill_phyint->phyint_ipsq;
5382 
5383 	/*
5384 	 * Mark it condemned. No new reference will be made to this ill.
5385 	 * Lookup functions will return an error. Threads that try to
5386 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5387 	 * that the refcnt will drop down to zero.
5388 	 */
5389 	mutex_enter(&ill->ill_lock);
5390 	ill->ill_state_flags |= ILL_CONDEMNED;
5391 	for (ipif = ill->ill_ipif; ipif != NULL;
5392 	    ipif = ipif->ipif_next) {
5393 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5394 	}
5395 	/*
5396 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5397 	 * returns  error if ILL_CONDEMNED is set
5398 	 */
5399 	cv_broadcast(&ill->ill_cv);
5400 	mutex_exit(&ill->ill_lock);
5401 
5402 	/*
5403 	 * Send all the deferred DLPI messages downstream which came in
5404 	 * during the small window right before ipsq_enter(). We do this
5405 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5406 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5407 	 */
5408 	ill_dlpi_send_deferred(ill);
5409 
5410 	/*
5411 	 * Shut down fragmentation reassembly.
5412 	 * ill_frag_timer won't start a timer again.
5413 	 * Now cancel any existing timer
5414 	 */
5415 	(void) untimeout(ill->ill_frag_timer_id);
5416 	(void) ill_frag_timeout(ill, 0);
5417 
5418 	/*
5419 	 * If MOVE was in progress, clear the
5420 	 * move_in_progress fields also.
5421 	 */
5422 	if (ill->ill_move_in_progress) {
5423 		ILL_CLEAR_MOVE(ill);
5424 	}
5425 
5426 	/*
5427 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5428 	 * this ill. Then wait for the refcnts to drop to zero.
5429 	 * ill_is_freeable checks whether the ill is really quiescent.
5430 	 * Then make sure that threads that are waiting to enter the
5431 	 * ipsq have seen the error returned by ipsq_enter and have
5432 	 * gone away. Then we call ill_delete_tail which does the
5433 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5434 	 */
5435 	ill_delete(ill);
5436 	mutex_enter(&ill->ill_lock);
5437 	while (!ill_is_freeable(ill))
5438 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5439 	while (ill->ill_waiters)
5440 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5441 
5442 	mutex_exit(&ill->ill_lock);
5443 
5444 	/*
5445 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5446 	 * it held until the end of the function since the cleanup
5447 	 * below needs to be able to use the ip_stack_t.
5448 	 */
5449 	netstack_hold(ipst->ips_netstack);
5450 
5451 	/* qprocsoff is called in ill_delete_tail */
5452 	ill_delete_tail(ill);
5453 	ASSERT(ill->ill_ipst == NULL);
5454 
5455 	/*
5456 	 * Walk through all upper (conn) streams and qenable
5457 	 * those that have queued data.
5458 	 * close synchronization needs this to
5459 	 * be done to ensure that all upper layers blocked
5460 	 * due to flow control to the closing device
5461 	 * get unblocked.
5462 	 */
5463 	ip1dbg(("ip_wsrv: walking\n"));
5464 	conn_walk_drain(ipst);
5465 
5466 	mutex_enter(&ipst->ips_ip_mi_lock);
5467 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5468 	mutex_exit(&ipst->ips_ip_mi_lock);
5469 
5470 	/*
5471 	 * credp could be null if the open didn't succeed and ip_modopen
5472 	 * itself calls ip_close.
5473 	 */
5474 	if (ill->ill_credp != NULL)
5475 		crfree(ill->ill_credp);
5476 
5477 	mutex_enter(&ill->ill_lock);
5478 	ill_nic_info_dispatch(ill);
5479 	mutex_exit(&ill->ill_lock);
5480 
5481 	/*
5482 	 * Now we are done with the module close pieces that
5483 	 * need the netstack_t.
5484 	 */
5485 	netstack_rele(ipst->ips_netstack);
5486 
5487 	mi_close_free((IDP)ill);
5488 	q->q_ptr = WR(q)->q_ptr = NULL;
5489 
5490 	ipsq_exit(ipsq);
5491 
5492 	return (0);
5493 }
5494 
5495 /*
5496  * This is called as part of close() for IP, UDP, ICMP, and RTS
5497  * in order to quiesce the conn.
5498  */
5499 void
5500 ip_quiesce_conn(conn_t *connp)
5501 {
5502 	boolean_t	drain_cleanup_reqd = B_FALSE;
5503 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5504 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5505 	ip_stack_t	*ipst;
5506 
5507 	ASSERT(!IPCL_IS_TCP(connp));
5508 	ipst = connp->conn_netstack->netstack_ip;
5509 
5510 	/*
5511 	 * Mark the conn as closing, and this conn must not be
5512 	 * inserted in future into any list. Eg. conn_drain_insert(),
5513 	 * won't insert this conn into the conn_drain_list.
5514 	 * Similarly ill_pending_mp_add() will not add any mp to
5515 	 * the pending mp list, after this conn has started closing.
5516 	 *
5517 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5518 	 * cannot get set henceforth.
5519 	 */
5520 	mutex_enter(&connp->conn_lock);
5521 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5522 	connp->conn_state_flags |= CONN_CLOSING;
5523 	if (connp->conn_idl != NULL)
5524 		drain_cleanup_reqd = B_TRUE;
5525 	if (connp->conn_oper_pending_ill != NULL)
5526 		conn_ioctl_cleanup_reqd = B_TRUE;
5527 	if (connp->conn_dhcpinit_ill != NULL) {
5528 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5529 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5530 		connp->conn_dhcpinit_ill = NULL;
5531 	}
5532 	if (connp->conn_ilg_inuse != 0)
5533 		ilg_cleanup_reqd = B_TRUE;
5534 	mutex_exit(&connp->conn_lock);
5535 
5536 	if (conn_ioctl_cleanup_reqd)
5537 		conn_ioctl_cleanup(connp);
5538 
5539 	if (is_system_labeled() && connp->conn_anon_port) {
5540 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5541 		    connp->conn_mlp_type, connp->conn_ulp,
5542 		    ntohs(connp->conn_lport), B_FALSE);
5543 		connp->conn_anon_port = 0;
5544 	}
5545 	connp->conn_mlp_type = mlptSingle;
5546 
5547 	/*
5548 	 * Remove this conn from any fanout list it is on.
5549 	 * and then wait for any threads currently operating
5550 	 * on this endpoint to finish
5551 	 */
5552 	ipcl_hash_remove(connp);
5553 
5554 	/*
5555 	 * Remove this conn from the drain list, and do
5556 	 * any other cleanup that may be required.
5557 	 * (Only non-tcp streams may have a non-null conn_idl.
5558 	 * TCP streams are never flow controlled, and
5559 	 * conn_idl will be null)
5560 	 */
5561 	if (drain_cleanup_reqd)
5562 		conn_drain_tail(connp, B_TRUE);
5563 
5564 	if (connp == ipst->ips_ip_g_mrouter)
5565 		(void) ip_mrouter_done(NULL, ipst);
5566 
5567 	if (ilg_cleanup_reqd)
5568 		ilg_delete_all(connp);
5569 
5570 	conn_delete_ire(connp, NULL);
5571 
5572 	/*
5573 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5574 	 * callers from write side can't be there now because close
5575 	 * is in progress. The only other caller is ipcl_walk
5576 	 * which checks for the condemned flag.
5577 	 */
5578 	mutex_enter(&connp->conn_lock);
5579 	connp->conn_state_flags |= CONN_CONDEMNED;
5580 	while (connp->conn_ref != 1)
5581 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5582 	connp->conn_state_flags |= CONN_QUIESCED;
5583 	mutex_exit(&connp->conn_lock);
5584 }
5585 
5586 /* ARGSUSED */
5587 int
5588 ip_close(queue_t *q, int flags)
5589 {
5590 	conn_t		*connp;
5591 
5592 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5593 
5594 	/*
5595 	 * Call the appropriate delete routine depending on whether this is
5596 	 * a module or device.
5597 	 */
5598 	if (WR(q)->q_next != NULL) {
5599 		/* This is a module close */
5600 		return (ip_modclose((ill_t *)q->q_ptr));
5601 	}
5602 
5603 	connp = q->q_ptr;
5604 	ip_quiesce_conn(connp);
5605 
5606 	qprocsoff(q);
5607 
5608 	/*
5609 	 * Now we are truly single threaded on this stream, and can
5610 	 * delete the things hanging off the connp, and finally the connp.
5611 	 * We removed this connp from the fanout list, it cannot be
5612 	 * accessed thru the fanouts, and we already waited for the
5613 	 * conn_ref to drop to 0. We are already in close, so
5614 	 * there cannot be any other thread from the top. qprocsoff
5615 	 * has completed, and service has completed or won't run in
5616 	 * future.
5617 	 */
5618 	ASSERT(connp->conn_ref == 1);
5619 
5620 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5621 
5622 	connp->conn_ref--;
5623 	ipcl_conn_destroy(connp);
5624 
5625 	q->q_ptr = WR(q)->q_ptr = NULL;
5626 	return (0);
5627 }
5628 
5629 /*
5630  * Wapper around putnext() so that ip_rts_request can merely use
5631  * conn_recv.
5632  */
5633 /*ARGSUSED2*/
5634 static void
5635 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5636 {
5637 	conn_t *connp = (conn_t *)arg1;
5638 
5639 	putnext(connp->conn_rq, mp);
5640 }
5641 
5642 /* Return the IP checksum for the IP header at "iph". */
5643 uint16_t
5644 ip_csum_hdr(ipha_t *ipha)
5645 {
5646 	uint16_t	*uph;
5647 	uint32_t	sum;
5648 	int		opt_len;
5649 
5650 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5651 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5652 	uph = (uint16_t *)ipha;
5653 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5654 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5655 	if (opt_len > 0) {
5656 		do {
5657 			sum += uph[10];
5658 			sum += uph[11];
5659 			uph += 2;
5660 		} while (--opt_len);
5661 	}
5662 	sum = (sum & 0xFFFF) + (sum >> 16);
5663 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5664 	if (sum == 0xffff)
5665 		sum = 0;
5666 	return ((uint16_t)sum);
5667 }
5668 
5669 /*
5670  * Called when the module is about to be unloaded
5671  */
5672 void
5673 ip_ddi_destroy(void)
5674 {
5675 	tnet_fini();
5676 
5677 	icmp_ddi_destroy();
5678 	rts_ddi_destroy();
5679 	udp_ddi_destroy();
5680 	sctp_ddi_g_destroy();
5681 	tcp_ddi_g_destroy();
5682 	ipsec_policy_g_destroy();
5683 	ipcl_g_destroy();
5684 	ip_net_g_destroy();
5685 	ip_ire_g_fini();
5686 	inet_minor_destroy(ip_minor_arena_sa);
5687 #if defined(_LP64)
5688 	inet_minor_destroy(ip_minor_arena_la);
5689 #endif
5690 
5691 #ifdef DEBUG
5692 	list_destroy(&ip_thread_list);
5693 	rw_destroy(&ip_thread_rwlock);
5694 	tsd_destroy(&ip_thread_data);
5695 #endif
5696 
5697 	netstack_unregister(NS_IP);
5698 }
5699 
5700 /*
5701  * First step in cleanup.
5702  */
5703 /* ARGSUSED */
5704 static void
5705 ip_stack_shutdown(netstackid_t stackid, void *arg)
5706 {
5707 	ip_stack_t *ipst = (ip_stack_t *)arg;
5708 
5709 #ifdef NS_DEBUG
5710 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5711 #endif
5712 
5713 	/* Get rid of loopback interfaces and their IREs */
5714 	ip_loopback_cleanup(ipst);
5715 }
5716 
5717 /*
5718  * Free the IP stack instance.
5719  */
5720 static void
5721 ip_stack_fini(netstackid_t stackid, void *arg)
5722 {
5723 	ip_stack_t *ipst = (ip_stack_t *)arg;
5724 	int ret;
5725 
5726 #ifdef NS_DEBUG
5727 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5728 #endif
5729 	ipv4_hook_destroy(ipst);
5730 	ipv6_hook_destroy(ipst);
5731 	ip_net_destroy(ipst);
5732 
5733 	rw_destroy(&ipst->ips_srcid_lock);
5734 
5735 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5736 	ipst->ips_ip_mibkp = NULL;
5737 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5738 	ipst->ips_icmp_mibkp = NULL;
5739 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5740 	ipst->ips_ip_kstat = NULL;
5741 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5742 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5743 	ipst->ips_ip6_kstat = NULL;
5744 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5745 
5746 	nd_free(&ipst->ips_ip_g_nd);
5747 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5748 	ipst->ips_param_arr = NULL;
5749 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5750 	ipst->ips_ndp_arr = NULL;
5751 
5752 	ip_mrouter_stack_destroy(ipst);
5753 
5754 	mutex_destroy(&ipst->ips_ip_mi_lock);
5755 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5756 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5757 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5758 
5759 	ret = untimeout(ipst->ips_igmp_timeout_id);
5760 	if (ret == -1) {
5761 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5762 	} else {
5763 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5764 		ipst->ips_igmp_timeout_id = 0;
5765 	}
5766 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5767 	if (ret == -1) {
5768 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5769 	} else {
5770 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5771 		ipst->ips_igmp_slowtimeout_id = 0;
5772 	}
5773 	ret = untimeout(ipst->ips_mld_timeout_id);
5774 	if (ret == -1) {
5775 		ASSERT(ipst->ips_mld_timeout_id == 0);
5776 	} else {
5777 		ASSERT(ipst->ips_mld_timeout_id != 0);
5778 		ipst->ips_mld_timeout_id = 0;
5779 	}
5780 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5781 	if (ret == -1) {
5782 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5783 	} else {
5784 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5785 		ipst->ips_mld_slowtimeout_id = 0;
5786 	}
5787 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5788 	if (ret == -1) {
5789 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5790 	} else {
5791 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5792 		ipst->ips_ip_ire_expire_id = 0;
5793 	}
5794 
5795 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5796 	mutex_destroy(&ipst->ips_mld_timer_lock);
5797 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5798 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5799 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5800 	rw_destroy(&ipst->ips_ill_g_lock);
5801 
5802 	ip_ire_fini(ipst);
5803 	ip6_asp_free(ipst);
5804 	conn_drain_fini(ipst);
5805 	ipcl_destroy(ipst);
5806 
5807 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5808 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5809 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5810 	ipst->ips_ndp4 = NULL;
5811 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5812 	ipst->ips_ndp6 = NULL;
5813 
5814 	if (ipst->ips_loopback_ksp != NULL) {
5815 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5816 		ipst->ips_loopback_ksp = NULL;
5817 	}
5818 
5819 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5820 	ipst->ips_phyint_g_list = NULL;
5821 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5822 	ipst->ips_ill_g_heads = NULL;
5823 
5824 	kmem_free(ipst, sizeof (*ipst));
5825 }
5826 
5827 /*
5828  * This function is called from the TSD destructor, and is used to debug
5829  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5830  * details.
5831  */
5832 static void
5833 ip_thread_exit(void *phash)
5834 {
5835 	th_hash_t *thh = phash;
5836 
5837 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5838 	list_remove(&ip_thread_list, thh);
5839 	rw_exit(&ip_thread_rwlock);
5840 	mod_hash_destroy_hash(thh->thh_hash);
5841 	kmem_free(thh, sizeof (*thh));
5842 }
5843 
5844 /*
5845  * Called when the IP kernel module is loaded into the kernel
5846  */
5847 void
5848 ip_ddi_init(void)
5849 {
5850 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5851 
5852 	/*
5853 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5854 	 * initial devices: ip, ip6, tcp, tcp6.
5855 	 */
5856 	/*
5857 	 * If this is a 64-bit kernel, then create two separate arenas -
5858 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5859 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5860 	 */
5861 	ip_minor_arena_la = NULL;
5862 	ip_minor_arena_sa = NULL;
5863 #if defined(_LP64)
5864 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5865 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5866 		cmn_err(CE_PANIC,
5867 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5868 	}
5869 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5870 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5871 		cmn_err(CE_PANIC,
5872 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5873 	}
5874 #else
5875 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5876 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5877 		cmn_err(CE_PANIC,
5878 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5879 	}
5880 #endif
5881 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5882 
5883 	ipcl_g_init();
5884 	ip_ire_g_init();
5885 	ip_net_g_init();
5886 
5887 #ifdef DEBUG
5888 	tsd_create(&ip_thread_data, ip_thread_exit);
5889 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5890 	list_create(&ip_thread_list, sizeof (th_hash_t),
5891 	    offsetof(th_hash_t, thh_link));
5892 #endif
5893 
5894 	/*
5895 	 * We want to be informed each time a stack is created or
5896 	 * destroyed in the kernel, so we can maintain the
5897 	 * set of udp_stack_t's.
5898 	 */
5899 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5900 	    ip_stack_fini);
5901 
5902 	ipsec_policy_g_init();
5903 	tcp_ddi_g_init();
5904 	sctp_ddi_g_init();
5905 
5906 	tnet_init();
5907 
5908 	udp_ddi_init();
5909 	rts_ddi_init();
5910 	icmp_ddi_init();
5911 }
5912 
5913 /*
5914  * Initialize the IP stack instance.
5915  */
5916 static void *
5917 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5918 {
5919 	ip_stack_t	*ipst;
5920 	ipparam_t	*pa;
5921 	ipndp_t		*na;
5922 
5923 #ifdef NS_DEBUG
5924 	printf("ip_stack_init(stack %d)\n", stackid);
5925 #endif
5926 
5927 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5928 	ipst->ips_netstack = ns;
5929 
5930 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5931 	    KM_SLEEP);
5932 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5933 	    KM_SLEEP);
5934 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5935 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5936 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5937 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5938 
5939 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5940 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5941 	ipst->ips_igmp_deferred_next = INFINITY;
5942 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5943 	ipst->ips_mld_deferred_next = INFINITY;
5944 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5945 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5946 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5947 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5948 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5949 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5950 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5951 
5952 	ipcl_init(ipst);
5953 	ip_ire_init(ipst);
5954 	ip6_asp_init(ipst);
5955 	ipif_init(ipst);
5956 	conn_drain_init(ipst);
5957 	ip_mrouter_stack_init(ipst);
5958 
5959 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5960 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5961 
5962 	ipst->ips_ip_multirt_log_interval = 1000;
5963 
5964 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5965 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5966 	ipst->ips_ill_index = 1;
5967 
5968 	ipst->ips_saved_ip_g_forward = -1;
5969 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5970 
5971 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5972 	ipst->ips_param_arr = pa;
5973 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5974 
5975 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5976 	ipst->ips_ndp_arr = na;
5977 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5978 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5979 	    (caddr_t)&ipst->ips_ip_g_forward;
5980 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5981 	    (caddr_t)&ipst->ips_ipv6_forward;
5982 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5983 	    "ip_cgtp_filter") == 0);
5984 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5985 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5986 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5987 	    "ipmp_hook_emulation") == 0);
5988 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5989 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5990 
5991 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5992 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5993 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5994 
5995 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
5996 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
5997 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
5998 	ipst->ips_ip6_kstat =
5999 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6000 
6001 	ipst->ips_ipmp_enable_failback = B_TRUE;
6002 
6003 	ipst->ips_ip_src_id = 1;
6004 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6005 
6006 	ip_net_init(ipst, ns);
6007 	ipv4_hook_init(ipst);
6008 	ipv6_hook_init(ipst);
6009 
6010 	return (ipst);
6011 }
6012 
6013 /*
6014  * Allocate and initialize a DLPI template of the specified length.  (May be
6015  * called as writer.)
6016  */
6017 mblk_t *
6018 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6019 {
6020 	mblk_t	*mp;
6021 
6022 	mp = allocb(len, BPRI_MED);
6023 	if (!mp)
6024 		return (NULL);
6025 
6026 	/*
6027 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6028 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6029 	 * that other DLPI are M_PROTO.
6030 	 */
6031 	if (prim == DL_INFO_REQ) {
6032 		mp->b_datap->db_type = M_PCPROTO;
6033 	} else {
6034 		mp->b_datap->db_type = M_PROTO;
6035 	}
6036 
6037 	mp->b_wptr = mp->b_rptr + len;
6038 	bzero(mp->b_rptr, len);
6039 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6040 	return (mp);
6041 }
6042 
6043 /*
6044  * Debug formatting routine.  Returns a character string representation of the
6045  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6046  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6047  *
6048  * Once the ndd table-printing interfaces are removed, this can be changed to
6049  * standard dotted-decimal form.
6050  */
6051 char *
6052 ip_dot_addr(ipaddr_t addr, char *buf)
6053 {
6054 	uint8_t *ap = (uint8_t *)&addr;
6055 
6056 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6057 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6058 	return (buf);
6059 }
6060 
6061 /*
6062  * Write the given MAC address as a printable string in the usual colon-
6063  * separated format.
6064  */
6065 const char *
6066 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6067 {
6068 	char *bp;
6069 
6070 	if (alen == 0 || buflen < 4)
6071 		return ("?");
6072 	bp = buf;
6073 	for (;;) {
6074 		/*
6075 		 * If there are more MAC address bytes available, but we won't
6076 		 * have any room to print them, then add "..." to the string
6077 		 * instead.  See below for the 'magic number' explanation.
6078 		 */
6079 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6080 			(void) strcpy(bp, "...");
6081 			break;
6082 		}
6083 		(void) sprintf(bp, "%02x", *addr++);
6084 		bp += 2;
6085 		if (--alen == 0)
6086 			break;
6087 		*bp++ = ':';
6088 		buflen -= 3;
6089 		/*
6090 		 * At this point, based on the first 'if' statement above,
6091 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6092 		 * buflen >= 4.  The first case leaves room for the final "xx"
6093 		 * number and trailing NUL byte.  The second leaves room for at
6094 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6095 		 * that statement.
6096 		 */
6097 	}
6098 	return (buf);
6099 }
6100 
6101 /*
6102  * Send an ICMP error after patching up the packet appropriately.  Returns
6103  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6104  */
6105 static boolean_t
6106 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6107     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6108     zoneid_t zoneid, ip_stack_t *ipst)
6109 {
6110 	ipha_t *ipha;
6111 	mblk_t *first_mp;
6112 	boolean_t secure;
6113 	unsigned char db_type;
6114 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6115 
6116 	first_mp = mp;
6117 	if (mctl_present) {
6118 		mp = mp->b_cont;
6119 		secure = ipsec_in_is_secure(first_mp);
6120 		ASSERT(mp != NULL);
6121 	} else {
6122 		/*
6123 		 * If this is an ICMP error being reported - which goes
6124 		 * up as M_CTLs, we need to convert them to M_DATA till
6125 		 * we finish checking with global policy because
6126 		 * ipsec_check_global_policy() assumes M_DATA as clear
6127 		 * and M_CTL as secure.
6128 		 */
6129 		db_type = DB_TYPE(mp);
6130 		DB_TYPE(mp) = M_DATA;
6131 		secure = B_FALSE;
6132 	}
6133 	/*
6134 	 * We are generating an icmp error for some inbound packet.
6135 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6136 	 * Before we generate an error, check with global policy
6137 	 * to see whether this is allowed to enter the system. As
6138 	 * there is no "conn", we are checking with global policy.
6139 	 */
6140 	ipha = (ipha_t *)mp->b_rptr;
6141 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6142 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6143 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6144 		if (first_mp == NULL)
6145 			return (B_FALSE);
6146 	}
6147 
6148 	if (!mctl_present)
6149 		DB_TYPE(mp) = db_type;
6150 
6151 	if (flags & IP_FF_SEND_ICMP) {
6152 		if (flags & IP_FF_HDR_COMPLETE) {
6153 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6154 				freemsg(first_mp);
6155 				return (B_TRUE);
6156 			}
6157 		}
6158 		if (flags & IP_FF_CKSUM) {
6159 			/*
6160 			 * Have to correct checksum since
6161 			 * the packet might have been
6162 			 * fragmented and the reassembly code in ip_rput
6163 			 * does not restore the IP checksum.
6164 			 */
6165 			ipha->ipha_hdr_checksum = 0;
6166 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6167 		}
6168 		switch (icmp_type) {
6169 		case ICMP_DEST_UNREACHABLE:
6170 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6171 			    ipst);
6172 			break;
6173 		default:
6174 			freemsg(first_mp);
6175 			break;
6176 		}
6177 	} else {
6178 		freemsg(first_mp);
6179 		return (B_FALSE);
6180 	}
6181 
6182 	return (B_TRUE);
6183 }
6184 
6185 /*
6186  * Used to send an ICMP error message when a packet is received for
6187  * a protocol that is not supported. The mblk passed as argument
6188  * is consumed by this function.
6189  */
6190 void
6191 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6192     ip_stack_t *ipst)
6193 {
6194 	mblk_t *mp;
6195 	ipha_t *ipha;
6196 	ill_t *ill;
6197 	ipsec_in_t *ii;
6198 
6199 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6200 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6201 
6202 	mp = ipsec_mp->b_cont;
6203 	ipsec_mp->b_cont = NULL;
6204 	ipha = (ipha_t *)mp->b_rptr;
6205 	/* Get ill from index in ipsec_in_t. */
6206 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6207 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6208 	    ipst);
6209 	if (ill != NULL) {
6210 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6211 			if (ip_fanout_send_icmp(q, mp, flags,
6212 			    ICMP_DEST_UNREACHABLE,
6213 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6214 				BUMP_MIB(ill->ill_ip_mib,
6215 				    ipIfStatsInUnknownProtos);
6216 			}
6217 		} else {
6218 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6219 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6220 			    0, B_FALSE, zoneid, ipst)) {
6221 				BUMP_MIB(ill->ill_ip_mib,
6222 				    ipIfStatsInUnknownProtos);
6223 			}
6224 		}
6225 		ill_refrele(ill);
6226 	} else { /* re-link for the freemsg() below. */
6227 		ipsec_mp->b_cont = mp;
6228 	}
6229 
6230 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6231 	freemsg(ipsec_mp);
6232 }
6233 
6234 /*
6235  * See if the inbound datagram has had IPsec processing applied to it.
6236  */
6237 boolean_t
6238 ipsec_in_is_secure(mblk_t *ipsec_mp)
6239 {
6240 	ipsec_in_t *ii;
6241 
6242 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6243 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6244 
6245 	if (ii->ipsec_in_loopback) {
6246 		return (ii->ipsec_in_secure);
6247 	} else {
6248 		return (ii->ipsec_in_ah_sa != NULL ||
6249 		    ii->ipsec_in_esp_sa != NULL ||
6250 		    ii->ipsec_in_decaps);
6251 	}
6252 }
6253 
6254 /*
6255  * Handle protocols with which IP is less intimate.  There
6256  * can be more than one stream bound to a particular
6257  * protocol.  When this is the case, normally each one gets a copy
6258  * of any incoming packets.
6259  *
6260  * IPsec NOTE :
6261  *
6262  * Don't allow a secure packet going up a non-secure connection.
6263  * We don't allow this because
6264  *
6265  * 1) Reply might go out in clear which will be dropped at
6266  *    the sending side.
6267  * 2) If the reply goes out in clear it will give the
6268  *    adversary enough information for getting the key in
6269  *    most of the cases.
6270  *
6271  * Moreover getting a secure packet when we expect clear
6272  * implies that SA's were added without checking for
6273  * policy on both ends. This should not happen once ISAKMP
6274  * is used to negotiate SAs as SAs will be added only after
6275  * verifying the policy.
6276  *
6277  * NOTE : If the packet was tunneled and not multicast we only send
6278  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6279  * back to delivering packets to AF_INET6 raw sockets.
6280  *
6281  * IPQoS Notes:
6282  * Once we have determined the client, invoke IPPF processing.
6283  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6284  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6285  * ip_policy will be false.
6286  *
6287  * Zones notes:
6288  * Currently only applications in the global zone can create raw sockets for
6289  * protocols other than ICMP. So unlike the broadcast / multicast case of
6290  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6291  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6292  */
6293 static void
6294 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6295     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6296     zoneid_t zoneid)
6297 {
6298 	queue_t	*rq;
6299 	mblk_t	*mp1, *first_mp1;
6300 	uint_t	protocol = ipha->ipha_protocol;
6301 	ipaddr_t dst;
6302 	boolean_t one_only;
6303 	mblk_t *first_mp = mp;
6304 	boolean_t secure;
6305 	uint32_t ill_index;
6306 	conn_t	*connp, *first_connp, *next_connp;
6307 	connf_t	*connfp;
6308 	boolean_t shared_addr;
6309 	mib2_ipIfStatsEntry_t *mibptr;
6310 	ip_stack_t *ipst = recv_ill->ill_ipst;
6311 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6312 
6313 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6314 	if (mctl_present) {
6315 		mp = first_mp->b_cont;
6316 		secure = ipsec_in_is_secure(first_mp);
6317 		ASSERT(mp != NULL);
6318 	} else {
6319 		secure = B_FALSE;
6320 	}
6321 	dst = ipha->ipha_dst;
6322 	/*
6323 	 * If the packet was tunneled and not multicast we only send to it
6324 	 * the first match.
6325 	 */
6326 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6327 	    !CLASSD(dst));
6328 
6329 	shared_addr = (zoneid == ALL_ZONES);
6330 	if (shared_addr) {
6331 		/*
6332 		 * We don't allow multilevel ports for raw IP, so no need to
6333 		 * check for that here.
6334 		 */
6335 		zoneid = tsol_packet_to_zoneid(mp);
6336 	}
6337 
6338 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6339 	mutex_enter(&connfp->connf_lock);
6340 	connp = connfp->connf_head;
6341 	for (connp = connfp->connf_head; connp != NULL;
6342 	    connp = connp->conn_next) {
6343 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6344 		    zoneid) &&
6345 		    (!is_system_labeled() ||
6346 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6347 		    connp))) {
6348 			break;
6349 		}
6350 	}
6351 
6352 	if (connp == NULL || connp->conn_upq == NULL) {
6353 		/*
6354 		 * No one bound to these addresses.  Is
6355 		 * there a client that wants all
6356 		 * unclaimed datagrams?
6357 		 */
6358 		mutex_exit(&connfp->connf_lock);
6359 		/*
6360 		 * Check for IPPROTO_ENCAP...
6361 		 */
6362 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6363 			/*
6364 			 * If an IPsec mblk is here on a multicast
6365 			 * tunnel (using ip_mroute stuff), check policy here,
6366 			 * THEN ship off to ip_mroute_decap().
6367 			 *
6368 			 * BTW,  If I match a configured IP-in-IP
6369 			 * tunnel, this path will not be reached, and
6370 			 * ip_mroute_decap will never be called.
6371 			 */
6372 			first_mp = ipsec_check_global_policy(first_mp, connp,
6373 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6374 			if (first_mp != NULL) {
6375 				if (mctl_present)
6376 					freeb(first_mp);
6377 				ip_mroute_decap(q, mp, ill);
6378 			} /* Else we already freed everything! */
6379 		} else {
6380 			/*
6381 			 * Otherwise send an ICMP protocol unreachable.
6382 			 */
6383 			if (ip_fanout_send_icmp(q, first_mp, flags,
6384 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6385 			    mctl_present, zoneid, ipst)) {
6386 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6387 			}
6388 		}
6389 		return;
6390 	}
6391 	CONN_INC_REF(connp);
6392 	first_connp = connp;
6393 
6394 	/*
6395 	 * Only send message to one tunnel driver by immediately
6396 	 * terminating the loop.
6397 	 */
6398 	connp = one_only ? NULL : connp->conn_next;
6399 
6400 	for (;;) {
6401 		while (connp != NULL) {
6402 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6403 			    flags, zoneid) &&
6404 			    (!is_system_labeled() ||
6405 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6406 			    shared_addr, connp)))
6407 				break;
6408 			connp = connp->conn_next;
6409 		}
6410 
6411 		/*
6412 		 * Copy the packet.
6413 		 */
6414 		if (connp == NULL || connp->conn_upq == NULL ||
6415 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6416 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6417 			/*
6418 			 * No more interested clients or memory
6419 			 * allocation failed
6420 			 */
6421 			connp = first_connp;
6422 			break;
6423 		}
6424 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6425 		CONN_INC_REF(connp);
6426 		mutex_exit(&connfp->connf_lock);
6427 		rq = connp->conn_rq;
6428 		if (!canputnext(rq)) {
6429 			if (flags & IP_FF_RAWIP) {
6430 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6431 			} else {
6432 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6433 			}
6434 
6435 			freemsg(first_mp1);
6436 		} else {
6437 			/*
6438 			 * Don't enforce here if we're an actual tunnel -
6439 			 * let "tun" do it instead.
6440 			 */
6441 			if (!IPCL_IS_IPTUN(connp) &&
6442 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6443 			    secure)) {
6444 				first_mp1 = ipsec_check_inbound_policy
6445 				    (first_mp1, connp, ipha, NULL,
6446 				    mctl_present);
6447 			}
6448 			if (first_mp1 != NULL) {
6449 				int in_flags = 0;
6450 				/*
6451 				 * ip_fanout_proto also gets called from
6452 				 * icmp_inbound_error_fanout, in which case
6453 				 * the msg type is M_CTL.  Don't add info
6454 				 * in this case for the time being. In future
6455 				 * when there is a need for knowing the
6456 				 * inbound iface index for ICMP error msgs,
6457 				 * then this can be changed.
6458 				 */
6459 				if (connp->conn_recvif)
6460 					in_flags = IPF_RECVIF;
6461 				/*
6462 				 * The ULP may support IP_RECVPKTINFO for both
6463 				 * IP v4 and v6 so pass the appropriate argument
6464 				 * based on conn IP version.
6465 				 */
6466 				if (connp->conn_ip_recvpktinfo) {
6467 					if (connp->conn_af_isv6) {
6468 						/*
6469 						 * V6 only needs index
6470 						 */
6471 						in_flags |= IPF_RECVIF;
6472 					} else {
6473 						/*
6474 						 * V4 needs index +
6475 						 * matching address.
6476 						 */
6477 						in_flags |= IPF_RECVADDR;
6478 					}
6479 				}
6480 				if ((in_flags != 0) &&
6481 				    (mp->b_datap->db_type != M_CTL)) {
6482 					/*
6483 					 * the actual data will be
6484 					 * contained in b_cont upon
6485 					 * successful return of the
6486 					 * following call else
6487 					 * original mblk is returned
6488 					 */
6489 					ASSERT(recv_ill != NULL);
6490 					mp1 = ip_add_info(mp1, recv_ill,
6491 					    in_flags, IPCL_ZONEID(connp), ipst);
6492 				}
6493 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6494 				if (mctl_present)
6495 					freeb(first_mp1);
6496 				(connp->conn_recv)(connp, mp1, NULL);
6497 			}
6498 		}
6499 		mutex_enter(&connfp->connf_lock);
6500 		/* Follow the next pointer before releasing the conn. */
6501 		next_connp = connp->conn_next;
6502 		CONN_DEC_REF(connp);
6503 		connp = next_connp;
6504 	}
6505 
6506 	/* Last one.  Send it upstream. */
6507 	mutex_exit(&connfp->connf_lock);
6508 
6509 	/*
6510 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6511 	 * will be set to false.
6512 	 */
6513 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6514 		ill_index = ill->ill_phyint->phyint_ifindex;
6515 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6516 		if (mp == NULL) {
6517 			CONN_DEC_REF(connp);
6518 			if (mctl_present) {
6519 				freeb(first_mp);
6520 			}
6521 			return;
6522 		}
6523 	}
6524 
6525 	rq = connp->conn_rq;
6526 	if (!canputnext(rq)) {
6527 		if (flags & IP_FF_RAWIP) {
6528 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6529 		} else {
6530 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6531 		}
6532 
6533 		freemsg(first_mp);
6534 	} else {
6535 		if (IPCL_IS_IPTUN(connp)) {
6536 			/*
6537 			 * Tunneled packet.  We enforce policy in the tunnel
6538 			 * module itself.
6539 			 *
6540 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6541 			 * a policy check.
6542 			 * FIXME to use conn_recv for tun later.
6543 			 */
6544 			putnext(rq, first_mp);
6545 			CONN_DEC_REF(connp);
6546 			return;
6547 		}
6548 
6549 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6550 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6551 			    ipha, NULL, mctl_present);
6552 		}
6553 
6554 		if (first_mp != NULL) {
6555 			int in_flags = 0;
6556 
6557 			/*
6558 			 * ip_fanout_proto also gets called
6559 			 * from icmp_inbound_error_fanout, in
6560 			 * which case the msg type is M_CTL.
6561 			 * Don't add info in this case for time
6562 			 * being. In future when there is a
6563 			 * need for knowing the inbound iface
6564 			 * index for ICMP error msgs, then this
6565 			 * can be changed
6566 			 */
6567 			if (connp->conn_recvif)
6568 				in_flags = IPF_RECVIF;
6569 			if (connp->conn_ip_recvpktinfo) {
6570 				if (connp->conn_af_isv6) {
6571 					/*
6572 					 * V6 only needs index
6573 					 */
6574 					in_flags |= IPF_RECVIF;
6575 				} else {
6576 					/*
6577 					 * V4 needs index +
6578 					 * matching address.
6579 					 */
6580 					in_flags |= IPF_RECVADDR;
6581 				}
6582 			}
6583 			if ((in_flags != 0) &&
6584 			    (mp->b_datap->db_type != M_CTL)) {
6585 
6586 				/*
6587 				 * the actual data will be contained in
6588 				 * b_cont upon successful return
6589 				 * of the following call else original
6590 				 * mblk is returned
6591 				 */
6592 				ASSERT(recv_ill != NULL);
6593 				mp = ip_add_info(mp, recv_ill,
6594 				    in_flags, IPCL_ZONEID(connp), ipst);
6595 			}
6596 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6597 			(connp->conn_recv)(connp, mp, NULL);
6598 			if (mctl_present)
6599 				freeb(first_mp);
6600 		}
6601 	}
6602 	CONN_DEC_REF(connp);
6603 }
6604 
6605 /*
6606  * Fanout for TCP packets
6607  * The caller puts <fport, lport> in the ports parameter.
6608  *
6609  * IPQoS Notes
6610  * Before sending it to the client, invoke IPPF processing.
6611  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6612  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6613  * ip_policy is false.
6614  */
6615 static void
6616 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6617     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6618 {
6619 	mblk_t  *first_mp;
6620 	boolean_t secure;
6621 	uint32_t ill_index;
6622 	int	ip_hdr_len;
6623 	tcph_t	*tcph;
6624 	boolean_t syn_present = B_FALSE;
6625 	conn_t	*connp;
6626 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6627 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6628 
6629 	ASSERT(recv_ill != NULL);
6630 
6631 	first_mp = mp;
6632 	if (mctl_present) {
6633 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6634 		mp = first_mp->b_cont;
6635 		secure = ipsec_in_is_secure(first_mp);
6636 		ASSERT(mp != NULL);
6637 	} else {
6638 		secure = B_FALSE;
6639 	}
6640 
6641 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6642 
6643 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6644 	    zoneid, ipst)) == NULL) {
6645 		/*
6646 		 * No connected connection or listener. Send a
6647 		 * TH_RST via tcp_xmit_listeners_reset.
6648 		 */
6649 
6650 		/* Initiate IPPf processing, if needed. */
6651 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6652 			uint32_t ill_index;
6653 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6654 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6655 			if (first_mp == NULL)
6656 				return;
6657 		}
6658 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6659 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6660 		    zoneid));
6661 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6662 		    ipst->ips_netstack->netstack_tcp, NULL);
6663 		return;
6664 	}
6665 
6666 	/*
6667 	 * Allocate the SYN for the TCP connection here itself
6668 	 */
6669 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6670 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6671 		if (IPCL_IS_TCP(connp)) {
6672 			squeue_t *sqp;
6673 
6674 			/*
6675 			 * For fused tcp loopback, assign the eager's
6676 			 * squeue to be that of the active connect's.
6677 			 * Note that we don't check for IP_FF_LOOPBACK
6678 			 * here since this routine gets called only
6679 			 * for loopback (unlike the IPv6 counterpart).
6680 			 */
6681 			ASSERT(Q_TO_CONN(q) != NULL);
6682 			if (do_tcp_fusion &&
6683 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6684 			    !secure &&
6685 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6686 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6687 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6688 				sqp = Q_TO_CONN(q)->conn_sqp;
6689 			} else {
6690 				sqp = IP_SQUEUE_GET(lbolt);
6691 			}
6692 
6693 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6694 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6695 			syn_present = B_TRUE;
6696 		}
6697 	}
6698 
6699 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6700 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6701 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6702 		if ((flags & TH_RST) || (flags & TH_URG)) {
6703 			CONN_DEC_REF(connp);
6704 			freemsg(first_mp);
6705 			return;
6706 		}
6707 		if (flags & TH_ACK) {
6708 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6709 			    ipst->ips_netstack->netstack_tcp, connp);
6710 			CONN_DEC_REF(connp);
6711 			return;
6712 		}
6713 
6714 		CONN_DEC_REF(connp);
6715 		freemsg(first_mp);
6716 		return;
6717 	}
6718 
6719 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6720 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6721 		    NULL, mctl_present);
6722 		if (first_mp == NULL) {
6723 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6724 			CONN_DEC_REF(connp);
6725 			return;
6726 		}
6727 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6728 			ASSERT(syn_present);
6729 			if (mctl_present) {
6730 				ASSERT(first_mp != mp);
6731 				first_mp->b_datap->db_struioflag |=
6732 				    STRUIO_POLICY;
6733 			} else {
6734 				ASSERT(first_mp == mp);
6735 				mp->b_datap->db_struioflag &=
6736 				    ~STRUIO_EAGER;
6737 				mp->b_datap->db_struioflag |=
6738 				    STRUIO_POLICY;
6739 			}
6740 		} else {
6741 			/*
6742 			 * Discard first_mp early since we're dealing with a
6743 			 * fully-connected conn_t and tcp doesn't do policy in
6744 			 * this case.
6745 			 */
6746 			if (mctl_present) {
6747 				freeb(first_mp);
6748 				mctl_present = B_FALSE;
6749 			}
6750 			first_mp = mp;
6751 		}
6752 	}
6753 
6754 	/*
6755 	 * Initiate policy processing here if needed. If we get here from
6756 	 * icmp_inbound_error_fanout, ip_policy is false.
6757 	 */
6758 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6759 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6760 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6761 		if (mp == NULL) {
6762 			CONN_DEC_REF(connp);
6763 			if (mctl_present)
6764 				freeb(first_mp);
6765 			return;
6766 		} else if (mctl_present) {
6767 			ASSERT(first_mp != mp);
6768 			first_mp->b_cont = mp;
6769 		} else {
6770 			first_mp = mp;
6771 		}
6772 	}
6773 
6774 
6775 
6776 	/* Handle socket options. */
6777 	if (!syn_present &&
6778 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6779 		/* Add header */
6780 		ASSERT(recv_ill != NULL);
6781 		/*
6782 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6783 		 * IPF_RECVIF.
6784 		 */
6785 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6786 		    ipst);
6787 		if (mp == NULL) {
6788 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6789 			CONN_DEC_REF(connp);
6790 			if (mctl_present)
6791 				freeb(first_mp);
6792 			return;
6793 		} else if (mctl_present) {
6794 			/*
6795 			 * ip_add_info might return a new mp.
6796 			 */
6797 			ASSERT(first_mp != mp);
6798 			first_mp->b_cont = mp;
6799 		} else {
6800 			first_mp = mp;
6801 		}
6802 	}
6803 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6804 	if (IPCL_IS_TCP(connp)) {
6805 		/* do not drain, certain use cases can blow the stack */
6806 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6807 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6808 	} else {
6809 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6810 		(connp->conn_recv)(connp, first_mp, NULL);
6811 		CONN_DEC_REF(connp);
6812 	}
6813 }
6814 
6815 /*
6816  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6817  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6818  * is not consumed.
6819  *
6820  * One of four things can happen, all of which affect the passed-in mblk:
6821  *
6822  * 1.) ICMP messages that go through here just get returned TRUE.
6823  *
6824  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6825  *
6826  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6827  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6828  *
6829  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6830  */
6831 static boolean_t
6832 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6833     ipsec_stack_t *ipss)
6834 {
6835 	int shift, plen, iph_len;
6836 	ipha_t *ipha;
6837 	udpha_t *udpha;
6838 	uint32_t *spi;
6839 	uint32_t esp_ports;
6840 	uint8_t *orptr;
6841 	boolean_t free_ire;
6842 
6843 	if (DB_TYPE(mp) == M_CTL) {
6844 		/*
6845 		 * ICMP message with UDP inside.  Don't bother stripping, just
6846 		 * send it up.
6847 		 *
6848 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6849 		 * to ignore errors set by ICMP anyway ('cause they might be
6850 		 * forged), but that's the app's decision, not ours.
6851 		 */
6852 
6853 		/* Bunch of reality checks for DEBUG kernels... */
6854 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6855 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6856 
6857 		return (B_TRUE);
6858 	}
6859 
6860 	ipha = (ipha_t *)mp->b_rptr;
6861 	iph_len = IPH_HDR_LENGTH(ipha);
6862 	plen = ntohs(ipha->ipha_length);
6863 
6864 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6865 		/*
6866 		 * Most likely a keepalive for the benefit of an intervening
6867 		 * NAT.  These aren't for us, per se, so drop it.
6868 		 *
6869 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6870 		 * byte packets (keepalives are 1-byte), but we'll drop them
6871 		 * also.
6872 		 */
6873 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6874 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6875 		return (B_FALSE);
6876 	}
6877 
6878 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6879 		/* might as well pull it all up - it might be ESP. */
6880 		if (!pullupmsg(mp, -1)) {
6881 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6882 			    DROPPER(ipss, ipds_esp_nomem),
6883 			    &ipss->ipsec_dropper);
6884 			return (B_FALSE);
6885 		}
6886 
6887 		ipha = (ipha_t *)mp->b_rptr;
6888 	}
6889 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6890 	if (*spi == 0) {
6891 		/* UDP packet - remove 0-spi. */
6892 		shift = sizeof (uint32_t);
6893 	} else {
6894 		/* ESP-in-UDP packet - reduce to ESP. */
6895 		ipha->ipha_protocol = IPPROTO_ESP;
6896 		shift = sizeof (udpha_t);
6897 	}
6898 
6899 	/* Fix IP header */
6900 	ipha->ipha_length = htons(plen - shift);
6901 	ipha->ipha_hdr_checksum = 0;
6902 
6903 	orptr = mp->b_rptr;
6904 	mp->b_rptr += shift;
6905 
6906 	udpha = (udpha_t *)(orptr + iph_len);
6907 	if (*spi == 0) {
6908 		ASSERT((uint8_t *)ipha == orptr);
6909 		udpha->uha_length = htons(plen - shift - iph_len);
6910 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6911 		esp_ports = 0;
6912 	} else {
6913 		esp_ports = *((uint32_t *)udpha);
6914 		ASSERT(esp_ports != 0);
6915 	}
6916 	ovbcopy(orptr, orptr + shift, iph_len);
6917 	if (esp_ports != 0) /* Punt up for ESP processing. */ {
6918 		ipha = (ipha_t *)(orptr + shift);
6919 
6920 		free_ire = (ire == NULL);
6921 		if (free_ire) {
6922 			/* Re-acquire ire. */
6923 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6924 			    ipss->ipsec_netstack->netstack_ip);
6925 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6926 				if (ire != NULL)
6927 					ire_refrele(ire);
6928 				/*
6929 				 * Do a regular freemsg(), as this is an IP
6930 				 * error (no local route) not an IPsec one.
6931 				 */
6932 				freemsg(mp);
6933 			}
6934 		}
6935 
6936 		ip_proto_input(q, mp, ipha, ire, recv_ill, esp_ports);
6937 		if (free_ire)
6938 			ire_refrele(ire);
6939 	}
6940 
6941 	return (esp_ports == 0);
6942 }
6943 
6944 /*
6945  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6946  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6947  * Caller is responsible for dropping references to the conn, and freeing
6948  * first_mp.
6949  *
6950  * IPQoS Notes
6951  * Before sending it to the client, invoke IPPF processing. Policy processing
6952  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6953  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6954  * ip_wput_local, ip_policy is false.
6955  */
6956 static void
6957 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6958     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6959     boolean_t ip_policy)
6960 {
6961 	boolean_t	mctl_present = (first_mp != NULL);
6962 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6963 	uint32_t	ill_index;
6964 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6965 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6966 
6967 	ASSERT(ill != NULL);
6968 
6969 	if (mctl_present)
6970 		first_mp->b_cont = mp;
6971 	else
6972 		first_mp = mp;
6973 
6974 	if (CONN_UDP_FLOWCTLD(connp)) {
6975 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6976 		freemsg(first_mp);
6977 		return;
6978 	}
6979 
6980 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6981 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6982 		    NULL, mctl_present);
6983 		if (first_mp == NULL) {
6984 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6985 			return;	/* Freed by ipsec_check_inbound_policy(). */
6986 		}
6987 	}
6988 	if (mctl_present)
6989 		freeb(first_mp);
6990 
6991 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6992 	if (connp->conn_udp->udp_nat_t_endpoint) {
6993 		if (mctl_present) {
6994 			/* mctl_present *shouldn't* happen. */
6995 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
6996 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
6997 			    &ipss->ipsec_dropper);
6998 			return;
6999 		}
7000 
7001 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7002 			return;
7003 	}
7004 
7005 	/* Handle options. */
7006 	if (connp->conn_recvif)
7007 		in_flags = IPF_RECVIF;
7008 	/*
7009 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7010 	 * passed to ip_add_info is based on IP version of connp.
7011 	 */
7012 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7013 		if (connp->conn_af_isv6) {
7014 			/*
7015 			 * V6 only needs index
7016 			 */
7017 			in_flags |= IPF_RECVIF;
7018 		} else {
7019 			/*
7020 			 * V4 needs index + matching address.
7021 			 */
7022 			in_flags |= IPF_RECVADDR;
7023 		}
7024 	}
7025 
7026 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7027 		in_flags |= IPF_RECVSLLA;
7028 
7029 	/*
7030 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7031 	 * freed if the packet is dropped. The caller will do so.
7032 	 */
7033 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7034 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7035 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7036 		if (mp == NULL) {
7037 			return;
7038 		}
7039 	}
7040 	if ((in_flags != 0) &&
7041 	    (mp->b_datap->db_type != M_CTL)) {
7042 		/*
7043 		 * The actual data will be contained in b_cont
7044 		 * upon successful return of the following call
7045 		 * else original mblk is returned
7046 		 */
7047 		ASSERT(recv_ill != NULL);
7048 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7049 		    ipst);
7050 	}
7051 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7052 	/* Send it upstream */
7053 	(connp->conn_recv)(connp, mp, NULL);
7054 }
7055 
7056 /*
7057  * Fanout for UDP packets.
7058  * The caller puts <fport, lport> in the ports parameter.
7059  *
7060  * If SO_REUSEADDR is set all multicast and broadcast packets
7061  * will be delivered to all streams bound to the same port.
7062  *
7063  * Zones notes:
7064  * Multicast and broadcast packets will be distributed to streams in all zones.
7065  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7066  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7067  * packets. To maintain this behavior with multiple zones, the conns are grouped
7068  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7069  * each zone. If unset, all the following conns in the same zone are skipped.
7070  */
7071 static void
7072 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7073     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7074     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7075 {
7076 	uint32_t	dstport, srcport;
7077 	ipaddr_t	dst;
7078 	mblk_t		*first_mp;
7079 	boolean_t	secure;
7080 	in6_addr_t	v6src;
7081 	conn_t		*connp;
7082 	connf_t		*connfp;
7083 	conn_t		*first_connp;
7084 	conn_t		*next_connp;
7085 	mblk_t		*mp1, *first_mp1;
7086 	ipaddr_t	src;
7087 	zoneid_t	last_zoneid;
7088 	boolean_t	reuseaddr;
7089 	boolean_t	shared_addr;
7090 	boolean_t	unlabeled;
7091 	ip_stack_t	*ipst;
7092 
7093 	ASSERT(recv_ill != NULL);
7094 	ipst = recv_ill->ill_ipst;
7095 
7096 	first_mp = mp;
7097 	if (mctl_present) {
7098 		mp = first_mp->b_cont;
7099 		first_mp->b_cont = NULL;
7100 		secure = ipsec_in_is_secure(first_mp);
7101 		ASSERT(mp != NULL);
7102 	} else {
7103 		first_mp = NULL;
7104 		secure = B_FALSE;
7105 	}
7106 
7107 	/* Extract ports in net byte order */
7108 	dstport = htons(ntohl(ports) & 0xFFFF);
7109 	srcport = htons(ntohl(ports) >> 16);
7110 	dst = ipha->ipha_dst;
7111 	src = ipha->ipha_src;
7112 
7113 	unlabeled = B_FALSE;
7114 	if (is_system_labeled())
7115 		/* Cred cannot be null on IPv4 */
7116 		unlabeled = (crgetlabel(DB_CRED(mp))->tsl_flags &
7117 		    TSLF_UNLABELED) != 0;
7118 	shared_addr = (zoneid == ALL_ZONES);
7119 	if (shared_addr) {
7120 		/*
7121 		 * No need to handle exclusive-stack zones since ALL_ZONES
7122 		 * only applies to the shared stack.
7123 		 */
7124 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7125 		/*
7126 		 * If no shared MLP is found, tsol_mlp_findzone returns
7127 		 * ALL_ZONES.  In that case, we assume it's SLP, and
7128 		 * search for the zone based on the packet label.
7129 		 *
7130 		 * If there is such a zone, we prefer to find a
7131 		 * connection in it.  Otherwise, we look for a
7132 		 * MAC-exempt connection in any zone whose label
7133 		 * dominates the default label on the packet.
7134 		 */
7135 		if (zoneid == ALL_ZONES)
7136 			zoneid = tsol_packet_to_zoneid(mp);
7137 		else
7138 			unlabeled = B_FALSE;
7139 	}
7140 
7141 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7142 	mutex_enter(&connfp->connf_lock);
7143 	connp = connfp->connf_head;
7144 	if (!broadcast && !CLASSD(dst)) {
7145 		/*
7146 		 * Not broadcast or multicast. Send to the one (first)
7147 		 * client we find. No need to check conn_wantpacket()
7148 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7149 		 * IPv4 unicast packets.
7150 		 */
7151 		while ((connp != NULL) &&
7152 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7153 		    (!IPCL_ZONE_MATCH(connp, zoneid) &&
7154 		    !(unlabeled && connp->conn_mac_exempt)))) {
7155 			/*
7156 			 * We keep searching since the conn did not match,
7157 			 * or its zone did not match and it is not either
7158 			 * an allzones conn or a mac exempt conn (if the
7159 			 * sender is unlabeled.)
7160 			 */
7161 			connp = connp->conn_next;
7162 		}
7163 
7164 		if (connp == NULL || connp->conn_upq == NULL)
7165 			goto notfound;
7166 
7167 		if (is_system_labeled() &&
7168 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7169 		    connp))
7170 			goto notfound;
7171 
7172 		CONN_INC_REF(connp);
7173 		mutex_exit(&connfp->connf_lock);
7174 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7175 		    flags, recv_ill, ip_policy);
7176 		IP_STAT(ipst, ip_udp_fannorm);
7177 		CONN_DEC_REF(connp);
7178 		return;
7179 	}
7180 
7181 	/*
7182 	 * Broadcast and multicast case
7183 	 *
7184 	 * Need to check conn_wantpacket().
7185 	 * If SO_REUSEADDR has been set on the first we send the
7186 	 * packet to all clients that have joined the group and
7187 	 * match the port.
7188 	 */
7189 
7190 	while (connp != NULL) {
7191 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7192 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7193 		    (!is_system_labeled() ||
7194 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7195 		    connp)))
7196 			break;
7197 		connp = connp->conn_next;
7198 	}
7199 
7200 	if (connp == NULL || connp->conn_upq == NULL)
7201 		goto notfound;
7202 
7203 	first_connp = connp;
7204 	/*
7205 	 * When SO_REUSEADDR is not set, send the packet only to the first
7206 	 * matching connection in its zone by keeping track of the zoneid.
7207 	 */
7208 	reuseaddr = first_connp->conn_reuseaddr;
7209 	last_zoneid = first_connp->conn_zoneid;
7210 
7211 	CONN_INC_REF(connp);
7212 	connp = connp->conn_next;
7213 	for (;;) {
7214 		while (connp != NULL) {
7215 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7216 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7217 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7218 			    (!is_system_labeled() ||
7219 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7220 			    shared_addr, connp)))
7221 				break;
7222 			connp = connp->conn_next;
7223 		}
7224 		/*
7225 		 * Just copy the data part alone. The mctl part is
7226 		 * needed just for verifying policy and it is never
7227 		 * sent up.
7228 		 */
7229 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7230 		    ((mp1 = copymsg(mp)) == NULL))) {
7231 			/*
7232 			 * No more interested clients or memory
7233 			 * allocation failed
7234 			 */
7235 			connp = first_connp;
7236 			break;
7237 		}
7238 		if (connp->conn_zoneid != last_zoneid) {
7239 			/*
7240 			 * Update the zoneid so that the packet isn't sent to
7241 			 * any more conns in the same zone unless SO_REUSEADDR
7242 			 * is set.
7243 			 */
7244 			reuseaddr = connp->conn_reuseaddr;
7245 			last_zoneid = connp->conn_zoneid;
7246 		}
7247 		if (first_mp != NULL) {
7248 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7249 			    ipsec_info_type == IPSEC_IN);
7250 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7251 			    ipst->ips_netstack);
7252 			if (first_mp1 == NULL) {
7253 				freemsg(mp1);
7254 				connp = first_connp;
7255 				break;
7256 			}
7257 		} else {
7258 			first_mp1 = NULL;
7259 		}
7260 		CONN_INC_REF(connp);
7261 		mutex_exit(&connfp->connf_lock);
7262 		/*
7263 		 * IPQoS notes: We don't send the packet for policy
7264 		 * processing here, will do it for the last one (below).
7265 		 * i.e. we do it per-packet now, but if we do policy
7266 		 * processing per-conn, then we would need to do it
7267 		 * here too.
7268 		 */
7269 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7270 		    ipha, flags, recv_ill, B_FALSE);
7271 		mutex_enter(&connfp->connf_lock);
7272 		/* Follow the next pointer before releasing the conn. */
7273 		next_connp = connp->conn_next;
7274 		IP_STAT(ipst, ip_udp_fanmb);
7275 		CONN_DEC_REF(connp);
7276 		connp = next_connp;
7277 	}
7278 
7279 	/* Last one.  Send it upstream. */
7280 	mutex_exit(&connfp->connf_lock);
7281 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7282 	    recv_ill, ip_policy);
7283 	IP_STAT(ipst, ip_udp_fanmb);
7284 	CONN_DEC_REF(connp);
7285 	return;
7286 
7287 notfound:
7288 
7289 	mutex_exit(&connfp->connf_lock);
7290 	IP_STAT(ipst, ip_udp_fanothers);
7291 	/*
7292 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7293 	 * have already been matched above, since they live in the IPv4
7294 	 * fanout tables. This implies we only need to
7295 	 * check for IPv6 in6addr_any endpoints here.
7296 	 * Thus we compare using ipv6_all_zeros instead of the destination
7297 	 * address, except for the multicast group membership lookup which
7298 	 * uses the IPv4 destination.
7299 	 */
7300 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7301 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7302 	mutex_enter(&connfp->connf_lock);
7303 	connp = connfp->connf_head;
7304 	if (!broadcast && !CLASSD(dst)) {
7305 		while (connp != NULL) {
7306 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7307 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7308 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7309 			    !connp->conn_ipv6_v6only)
7310 				break;
7311 			connp = connp->conn_next;
7312 		}
7313 
7314 		if (connp != NULL && is_system_labeled() &&
7315 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7316 		    connp))
7317 			connp = NULL;
7318 
7319 		if (connp == NULL || connp->conn_upq == NULL) {
7320 			/*
7321 			 * No one bound to this port.  Is
7322 			 * there a client that wants all
7323 			 * unclaimed datagrams?
7324 			 */
7325 			mutex_exit(&connfp->connf_lock);
7326 
7327 			if (mctl_present)
7328 				first_mp->b_cont = mp;
7329 			else
7330 				first_mp = mp;
7331 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7332 			    connf_head != NULL) {
7333 				ip_fanout_proto(q, first_mp, ill, ipha,
7334 				    flags | IP_FF_RAWIP, mctl_present,
7335 				    ip_policy, recv_ill, zoneid);
7336 			} else {
7337 				if (ip_fanout_send_icmp(q, first_mp, flags,
7338 				    ICMP_DEST_UNREACHABLE,
7339 				    ICMP_PORT_UNREACHABLE,
7340 				    mctl_present, zoneid, ipst)) {
7341 					BUMP_MIB(ill->ill_ip_mib,
7342 					    udpIfStatsNoPorts);
7343 				}
7344 			}
7345 			return;
7346 		}
7347 
7348 		CONN_INC_REF(connp);
7349 		mutex_exit(&connfp->connf_lock);
7350 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7351 		    flags, recv_ill, ip_policy);
7352 		CONN_DEC_REF(connp);
7353 		return;
7354 	}
7355 	/*
7356 	 * IPv4 multicast packet being delivered to an AF_INET6
7357 	 * in6addr_any endpoint.
7358 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7359 	 * and not conn_wantpacket_v6() since any multicast membership is
7360 	 * for an IPv4-mapped multicast address.
7361 	 * The packet is sent to all clients in all zones that have joined the
7362 	 * group and match the port.
7363 	 */
7364 	while (connp != NULL) {
7365 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7366 		    srcport, v6src) &&
7367 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7368 		    (!is_system_labeled() ||
7369 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7370 		    connp)))
7371 			break;
7372 		connp = connp->conn_next;
7373 	}
7374 
7375 	if (connp == NULL || connp->conn_upq == NULL) {
7376 		/*
7377 		 * No one bound to this port.  Is
7378 		 * there a client that wants all
7379 		 * unclaimed datagrams?
7380 		 */
7381 		mutex_exit(&connfp->connf_lock);
7382 
7383 		if (mctl_present)
7384 			first_mp->b_cont = mp;
7385 		else
7386 			first_mp = mp;
7387 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7388 		    NULL) {
7389 			ip_fanout_proto(q, first_mp, ill, ipha,
7390 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7391 			    recv_ill, zoneid);
7392 		} else {
7393 			/*
7394 			 * We used to attempt to send an icmp error here, but
7395 			 * since this is known to be a multicast packet
7396 			 * and we don't send icmp errors in response to
7397 			 * multicast, just drop the packet and give up sooner.
7398 			 */
7399 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7400 			freemsg(first_mp);
7401 		}
7402 		return;
7403 	}
7404 
7405 	first_connp = connp;
7406 
7407 	CONN_INC_REF(connp);
7408 	connp = connp->conn_next;
7409 	for (;;) {
7410 		while (connp != NULL) {
7411 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7412 			    ipv6_all_zeros, srcport, v6src) &&
7413 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7414 			    (!is_system_labeled() ||
7415 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7416 			    shared_addr, connp)))
7417 				break;
7418 			connp = connp->conn_next;
7419 		}
7420 		/*
7421 		 * Just copy the data part alone. The mctl part is
7422 		 * needed just for verifying policy and it is never
7423 		 * sent up.
7424 		 */
7425 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7426 		    ((mp1 = copymsg(mp)) == NULL))) {
7427 			/*
7428 			 * No more intested clients or memory
7429 			 * allocation failed
7430 			 */
7431 			connp = first_connp;
7432 			break;
7433 		}
7434 		if (first_mp != NULL) {
7435 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7436 			    ipsec_info_type == IPSEC_IN);
7437 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7438 			    ipst->ips_netstack);
7439 			if (first_mp1 == NULL) {
7440 				freemsg(mp1);
7441 				connp = first_connp;
7442 				break;
7443 			}
7444 		} else {
7445 			first_mp1 = NULL;
7446 		}
7447 		CONN_INC_REF(connp);
7448 		mutex_exit(&connfp->connf_lock);
7449 		/*
7450 		 * IPQoS notes: We don't send the packet for policy
7451 		 * processing here, will do it for the last one (below).
7452 		 * i.e. we do it per-packet now, but if we do policy
7453 		 * processing per-conn, then we would need to do it
7454 		 * here too.
7455 		 */
7456 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7457 		    ipha, flags, recv_ill, B_FALSE);
7458 		mutex_enter(&connfp->connf_lock);
7459 		/* Follow the next pointer before releasing the conn. */
7460 		next_connp = connp->conn_next;
7461 		CONN_DEC_REF(connp);
7462 		connp = next_connp;
7463 	}
7464 
7465 	/* Last one.  Send it upstream. */
7466 	mutex_exit(&connfp->connf_lock);
7467 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7468 	    recv_ill, ip_policy);
7469 	CONN_DEC_REF(connp);
7470 }
7471 
7472 /*
7473  * Complete the ip_wput header so that it
7474  * is possible to generate ICMP
7475  * errors.
7476  */
7477 int
7478 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7479 {
7480 	ire_t *ire;
7481 
7482 	if (ipha->ipha_src == INADDR_ANY) {
7483 		ire = ire_lookup_local(zoneid, ipst);
7484 		if (ire == NULL) {
7485 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7486 			return (1);
7487 		}
7488 		ipha->ipha_src = ire->ire_addr;
7489 		ire_refrele(ire);
7490 	}
7491 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7492 	ipha->ipha_hdr_checksum = 0;
7493 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7494 	return (0);
7495 }
7496 
7497 /*
7498  * Nobody should be sending
7499  * packets up this stream
7500  */
7501 static void
7502 ip_lrput(queue_t *q, mblk_t *mp)
7503 {
7504 	mblk_t *mp1;
7505 
7506 	switch (mp->b_datap->db_type) {
7507 	case M_FLUSH:
7508 		/* Turn around */
7509 		if (*mp->b_rptr & FLUSHW) {
7510 			*mp->b_rptr &= ~FLUSHR;
7511 			qreply(q, mp);
7512 			return;
7513 		}
7514 		break;
7515 	}
7516 	/* Could receive messages that passed through ar_rput */
7517 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7518 		mp1->b_prev = mp1->b_next = NULL;
7519 	freemsg(mp);
7520 }
7521 
7522 /* Nobody should be sending packets down this stream */
7523 /* ARGSUSED */
7524 void
7525 ip_lwput(queue_t *q, mblk_t *mp)
7526 {
7527 	freemsg(mp);
7528 }
7529 
7530 /*
7531  * Move the first hop in any source route to ipha_dst and remove that part of
7532  * the source route.  Called by other protocols.  Errors in option formatting
7533  * are ignored - will be handled by ip_wput_options Return the final
7534  * destination (either ipha_dst or the last entry in a source route.)
7535  */
7536 ipaddr_t
7537 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7538 {
7539 	ipoptp_t	opts;
7540 	uchar_t		*opt;
7541 	uint8_t		optval;
7542 	uint8_t		optlen;
7543 	ipaddr_t	dst;
7544 	int		i;
7545 	ire_t		*ire;
7546 	ip_stack_t	*ipst = ns->netstack_ip;
7547 
7548 	ip2dbg(("ip_massage_options\n"));
7549 	dst = ipha->ipha_dst;
7550 	for (optval = ipoptp_first(&opts, ipha);
7551 	    optval != IPOPT_EOL;
7552 	    optval = ipoptp_next(&opts)) {
7553 		opt = opts.ipoptp_cur;
7554 		switch (optval) {
7555 			uint8_t off;
7556 		case IPOPT_SSRR:
7557 		case IPOPT_LSRR:
7558 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7559 				ip1dbg(("ip_massage_options: bad src route\n"));
7560 				break;
7561 			}
7562 			optlen = opts.ipoptp_len;
7563 			off = opt[IPOPT_OFFSET];
7564 			off--;
7565 		redo_srr:
7566 			if (optlen < IP_ADDR_LEN ||
7567 			    off > optlen - IP_ADDR_LEN) {
7568 				/* End of source route */
7569 				ip1dbg(("ip_massage_options: end of SR\n"));
7570 				break;
7571 			}
7572 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7573 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7574 			    ntohl(dst)));
7575 			/*
7576 			 * Check if our address is present more than
7577 			 * once as consecutive hops in source route.
7578 			 * XXX verify per-interface ip_forwarding
7579 			 * for source route?
7580 			 */
7581 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7582 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7583 			if (ire != NULL) {
7584 				ire_refrele(ire);
7585 				off += IP_ADDR_LEN;
7586 				goto redo_srr;
7587 			}
7588 			if (dst == htonl(INADDR_LOOPBACK)) {
7589 				ip1dbg(("ip_massage_options: loopback addr in "
7590 				    "source route!\n"));
7591 				break;
7592 			}
7593 			/*
7594 			 * Update ipha_dst to be the first hop and remove the
7595 			 * first hop from the source route (by overwriting
7596 			 * part of the option with NOP options).
7597 			 */
7598 			ipha->ipha_dst = dst;
7599 			/* Put the last entry in dst */
7600 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7601 			    3;
7602 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7603 
7604 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7605 			    ntohl(dst)));
7606 			/* Move down and overwrite */
7607 			opt[IP_ADDR_LEN] = opt[0];
7608 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7609 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7610 			for (i = 0; i < IP_ADDR_LEN; i++)
7611 				opt[i] = IPOPT_NOP;
7612 			break;
7613 		}
7614 	}
7615 	return (dst);
7616 }
7617 
7618 /*
7619  * Return the network mask
7620  * associated with the specified address.
7621  */
7622 ipaddr_t
7623 ip_net_mask(ipaddr_t addr)
7624 {
7625 	uchar_t	*up = (uchar_t *)&addr;
7626 	ipaddr_t mask = 0;
7627 	uchar_t	*maskp = (uchar_t *)&mask;
7628 
7629 #if defined(__i386) || defined(__amd64)
7630 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7631 #endif
7632 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7633 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7634 #endif
7635 	if (CLASSD(addr)) {
7636 		maskp[0] = 0xF0;
7637 		return (mask);
7638 	}
7639 
7640 	/* We assume Class E default netmask to be 32 */
7641 	if (CLASSE(addr))
7642 		return (0xffffffffU);
7643 
7644 	if (addr == 0)
7645 		return (0);
7646 	maskp[0] = 0xFF;
7647 	if ((up[0] & 0x80) == 0)
7648 		return (mask);
7649 
7650 	maskp[1] = 0xFF;
7651 	if ((up[0] & 0xC0) == 0x80)
7652 		return (mask);
7653 
7654 	maskp[2] = 0xFF;
7655 	if ((up[0] & 0xE0) == 0xC0)
7656 		return (mask);
7657 
7658 	/* Otherwise return no mask */
7659 	return ((ipaddr_t)0);
7660 }
7661 
7662 /*
7663  * Select an ill for the packet by considering load spreading across
7664  * a different ill in the group if dst_ill is part of some group.
7665  */
7666 ill_t *
7667 ip_newroute_get_dst_ill(ill_t *dst_ill)
7668 {
7669 	ill_t *ill;
7670 
7671 	/*
7672 	 * We schedule irrespective of whether the source address is
7673 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7674 	 */
7675 	ill = illgrp_scheduler(dst_ill);
7676 	if (ill == NULL)
7677 		return (NULL);
7678 
7679 	/*
7680 	 * For groups with names ip_sioctl_groupname ensures that all
7681 	 * ills are of same type. For groups without names, ifgrp_insert
7682 	 * ensures this.
7683 	 */
7684 	ASSERT(dst_ill->ill_type == ill->ill_type);
7685 
7686 	return (ill);
7687 }
7688 
7689 /*
7690  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7691  */
7692 ill_t *
7693 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7694     ip_stack_t *ipst)
7695 {
7696 	ill_t *ret_ill;
7697 
7698 	ASSERT(ifindex != 0);
7699 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7700 	    ipst);
7701 	if (ret_ill == NULL ||
7702 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7703 		if (isv6) {
7704 			if (ill != NULL) {
7705 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7706 			} else {
7707 				BUMP_MIB(&ipst->ips_ip6_mib,
7708 				    ipIfStatsOutDiscards);
7709 			}
7710 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7711 			    "bad ifindex %d.\n", ifindex));
7712 		} else {
7713 			if (ill != NULL) {
7714 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7715 			} else {
7716 				BUMP_MIB(&ipst->ips_ip_mib,
7717 				    ipIfStatsOutDiscards);
7718 			}
7719 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7720 			    "bad ifindex %d.\n", ifindex));
7721 		}
7722 		if (ret_ill != NULL)
7723 			ill_refrele(ret_ill);
7724 		freemsg(first_mp);
7725 		return (NULL);
7726 	}
7727 
7728 	return (ret_ill);
7729 }
7730 
7731 /*
7732  * IPv4 -
7733  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7734  * out a packet to a destination address for which we do not have specific
7735  * (or sufficient) routing information.
7736  *
7737  * NOTE : These are the scopes of some of the variables that point at IRE,
7738  *	  which needs to be followed while making any future modifications
7739  *	  to avoid memory leaks.
7740  *
7741  *	- ire and sire are the entries looked up initially by
7742  *	  ire_ftable_lookup.
7743  *	- ipif_ire is used to hold the interface ire associated with
7744  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7745  *	  it before branching out to error paths.
7746  *	- save_ire is initialized before ire_create, so that ire returned
7747  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7748  *	  before breaking out of the switch.
7749  *
7750  *	Thus on failures, we have to REFRELE only ire and sire, if they
7751  *	are not NULL.
7752  */
7753 void
7754 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7755     zoneid_t zoneid, ip_stack_t *ipst)
7756 {
7757 	areq_t	*areq;
7758 	ipaddr_t gw = 0;
7759 	ire_t	*ire = NULL;
7760 	mblk_t	*res_mp;
7761 	ipaddr_t *addrp;
7762 	ipaddr_t nexthop_addr;
7763 	ipif_t  *src_ipif = NULL;
7764 	ill_t	*dst_ill = NULL;
7765 	ipha_t  *ipha;
7766 	ire_t	*sire = NULL;
7767 	mblk_t	*first_mp;
7768 	ire_t	*save_ire;
7769 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7770 	ushort_t ire_marks = 0;
7771 	boolean_t mctl_present;
7772 	ipsec_out_t *io;
7773 	mblk_t	*saved_mp;
7774 	ire_t	*first_sire = NULL;
7775 	mblk_t	*copy_mp = NULL;
7776 	mblk_t	*xmit_mp = NULL;
7777 	ipaddr_t save_dst;
7778 	uint32_t multirt_flags =
7779 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7780 	boolean_t multirt_is_resolvable;
7781 	boolean_t multirt_resolve_next;
7782 	boolean_t unspec_src;
7783 	boolean_t do_attach_ill = B_FALSE;
7784 	boolean_t ip_nexthop = B_FALSE;
7785 	tsol_ire_gw_secattr_t *attrp = NULL;
7786 	tsol_gcgrp_t *gcgrp = NULL;
7787 	tsol_gcgrp_addr_t ga;
7788 
7789 	if (ip_debug > 2) {
7790 		/* ip1dbg */
7791 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7792 	}
7793 
7794 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7795 	if (mctl_present) {
7796 		io = (ipsec_out_t *)first_mp->b_rptr;
7797 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7798 		ASSERT(zoneid == io->ipsec_out_zoneid);
7799 		ASSERT(zoneid != ALL_ZONES);
7800 	}
7801 
7802 	ipha = (ipha_t *)mp->b_rptr;
7803 
7804 	/* All multicast lookups come through ip_newroute_ipif() */
7805 	if (CLASSD(dst)) {
7806 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7807 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7808 		freemsg(first_mp);
7809 		return;
7810 	}
7811 
7812 	if (mctl_present && io->ipsec_out_attach_if) {
7813 		/* ip_grab_attach_ill returns a held ill */
7814 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7815 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7816 
7817 		/* Failure case frees things for us. */
7818 		if (attach_ill == NULL)
7819 			return;
7820 
7821 		/*
7822 		 * Check if we need an ire that will not be
7823 		 * looked up by anybody else i.e. HIDDEN.
7824 		 */
7825 		if (ill_is_probeonly(attach_ill))
7826 			ire_marks = IRE_MARK_HIDDEN;
7827 	}
7828 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7829 		ip_nexthop = B_TRUE;
7830 		nexthop_addr = io->ipsec_out_nexthop_addr;
7831 	}
7832 	/*
7833 	 * If this IRE is created for forwarding or it is not for
7834 	 * traffic for congestion controlled protocols, mark it as temporary.
7835 	 */
7836 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7837 		ire_marks |= IRE_MARK_TEMPORARY;
7838 
7839 	/*
7840 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7841 	 * chain until it gets the most specific information available.
7842 	 * For example, we know that there is no IRE_CACHE for this dest,
7843 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7844 	 * ire_ftable_lookup will look up the gateway, etc.
7845 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7846 	 * to the destination, of equal netmask length in the forward table,
7847 	 * will be recursively explored. If no information is available
7848 	 * for the final gateway of that route, we force the returned ire
7849 	 * to be equal to sire using MATCH_IRE_PARENT.
7850 	 * At least, in this case we have a starting point (in the buckets)
7851 	 * to look for other routes to the destination in the forward table.
7852 	 * This is actually used only for multirouting, where a list
7853 	 * of routes has to be processed in sequence.
7854 	 *
7855 	 * In the process of coming up with the most specific information,
7856 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7857 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7858 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7859 	 * Two caveats when handling incomplete ire's in ip_newroute:
7860 	 * - we should be careful when accessing its ire_nce (specifically
7861 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7862 	 * - not all legacy code path callers are prepared to handle
7863 	 *   incomplete ire's, so we should not create/add incomplete
7864 	 *   ire_cache entries here. (See discussion about temporary solution
7865 	 *   further below).
7866 	 *
7867 	 * In order to minimize packet dropping, and to preserve existing
7868 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7869 	 * gateway, and instead use the IF_RESOLVER ire to send out
7870 	 * another request to ARP (this is achieved by passing the
7871 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7872 	 * arp response comes back in ip_wput_nondata, we will create
7873 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7874 	 *
7875 	 * Note that this is a temporary solution; the correct solution is
7876 	 * to create an incomplete  per-dst ire_cache entry, and send the
7877 	 * packet out when the gw's nce is resolved. In order to achieve this,
7878 	 * all packet processing must have been completed prior to calling
7879 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7880 	 * to be modified to accomodate this solution.
7881 	 */
7882 	if (ip_nexthop) {
7883 		/*
7884 		 * The first time we come here, we look for an IRE_INTERFACE
7885 		 * entry for the specified nexthop, set the dst to be the
7886 		 * nexthop address and create an IRE_CACHE entry for the
7887 		 * nexthop. The next time around, we are able to find an
7888 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7889 		 * nexthop address and create an IRE_CACHE entry for the
7890 		 * destination address via the specified nexthop.
7891 		 */
7892 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7893 		    MBLK_GETLABEL(mp), ipst);
7894 		if (ire != NULL) {
7895 			gw = nexthop_addr;
7896 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7897 		} else {
7898 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7899 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7900 			    MBLK_GETLABEL(mp),
7901 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7902 			    ipst);
7903 			if (ire != NULL) {
7904 				dst = nexthop_addr;
7905 			}
7906 		}
7907 	} else if (attach_ill == NULL) {
7908 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7909 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7910 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7911 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7912 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7913 		    ipst);
7914 	} else {
7915 		/*
7916 		 * attach_ill is set only for communicating with
7917 		 * on-link hosts. So, don't look for DEFAULT.
7918 		 */
7919 		ipif_t	*attach_ipif;
7920 
7921 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7922 		if (attach_ipif == NULL) {
7923 			ill_refrele(attach_ill);
7924 			goto icmp_err_ret;
7925 		}
7926 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7927 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7928 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7929 		    MATCH_IRE_SECATTR, ipst);
7930 		ipif_refrele(attach_ipif);
7931 	}
7932 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7933 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7934 
7935 	/*
7936 	 * This loop is run only once in most cases.
7937 	 * We loop to resolve further routes only when the destination
7938 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7939 	 */
7940 	do {
7941 		/* Clear the previous iteration's values */
7942 		if (src_ipif != NULL) {
7943 			ipif_refrele(src_ipif);
7944 			src_ipif = NULL;
7945 		}
7946 		if (dst_ill != NULL) {
7947 			ill_refrele(dst_ill);
7948 			dst_ill = NULL;
7949 		}
7950 
7951 		multirt_resolve_next = B_FALSE;
7952 		/*
7953 		 * We check if packets have to be multirouted.
7954 		 * In this case, given the current <ire, sire> couple,
7955 		 * we look for the next suitable <ire, sire>.
7956 		 * This check is done in ire_multirt_lookup(),
7957 		 * which applies various criteria to find the next route
7958 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7959 		 * unchanged if it detects it has not been tried yet.
7960 		 */
7961 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7962 			ip3dbg(("ip_newroute: starting next_resolution "
7963 			    "with first_mp %p, tag %d\n",
7964 			    (void *)first_mp,
7965 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7966 
7967 			ASSERT(sire != NULL);
7968 			multirt_is_resolvable =
7969 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7970 			    MBLK_GETLABEL(mp), ipst);
7971 
7972 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7973 			    "ire %p, sire %p\n",
7974 			    multirt_is_resolvable,
7975 			    (void *)ire, (void *)sire));
7976 
7977 			if (!multirt_is_resolvable) {
7978 				/*
7979 				 * No more multirt route to resolve; give up
7980 				 * (all routes resolved or no more
7981 				 * resolvable routes).
7982 				 */
7983 				if (ire != NULL) {
7984 					ire_refrele(ire);
7985 					ire = NULL;
7986 				}
7987 			} else {
7988 				ASSERT(sire != NULL);
7989 				ASSERT(ire != NULL);
7990 				/*
7991 				 * We simply use first_sire as a flag that
7992 				 * indicates if a resolvable multirt route
7993 				 * has already been found.
7994 				 * If it is not the case, we may have to send
7995 				 * an ICMP error to report that the
7996 				 * destination is unreachable.
7997 				 * We do not IRE_REFHOLD first_sire.
7998 				 */
7999 				if (first_sire == NULL) {
8000 					first_sire = sire;
8001 				}
8002 			}
8003 		}
8004 		if (ire == NULL) {
8005 			if (ip_debug > 3) {
8006 				/* ip2dbg */
8007 				pr_addr_dbg("ip_newroute: "
8008 				    "can't resolve %s\n", AF_INET, &dst);
8009 			}
8010 			ip3dbg(("ip_newroute: "
8011 			    "ire %p, sire %p, first_sire %p\n",
8012 			    (void *)ire, (void *)sire, (void *)first_sire));
8013 
8014 			if (sire != NULL) {
8015 				ire_refrele(sire);
8016 				sire = NULL;
8017 			}
8018 
8019 			if (first_sire != NULL) {
8020 				/*
8021 				 * At least one multirt route has been found
8022 				 * in the same call to ip_newroute();
8023 				 * there is no need to report an ICMP error.
8024 				 * first_sire was not IRE_REFHOLDed.
8025 				 */
8026 				MULTIRT_DEBUG_UNTAG(first_mp);
8027 				freemsg(first_mp);
8028 				return;
8029 			}
8030 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8031 			    RTA_DST, ipst);
8032 			if (attach_ill != NULL)
8033 				ill_refrele(attach_ill);
8034 			goto icmp_err_ret;
8035 		}
8036 
8037 		/*
8038 		 * Verify that the returned IRE does not have either
8039 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8040 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8041 		 */
8042 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8043 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8044 			if (attach_ill != NULL)
8045 				ill_refrele(attach_ill);
8046 			goto icmp_err_ret;
8047 		}
8048 		/*
8049 		 * Increment the ire_ob_pkt_count field for ire if it is an
8050 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8051 		 * increment the same for the parent IRE, sire, if it is some
8052 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8053 		 */
8054 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8055 			UPDATE_OB_PKT_COUNT(ire);
8056 			ire->ire_last_used_time = lbolt;
8057 		}
8058 
8059 		if (sire != NULL) {
8060 			gw = sire->ire_gateway_addr;
8061 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8062 			    IRE_INTERFACE)) == 0);
8063 			UPDATE_OB_PKT_COUNT(sire);
8064 			sire->ire_last_used_time = lbolt;
8065 		}
8066 		/*
8067 		 * We have a route to reach the destination.
8068 		 *
8069 		 * 1) If the interface is part of ill group, try to get a new
8070 		 *    ill taking load spreading into account.
8071 		 *
8072 		 * 2) After selecting the ill, get a source address that
8073 		 *    might create good inbound load spreading.
8074 		 *    ipif_select_source does this for us.
8075 		 *
8076 		 * If the application specified the ill (ifindex), we still
8077 		 * load spread. Only if the packets needs to go out
8078 		 * specifically on a given ill e.g. binding to
8079 		 * IPIF_NOFAILOVER address, then we don't try to use a
8080 		 * different ill for load spreading.
8081 		 */
8082 		if (attach_ill == NULL) {
8083 			/*
8084 			 * Don't perform outbound load spreading in the
8085 			 * case of an RTF_MULTIRT route, as we actually
8086 			 * typically want to replicate outgoing packets
8087 			 * through particular interfaces.
8088 			 */
8089 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8090 				dst_ill = ire->ire_ipif->ipif_ill;
8091 				/* for uniformity */
8092 				ill_refhold(dst_ill);
8093 			} else {
8094 				/*
8095 				 * If we are here trying to create an IRE_CACHE
8096 				 * for an offlink destination and have the
8097 				 * IRE_CACHE for the next hop and the latter is
8098 				 * using virtual IP source address selection i.e
8099 				 * it's ire->ire_ipif is pointing to a virtual
8100 				 * network interface (vni) then
8101 				 * ip_newroute_get_dst_ll() will return the vni
8102 				 * interface as the dst_ill. Since the vni is
8103 				 * virtual i.e not associated with any physical
8104 				 * interface, it cannot be the dst_ill, hence
8105 				 * in such a case call ip_newroute_get_dst_ll()
8106 				 * with the stq_ill instead of the ire_ipif ILL.
8107 				 * The function returns a refheld ill.
8108 				 */
8109 				if ((ire->ire_type == IRE_CACHE) &&
8110 				    IS_VNI(ire->ire_ipif->ipif_ill))
8111 					dst_ill = ip_newroute_get_dst_ill(
8112 					    ire->ire_stq->q_ptr);
8113 				else
8114 					dst_ill = ip_newroute_get_dst_ill(
8115 					    ire->ire_ipif->ipif_ill);
8116 			}
8117 			if (dst_ill == NULL) {
8118 				if (ip_debug > 2) {
8119 					pr_addr_dbg("ip_newroute: "
8120 					    "no dst ill for dst"
8121 					    " %s\n", AF_INET, &dst);
8122 				}
8123 				goto icmp_err_ret;
8124 			}
8125 		} else {
8126 			dst_ill = ire->ire_ipif->ipif_ill;
8127 			/* for uniformity */
8128 			ill_refhold(dst_ill);
8129 			/*
8130 			 * We should have found a route matching ill as we
8131 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8132 			 * Rather than asserting, when there is a mismatch,
8133 			 * we just drop the packet.
8134 			 */
8135 			if (dst_ill != attach_ill) {
8136 				ip0dbg(("ip_newroute: Packet dropped as "
8137 				    "IPIF_NOFAILOVER ill is %s, "
8138 				    "ire->ire_ipif->ipif_ill is %s\n",
8139 				    attach_ill->ill_name,
8140 				    dst_ill->ill_name));
8141 				ill_refrele(attach_ill);
8142 				goto icmp_err_ret;
8143 			}
8144 		}
8145 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8146 		if (attach_ill != NULL) {
8147 			ill_refrele(attach_ill);
8148 			attach_ill = NULL;
8149 			do_attach_ill = B_TRUE;
8150 		}
8151 		ASSERT(dst_ill != NULL);
8152 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8153 
8154 		/*
8155 		 * Pick the best source address from dst_ill.
8156 		 *
8157 		 * 1) If it is part of a multipathing group, we would
8158 		 *    like to spread the inbound packets across different
8159 		 *    interfaces. ipif_select_source picks a random source
8160 		 *    across the different ills in the group.
8161 		 *
8162 		 * 2) If it is not part of a multipathing group, we try
8163 		 *    to pick the source address from the destination
8164 		 *    route. Clustering assumes that when we have multiple
8165 		 *    prefixes hosted on an interface, the prefix of the
8166 		 *    source address matches the prefix of the destination
8167 		 *    route. We do this only if the address is not
8168 		 *    DEPRECATED.
8169 		 *
8170 		 * 3) If the conn is in a different zone than the ire, we
8171 		 *    need to pick a source address from the right zone.
8172 		 *
8173 		 * NOTE : If we hit case (1) above, the prefix of the source
8174 		 *	  address picked may not match the prefix of the
8175 		 *	  destination routes prefix as ipif_select_source
8176 		 *	  does not look at "dst" while picking a source
8177 		 *	  address.
8178 		 *	  If we want the same behavior as (2), we will need
8179 		 *	  to change the behavior of ipif_select_source.
8180 		 */
8181 		ASSERT(src_ipif == NULL);
8182 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8183 			/*
8184 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8185 			 * Check that the ipif matching the requested source
8186 			 * address still exists.
8187 			 */
8188 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8189 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8190 		}
8191 
8192 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8193 
8194 		if (src_ipif == NULL &&
8195 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8196 			ire_marks |= IRE_MARK_USESRC_CHECK;
8197 			if ((dst_ill->ill_group != NULL) ||
8198 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8199 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8200 			    ire->ire_zoneid != ALL_ZONES) ||
8201 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8202 				/*
8203 				 * If the destination is reachable via a
8204 				 * given gateway, the selected source address
8205 				 * should be in the same subnet as the gateway.
8206 				 * Otherwise, the destination is not reachable.
8207 				 *
8208 				 * If there are no interfaces on the same subnet
8209 				 * as the destination, ipif_select_source gives
8210 				 * first non-deprecated interface which might be
8211 				 * on a different subnet than the gateway.
8212 				 * This is not desirable. Hence pass the dst_ire
8213 				 * source address to ipif_select_source.
8214 				 * It is sure that the destination is reachable
8215 				 * with the dst_ire source address subnet.
8216 				 * So passing dst_ire source address to
8217 				 * ipif_select_source will make sure that the
8218 				 * selected source will be on the same subnet
8219 				 * as dst_ire source address.
8220 				 */
8221 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8222 				src_ipif = ipif_select_source(dst_ill, saddr,
8223 				    zoneid);
8224 				if (src_ipif == NULL) {
8225 					if (ip_debug > 2) {
8226 						pr_addr_dbg("ip_newroute: "
8227 						    "no src for dst %s ",
8228 						    AF_INET, &dst);
8229 						printf("through interface %s\n",
8230 						    dst_ill->ill_name);
8231 					}
8232 					goto icmp_err_ret;
8233 				}
8234 			} else {
8235 				src_ipif = ire->ire_ipif;
8236 				ASSERT(src_ipif != NULL);
8237 				/* hold src_ipif for uniformity */
8238 				ipif_refhold(src_ipif);
8239 			}
8240 		}
8241 
8242 		/*
8243 		 * Assign a source address while we have the conn.
8244 		 * We can't have ip_wput_ire pick a source address when the
8245 		 * packet returns from arp since we need to look at
8246 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8247 		 * going through arp.
8248 		 *
8249 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8250 		 *	  it uses ip6i to store this information.
8251 		 */
8252 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8253 			ipha->ipha_src = src_ipif->ipif_src_addr;
8254 
8255 		if (ip_debug > 3) {
8256 			/* ip2dbg */
8257 			pr_addr_dbg("ip_newroute: first hop %s\n",
8258 			    AF_INET, &gw);
8259 		}
8260 		ip2dbg(("\tire type %s (%d)\n",
8261 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8262 
8263 		/*
8264 		 * The TTL of multirouted packets is bounded by the
8265 		 * ip_multirt_ttl ndd variable.
8266 		 */
8267 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8268 			/* Force TTL of multirouted packets */
8269 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8270 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8271 				ip2dbg(("ip_newroute: forcing multirt TTL "
8272 				    "to %d (was %d), dst 0x%08x\n",
8273 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8274 				    ntohl(sire->ire_addr)));
8275 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8276 			}
8277 		}
8278 		/*
8279 		 * At this point in ip_newroute(), ire is either the
8280 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8281 		 * destination or an IRE_INTERFACE type that should be used
8282 		 * to resolve an on-subnet destination or an on-subnet
8283 		 * next-hop gateway.
8284 		 *
8285 		 * In the IRE_CACHE case, we have the following :
8286 		 *
8287 		 * 1) src_ipif - used for getting a source address.
8288 		 *
8289 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8290 		 *    means packets using this IRE_CACHE will go out on
8291 		 *    dst_ill.
8292 		 *
8293 		 * 3) The IRE sire will point to the prefix that is the
8294 		 *    longest  matching route for the destination. These
8295 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8296 		 *
8297 		 *    The newly created IRE_CACHE entry for the off-subnet
8298 		 *    destination is tied to both the prefix route and the
8299 		 *    interface route used to resolve the next-hop gateway
8300 		 *    via the ire_phandle and ire_ihandle fields,
8301 		 *    respectively.
8302 		 *
8303 		 * In the IRE_INTERFACE case, we have the following :
8304 		 *
8305 		 * 1) src_ipif - used for getting a source address.
8306 		 *
8307 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8308 		 *    means packets using the IRE_CACHE that we will build
8309 		 *    here will go out on dst_ill.
8310 		 *
8311 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8312 		 *    to be created will only be tied to the IRE_INTERFACE
8313 		 *    that was derived from the ire_ihandle field.
8314 		 *
8315 		 *    If sire is non-NULL, it means the destination is
8316 		 *    off-link and we will first create the IRE_CACHE for the
8317 		 *    gateway. Next time through ip_newroute, we will create
8318 		 *    the IRE_CACHE for the final destination as described
8319 		 *    above.
8320 		 *
8321 		 * In both cases, after the current resolution has been
8322 		 * completed (or possibly initialised, in the IRE_INTERFACE
8323 		 * case), the loop may be re-entered to attempt the resolution
8324 		 * of another RTF_MULTIRT route.
8325 		 *
8326 		 * When an IRE_CACHE entry for the off-subnet destination is
8327 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8328 		 * for further processing in emission loops.
8329 		 */
8330 		save_ire = ire;
8331 		switch (ire->ire_type) {
8332 		case IRE_CACHE: {
8333 			ire_t	*ipif_ire;
8334 
8335 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8336 			if (gw == 0)
8337 				gw = ire->ire_gateway_addr;
8338 			/*
8339 			 * We need 3 ire's to create a new cache ire for an
8340 			 * off-link destination from the cache ire of the
8341 			 * gateway.
8342 			 *
8343 			 *	1. The prefix ire 'sire' (Note that this does
8344 			 *	   not apply to the conn_nexthop_set case)
8345 			 *	2. The cache ire of the gateway 'ire'
8346 			 *	3. The interface ire 'ipif_ire'
8347 			 *
8348 			 * We have (1) and (2). We lookup (3) below.
8349 			 *
8350 			 * If there is no interface route to the gateway,
8351 			 * it is a race condition, where we found the cache
8352 			 * but the interface route has been deleted.
8353 			 */
8354 			if (ip_nexthop) {
8355 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8356 			} else {
8357 				ipif_ire =
8358 				    ire_ihandle_lookup_offlink(ire, sire);
8359 			}
8360 			if (ipif_ire == NULL) {
8361 				ip1dbg(("ip_newroute: "
8362 				    "ire_ihandle_lookup_offlink failed\n"));
8363 				goto icmp_err_ret;
8364 			}
8365 
8366 			/*
8367 			 * Check cached gateway IRE for any security
8368 			 * attributes; if found, associate the gateway
8369 			 * credentials group to the destination IRE.
8370 			 */
8371 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8372 				mutex_enter(&attrp->igsa_lock);
8373 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8374 					GCGRP_REFHOLD(gcgrp);
8375 				mutex_exit(&attrp->igsa_lock);
8376 			}
8377 
8378 			/*
8379 			 * XXX For the source of the resolver mp,
8380 			 * we are using the same DL_UNITDATA_REQ
8381 			 * (from save_ire->ire_nce->nce_res_mp)
8382 			 * though the save_ire is not pointing at the same ill.
8383 			 * This is incorrect. We need to send it up to the
8384 			 * resolver to get the right res_mp. For ethernets
8385 			 * this may be okay (ill_type == DL_ETHER).
8386 			 */
8387 
8388 			ire = ire_create(
8389 			    (uchar_t *)&dst,		/* dest address */
8390 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8391 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8392 			    (uchar_t *)&gw,		/* gateway address */
8393 			    &save_ire->ire_max_frag,
8394 			    save_ire->ire_nce,		/* src nce */
8395 			    dst_ill->ill_rq,		/* recv-from queue */
8396 			    dst_ill->ill_wq,		/* send-to queue */
8397 			    IRE_CACHE,			/* IRE type */
8398 			    src_ipif,
8399 			    (sire != NULL) ?
8400 			    sire->ire_mask : 0, 	/* Parent mask */
8401 			    (sire != NULL) ?
8402 			    sire->ire_phandle : 0,	/* Parent handle */
8403 			    ipif_ire->ire_ihandle,	/* Interface handle */
8404 			    (sire != NULL) ? (sire->ire_flags &
8405 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8406 			    (sire != NULL) ?
8407 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8408 			    NULL,
8409 			    gcgrp,
8410 			    ipst);
8411 
8412 			if (ire == NULL) {
8413 				if (gcgrp != NULL) {
8414 					GCGRP_REFRELE(gcgrp);
8415 					gcgrp = NULL;
8416 				}
8417 				ire_refrele(ipif_ire);
8418 				ire_refrele(save_ire);
8419 				break;
8420 			}
8421 
8422 			/* reference now held by IRE */
8423 			gcgrp = NULL;
8424 
8425 			ire->ire_marks |= ire_marks;
8426 
8427 			/*
8428 			 * Prevent sire and ipif_ire from getting deleted.
8429 			 * The newly created ire is tied to both of them via
8430 			 * the phandle and ihandle respectively.
8431 			 */
8432 			if (sire != NULL) {
8433 				IRB_REFHOLD(sire->ire_bucket);
8434 				/* Has it been removed already ? */
8435 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8436 					IRB_REFRELE(sire->ire_bucket);
8437 					ire_refrele(ipif_ire);
8438 					ire_refrele(save_ire);
8439 					break;
8440 				}
8441 			}
8442 
8443 			IRB_REFHOLD(ipif_ire->ire_bucket);
8444 			/* Has it been removed already ? */
8445 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8446 				IRB_REFRELE(ipif_ire->ire_bucket);
8447 				if (sire != NULL)
8448 					IRB_REFRELE(sire->ire_bucket);
8449 				ire_refrele(ipif_ire);
8450 				ire_refrele(save_ire);
8451 				break;
8452 			}
8453 
8454 			xmit_mp = first_mp;
8455 			/*
8456 			 * In the case of multirouting, a copy
8457 			 * of the packet is done before its sending.
8458 			 * The copy is used to attempt another
8459 			 * route resolution, in a next loop.
8460 			 */
8461 			if (ire->ire_flags & RTF_MULTIRT) {
8462 				copy_mp = copymsg(first_mp);
8463 				if (copy_mp != NULL) {
8464 					xmit_mp = copy_mp;
8465 					MULTIRT_DEBUG_TAG(first_mp);
8466 				}
8467 			}
8468 			ire_add_then_send(q, ire, xmit_mp);
8469 			ire_refrele(save_ire);
8470 
8471 			/* Assert that sire is not deleted yet. */
8472 			if (sire != NULL) {
8473 				ASSERT(sire->ire_ptpn != NULL);
8474 				IRB_REFRELE(sire->ire_bucket);
8475 			}
8476 
8477 			/* Assert that ipif_ire is not deleted yet. */
8478 			ASSERT(ipif_ire->ire_ptpn != NULL);
8479 			IRB_REFRELE(ipif_ire->ire_bucket);
8480 			ire_refrele(ipif_ire);
8481 
8482 			/*
8483 			 * If copy_mp is not NULL, multirouting was
8484 			 * requested. We loop to initiate a next
8485 			 * route resolution attempt, starting from sire.
8486 			 */
8487 			if (copy_mp != NULL) {
8488 				/*
8489 				 * Search for the next unresolved
8490 				 * multirt route.
8491 				 */
8492 				copy_mp = NULL;
8493 				ipif_ire = NULL;
8494 				ire = NULL;
8495 				multirt_resolve_next = B_TRUE;
8496 				continue;
8497 			}
8498 			if (sire != NULL)
8499 				ire_refrele(sire);
8500 			ipif_refrele(src_ipif);
8501 			ill_refrele(dst_ill);
8502 			return;
8503 		}
8504 		case IRE_IF_NORESOLVER: {
8505 
8506 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8507 			    dst_ill->ill_resolver_mp == NULL) {
8508 				ip1dbg(("ip_newroute: dst_ill %p "
8509 				    "for IRE_IF_NORESOLVER ire %p has "
8510 				    "no ill_resolver_mp\n",
8511 				    (void *)dst_ill, (void *)ire));
8512 				break;
8513 			}
8514 
8515 			/*
8516 			 * TSol note: We are creating the ire cache for the
8517 			 * destination 'dst'. If 'dst' is offlink, going
8518 			 * through the first hop 'gw', the security attributes
8519 			 * of 'dst' must be set to point to the gateway
8520 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8521 			 * is possible that 'dst' is a potential gateway that is
8522 			 * referenced by some route that has some security
8523 			 * attributes. Thus in the former case, we need to do a
8524 			 * gcgrp_lookup of 'gw' while in the latter case we
8525 			 * need to do gcgrp_lookup of 'dst' itself.
8526 			 */
8527 			ga.ga_af = AF_INET;
8528 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8529 			    &ga.ga_addr);
8530 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8531 
8532 			ire = ire_create(
8533 			    (uchar_t *)&dst,		/* dest address */
8534 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8535 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8536 			    (uchar_t *)&gw,		/* gateway address */
8537 			    &save_ire->ire_max_frag,
8538 			    NULL,			/* no src nce */
8539 			    dst_ill->ill_rq,		/* recv-from queue */
8540 			    dst_ill->ill_wq,		/* send-to queue */
8541 			    IRE_CACHE,
8542 			    src_ipif,
8543 			    save_ire->ire_mask,		/* Parent mask */
8544 			    (sire != NULL) ?		/* Parent handle */
8545 			    sire->ire_phandle : 0,
8546 			    save_ire->ire_ihandle,	/* Interface handle */
8547 			    (sire != NULL) ? sire->ire_flags &
8548 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8549 			    &(save_ire->ire_uinfo),
8550 			    NULL,
8551 			    gcgrp,
8552 			    ipst);
8553 
8554 			if (ire == NULL) {
8555 				if (gcgrp != NULL) {
8556 					GCGRP_REFRELE(gcgrp);
8557 					gcgrp = NULL;
8558 				}
8559 				ire_refrele(save_ire);
8560 				break;
8561 			}
8562 
8563 			/* reference now held by IRE */
8564 			gcgrp = NULL;
8565 
8566 			ire->ire_marks |= ire_marks;
8567 
8568 			/* Prevent save_ire from getting deleted */
8569 			IRB_REFHOLD(save_ire->ire_bucket);
8570 			/* Has it been removed already ? */
8571 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8572 				IRB_REFRELE(save_ire->ire_bucket);
8573 				ire_refrele(save_ire);
8574 				break;
8575 			}
8576 
8577 			/*
8578 			 * In the case of multirouting, a copy
8579 			 * of the packet is made before it is sent.
8580 			 * The copy is used in the next
8581 			 * loop to attempt another resolution.
8582 			 */
8583 			xmit_mp = first_mp;
8584 			if ((sire != NULL) &&
8585 			    (sire->ire_flags & RTF_MULTIRT)) {
8586 				copy_mp = copymsg(first_mp);
8587 				if (copy_mp != NULL) {
8588 					xmit_mp = copy_mp;
8589 					MULTIRT_DEBUG_TAG(first_mp);
8590 				}
8591 			}
8592 			ire_add_then_send(q, ire, xmit_mp);
8593 
8594 			/* Assert that it is not deleted yet. */
8595 			ASSERT(save_ire->ire_ptpn != NULL);
8596 			IRB_REFRELE(save_ire->ire_bucket);
8597 			ire_refrele(save_ire);
8598 
8599 			if (copy_mp != NULL) {
8600 				/*
8601 				 * If we found a (no)resolver, we ignore any
8602 				 * trailing top priority IRE_CACHE in further
8603 				 * loops. This ensures that we do not omit any
8604 				 * (no)resolver.
8605 				 * This IRE_CACHE, if any, will be processed
8606 				 * by another thread entering ip_newroute().
8607 				 * IRE_CACHE entries, if any, will be processed
8608 				 * by another thread entering ip_newroute(),
8609 				 * (upon resolver response, for instance).
8610 				 * This aims to force parallel multirt
8611 				 * resolutions as soon as a packet must be sent.
8612 				 * In the best case, after the tx of only one
8613 				 * packet, all reachable routes are resolved.
8614 				 * Otherwise, the resolution of all RTF_MULTIRT
8615 				 * routes would require several emissions.
8616 				 */
8617 				multirt_flags &= ~MULTIRT_CACHEGW;
8618 
8619 				/*
8620 				 * Search for the next unresolved multirt
8621 				 * route.
8622 				 */
8623 				copy_mp = NULL;
8624 				save_ire = NULL;
8625 				ire = NULL;
8626 				multirt_resolve_next = B_TRUE;
8627 				continue;
8628 			}
8629 
8630 			/*
8631 			 * Don't need sire anymore
8632 			 */
8633 			if (sire != NULL)
8634 				ire_refrele(sire);
8635 
8636 			ipif_refrele(src_ipif);
8637 			ill_refrele(dst_ill);
8638 			return;
8639 		}
8640 		case IRE_IF_RESOLVER:
8641 			/*
8642 			 * We can't build an IRE_CACHE yet, but at least we
8643 			 * found a resolver that can help.
8644 			 */
8645 			res_mp = dst_ill->ill_resolver_mp;
8646 			if (!OK_RESOLVER_MP(res_mp))
8647 				break;
8648 
8649 			/*
8650 			 * To be at this point in the code with a non-zero gw
8651 			 * means that dst is reachable through a gateway that
8652 			 * we have never resolved.  By changing dst to the gw
8653 			 * addr we resolve the gateway first.
8654 			 * When ire_add_then_send() tries to put the IP dg
8655 			 * to dst, it will reenter ip_newroute() at which
8656 			 * time we will find the IRE_CACHE for the gw and
8657 			 * create another IRE_CACHE in case IRE_CACHE above.
8658 			 */
8659 			if (gw != INADDR_ANY) {
8660 				/*
8661 				 * The source ipif that was determined above was
8662 				 * relative to the destination address, not the
8663 				 * gateway's. If src_ipif was not taken out of
8664 				 * the IRE_IF_RESOLVER entry, we'll need to call
8665 				 * ipif_select_source() again.
8666 				 */
8667 				if (src_ipif != ire->ire_ipif) {
8668 					ipif_refrele(src_ipif);
8669 					src_ipif = ipif_select_source(dst_ill,
8670 					    gw, zoneid);
8671 					if (src_ipif == NULL) {
8672 						if (ip_debug > 2) {
8673 							pr_addr_dbg(
8674 							    "ip_newroute: no "
8675 							    "src for gw %s ",
8676 							    AF_INET, &gw);
8677 							printf("through "
8678 							    "interface %s\n",
8679 							    dst_ill->ill_name);
8680 						}
8681 						goto icmp_err_ret;
8682 					}
8683 				}
8684 				save_dst = dst;
8685 				dst = gw;
8686 				gw = INADDR_ANY;
8687 			}
8688 
8689 			/*
8690 			 * We obtain a partial IRE_CACHE which we will pass
8691 			 * along with the resolver query.  When the response
8692 			 * comes back it will be there ready for us to add.
8693 			 * The ire_max_frag is atomically set under the
8694 			 * irebucket lock in ire_add_v[46].
8695 			 */
8696 
8697 			ire = ire_create_mp(
8698 			    (uchar_t *)&dst,		/* dest address */
8699 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8700 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8701 			    (uchar_t *)&gw,		/* gateway address */
8702 			    NULL,			/* ire_max_frag */
8703 			    NULL,			/* no src nce */
8704 			    dst_ill->ill_rq,		/* recv-from queue */
8705 			    dst_ill->ill_wq,		/* send-to queue */
8706 			    IRE_CACHE,
8707 			    src_ipif,			/* Interface ipif */
8708 			    save_ire->ire_mask,		/* Parent mask */
8709 			    0,
8710 			    save_ire->ire_ihandle,	/* Interface handle */
8711 			    0,				/* flags if any */
8712 			    &(save_ire->ire_uinfo),
8713 			    NULL,
8714 			    NULL,
8715 			    ipst);
8716 
8717 			if (ire == NULL) {
8718 				ire_refrele(save_ire);
8719 				break;
8720 			}
8721 
8722 			if ((sire != NULL) &&
8723 			    (sire->ire_flags & RTF_MULTIRT)) {
8724 				copy_mp = copymsg(first_mp);
8725 				if (copy_mp != NULL)
8726 					MULTIRT_DEBUG_TAG(copy_mp);
8727 			}
8728 
8729 			ire->ire_marks |= ire_marks;
8730 
8731 			/*
8732 			 * Construct message chain for the resolver
8733 			 * of the form:
8734 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8735 			 * Packet could contain a IPSEC_OUT mp.
8736 			 *
8737 			 * NOTE : ire will be added later when the response
8738 			 * comes back from ARP. If the response does not
8739 			 * come back, ARP frees the packet. For this reason,
8740 			 * we can't REFHOLD the bucket of save_ire to prevent
8741 			 * deletions. We may not be able to REFRELE the bucket
8742 			 * if the response never comes back. Thus, before
8743 			 * adding the ire, ire_add_v4 will make sure that the
8744 			 * interface route does not get deleted. This is the
8745 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8746 			 * where we can always prevent deletions because of
8747 			 * the synchronous nature of adding IRES i.e
8748 			 * ire_add_then_send is called after creating the IRE.
8749 			 */
8750 			ASSERT(ire->ire_mp != NULL);
8751 			ire->ire_mp->b_cont = first_mp;
8752 			/* Have saved_mp handy, for cleanup if canput fails */
8753 			saved_mp = mp;
8754 			mp = copyb(res_mp);
8755 			if (mp == NULL) {
8756 				/* Prepare for cleanup */
8757 				mp = saved_mp; /* pkt */
8758 				ire_delete(ire); /* ire_mp */
8759 				ire = NULL;
8760 				ire_refrele(save_ire);
8761 				if (copy_mp != NULL) {
8762 					MULTIRT_DEBUG_UNTAG(copy_mp);
8763 					freemsg(copy_mp);
8764 					copy_mp = NULL;
8765 				}
8766 				break;
8767 			}
8768 			linkb(mp, ire->ire_mp);
8769 
8770 			/*
8771 			 * Fill in the source and dest addrs for the resolver.
8772 			 * NOTE: this depends on memory layouts imposed by
8773 			 * ill_init().
8774 			 */
8775 			areq = (areq_t *)mp->b_rptr;
8776 			addrp = (ipaddr_t *)((char *)areq +
8777 			    areq->areq_sender_addr_offset);
8778 			if (do_attach_ill) {
8779 				/*
8780 				 * This is bind to no failover case.
8781 				 * arp packet also must go out on attach_ill.
8782 				 */
8783 				ASSERT(ipha->ipha_src != NULL);
8784 				*addrp = ipha->ipha_src;
8785 			} else {
8786 				*addrp = save_ire->ire_src_addr;
8787 			}
8788 
8789 			ire_refrele(save_ire);
8790 			addrp = (ipaddr_t *)((char *)areq +
8791 			    areq->areq_target_addr_offset);
8792 			*addrp = dst;
8793 			/* Up to the resolver. */
8794 			if (canputnext(dst_ill->ill_rq) &&
8795 			    !(dst_ill->ill_arp_closing)) {
8796 				putnext(dst_ill->ill_rq, mp);
8797 				ire = NULL;
8798 				if (copy_mp != NULL) {
8799 					/*
8800 					 * If we found a resolver, we ignore
8801 					 * any trailing top priority IRE_CACHE
8802 					 * in the further loops. This ensures
8803 					 * that we do not omit any resolver.
8804 					 * IRE_CACHE entries, if any, will be
8805 					 * processed next time we enter
8806 					 * ip_newroute().
8807 					 */
8808 					multirt_flags &= ~MULTIRT_CACHEGW;
8809 					/*
8810 					 * Search for the next unresolved
8811 					 * multirt route.
8812 					 */
8813 					first_mp = copy_mp;
8814 					copy_mp = NULL;
8815 					/* Prepare the next resolution loop. */
8816 					mp = first_mp;
8817 					EXTRACT_PKT_MP(mp, first_mp,
8818 					    mctl_present);
8819 					if (mctl_present)
8820 						io = (ipsec_out_t *)
8821 						    first_mp->b_rptr;
8822 					ipha = (ipha_t *)mp->b_rptr;
8823 
8824 					ASSERT(sire != NULL);
8825 
8826 					dst = save_dst;
8827 					multirt_resolve_next = B_TRUE;
8828 					continue;
8829 				}
8830 
8831 				if (sire != NULL)
8832 					ire_refrele(sire);
8833 
8834 				/*
8835 				 * The response will come back in ip_wput
8836 				 * with db_type IRE_DB_TYPE.
8837 				 */
8838 				ipif_refrele(src_ipif);
8839 				ill_refrele(dst_ill);
8840 				return;
8841 			} else {
8842 				/* Prepare for cleanup */
8843 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8844 				    mp);
8845 				mp->b_cont = NULL;
8846 				freeb(mp); /* areq */
8847 				/*
8848 				 * this is an ire that is not added to the
8849 				 * cache. ire_freemblk will handle the release
8850 				 * of any resources associated with the ire.
8851 				 */
8852 				ire_delete(ire); /* ire_mp */
8853 				mp = saved_mp; /* pkt */
8854 				ire = NULL;
8855 				if (copy_mp != NULL) {
8856 					MULTIRT_DEBUG_UNTAG(copy_mp);
8857 					freemsg(copy_mp);
8858 					copy_mp = NULL;
8859 				}
8860 				break;
8861 			}
8862 		default:
8863 			break;
8864 		}
8865 	} while (multirt_resolve_next);
8866 
8867 	ip1dbg(("ip_newroute: dropped\n"));
8868 	/* Did this packet originate externally? */
8869 	if (mp->b_prev) {
8870 		mp->b_next = NULL;
8871 		mp->b_prev = NULL;
8872 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8873 	} else {
8874 		if (dst_ill != NULL) {
8875 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8876 		} else {
8877 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8878 		}
8879 	}
8880 	ASSERT(copy_mp == NULL);
8881 	MULTIRT_DEBUG_UNTAG(first_mp);
8882 	freemsg(first_mp);
8883 	if (ire != NULL)
8884 		ire_refrele(ire);
8885 	if (sire != NULL)
8886 		ire_refrele(sire);
8887 	if (src_ipif != NULL)
8888 		ipif_refrele(src_ipif);
8889 	if (dst_ill != NULL)
8890 		ill_refrele(dst_ill);
8891 	return;
8892 
8893 icmp_err_ret:
8894 	ip1dbg(("ip_newroute: no route\n"));
8895 	if (src_ipif != NULL)
8896 		ipif_refrele(src_ipif);
8897 	if (dst_ill != NULL)
8898 		ill_refrele(dst_ill);
8899 	if (sire != NULL)
8900 		ire_refrele(sire);
8901 	/* Did this packet originate externally? */
8902 	if (mp->b_prev) {
8903 		mp->b_next = NULL;
8904 		mp->b_prev = NULL;
8905 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8906 		q = WR(q);
8907 	} else {
8908 		/*
8909 		 * There is no outgoing ill, so just increment the
8910 		 * system MIB.
8911 		 */
8912 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8913 		/*
8914 		 * Since ip_wput() isn't close to finished, we fill
8915 		 * in enough of the header for credible error reporting.
8916 		 */
8917 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8918 			/* Failed */
8919 			MULTIRT_DEBUG_UNTAG(first_mp);
8920 			freemsg(first_mp);
8921 			if (ire != NULL)
8922 				ire_refrele(ire);
8923 			return;
8924 		}
8925 	}
8926 
8927 	/*
8928 	 * At this point we will have ire only if RTF_BLACKHOLE
8929 	 * or RTF_REJECT flags are set on the IRE. It will not
8930 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8931 	 */
8932 	if (ire != NULL) {
8933 		if (ire->ire_flags & RTF_BLACKHOLE) {
8934 			ire_refrele(ire);
8935 			MULTIRT_DEBUG_UNTAG(first_mp);
8936 			freemsg(first_mp);
8937 			return;
8938 		}
8939 		ire_refrele(ire);
8940 	}
8941 	if (ip_source_routed(ipha, ipst)) {
8942 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8943 		    zoneid, ipst);
8944 		return;
8945 	}
8946 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8947 }
8948 
8949 ip_opt_info_t zero_info;
8950 
8951 /*
8952  * IPv4 -
8953  * ip_newroute_ipif is called by ip_wput_multicast and
8954  * ip_rput_forward_multicast whenever we need to send
8955  * out a packet to a destination address for which we do not have specific
8956  * routing information. It is used when the packet will be sent out
8957  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8958  * socket option is set or icmp error message wants to go out on a particular
8959  * interface for a unicast packet.
8960  *
8961  * In most cases, the destination address is resolved thanks to the ipif
8962  * intrinsic resolver. However, there are some cases where the call to
8963  * ip_newroute_ipif must take into account the potential presence of
8964  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8965  * that uses the interface. This is specified through flags,
8966  * which can be a combination of:
8967  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8968  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8969  *   and flags. Additionally, the packet source address has to be set to
8970  *   the specified address. The caller is thus expected to set this flag
8971  *   if the packet has no specific source address yet.
8972  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8973  *   flag, the resulting ire will inherit the flag. All unresolved routes
8974  *   to the destination must be explored in the same call to
8975  *   ip_newroute_ipif().
8976  */
8977 static void
8978 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8979     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8980 {
8981 	areq_t	*areq;
8982 	ire_t	*ire = NULL;
8983 	mblk_t	*res_mp;
8984 	ipaddr_t *addrp;
8985 	mblk_t *first_mp;
8986 	ire_t	*save_ire = NULL;
8987 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8988 	ipif_t	*src_ipif = NULL;
8989 	ushort_t ire_marks = 0;
8990 	ill_t	*dst_ill = NULL;
8991 	boolean_t mctl_present;
8992 	ipsec_out_t *io;
8993 	ipha_t *ipha;
8994 	int	ihandle = 0;
8995 	mblk_t	*saved_mp;
8996 	ire_t   *fire = NULL;
8997 	mblk_t  *copy_mp = NULL;
8998 	boolean_t multirt_resolve_next;
8999 	boolean_t unspec_src;
9000 	ipaddr_t ipha_dst;
9001 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9002 
9003 	/*
9004 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9005 	 * here for uniformity
9006 	 */
9007 	ipif_refhold(ipif);
9008 
9009 	/*
9010 	 * This loop is run only once in most cases.
9011 	 * We loop to resolve further routes only when the destination
9012 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9013 	 */
9014 	do {
9015 		if (dst_ill != NULL) {
9016 			ill_refrele(dst_ill);
9017 			dst_ill = NULL;
9018 		}
9019 		if (src_ipif != NULL) {
9020 			ipif_refrele(src_ipif);
9021 			src_ipif = NULL;
9022 		}
9023 		multirt_resolve_next = B_FALSE;
9024 
9025 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9026 		    ipif->ipif_ill->ill_name));
9027 
9028 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9029 		if (mctl_present)
9030 			io = (ipsec_out_t *)first_mp->b_rptr;
9031 
9032 		ipha = (ipha_t *)mp->b_rptr;
9033 
9034 		/*
9035 		 * Save the packet destination address, we may need it after
9036 		 * the packet has been consumed.
9037 		 */
9038 		ipha_dst = ipha->ipha_dst;
9039 
9040 		/*
9041 		 * If the interface is a pt-pt interface we look for an
9042 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9043 		 * local_address and the pt-pt destination address. Otherwise
9044 		 * we just match the local address.
9045 		 * NOTE: dst could be different than ipha->ipha_dst in case
9046 		 * of sending igmp multicast packets over a point-to-point
9047 		 * connection.
9048 		 * Thus we must be careful enough to check ipha_dst to be a
9049 		 * multicast address, otherwise it will take xmit_if path for
9050 		 * multicast packets resulting into kernel stack overflow by
9051 		 * repeated calls to ip_newroute_ipif from ire_send().
9052 		 */
9053 		if (CLASSD(ipha_dst) &&
9054 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9055 			goto err_ret;
9056 		}
9057 
9058 		/*
9059 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9060 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9061 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9062 		 * propagate its flags to the new ire.
9063 		 */
9064 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9065 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9066 			ip2dbg(("ip_newroute_ipif: "
9067 			    "ipif_lookup_multi_ire("
9068 			    "ipif %p, dst %08x) = fire %p\n",
9069 			    (void *)ipif, ntohl(dst), (void *)fire));
9070 		}
9071 
9072 		if (mctl_present && io->ipsec_out_attach_if) {
9073 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9074 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9075 
9076 			/* Failure case frees things for us. */
9077 			if (attach_ill == NULL) {
9078 				ipif_refrele(ipif);
9079 				if (fire != NULL)
9080 					ire_refrele(fire);
9081 				return;
9082 			}
9083 
9084 			/*
9085 			 * Check if we need an ire that will not be
9086 			 * looked up by anybody else i.e. HIDDEN.
9087 			 */
9088 			if (ill_is_probeonly(attach_ill)) {
9089 				ire_marks = IRE_MARK_HIDDEN;
9090 			}
9091 			/*
9092 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9093 			 * case.
9094 			 */
9095 			dst_ill = ipif->ipif_ill;
9096 			/* attach_ill has been refheld by ip_grab_attach_ill */
9097 			ASSERT(dst_ill == attach_ill);
9098 		} else {
9099 			/*
9100 			 * If the interface belongs to an interface group,
9101 			 * make sure the next possible interface in the group
9102 			 * is used.  This encourages load spreading among
9103 			 * peers in an interface group.
9104 			 * Note: load spreading is disabled for RTF_MULTIRT
9105 			 * routes.
9106 			 */
9107 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9108 			    (fire->ire_flags & RTF_MULTIRT)) {
9109 				/*
9110 				 * Don't perform outbound load spreading
9111 				 * in the case of an RTF_MULTIRT issued route,
9112 				 * we actually typically want to replicate
9113 				 * outgoing packets through particular
9114 				 * interfaces.
9115 				 */
9116 				dst_ill = ipif->ipif_ill;
9117 				ill_refhold(dst_ill);
9118 			} else {
9119 				dst_ill = ip_newroute_get_dst_ill(
9120 				    ipif->ipif_ill);
9121 			}
9122 			if (dst_ill == NULL) {
9123 				if (ip_debug > 2) {
9124 					pr_addr_dbg("ip_newroute_ipif: "
9125 					    "no dst ill for dst %s\n",
9126 					    AF_INET, &dst);
9127 				}
9128 				goto err_ret;
9129 			}
9130 		}
9131 
9132 		/*
9133 		 * Pick a source address preferring non-deprecated ones.
9134 		 * Unlike ip_newroute, we don't do any source address
9135 		 * selection here since for multicast it really does not help
9136 		 * in inbound load spreading as in the unicast case.
9137 		 */
9138 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9139 		    (fire->ire_flags & RTF_SETSRC)) {
9140 			/*
9141 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9142 			 * on that interface. This ire has RTF_SETSRC flag, so
9143 			 * the source address of the packet must be changed.
9144 			 * Check that the ipif matching the requested source
9145 			 * address still exists.
9146 			 */
9147 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9148 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9149 		}
9150 
9151 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9152 
9153 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9154 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9155 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9156 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9157 		    (src_ipif == NULL) &&
9158 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9159 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9160 			if (src_ipif == NULL) {
9161 				if (ip_debug > 2) {
9162 					/* ip1dbg */
9163 					pr_addr_dbg("ip_newroute_ipif: "
9164 					    "no src for dst %s",
9165 					    AF_INET, &dst);
9166 				}
9167 				ip1dbg((" through interface %s\n",
9168 				    dst_ill->ill_name));
9169 				goto err_ret;
9170 			}
9171 			ipif_refrele(ipif);
9172 			ipif = src_ipif;
9173 			ipif_refhold(ipif);
9174 		}
9175 		if (src_ipif == NULL) {
9176 			src_ipif = ipif;
9177 			ipif_refhold(src_ipif);
9178 		}
9179 
9180 		/*
9181 		 * Assign a source address while we have the conn.
9182 		 * We can't have ip_wput_ire pick a source address when the
9183 		 * packet returns from arp since conn_unspec_src might be set
9184 		 * and we lose the conn when going through arp.
9185 		 */
9186 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9187 			ipha->ipha_src = src_ipif->ipif_src_addr;
9188 
9189 		/*
9190 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9191 		 * that the outgoing interface does not have an interface ire.
9192 		 */
9193 		if (CLASSD(ipha_dst) && (connp == NULL ||
9194 		    connp->conn_outgoing_ill == NULL) &&
9195 		    infop->ip_opt_ill_index == 0) {
9196 			/* ipif_to_ire returns an held ire */
9197 			ire = ipif_to_ire(ipif);
9198 			if (ire == NULL)
9199 				goto err_ret;
9200 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9201 				goto err_ret;
9202 			/*
9203 			 * ihandle is needed when the ire is added to
9204 			 * cache table.
9205 			 */
9206 			save_ire = ire;
9207 			ihandle = save_ire->ire_ihandle;
9208 
9209 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9210 			    "flags %04x\n",
9211 			    (void *)ire, (void *)ipif, flags));
9212 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9213 			    (fire->ire_flags & RTF_MULTIRT)) {
9214 				/*
9215 				 * As requested by flags, an IRE_OFFSUBNET was
9216 				 * looked up on that interface. This ire has
9217 				 * RTF_MULTIRT flag, so the resolution loop will
9218 				 * be re-entered to resolve additional routes on
9219 				 * other interfaces. For that purpose, a copy of
9220 				 * the packet is performed at this point.
9221 				 */
9222 				fire->ire_last_used_time = lbolt;
9223 				copy_mp = copymsg(first_mp);
9224 				if (copy_mp) {
9225 					MULTIRT_DEBUG_TAG(copy_mp);
9226 				}
9227 			}
9228 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9229 			    (fire->ire_flags & RTF_SETSRC)) {
9230 				/*
9231 				 * As requested by flags, an IRE_OFFSUBET was
9232 				 * looked up on that interface. This ire has
9233 				 * RTF_SETSRC flag, so the source address of the
9234 				 * packet must be changed.
9235 				 */
9236 				ipha->ipha_src = fire->ire_src_addr;
9237 			}
9238 		} else {
9239 			ASSERT((connp == NULL) ||
9240 			    (connp->conn_outgoing_ill != NULL) ||
9241 			    (connp->conn_dontroute) ||
9242 			    infop->ip_opt_ill_index != 0);
9243 			/*
9244 			 * The only ways we can come here are:
9245 			 * 1) IP_BOUND_IF socket option is set
9246 			 * 2) SO_DONTROUTE socket option is set
9247 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9248 			 * In all cases, the new ire will not be added
9249 			 * into cache table.
9250 			 */
9251 			ire_marks |= IRE_MARK_NOADD;
9252 		}
9253 
9254 		switch (ipif->ipif_net_type) {
9255 		case IRE_IF_NORESOLVER: {
9256 			/* We have what we need to build an IRE_CACHE. */
9257 
9258 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9259 			    (dst_ill->ill_resolver_mp == NULL)) {
9260 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9261 				    "for IRE_IF_NORESOLVER ire %p has "
9262 				    "no ill_resolver_mp\n",
9263 				    (void *)dst_ill, (void *)ire));
9264 				break;
9265 			}
9266 
9267 			/*
9268 			 * The new ire inherits the IRE_OFFSUBNET flags
9269 			 * and source address, if this was requested.
9270 			 */
9271 			ire = ire_create(
9272 			    (uchar_t *)&dst,		/* dest address */
9273 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9274 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9275 			    NULL,			/* gateway address */
9276 			    &ipif->ipif_mtu,
9277 			    NULL,			/* no src nce */
9278 			    dst_ill->ill_rq,		/* recv-from queue */
9279 			    dst_ill->ill_wq,		/* send-to queue */
9280 			    IRE_CACHE,
9281 			    src_ipif,
9282 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9283 			    (fire != NULL) ?		/* Parent handle */
9284 			    fire->ire_phandle : 0,
9285 			    ihandle,			/* Interface handle */
9286 			    (fire != NULL) ?
9287 			    (fire->ire_flags &
9288 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9289 			    (save_ire == NULL ? &ire_uinfo_null :
9290 			    &save_ire->ire_uinfo),
9291 			    NULL,
9292 			    NULL,
9293 			    ipst);
9294 
9295 			if (ire == NULL) {
9296 				if (save_ire != NULL)
9297 					ire_refrele(save_ire);
9298 				break;
9299 			}
9300 
9301 			ire->ire_marks |= ire_marks;
9302 
9303 			/*
9304 			 * If IRE_MARK_NOADD is set then we need to convert
9305 			 * the max_fragp to a useable value now. This is
9306 			 * normally done in ire_add_v[46]. We also need to
9307 			 * associate the ire with an nce (normally would be
9308 			 * done in ip_wput_nondata()).
9309 			 *
9310 			 * Note that IRE_MARK_NOADD packets created here
9311 			 * do not have a non-null ire_mp pointer. The null
9312 			 * value of ire_bucket indicates that they were
9313 			 * never added.
9314 			 */
9315 			if (ire->ire_marks & IRE_MARK_NOADD) {
9316 				uint_t  max_frag;
9317 
9318 				max_frag = *ire->ire_max_fragp;
9319 				ire->ire_max_fragp = NULL;
9320 				ire->ire_max_frag = max_frag;
9321 
9322 				if ((ire->ire_nce = ndp_lookup_v4(
9323 				    ire_to_ill(ire),
9324 				    (ire->ire_gateway_addr != INADDR_ANY ?
9325 				    &ire->ire_gateway_addr : &ire->ire_addr),
9326 				    B_FALSE)) == NULL) {
9327 					if (save_ire != NULL)
9328 						ire_refrele(save_ire);
9329 					break;
9330 				}
9331 				ASSERT(ire->ire_nce->nce_state ==
9332 				    ND_REACHABLE);
9333 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9334 			}
9335 
9336 			/* Prevent save_ire from getting deleted */
9337 			if (save_ire != NULL) {
9338 				IRB_REFHOLD(save_ire->ire_bucket);
9339 				/* Has it been removed already ? */
9340 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9341 					IRB_REFRELE(save_ire->ire_bucket);
9342 					ire_refrele(save_ire);
9343 					break;
9344 				}
9345 			}
9346 
9347 			ire_add_then_send(q, ire, first_mp);
9348 
9349 			/* Assert that save_ire is not deleted yet. */
9350 			if (save_ire != NULL) {
9351 				ASSERT(save_ire->ire_ptpn != NULL);
9352 				IRB_REFRELE(save_ire->ire_bucket);
9353 				ire_refrele(save_ire);
9354 				save_ire = NULL;
9355 			}
9356 			if (fire != NULL) {
9357 				ire_refrele(fire);
9358 				fire = NULL;
9359 			}
9360 
9361 			/*
9362 			 * the resolution loop is re-entered if this
9363 			 * was requested through flags and if we
9364 			 * actually are in a multirouting case.
9365 			 */
9366 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9367 				boolean_t need_resolve =
9368 				    ire_multirt_need_resolve(ipha_dst,
9369 				    MBLK_GETLABEL(copy_mp), ipst);
9370 				if (!need_resolve) {
9371 					MULTIRT_DEBUG_UNTAG(copy_mp);
9372 					freemsg(copy_mp);
9373 					copy_mp = NULL;
9374 				} else {
9375 					/*
9376 					 * ipif_lookup_group() calls
9377 					 * ire_lookup_multi() that uses
9378 					 * ire_ftable_lookup() to find
9379 					 * an IRE_INTERFACE for the group.
9380 					 * In the multirt case,
9381 					 * ire_lookup_multi() then invokes
9382 					 * ire_multirt_lookup() to find
9383 					 * the next resolvable ire.
9384 					 * As a result, we obtain an new
9385 					 * interface, derived from the
9386 					 * next ire.
9387 					 */
9388 					ipif_refrele(ipif);
9389 					ipif = ipif_lookup_group(ipha_dst,
9390 					    zoneid, ipst);
9391 					ip2dbg(("ip_newroute_ipif: "
9392 					    "multirt dst %08x, ipif %p\n",
9393 					    htonl(dst), (void *)ipif));
9394 					if (ipif != NULL) {
9395 						mp = copy_mp;
9396 						copy_mp = NULL;
9397 						multirt_resolve_next = B_TRUE;
9398 						continue;
9399 					} else {
9400 						freemsg(copy_mp);
9401 					}
9402 				}
9403 			}
9404 			if (ipif != NULL)
9405 				ipif_refrele(ipif);
9406 			ill_refrele(dst_ill);
9407 			ipif_refrele(src_ipif);
9408 			return;
9409 		}
9410 		case IRE_IF_RESOLVER:
9411 			/*
9412 			 * We can't build an IRE_CACHE yet, but at least
9413 			 * we found a resolver that can help.
9414 			 */
9415 			res_mp = dst_ill->ill_resolver_mp;
9416 			if (!OK_RESOLVER_MP(res_mp))
9417 				break;
9418 
9419 			/*
9420 			 * We obtain a partial IRE_CACHE which we will pass
9421 			 * along with the resolver query.  When the response
9422 			 * comes back it will be there ready for us to add.
9423 			 * The new ire inherits the IRE_OFFSUBNET flags
9424 			 * and source address, if this was requested.
9425 			 * The ire_max_frag is atomically set under the
9426 			 * irebucket lock in ire_add_v[46]. Only in the
9427 			 * case of IRE_MARK_NOADD, we set it here itself.
9428 			 */
9429 			ire = ire_create_mp(
9430 			    (uchar_t *)&dst,		/* dest address */
9431 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9432 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9433 			    NULL,			/* gateway address */
9434 			    (ire_marks & IRE_MARK_NOADD) ?
9435 			    ipif->ipif_mtu : 0,		/* max_frag */
9436 			    NULL,			/* no src nce */
9437 			    dst_ill->ill_rq,		/* recv-from queue */
9438 			    dst_ill->ill_wq,		/* send-to queue */
9439 			    IRE_CACHE,
9440 			    src_ipif,
9441 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9442 			    (fire != NULL) ?		/* Parent handle */
9443 			    fire->ire_phandle : 0,
9444 			    ihandle,			/* Interface handle */
9445 			    (fire != NULL) ?		/* flags if any */
9446 			    (fire->ire_flags &
9447 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9448 			    (save_ire == NULL ? &ire_uinfo_null :
9449 			    &save_ire->ire_uinfo),
9450 			    NULL,
9451 			    NULL,
9452 			    ipst);
9453 
9454 			if (save_ire != NULL) {
9455 				ire_refrele(save_ire);
9456 				save_ire = NULL;
9457 			}
9458 			if (ire == NULL)
9459 				break;
9460 
9461 			ire->ire_marks |= ire_marks;
9462 			/*
9463 			 * Construct message chain for the resolver of the
9464 			 * form:
9465 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9466 			 *
9467 			 * NOTE : ire will be added later when the response
9468 			 * comes back from ARP. If the response does not
9469 			 * come back, ARP frees the packet. For this reason,
9470 			 * we can't REFHOLD the bucket of save_ire to prevent
9471 			 * deletions. We may not be able to REFRELE the
9472 			 * bucket if the response never comes back.
9473 			 * Thus, before adding the ire, ire_add_v4 will make
9474 			 * sure that the interface route does not get deleted.
9475 			 * This is the only case unlike ip_newroute_v6,
9476 			 * ip_newroute_ipif_v6 where we can always prevent
9477 			 * deletions because ire_add_then_send is called after
9478 			 * creating the IRE.
9479 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9480 			 * does not add this IRE into the IRE CACHE.
9481 			 */
9482 			ASSERT(ire->ire_mp != NULL);
9483 			ire->ire_mp->b_cont = first_mp;
9484 			/* Have saved_mp handy, for cleanup if canput fails */
9485 			saved_mp = mp;
9486 			mp = copyb(res_mp);
9487 			if (mp == NULL) {
9488 				/* Prepare for cleanup */
9489 				mp = saved_mp; /* pkt */
9490 				ire_delete(ire); /* ire_mp */
9491 				ire = NULL;
9492 				if (copy_mp != NULL) {
9493 					MULTIRT_DEBUG_UNTAG(copy_mp);
9494 					freemsg(copy_mp);
9495 					copy_mp = NULL;
9496 				}
9497 				break;
9498 			}
9499 			linkb(mp, ire->ire_mp);
9500 
9501 			/*
9502 			 * Fill in the source and dest addrs for the resolver.
9503 			 * NOTE: this depends on memory layouts imposed by
9504 			 * ill_init().
9505 			 */
9506 			areq = (areq_t *)mp->b_rptr;
9507 			addrp = (ipaddr_t *)((char *)areq +
9508 			    areq->areq_sender_addr_offset);
9509 			*addrp = ire->ire_src_addr;
9510 			addrp = (ipaddr_t *)((char *)areq +
9511 			    areq->areq_target_addr_offset);
9512 			*addrp = dst;
9513 			/* Up to the resolver. */
9514 			if (canputnext(dst_ill->ill_rq) &&
9515 			    !(dst_ill->ill_arp_closing)) {
9516 				putnext(dst_ill->ill_rq, mp);
9517 				/*
9518 				 * The response will come back in ip_wput
9519 				 * with db_type IRE_DB_TYPE.
9520 				 */
9521 			} else {
9522 				mp->b_cont = NULL;
9523 				freeb(mp); /* areq */
9524 				ire_delete(ire); /* ire_mp */
9525 				saved_mp->b_next = NULL;
9526 				saved_mp->b_prev = NULL;
9527 				freemsg(first_mp); /* pkt */
9528 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9529 			}
9530 
9531 			if (fire != NULL) {
9532 				ire_refrele(fire);
9533 				fire = NULL;
9534 			}
9535 
9536 
9537 			/*
9538 			 * The resolution loop is re-entered if this was
9539 			 * requested through flags and we actually are
9540 			 * in a multirouting case.
9541 			 */
9542 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9543 				boolean_t need_resolve =
9544 				    ire_multirt_need_resolve(ipha_dst,
9545 				    MBLK_GETLABEL(copy_mp), ipst);
9546 				if (!need_resolve) {
9547 					MULTIRT_DEBUG_UNTAG(copy_mp);
9548 					freemsg(copy_mp);
9549 					copy_mp = NULL;
9550 				} else {
9551 					/*
9552 					 * ipif_lookup_group() calls
9553 					 * ire_lookup_multi() that uses
9554 					 * ire_ftable_lookup() to find
9555 					 * an IRE_INTERFACE for the group.
9556 					 * In the multirt case,
9557 					 * ire_lookup_multi() then invokes
9558 					 * ire_multirt_lookup() to find
9559 					 * the next resolvable ire.
9560 					 * As a result, we obtain an new
9561 					 * interface, derived from the
9562 					 * next ire.
9563 					 */
9564 					ipif_refrele(ipif);
9565 					ipif = ipif_lookup_group(ipha_dst,
9566 					    zoneid, ipst);
9567 					if (ipif != NULL) {
9568 						mp = copy_mp;
9569 						copy_mp = NULL;
9570 						multirt_resolve_next = B_TRUE;
9571 						continue;
9572 					} else {
9573 						freemsg(copy_mp);
9574 					}
9575 				}
9576 			}
9577 			if (ipif != NULL)
9578 				ipif_refrele(ipif);
9579 			ill_refrele(dst_ill);
9580 			ipif_refrele(src_ipif);
9581 			return;
9582 		default:
9583 			break;
9584 		}
9585 	} while (multirt_resolve_next);
9586 
9587 err_ret:
9588 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9589 	if (fire != NULL)
9590 		ire_refrele(fire);
9591 	ipif_refrele(ipif);
9592 	/* Did this packet originate externally? */
9593 	if (dst_ill != NULL)
9594 		ill_refrele(dst_ill);
9595 	if (src_ipif != NULL)
9596 		ipif_refrele(src_ipif);
9597 	if (mp->b_prev || mp->b_next) {
9598 		mp->b_next = NULL;
9599 		mp->b_prev = NULL;
9600 	} else {
9601 		/*
9602 		 * Since ip_wput() isn't close to finished, we fill
9603 		 * in enough of the header for credible error reporting.
9604 		 */
9605 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9606 			/* Failed */
9607 			freemsg(first_mp);
9608 			if (ire != NULL)
9609 				ire_refrele(ire);
9610 			return;
9611 		}
9612 	}
9613 	/*
9614 	 * At this point we will have ire only if RTF_BLACKHOLE
9615 	 * or RTF_REJECT flags are set on the IRE. It will not
9616 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9617 	 */
9618 	if (ire != NULL) {
9619 		if (ire->ire_flags & RTF_BLACKHOLE) {
9620 			ire_refrele(ire);
9621 			freemsg(first_mp);
9622 			return;
9623 		}
9624 		ire_refrele(ire);
9625 	}
9626 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9627 }
9628 
9629 /* Name/Value Table Lookup Routine */
9630 char *
9631 ip_nv_lookup(nv_t *nv, int value)
9632 {
9633 	if (!nv)
9634 		return (NULL);
9635 	for (; nv->nv_name; nv++) {
9636 		if (nv->nv_value == value)
9637 			return (nv->nv_name);
9638 	}
9639 	return ("unknown");
9640 }
9641 
9642 /*
9643  * This is a module open, i.e. this is a control stream for access
9644  * to a DLPI device.  We allocate an ill_t as the instance data in
9645  * this case.
9646  */
9647 int
9648 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9649 {
9650 	ill_t	*ill;
9651 	int	err;
9652 	zoneid_t zoneid;
9653 	netstack_t *ns;
9654 	ip_stack_t *ipst;
9655 
9656 	/*
9657 	 * Prevent unprivileged processes from pushing IP so that
9658 	 * they can't send raw IP.
9659 	 */
9660 	if (secpolicy_net_rawaccess(credp) != 0)
9661 		return (EPERM);
9662 
9663 	ns = netstack_find_by_cred(credp);
9664 	ASSERT(ns != NULL);
9665 	ipst = ns->netstack_ip;
9666 	ASSERT(ipst != NULL);
9667 
9668 	/*
9669 	 * For exclusive stacks we set the zoneid to zero
9670 	 * to make IP operate as if in the global zone.
9671 	 */
9672 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9673 		zoneid = GLOBAL_ZONEID;
9674 	else
9675 		zoneid = crgetzoneid(credp);
9676 
9677 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9678 	q->q_ptr = WR(q)->q_ptr = ill;
9679 	ill->ill_ipst = ipst;
9680 	ill->ill_zoneid = zoneid;
9681 
9682 	/*
9683 	 * ill_init initializes the ill fields and then sends down
9684 	 * down a DL_INFO_REQ after calling qprocson.
9685 	 */
9686 	err = ill_init(q, ill);
9687 	if (err != 0) {
9688 		mi_free(ill);
9689 		netstack_rele(ipst->ips_netstack);
9690 		q->q_ptr = NULL;
9691 		WR(q)->q_ptr = NULL;
9692 		return (err);
9693 	}
9694 
9695 	/* ill_init initializes the ipsq marking this thread as writer */
9696 	ipsq_exit(ill->ill_phyint->phyint_ipsq);
9697 	/* Wait for the DL_INFO_ACK */
9698 	mutex_enter(&ill->ill_lock);
9699 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9700 		/*
9701 		 * Return value of 0 indicates a pending signal.
9702 		 */
9703 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9704 		if (err == 0) {
9705 			mutex_exit(&ill->ill_lock);
9706 			(void) ip_close(q, 0);
9707 			return (EINTR);
9708 		}
9709 	}
9710 	mutex_exit(&ill->ill_lock);
9711 
9712 	/*
9713 	 * ip_rput_other could have set an error  in ill_error on
9714 	 * receipt of M_ERROR.
9715 	 */
9716 
9717 	err = ill->ill_error;
9718 	if (err != 0) {
9719 		(void) ip_close(q, 0);
9720 		return (err);
9721 	}
9722 
9723 	ill->ill_credp = credp;
9724 	crhold(credp);
9725 
9726 	mutex_enter(&ipst->ips_ip_mi_lock);
9727 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9728 	    credp);
9729 	mutex_exit(&ipst->ips_ip_mi_lock);
9730 	if (err) {
9731 		(void) ip_close(q, 0);
9732 		return (err);
9733 	}
9734 	return (0);
9735 }
9736 
9737 /* For /dev/ip aka AF_INET open */
9738 int
9739 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9740 {
9741 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9742 }
9743 
9744 /* For /dev/ip6 aka AF_INET6 open */
9745 int
9746 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9747 {
9748 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9749 }
9750 
9751 /* IP open routine. */
9752 int
9753 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9754     boolean_t isv6)
9755 {
9756 	conn_t 		*connp;
9757 	major_t		maj;
9758 	zoneid_t	zoneid;
9759 	netstack_t	*ns;
9760 	ip_stack_t	*ipst;
9761 
9762 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9763 
9764 	/* Allow reopen. */
9765 	if (q->q_ptr != NULL)
9766 		return (0);
9767 
9768 	if (sflag & MODOPEN) {
9769 		/* This is a module open */
9770 		return (ip_modopen(q, devp, flag, sflag, credp));
9771 	}
9772 
9773 	ns = netstack_find_by_cred(credp);
9774 	ASSERT(ns != NULL);
9775 	ipst = ns->netstack_ip;
9776 	ASSERT(ipst != NULL);
9777 
9778 	/*
9779 	 * For exclusive stacks we set the zoneid to zero
9780 	 * to make IP operate as if in the global zone.
9781 	 */
9782 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9783 		zoneid = GLOBAL_ZONEID;
9784 	else
9785 		zoneid = crgetzoneid(credp);
9786 
9787 	/*
9788 	 * We are opening as a device. This is an IP client stream, and we
9789 	 * allocate an conn_t as the instance data.
9790 	 */
9791 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9792 
9793 	/*
9794 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9795 	 * done by netstack_find_by_cred()
9796 	 */
9797 	netstack_rele(ipst->ips_netstack);
9798 
9799 	connp->conn_zoneid = zoneid;
9800 
9801 	connp->conn_upq = q;
9802 	q->q_ptr = WR(q)->q_ptr = connp;
9803 
9804 	if (flag & SO_SOCKSTR)
9805 		connp->conn_flags |= IPCL_SOCKET;
9806 
9807 	/* Minor tells us which /dev entry was opened */
9808 	if (isv6) {
9809 		connp->conn_flags |= IPCL_ISV6;
9810 		connp->conn_af_isv6 = B_TRUE;
9811 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9812 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9813 	} else {
9814 		connp->conn_af_isv6 = B_FALSE;
9815 		connp->conn_pkt_isv6 = B_FALSE;
9816 	}
9817 
9818 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9819 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9820 		connp->conn_minor_arena = ip_minor_arena_la;
9821 	} else {
9822 		/*
9823 		 * Either minor numbers in the large arena were exhausted
9824 		 * or a non socket application is doing the open.
9825 		 * Try to allocate from the small arena.
9826 		 */
9827 		if ((connp->conn_dev =
9828 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9829 			/* CONN_DEC_REF takes care of netstack_rele() */
9830 			q->q_ptr = WR(q)->q_ptr = NULL;
9831 			CONN_DEC_REF(connp);
9832 			return (EBUSY);
9833 		}
9834 		connp->conn_minor_arena = ip_minor_arena_sa;
9835 	}
9836 
9837 	maj = getemajor(*devp);
9838 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9839 
9840 	/*
9841 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9842 	 */
9843 	connp->conn_cred = credp;
9844 
9845 	/*
9846 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9847 	 */
9848 	connp->conn_recv = ip_conn_input;
9849 
9850 	crhold(connp->conn_cred);
9851 
9852 	/*
9853 	 * If the caller has the process-wide flag set, then default to MAC
9854 	 * exempt mode.  This allows read-down to unlabeled hosts.
9855 	 */
9856 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9857 		connp->conn_mac_exempt = B_TRUE;
9858 
9859 	connp->conn_rq = q;
9860 	connp->conn_wq = WR(q);
9861 
9862 	/* Non-zero default values */
9863 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9864 
9865 	/*
9866 	 * Make the conn globally visible to walkers
9867 	 */
9868 	ASSERT(connp->conn_ref == 1);
9869 	mutex_enter(&connp->conn_lock);
9870 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9871 	mutex_exit(&connp->conn_lock);
9872 
9873 	qprocson(q);
9874 
9875 	return (0);
9876 }
9877 
9878 /*
9879  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9880  * Note that there is no race since either ip_output function works - it
9881  * is just an optimization to enter the best ip_output routine directly.
9882  */
9883 void
9884 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9885     ip_stack_t *ipst)
9886 {
9887 	if (isv6)  {
9888 		if (bump_mib) {
9889 			BUMP_MIB(&ipst->ips_ip6_mib,
9890 			    ipIfStatsOutSwitchIPVersion);
9891 		}
9892 		connp->conn_send = ip_output_v6;
9893 		connp->conn_pkt_isv6 = B_TRUE;
9894 	} else {
9895 		if (bump_mib) {
9896 			BUMP_MIB(&ipst->ips_ip_mib,
9897 			    ipIfStatsOutSwitchIPVersion);
9898 		}
9899 		connp->conn_send = ip_output;
9900 		connp->conn_pkt_isv6 = B_FALSE;
9901 	}
9902 
9903 }
9904 
9905 /*
9906  * See if IPsec needs loading because of the options in mp.
9907  */
9908 static boolean_t
9909 ipsec_opt_present(mblk_t *mp)
9910 {
9911 	uint8_t *optcp, *next_optcp, *opt_endcp;
9912 	struct opthdr *opt;
9913 	struct T_opthdr *topt;
9914 	int opthdr_len;
9915 	t_uscalar_t optname, optlevel;
9916 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9917 	ipsec_req_t *ipsr;
9918 
9919 	/*
9920 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9921 	 * return TRUE.
9922 	 */
9923 
9924 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9925 	opt_endcp = optcp + tor->OPT_length;
9926 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9927 		opthdr_len = sizeof (struct T_opthdr);
9928 	} else {		/* O_OPTMGMT_REQ */
9929 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9930 		opthdr_len = sizeof (struct opthdr);
9931 	}
9932 	for (; optcp < opt_endcp; optcp = next_optcp) {
9933 		if (optcp + opthdr_len > opt_endcp)
9934 			return (B_FALSE);	/* Not enough option header. */
9935 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9936 			topt = (struct T_opthdr *)optcp;
9937 			optlevel = topt->level;
9938 			optname = topt->name;
9939 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9940 		} else {
9941 			opt = (struct opthdr *)optcp;
9942 			optlevel = opt->level;
9943 			optname = opt->name;
9944 			next_optcp = optcp + opthdr_len +
9945 			    _TPI_ALIGN_OPT(opt->len);
9946 		}
9947 		if ((next_optcp < optcp) || /* wraparound pointer space */
9948 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9949 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9950 			return (B_FALSE); /* bad option buffer */
9951 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9952 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9953 			/*
9954 			 * Check to see if it's an all-bypass or all-zeroes
9955 			 * IPsec request.  Don't bother loading IPsec if
9956 			 * the socket doesn't want to use it.  (A good example
9957 			 * is a bypass request.)
9958 			 *
9959 			 * Basically, if any of the non-NEVER bits are set,
9960 			 * load IPsec.
9961 			 */
9962 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9963 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9964 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9965 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9966 			    != 0)
9967 				return (B_TRUE);
9968 		}
9969 	}
9970 	return (B_FALSE);
9971 }
9972 
9973 /*
9974  * If conn is is waiting for ipsec to finish loading, kick it.
9975  */
9976 /* ARGSUSED */
9977 static void
9978 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9979 {
9980 	t_scalar_t	optreq_prim;
9981 	mblk_t		*mp;
9982 	cred_t		*cr;
9983 	int		err = 0;
9984 
9985 	/*
9986 	 * This function is called, after ipsec loading is complete.
9987 	 * Since IP checks exclusively and atomically (i.e it prevents
9988 	 * ipsec load from completing until ip_optcom_req completes)
9989 	 * whether ipsec load is complete, there cannot be a race with IP
9990 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9991 	 */
9992 	mutex_enter(&connp->conn_lock);
9993 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9994 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9995 		mp = connp->conn_ipsec_opt_mp;
9996 		connp->conn_ipsec_opt_mp = NULL;
9997 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9998 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9999 		mutex_exit(&connp->conn_lock);
10000 
10001 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10002 
10003 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10004 		if (optreq_prim == T_OPTMGMT_REQ) {
10005 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10006 			    &ip_opt_obj, B_FALSE);
10007 		} else {
10008 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10009 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10010 			    &ip_opt_obj, B_FALSE);
10011 		}
10012 		if (err != EINPROGRESS)
10013 			CONN_OPER_PENDING_DONE(connp);
10014 		return;
10015 	}
10016 	mutex_exit(&connp->conn_lock);
10017 }
10018 
10019 /*
10020  * Called from the ipsec_loader thread, outside any perimeter, to tell
10021  * ip qenable any of the queues waiting for the ipsec loader to
10022  * complete.
10023  */
10024 void
10025 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10026 {
10027 	netstack_t *ns = ipss->ipsec_netstack;
10028 
10029 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10030 }
10031 
10032 /*
10033  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10034  * determines the grp on which it has to become exclusive, queues the mp
10035  * and sq draining restarts the optmgmt
10036  */
10037 static boolean_t
10038 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10039 {
10040 	conn_t *connp = Q_TO_CONN(q);
10041 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10042 
10043 	/*
10044 	 * Take IPsec requests and treat them special.
10045 	 */
10046 	if (ipsec_opt_present(mp)) {
10047 		/* First check if IPsec is loaded. */
10048 		mutex_enter(&ipss->ipsec_loader_lock);
10049 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10050 			mutex_exit(&ipss->ipsec_loader_lock);
10051 			return (B_FALSE);
10052 		}
10053 		mutex_enter(&connp->conn_lock);
10054 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10055 
10056 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10057 		connp->conn_ipsec_opt_mp = mp;
10058 		mutex_exit(&connp->conn_lock);
10059 		mutex_exit(&ipss->ipsec_loader_lock);
10060 
10061 		ipsec_loader_loadnow(ipss);
10062 		return (B_TRUE);
10063 	}
10064 	return (B_FALSE);
10065 }
10066 
10067 /*
10068  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10069  * all of them are copied to the conn_t. If the req is "zero", the policy is
10070  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10071  * fields.
10072  * We keep only the latest setting of the policy and thus policy setting
10073  * is not incremental/cumulative.
10074  *
10075  * Requests to set policies with multiple alternative actions will
10076  * go through a different API.
10077  */
10078 int
10079 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10080 {
10081 	uint_t ah_req = 0;
10082 	uint_t esp_req = 0;
10083 	uint_t se_req = 0;
10084 	ipsec_selkey_t sel;
10085 	ipsec_act_t *actp = NULL;
10086 	uint_t nact;
10087 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10088 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10089 	ipsec_policy_root_t *pr;
10090 	ipsec_policy_head_t *ph;
10091 	int fam;
10092 	boolean_t is_pol_reset;
10093 	int error = 0;
10094 	netstack_t	*ns = connp->conn_netstack;
10095 	ip_stack_t	*ipst = ns->netstack_ip;
10096 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10097 
10098 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10099 
10100 	/*
10101 	 * The IP_SEC_OPT option does not allow variable length parameters,
10102 	 * hence a request cannot be NULL.
10103 	 */
10104 	if (req == NULL)
10105 		return (EINVAL);
10106 
10107 	ah_req = req->ipsr_ah_req;
10108 	esp_req = req->ipsr_esp_req;
10109 	se_req = req->ipsr_self_encap_req;
10110 
10111 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10112 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10113 		return (EINVAL);
10114 
10115 	/*
10116 	 * Are we dealing with a request to reset the policy (i.e.
10117 	 * zero requests).
10118 	 */
10119 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10120 	    (esp_req & REQ_MASK) == 0 &&
10121 	    (se_req & REQ_MASK) == 0);
10122 
10123 	if (!is_pol_reset) {
10124 		/*
10125 		 * If we couldn't load IPsec, fail with "protocol
10126 		 * not supported".
10127 		 * IPsec may not have been loaded for a request with zero
10128 		 * policies, so we don't fail in this case.
10129 		 */
10130 		mutex_enter(&ipss->ipsec_loader_lock);
10131 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10132 			mutex_exit(&ipss->ipsec_loader_lock);
10133 			return (EPROTONOSUPPORT);
10134 		}
10135 		mutex_exit(&ipss->ipsec_loader_lock);
10136 
10137 		/*
10138 		 * Test for valid requests. Invalid algorithms
10139 		 * need to be tested by IPsec code because new
10140 		 * algorithms can be added dynamically.
10141 		 */
10142 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10143 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10144 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10145 			return (EINVAL);
10146 		}
10147 
10148 		/*
10149 		 * Only privileged users can issue these
10150 		 * requests.
10151 		 */
10152 		if (((ah_req & IPSEC_PREF_NEVER) ||
10153 		    (esp_req & IPSEC_PREF_NEVER) ||
10154 		    (se_req & IPSEC_PREF_NEVER)) &&
10155 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10156 			return (EPERM);
10157 		}
10158 
10159 		/*
10160 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10161 		 * are mutually exclusive.
10162 		 */
10163 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10164 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10165 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10166 			/* Both of them are set */
10167 			return (EINVAL);
10168 		}
10169 	}
10170 
10171 	mutex_enter(&connp->conn_lock);
10172 
10173 	/*
10174 	 * If we have already cached policies in ip_bind_connected*(), don't
10175 	 * let them change now. We cache policies for connections
10176 	 * whose src,dst [addr, port] is known.
10177 	 */
10178 	if (connp->conn_policy_cached) {
10179 		mutex_exit(&connp->conn_lock);
10180 		return (EINVAL);
10181 	}
10182 
10183 	/*
10184 	 * We have a zero policies, reset the connection policy if already
10185 	 * set. This will cause the connection to inherit the
10186 	 * global policy, if any.
10187 	 */
10188 	if (is_pol_reset) {
10189 		if (connp->conn_policy != NULL) {
10190 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10191 			connp->conn_policy = NULL;
10192 		}
10193 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10194 		connp->conn_in_enforce_policy = B_FALSE;
10195 		connp->conn_out_enforce_policy = B_FALSE;
10196 		mutex_exit(&connp->conn_lock);
10197 		return (0);
10198 	}
10199 
10200 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10201 	    ipst->ips_netstack);
10202 	if (ph == NULL)
10203 		goto enomem;
10204 
10205 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10206 	if (actp == NULL)
10207 		goto enomem;
10208 
10209 	/*
10210 	 * Always allocate IPv4 policy entries, since they can also
10211 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10212 	 */
10213 	bzero(&sel, sizeof (sel));
10214 	sel.ipsl_valid = IPSL_IPV4;
10215 
10216 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10217 	    ipst->ips_netstack);
10218 	if (pin4 == NULL)
10219 		goto enomem;
10220 
10221 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10222 	    ipst->ips_netstack);
10223 	if (pout4 == NULL)
10224 		goto enomem;
10225 
10226 	if (connp->conn_af_isv6) {
10227 		/*
10228 		 * We're looking at a v6 socket, also allocate the
10229 		 * v6-specific entries...
10230 		 */
10231 		sel.ipsl_valid = IPSL_IPV6;
10232 		pin6 = ipsec_policy_create(&sel, actp, nact,
10233 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10234 		if (pin6 == NULL)
10235 			goto enomem;
10236 
10237 		pout6 = ipsec_policy_create(&sel, actp, nact,
10238 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10239 		if (pout6 == NULL)
10240 			goto enomem;
10241 
10242 		/*
10243 		 * .. and file them away in the right place.
10244 		 */
10245 		fam = IPSEC_AF_V6;
10246 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10247 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10248 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10249 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10250 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10251 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10252 	}
10253 
10254 	ipsec_actvec_free(actp, nact);
10255 
10256 	/*
10257 	 * File the v4 policies.
10258 	 */
10259 	fam = IPSEC_AF_V4;
10260 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10261 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10262 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10263 
10264 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10265 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10266 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10267 
10268 	/*
10269 	 * If the requests need security, set enforce_policy.
10270 	 * If the requests are IPSEC_PREF_NEVER, one should
10271 	 * still set conn_out_enforce_policy so that an ipsec_out
10272 	 * gets attached in ip_wput. This is needed so that
10273 	 * for connections that we don't cache policy in ip_bind,
10274 	 * if global policy matches in ip_wput_attach_policy, we
10275 	 * don't wrongly inherit global policy. Similarly, we need
10276 	 * to set conn_in_enforce_policy also so that we don't verify
10277 	 * policy wrongly.
10278 	 */
10279 	if ((ah_req & REQ_MASK) != 0 ||
10280 	    (esp_req & REQ_MASK) != 0 ||
10281 	    (se_req & REQ_MASK) != 0) {
10282 		connp->conn_in_enforce_policy = B_TRUE;
10283 		connp->conn_out_enforce_policy = B_TRUE;
10284 		connp->conn_flags |= IPCL_CHECK_POLICY;
10285 	}
10286 
10287 	mutex_exit(&connp->conn_lock);
10288 	return (error);
10289 #undef REQ_MASK
10290 
10291 	/*
10292 	 * Common memory-allocation-failure exit path.
10293 	 */
10294 enomem:
10295 	mutex_exit(&connp->conn_lock);
10296 	if (actp != NULL)
10297 		ipsec_actvec_free(actp, nact);
10298 	if (pin4 != NULL)
10299 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10300 	if (pout4 != NULL)
10301 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10302 	if (pin6 != NULL)
10303 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10304 	if (pout6 != NULL)
10305 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10306 	return (ENOMEM);
10307 }
10308 
10309 /*
10310  * Only for options that pass in an IP addr. Currently only V4 options
10311  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10312  * So this function assumes level is IPPROTO_IP
10313  */
10314 int
10315 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10316     mblk_t *first_mp)
10317 {
10318 	ipif_t *ipif = NULL;
10319 	int error;
10320 	ill_t *ill;
10321 	int zoneid;
10322 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10323 
10324 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10325 
10326 	if (addr != INADDR_ANY || checkonly) {
10327 		ASSERT(connp != NULL);
10328 		zoneid = IPCL_ZONEID(connp);
10329 		if (option == IP_NEXTHOP) {
10330 			ipif = ipif_lookup_onlink_addr(addr,
10331 			    connp->conn_zoneid, ipst);
10332 		} else {
10333 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10334 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10335 			    &error, ipst);
10336 		}
10337 		if (ipif == NULL) {
10338 			if (error == EINPROGRESS)
10339 				return (error);
10340 			else if ((option == IP_MULTICAST_IF) ||
10341 			    (option == IP_NEXTHOP))
10342 				return (EHOSTUNREACH);
10343 			else
10344 				return (EINVAL);
10345 		} else if (checkonly) {
10346 			if (option == IP_MULTICAST_IF) {
10347 				ill = ipif->ipif_ill;
10348 				/* not supported by the virtual network iface */
10349 				if (IS_VNI(ill)) {
10350 					ipif_refrele(ipif);
10351 					return (EINVAL);
10352 				}
10353 			}
10354 			ipif_refrele(ipif);
10355 			return (0);
10356 		}
10357 		ill = ipif->ipif_ill;
10358 		mutex_enter(&connp->conn_lock);
10359 		mutex_enter(&ill->ill_lock);
10360 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10361 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10362 			mutex_exit(&ill->ill_lock);
10363 			mutex_exit(&connp->conn_lock);
10364 			ipif_refrele(ipif);
10365 			return (option == IP_MULTICAST_IF ?
10366 			    EHOSTUNREACH : EINVAL);
10367 		}
10368 	} else {
10369 		mutex_enter(&connp->conn_lock);
10370 	}
10371 
10372 	/* None of the options below are supported on the VNI */
10373 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10374 		mutex_exit(&ill->ill_lock);
10375 		mutex_exit(&connp->conn_lock);
10376 		ipif_refrele(ipif);
10377 		return (EINVAL);
10378 	}
10379 
10380 	switch (option) {
10381 	case IP_DONTFAILOVER_IF:
10382 		/*
10383 		 * This option is used by in.mpathd to ensure
10384 		 * that IPMP probe packets only go out on the
10385 		 * test interfaces. in.mpathd sets this option
10386 		 * on the non-failover interfaces.
10387 		 * For backward compatibility, this option
10388 		 * implicitly sets IP_MULTICAST_IF, as used
10389 		 * be done in bind(), so that ip_wput gets
10390 		 * this ipif to send mcast packets.
10391 		 */
10392 		if (ipif != NULL) {
10393 			ASSERT(addr != INADDR_ANY);
10394 			connp->conn_nofailover_ill = ipif->ipif_ill;
10395 			connp->conn_multicast_ipif = ipif;
10396 		} else {
10397 			ASSERT(addr == INADDR_ANY);
10398 			connp->conn_nofailover_ill = NULL;
10399 			connp->conn_multicast_ipif = NULL;
10400 		}
10401 		break;
10402 
10403 	case IP_MULTICAST_IF:
10404 		connp->conn_multicast_ipif = ipif;
10405 		break;
10406 	case IP_NEXTHOP:
10407 		connp->conn_nexthop_v4 = addr;
10408 		connp->conn_nexthop_set = B_TRUE;
10409 		break;
10410 	}
10411 
10412 	if (ipif != NULL) {
10413 		mutex_exit(&ill->ill_lock);
10414 		mutex_exit(&connp->conn_lock);
10415 		ipif_refrele(ipif);
10416 		return (0);
10417 	}
10418 	mutex_exit(&connp->conn_lock);
10419 	/* We succeded in cleared the option */
10420 	return (0);
10421 }
10422 
10423 /*
10424  * For options that pass in an ifindex specifying the ill. V6 options always
10425  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10426  */
10427 int
10428 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10429     int level, int option, mblk_t *first_mp)
10430 {
10431 	ill_t *ill = NULL;
10432 	int error = 0;
10433 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10434 
10435 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10436 	if (ifindex != 0) {
10437 		ASSERT(connp != NULL);
10438 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10439 		    first_mp, ip_restart_optmgmt, &error, ipst);
10440 		if (ill != NULL) {
10441 			if (checkonly) {
10442 				/* not supported by the virtual network iface */
10443 				if (IS_VNI(ill)) {
10444 					ill_refrele(ill);
10445 					return (EINVAL);
10446 				}
10447 				ill_refrele(ill);
10448 				return (0);
10449 			}
10450 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10451 			    0, NULL)) {
10452 				ill_refrele(ill);
10453 				ill = NULL;
10454 				mutex_enter(&connp->conn_lock);
10455 				goto setit;
10456 			}
10457 			mutex_enter(&connp->conn_lock);
10458 			mutex_enter(&ill->ill_lock);
10459 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10460 				mutex_exit(&ill->ill_lock);
10461 				mutex_exit(&connp->conn_lock);
10462 				ill_refrele(ill);
10463 				ill = NULL;
10464 				mutex_enter(&connp->conn_lock);
10465 			}
10466 			goto setit;
10467 		} else if (error == EINPROGRESS) {
10468 			return (error);
10469 		} else {
10470 			error = 0;
10471 		}
10472 	}
10473 	mutex_enter(&connp->conn_lock);
10474 setit:
10475 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10476 
10477 	/*
10478 	 * The options below assume that the ILL (if any) transmits and/or
10479 	 * receives traffic. Neither of which is true for the virtual network
10480 	 * interface, so fail setting these on a VNI.
10481 	 */
10482 	if (IS_VNI(ill)) {
10483 		ASSERT(ill != NULL);
10484 		mutex_exit(&ill->ill_lock);
10485 		mutex_exit(&connp->conn_lock);
10486 		ill_refrele(ill);
10487 		return (EINVAL);
10488 	}
10489 
10490 	if (level == IPPROTO_IP) {
10491 		switch (option) {
10492 		case IP_BOUND_IF:
10493 			connp->conn_incoming_ill = ill;
10494 			connp->conn_outgoing_ill = ill;
10495 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10496 			    0 : ifindex;
10497 			break;
10498 
10499 		case IP_MULTICAST_IF:
10500 			/*
10501 			 * This option is an internal special. The socket
10502 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10503 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10504 			 * specifies an ifindex and we try first on V6 ill's.
10505 			 * If we don't find one, we they try using on v4 ill's
10506 			 * intenally and we come here.
10507 			 */
10508 			if (!checkonly && ill != NULL) {
10509 				ipif_t	*ipif;
10510 				ipif = ill->ill_ipif;
10511 
10512 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10513 					mutex_exit(&ill->ill_lock);
10514 					mutex_exit(&connp->conn_lock);
10515 					ill_refrele(ill);
10516 					ill = NULL;
10517 					mutex_enter(&connp->conn_lock);
10518 				} else {
10519 					connp->conn_multicast_ipif = ipif;
10520 				}
10521 			}
10522 			break;
10523 
10524 		case IP_DHCPINIT_IF:
10525 			if (connp->conn_dhcpinit_ill != NULL) {
10526 				/*
10527 				 * We've locked the conn so conn_cleanup_ill()
10528 				 * cannot clear conn_dhcpinit_ill -- so it's
10529 				 * safe to access the ill.
10530 				 */
10531 				ill_t *oill = connp->conn_dhcpinit_ill;
10532 
10533 				ASSERT(oill->ill_dhcpinit != 0);
10534 				atomic_dec_32(&oill->ill_dhcpinit);
10535 				connp->conn_dhcpinit_ill = NULL;
10536 			}
10537 
10538 			if (ill != NULL) {
10539 				connp->conn_dhcpinit_ill = ill;
10540 				atomic_inc_32(&ill->ill_dhcpinit);
10541 			}
10542 			break;
10543 		}
10544 	} else {
10545 		switch (option) {
10546 		case IPV6_BOUND_IF:
10547 			connp->conn_incoming_ill = ill;
10548 			connp->conn_outgoing_ill = ill;
10549 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10550 			    0 : ifindex;
10551 			break;
10552 
10553 		case IPV6_BOUND_PIF:
10554 			/*
10555 			 * Limit all transmit to this ill.
10556 			 * Unlike IPV6_BOUND_IF, using this option
10557 			 * prevents load spreading and failover from
10558 			 * happening when the interface is part of the
10559 			 * group. That's why we don't need to remember
10560 			 * the ifindex in orig_bound_ifindex as in
10561 			 * IPV6_BOUND_IF.
10562 			 */
10563 			connp->conn_outgoing_pill = ill;
10564 			break;
10565 
10566 		case IPV6_DONTFAILOVER_IF:
10567 			/*
10568 			 * This option is used by in.mpathd to ensure
10569 			 * that IPMP probe packets only go out on the
10570 			 * test interfaces. in.mpathd sets this option
10571 			 * on the non-failover interfaces.
10572 			 */
10573 			connp->conn_nofailover_ill = ill;
10574 			/*
10575 			 * For backward compatibility, this option
10576 			 * implicitly sets ip_multicast_ill as used in
10577 			 * IPV6_MULTICAST_IF so that ip_wput gets
10578 			 * this ill to send mcast packets.
10579 			 */
10580 			connp->conn_multicast_ill = ill;
10581 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10582 			    0 : ifindex;
10583 			break;
10584 
10585 		case IPV6_MULTICAST_IF:
10586 			/*
10587 			 * Set conn_multicast_ill to be the IPv6 ill.
10588 			 * Set conn_multicast_ipif to be an IPv4 ipif
10589 			 * for ifindex to make IPv4 mapped addresses
10590 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10591 			 * Even if no IPv6 ill exists for the ifindex
10592 			 * we need to check for an IPv4 ifindex in order
10593 			 * for this to work with mapped addresses. In that
10594 			 * case only set conn_multicast_ipif.
10595 			 */
10596 			if (!checkonly) {
10597 				if (ifindex == 0) {
10598 					connp->conn_multicast_ill = NULL;
10599 					connp->conn_orig_multicast_ifindex = 0;
10600 					connp->conn_multicast_ipif = NULL;
10601 				} else if (ill != NULL) {
10602 					connp->conn_multicast_ill = ill;
10603 					connp->conn_orig_multicast_ifindex =
10604 					    ifindex;
10605 				}
10606 			}
10607 			break;
10608 		}
10609 	}
10610 
10611 	if (ill != NULL) {
10612 		mutex_exit(&ill->ill_lock);
10613 		mutex_exit(&connp->conn_lock);
10614 		ill_refrele(ill);
10615 		return (0);
10616 	}
10617 	mutex_exit(&connp->conn_lock);
10618 	/*
10619 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10620 	 * locate the ill and could not set the option (ifindex != 0)
10621 	 */
10622 	return (ifindex == 0 ? 0 : EINVAL);
10623 }
10624 
10625 /* This routine sets socket options. */
10626 /* ARGSUSED */
10627 int
10628 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10629     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10630     void *dummy, cred_t *cr, mblk_t *first_mp)
10631 {
10632 	int		*i1 = (int *)invalp;
10633 	conn_t		*connp = Q_TO_CONN(q);
10634 	int		error = 0;
10635 	boolean_t	checkonly;
10636 	ire_t		*ire;
10637 	boolean_t	found;
10638 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10639 
10640 	switch (optset_context) {
10641 
10642 	case SETFN_OPTCOM_CHECKONLY:
10643 		checkonly = B_TRUE;
10644 		/*
10645 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10646 		 * inlen != 0 implies value supplied and
10647 		 * 	we have to "pretend" to set it.
10648 		 * inlen == 0 implies that there is no
10649 		 * 	value part in T_CHECK request and just validation
10650 		 * done elsewhere should be enough, we just return here.
10651 		 */
10652 		if (inlen == 0) {
10653 			*outlenp = 0;
10654 			return (0);
10655 		}
10656 		break;
10657 	case SETFN_OPTCOM_NEGOTIATE:
10658 	case SETFN_UD_NEGOTIATE:
10659 	case SETFN_CONN_NEGOTIATE:
10660 		checkonly = B_FALSE;
10661 		break;
10662 	default:
10663 		/*
10664 		 * We should never get here
10665 		 */
10666 		*outlenp = 0;
10667 		return (EINVAL);
10668 	}
10669 
10670 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10671 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10672 
10673 	/*
10674 	 * For fixed length options, no sanity check
10675 	 * of passed in length is done. It is assumed *_optcom_req()
10676 	 * routines do the right thing.
10677 	 */
10678 
10679 	switch (level) {
10680 	case SOL_SOCKET:
10681 		/*
10682 		 * conn_lock protects the bitfields, and is used to
10683 		 * set the fields atomically.
10684 		 */
10685 		switch (name) {
10686 		case SO_BROADCAST:
10687 			if (!checkonly) {
10688 				/* TODO: use value someplace? */
10689 				mutex_enter(&connp->conn_lock);
10690 				connp->conn_broadcast = *i1 ? 1 : 0;
10691 				mutex_exit(&connp->conn_lock);
10692 			}
10693 			break;	/* goto sizeof (int) option return */
10694 		case SO_USELOOPBACK:
10695 			if (!checkonly) {
10696 				/* TODO: use value someplace? */
10697 				mutex_enter(&connp->conn_lock);
10698 				connp->conn_loopback = *i1 ? 1 : 0;
10699 				mutex_exit(&connp->conn_lock);
10700 			}
10701 			break;	/* goto sizeof (int) option return */
10702 		case SO_DONTROUTE:
10703 			if (!checkonly) {
10704 				mutex_enter(&connp->conn_lock);
10705 				connp->conn_dontroute = *i1 ? 1 : 0;
10706 				mutex_exit(&connp->conn_lock);
10707 			}
10708 			break;	/* goto sizeof (int) option return */
10709 		case SO_REUSEADDR:
10710 			if (!checkonly) {
10711 				mutex_enter(&connp->conn_lock);
10712 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10713 				mutex_exit(&connp->conn_lock);
10714 			}
10715 			break;	/* goto sizeof (int) option return */
10716 		case SO_PROTOTYPE:
10717 			if (!checkonly) {
10718 				mutex_enter(&connp->conn_lock);
10719 				connp->conn_proto = *i1;
10720 				mutex_exit(&connp->conn_lock);
10721 			}
10722 			break;	/* goto sizeof (int) option return */
10723 		case SO_ALLZONES:
10724 			if (!checkonly) {
10725 				mutex_enter(&connp->conn_lock);
10726 				if (IPCL_IS_BOUND(connp)) {
10727 					mutex_exit(&connp->conn_lock);
10728 					return (EINVAL);
10729 				}
10730 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10731 				mutex_exit(&connp->conn_lock);
10732 			}
10733 			break;	/* goto sizeof (int) option return */
10734 		case SO_ANON_MLP:
10735 			if (!checkonly) {
10736 				mutex_enter(&connp->conn_lock);
10737 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10738 				mutex_exit(&connp->conn_lock);
10739 			}
10740 			break;	/* goto sizeof (int) option return */
10741 		case SO_MAC_EXEMPT:
10742 			if (secpolicy_net_mac_aware(cr) != 0 ||
10743 			    IPCL_IS_BOUND(connp))
10744 				return (EACCES);
10745 			if (!checkonly) {
10746 				mutex_enter(&connp->conn_lock);
10747 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10748 				mutex_exit(&connp->conn_lock);
10749 			}
10750 			break;	/* goto sizeof (int) option return */
10751 		default:
10752 			/*
10753 			 * "soft" error (negative)
10754 			 * option not handled at this level
10755 			 * Note: Do not modify *outlenp
10756 			 */
10757 			return (-EINVAL);
10758 		}
10759 		break;
10760 	case IPPROTO_IP:
10761 		switch (name) {
10762 		case IP_NEXTHOP:
10763 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10764 				return (EPERM);
10765 			/* FALLTHRU */
10766 		case IP_MULTICAST_IF:
10767 		case IP_DONTFAILOVER_IF: {
10768 			ipaddr_t addr = *i1;
10769 
10770 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10771 			    first_mp);
10772 			if (error != 0)
10773 				return (error);
10774 			break;	/* goto sizeof (int) option return */
10775 		}
10776 
10777 		case IP_MULTICAST_TTL:
10778 			/* Recorded in transport above IP */
10779 			*outvalp = *invalp;
10780 			*outlenp = sizeof (uchar_t);
10781 			return (0);
10782 		case IP_MULTICAST_LOOP:
10783 			if (!checkonly) {
10784 				mutex_enter(&connp->conn_lock);
10785 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10786 				mutex_exit(&connp->conn_lock);
10787 			}
10788 			*outvalp = *invalp;
10789 			*outlenp = sizeof (uchar_t);
10790 			return (0);
10791 		case IP_ADD_MEMBERSHIP:
10792 		case MCAST_JOIN_GROUP:
10793 		case IP_DROP_MEMBERSHIP:
10794 		case MCAST_LEAVE_GROUP: {
10795 			struct ip_mreq *mreqp;
10796 			struct group_req *greqp;
10797 			ire_t *ire;
10798 			boolean_t done = B_FALSE;
10799 			ipaddr_t group, ifaddr;
10800 			struct sockaddr_in *sin;
10801 			uint32_t *ifindexp;
10802 			boolean_t mcast_opt = B_TRUE;
10803 			mcast_record_t fmode;
10804 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10805 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10806 
10807 			switch (name) {
10808 			case IP_ADD_MEMBERSHIP:
10809 				mcast_opt = B_FALSE;
10810 				/* FALLTHRU */
10811 			case MCAST_JOIN_GROUP:
10812 				fmode = MODE_IS_EXCLUDE;
10813 				optfn = ip_opt_add_group;
10814 				break;
10815 
10816 			case IP_DROP_MEMBERSHIP:
10817 				mcast_opt = B_FALSE;
10818 				/* FALLTHRU */
10819 			case MCAST_LEAVE_GROUP:
10820 				fmode = MODE_IS_INCLUDE;
10821 				optfn = ip_opt_delete_group;
10822 				break;
10823 			}
10824 
10825 			if (mcast_opt) {
10826 				greqp = (struct group_req *)i1;
10827 				sin = (struct sockaddr_in *)&greqp->gr_group;
10828 				if (sin->sin_family != AF_INET) {
10829 					*outlenp = 0;
10830 					return (ENOPROTOOPT);
10831 				}
10832 				group = (ipaddr_t)sin->sin_addr.s_addr;
10833 				ifaddr = INADDR_ANY;
10834 				ifindexp = &greqp->gr_interface;
10835 			} else {
10836 				mreqp = (struct ip_mreq *)i1;
10837 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10838 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10839 				ifindexp = NULL;
10840 			}
10841 
10842 			/*
10843 			 * In the multirouting case, we need to replicate
10844 			 * the request on all interfaces that will take part
10845 			 * in replication.  We do so because multirouting is
10846 			 * reflective, thus we will probably receive multi-
10847 			 * casts on those interfaces.
10848 			 * The ip_multirt_apply_membership() succeeds if the
10849 			 * operation succeeds on at least one interface.
10850 			 */
10851 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10852 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10853 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10854 			if (ire != NULL) {
10855 				if (ire->ire_flags & RTF_MULTIRT) {
10856 					error = ip_multirt_apply_membership(
10857 					    optfn, ire, connp, checkonly, group,
10858 					    fmode, INADDR_ANY, first_mp);
10859 					done = B_TRUE;
10860 				}
10861 				ire_refrele(ire);
10862 			}
10863 			if (!done) {
10864 				error = optfn(connp, checkonly, group, ifaddr,
10865 				    ifindexp, fmode, INADDR_ANY, first_mp);
10866 			}
10867 			if (error) {
10868 				/*
10869 				 * EINPROGRESS is a soft error, needs retry
10870 				 * so don't make *outlenp zero.
10871 				 */
10872 				if (error != EINPROGRESS)
10873 					*outlenp = 0;
10874 				return (error);
10875 			}
10876 			/* OK return - copy input buffer into output buffer */
10877 			if (invalp != outvalp) {
10878 				/* don't trust bcopy for identical src/dst */
10879 				bcopy(invalp, outvalp, inlen);
10880 			}
10881 			*outlenp = inlen;
10882 			return (0);
10883 		}
10884 		case IP_BLOCK_SOURCE:
10885 		case IP_UNBLOCK_SOURCE:
10886 		case IP_ADD_SOURCE_MEMBERSHIP:
10887 		case IP_DROP_SOURCE_MEMBERSHIP:
10888 		case MCAST_BLOCK_SOURCE:
10889 		case MCAST_UNBLOCK_SOURCE:
10890 		case MCAST_JOIN_SOURCE_GROUP:
10891 		case MCAST_LEAVE_SOURCE_GROUP: {
10892 			struct ip_mreq_source *imreqp;
10893 			struct group_source_req *gsreqp;
10894 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10895 			uint32_t ifindex = 0;
10896 			mcast_record_t fmode;
10897 			struct sockaddr_in *sin;
10898 			ire_t *ire;
10899 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10900 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10901 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10902 
10903 			switch (name) {
10904 			case IP_BLOCK_SOURCE:
10905 				mcast_opt = B_FALSE;
10906 				/* FALLTHRU */
10907 			case MCAST_BLOCK_SOURCE:
10908 				fmode = MODE_IS_EXCLUDE;
10909 				optfn = ip_opt_add_group;
10910 				break;
10911 
10912 			case IP_UNBLOCK_SOURCE:
10913 				mcast_opt = B_FALSE;
10914 				/* FALLTHRU */
10915 			case MCAST_UNBLOCK_SOURCE:
10916 				fmode = MODE_IS_EXCLUDE;
10917 				optfn = ip_opt_delete_group;
10918 				break;
10919 
10920 			case IP_ADD_SOURCE_MEMBERSHIP:
10921 				mcast_opt = B_FALSE;
10922 				/* FALLTHRU */
10923 			case MCAST_JOIN_SOURCE_GROUP:
10924 				fmode = MODE_IS_INCLUDE;
10925 				optfn = ip_opt_add_group;
10926 				break;
10927 
10928 			case IP_DROP_SOURCE_MEMBERSHIP:
10929 				mcast_opt = B_FALSE;
10930 				/* FALLTHRU */
10931 			case MCAST_LEAVE_SOURCE_GROUP:
10932 				fmode = MODE_IS_INCLUDE;
10933 				optfn = ip_opt_delete_group;
10934 				break;
10935 			}
10936 
10937 			if (mcast_opt) {
10938 				gsreqp = (struct group_source_req *)i1;
10939 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10940 					*outlenp = 0;
10941 					return (ENOPROTOOPT);
10942 				}
10943 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10944 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10945 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10946 				src = (ipaddr_t)sin->sin_addr.s_addr;
10947 				ifindex = gsreqp->gsr_interface;
10948 			} else {
10949 				imreqp = (struct ip_mreq_source *)i1;
10950 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10951 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10952 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10953 			}
10954 
10955 			/*
10956 			 * In the multirouting case, we need to replicate
10957 			 * the request as noted in the mcast cases above.
10958 			 */
10959 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10960 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10961 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10962 			if (ire != NULL) {
10963 				if (ire->ire_flags & RTF_MULTIRT) {
10964 					error = ip_multirt_apply_membership(
10965 					    optfn, ire, connp, checkonly, grp,
10966 					    fmode, src, first_mp);
10967 					done = B_TRUE;
10968 				}
10969 				ire_refrele(ire);
10970 			}
10971 			if (!done) {
10972 				error = optfn(connp, checkonly, grp, ifaddr,
10973 				    &ifindex, fmode, src, first_mp);
10974 			}
10975 			if (error != 0) {
10976 				/*
10977 				 * EINPROGRESS is a soft error, needs retry
10978 				 * so don't make *outlenp zero.
10979 				 */
10980 				if (error != EINPROGRESS)
10981 					*outlenp = 0;
10982 				return (error);
10983 			}
10984 			/* OK return - copy input buffer into output buffer */
10985 			if (invalp != outvalp) {
10986 				bcopy(invalp, outvalp, inlen);
10987 			}
10988 			*outlenp = inlen;
10989 			return (0);
10990 		}
10991 		case IP_SEC_OPT:
10992 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10993 			if (error != 0) {
10994 				*outlenp = 0;
10995 				return (error);
10996 			}
10997 			break;
10998 		case IP_HDRINCL:
10999 		case IP_OPTIONS:
11000 		case T_IP_OPTIONS:
11001 		case IP_TOS:
11002 		case T_IP_TOS:
11003 		case IP_TTL:
11004 		case IP_RECVDSTADDR:
11005 		case IP_RECVOPTS:
11006 			/* OK return - copy input buffer into output buffer */
11007 			if (invalp != outvalp) {
11008 				/* don't trust bcopy for identical src/dst */
11009 				bcopy(invalp, outvalp, inlen);
11010 			}
11011 			*outlenp = inlen;
11012 			return (0);
11013 		case IP_RECVIF:
11014 			/* Retrieve the inbound interface index */
11015 			if (!checkonly) {
11016 				mutex_enter(&connp->conn_lock);
11017 				connp->conn_recvif = *i1 ? 1 : 0;
11018 				mutex_exit(&connp->conn_lock);
11019 			}
11020 			break;	/* goto sizeof (int) option return */
11021 		case IP_RECVPKTINFO:
11022 			if (!checkonly) {
11023 				mutex_enter(&connp->conn_lock);
11024 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11025 				mutex_exit(&connp->conn_lock);
11026 			}
11027 			break;	/* goto sizeof (int) option return */
11028 		case IP_RECVSLLA:
11029 			/* Retrieve the source link layer address */
11030 			if (!checkonly) {
11031 				mutex_enter(&connp->conn_lock);
11032 				connp->conn_recvslla = *i1 ? 1 : 0;
11033 				mutex_exit(&connp->conn_lock);
11034 			}
11035 			break;	/* goto sizeof (int) option return */
11036 		case MRT_INIT:
11037 		case MRT_DONE:
11038 		case MRT_ADD_VIF:
11039 		case MRT_DEL_VIF:
11040 		case MRT_ADD_MFC:
11041 		case MRT_DEL_MFC:
11042 		case MRT_ASSERT:
11043 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11044 				*outlenp = 0;
11045 				return (error);
11046 			}
11047 			error = ip_mrouter_set((int)name, q, checkonly,
11048 			    (uchar_t *)invalp, inlen, first_mp);
11049 			if (error) {
11050 				*outlenp = 0;
11051 				return (error);
11052 			}
11053 			/* OK return - copy input buffer into output buffer */
11054 			if (invalp != outvalp) {
11055 				/* don't trust bcopy for identical src/dst */
11056 				bcopy(invalp, outvalp, inlen);
11057 			}
11058 			*outlenp = inlen;
11059 			return (0);
11060 		case IP_BOUND_IF:
11061 		case IP_DHCPINIT_IF:
11062 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11063 			    level, name, first_mp);
11064 			if (error != 0)
11065 				return (error);
11066 			break; 		/* goto sizeof (int) option return */
11067 
11068 		case IP_UNSPEC_SRC:
11069 			/* Allow sending with a zero source address */
11070 			if (!checkonly) {
11071 				mutex_enter(&connp->conn_lock);
11072 				connp->conn_unspec_src = *i1 ? 1 : 0;
11073 				mutex_exit(&connp->conn_lock);
11074 			}
11075 			break;	/* goto sizeof (int) option return */
11076 		default:
11077 			/*
11078 			 * "soft" error (negative)
11079 			 * option not handled at this level
11080 			 * Note: Do not modify *outlenp
11081 			 */
11082 			return (-EINVAL);
11083 		}
11084 		break;
11085 	case IPPROTO_IPV6:
11086 		switch (name) {
11087 		case IPV6_BOUND_IF:
11088 		case IPV6_BOUND_PIF:
11089 		case IPV6_DONTFAILOVER_IF:
11090 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11091 			    level, name, first_mp);
11092 			if (error != 0)
11093 				return (error);
11094 			break; 		/* goto sizeof (int) option return */
11095 
11096 		case IPV6_MULTICAST_IF:
11097 			/*
11098 			 * The only possible errors are EINPROGRESS and
11099 			 * EINVAL. EINPROGRESS will be restarted and is not
11100 			 * a hard error. We call this option on both V4 and V6
11101 			 * If both return EINVAL, then this call returns
11102 			 * EINVAL. If at least one of them succeeds we
11103 			 * return success.
11104 			 */
11105 			found = B_FALSE;
11106 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11107 			    level, name, first_mp);
11108 			if (error == EINPROGRESS)
11109 				return (error);
11110 			if (error == 0)
11111 				found = B_TRUE;
11112 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11113 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11114 			if (error == 0)
11115 				found = B_TRUE;
11116 			if (!found)
11117 				return (error);
11118 			break; 		/* goto sizeof (int) option return */
11119 
11120 		case IPV6_MULTICAST_HOPS:
11121 			/* Recorded in transport above IP */
11122 			break;	/* goto sizeof (int) option return */
11123 		case IPV6_MULTICAST_LOOP:
11124 			if (!checkonly) {
11125 				mutex_enter(&connp->conn_lock);
11126 				connp->conn_multicast_loop = *i1;
11127 				mutex_exit(&connp->conn_lock);
11128 			}
11129 			break;	/* goto sizeof (int) option return */
11130 		case IPV6_JOIN_GROUP:
11131 		case MCAST_JOIN_GROUP:
11132 		case IPV6_LEAVE_GROUP:
11133 		case MCAST_LEAVE_GROUP: {
11134 			struct ipv6_mreq *ip_mreqp;
11135 			struct group_req *greqp;
11136 			ire_t *ire;
11137 			boolean_t done = B_FALSE;
11138 			in6_addr_t groupv6;
11139 			uint32_t ifindex;
11140 			boolean_t mcast_opt = B_TRUE;
11141 			mcast_record_t fmode;
11142 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11143 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11144 
11145 			switch (name) {
11146 			case IPV6_JOIN_GROUP:
11147 				mcast_opt = B_FALSE;
11148 				/* FALLTHRU */
11149 			case MCAST_JOIN_GROUP:
11150 				fmode = MODE_IS_EXCLUDE;
11151 				optfn = ip_opt_add_group_v6;
11152 				break;
11153 
11154 			case IPV6_LEAVE_GROUP:
11155 				mcast_opt = B_FALSE;
11156 				/* FALLTHRU */
11157 			case MCAST_LEAVE_GROUP:
11158 				fmode = MODE_IS_INCLUDE;
11159 				optfn = ip_opt_delete_group_v6;
11160 				break;
11161 			}
11162 
11163 			if (mcast_opt) {
11164 				struct sockaddr_in *sin;
11165 				struct sockaddr_in6 *sin6;
11166 				greqp = (struct group_req *)i1;
11167 				if (greqp->gr_group.ss_family == AF_INET) {
11168 					sin = (struct sockaddr_in *)
11169 					    &(greqp->gr_group);
11170 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11171 					    &groupv6);
11172 				} else {
11173 					sin6 = (struct sockaddr_in6 *)
11174 					    &(greqp->gr_group);
11175 					groupv6 = sin6->sin6_addr;
11176 				}
11177 				ifindex = greqp->gr_interface;
11178 			} else {
11179 				ip_mreqp = (struct ipv6_mreq *)i1;
11180 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11181 				ifindex = ip_mreqp->ipv6mr_interface;
11182 			}
11183 			/*
11184 			 * In the multirouting case, we need to replicate
11185 			 * the request on all interfaces that will take part
11186 			 * in replication.  We do so because multirouting is
11187 			 * reflective, thus we will probably receive multi-
11188 			 * casts on those interfaces.
11189 			 * The ip_multirt_apply_membership_v6() succeeds if
11190 			 * the operation succeeds on at least one interface.
11191 			 */
11192 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11193 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11194 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11195 			if (ire != NULL) {
11196 				if (ire->ire_flags & RTF_MULTIRT) {
11197 					error = ip_multirt_apply_membership_v6(
11198 					    optfn, ire, connp, checkonly,
11199 					    &groupv6, fmode, &ipv6_all_zeros,
11200 					    first_mp);
11201 					done = B_TRUE;
11202 				}
11203 				ire_refrele(ire);
11204 			}
11205 			if (!done) {
11206 				error = optfn(connp, checkonly, &groupv6,
11207 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11208 			}
11209 			if (error) {
11210 				/*
11211 				 * EINPROGRESS is a soft error, needs retry
11212 				 * so don't make *outlenp zero.
11213 				 */
11214 				if (error != EINPROGRESS)
11215 					*outlenp = 0;
11216 				return (error);
11217 			}
11218 			/* OK return - copy input buffer into output buffer */
11219 			if (invalp != outvalp) {
11220 				/* don't trust bcopy for identical src/dst */
11221 				bcopy(invalp, outvalp, inlen);
11222 			}
11223 			*outlenp = inlen;
11224 			return (0);
11225 		}
11226 		case MCAST_BLOCK_SOURCE:
11227 		case MCAST_UNBLOCK_SOURCE:
11228 		case MCAST_JOIN_SOURCE_GROUP:
11229 		case MCAST_LEAVE_SOURCE_GROUP: {
11230 			struct group_source_req *gsreqp;
11231 			in6_addr_t v6grp, v6src;
11232 			uint32_t ifindex;
11233 			mcast_record_t fmode;
11234 			ire_t *ire;
11235 			boolean_t done = B_FALSE;
11236 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11237 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11238 
11239 			switch (name) {
11240 			case MCAST_BLOCK_SOURCE:
11241 				fmode = MODE_IS_EXCLUDE;
11242 				optfn = ip_opt_add_group_v6;
11243 				break;
11244 			case MCAST_UNBLOCK_SOURCE:
11245 				fmode = MODE_IS_EXCLUDE;
11246 				optfn = ip_opt_delete_group_v6;
11247 				break;
11248 			case MCAST_JOIN_SOURCE_GROUP:
11249 				fmode = MODE_IS_INCLUDE;
11250 				optfn = ip_opt_add_group_v6;
11251 				break;
11252 			case MCAST_LEAVE_SOURCE_GROUP:
11253 				fmode = MODE_IS_INCLUDE;
11254 				optfn = ip_opt_delete_group_v6;
11255 				break;
11256 			}
11257 
11258 			gsreqp = (struct group_source_req *)i1;
11259 			ifindex = gsreqp->gsr_interface;
11260 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11261 				struct sockaddr_in *s;
11262 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11263 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11264 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11265 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11266 			} else {
11267 				struct sockaddr_in6 *s6;
11268 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11269 				v6grp = s6->sin6_addr;
11270 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11271 				v6src = s6->sin6_addr;
11272 			}
11273 
11274 			/*
11275 			 * In the multirouting case, we need to replicate
11276 			 * the request as noted in the mcast cases above.
11277 			 */
11278 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11279 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11280 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11281 			if (ire != NULL) {
11282 				if (ire->ire_flags & RTF_MULTIRT) {
11283 					error = ip_multirt_apply_membership_v6(
11284 					    optfn, ire, connp, checkonly,
11285 					    &v6grp, fmode, &v6src, first_mp);
11286 					done = B_TRUE;
11287 				}
11288 				ire_refrele(ire);
11289 			}
11290 			if (!done) {
11291 				error = optfn(connp, checkonly, &v6grp,
11292 				    ifindex, fmode, &v6src, first_mp);
11293 			}
11294 			if (error != 0) {
11295 				/*
11296 				 * EINPROGRESS is a soft error, needs retry
11297 				 * so don't make *outlenp zero.
11298 				 */
11299 				if (error != EINPROGRESS)
11300 					*outlenp = 0;
11301 				return (error);
11302 			}
11303 			/* OK return - copy input buffer into output buffer */
11304 			if (invalp != outvalp) {
11305 				bcopy(invalp, outvalp, inlen);
11306 			}
11307 			*outlenp = inlen;
11308 			return (0);
11309 		}
11310 		case IPV6_UNICAST_HOPS:
11311 			/* Recorded in transport above IP */
11312 			break;	/* goto sizeof (int) option return */
11313 		case IPV6_UNSPEC_SRC:
11314 			/* Allow sending with a zero source address */
11315 			if (!checkonly) {
11316 				mutex_enter(&connp->conn_lock);
11317 				connp->conn_unspec_src = *i1 ? 1 : 0;
11318 				mutex_exit(&connp->conn_lock);
11319 			}
11320 			break;	/* goto sizeof (int) option return */
11321 		case IPV6_RECVPKTINFO:
11322 			if (!checkonly) {
11323 				mutex_enter(&connp->conn_lock);
11324 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11325 				mutex_exit(&connp->conn_lock);
11326 			}
11327 			break;	/* goto sizeof (int) option return */
11328 		case IPV6_RECVTCLASS:
11329 			if (!checkonly) {
11330 				if (*i1 < 0 || *i1 > 1) {
11331 					return (EINVAL);
11332 				}
11333 				mutex_enter(&connp->conn_lock);
11334 				connp->conn_ipv6_recvtclass = *i1;
11335 				mutex_exit(&connp->conn_lock);
11336 			}
11337 			break;
11338 		case IPV6_RECVPATHMTU:
11339 			if (!checkonly) {
11340 				if (*i1 < 0 || *i1 > 1) {
11341 					return (EINVAL);
11342 				}
11343 				mutex_enter(&connp->conn_lock);
11344 				connp->conn_ipv6_recvpathmtu = *i1;
11345 				mutex_exit(&connp->conn_lock);
11346 			}
11347 			break;
11348 		case IPV6_RECVHOPLIMIT:
11349 			if (!checkonly) {
11350 				mutex_enter(&connp->conn_lock);
11351 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11352 				mutex_exit(&connp->conn_lock);
11353 			}
11354 			break;	/* goto sizeof (int) option return */
11355 		case IPV6_RECVHOPOPTS:
11356 			if (!checkonly) {
11357 				mutex_enter(&connp->conn_lock);
11358 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11359 				mutex_exit(&connp->conn_lock);
11360 			}
11361 			break;	/* goto sizeof (int) option return */
11362 		case IPV6_RECVDSTOPTS:
11363 			if (!checkonly) {
11364 				mutex_enter(&connp->conn_lock);
11365 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11366 				mutex_exit(&connp->conn_lock);
11367 			}
11368 			break;	/* goto sizeof (int) option return */
11369 		case IPV6_RECVRTHDR:
11370 			if (!checkonly) {
11371 				mutex_enter(&connp->conn_lock);
11372 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11373 				mutex_exit(&connp->conn_lock);
11374 			}
11375 			break;	/* goto sizeof (int) option return */
11376 		case IPV6_RECVRTHDRDSTOPTS:
11377 			if (!checkonly) {
11378 				mutex_enter(&connp->conn_lock);
11379 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11380 				mutex_exit(&connp->conn_lock);
11381 			}
11382 			break;	/* goto sizeof (int) option return */
11383 		case IPV6_PKTINFO:
11384 			if (inlen == 0)
11385 				return (-EINVAL);	/* clearing option */
11386 			error = ip6_set_pktinfo(cr, connp,
11387 			    (struct in6_pktinfo *)invalp, first_mp);
11388 			if (error != 0)
11389 				*outlenp = 0;
11390 			else
11391 				*outlenp = inlen;
11392 			return (error);
11393 		case IPV6_NEXTHOP: {
11394 			struct sockaddr_in6 *sin6;
11395 
11396 			/* Verify that the nexthop is reachable */
11397 			if (inlen == 0)
11398 				return (-EINVAL);	/* clearing option */
11399 
11400 			sin6 = (struct sockaddr_in6 *)invalp;
11401 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11402 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11403 			    NULL, MATCH_IRE_DEFAULT, ipst);
11404 
11405 			if (ire == NULL) {
11406 				*outlenp = 0;
11407 				return (EHOSTUNREACH);
11408 			}
11409 			ire_refrele(ire);
11410 			return (-EINVAL);
11411 		}
11412 		case IPV6_SEC_OPT:
11413 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11414 			if (error != 0) {
11415 				*outlenp = 0;
11416 				return (error);
11417 			}
11418 			break;
11419 		case IPV6_SRC_PREFERENCES: {
11420 			/*
11421 			 * This is implemented strictly in the ip module
11422 			 * (here and in tcp_opt_*() to accomodate tcp
11423 			 * sockets).  Modules above ip pass this option
11424 			 * down here since ip is the only one that needs to
11425 			 * be aware of source address preferences.
11426 			 *
11427 			 * This socket option only affects connected
11428 			 * sockets that haven't already bound to a specific
11429 			 * IPv6 address.  In other words, sockets that
11430 			 * don't call bind() with an address other than the
11431 			 * unspecified address and that call connect().
11432 			 * ip_bind_connected_v6() passes these preferences
11433 			 * to the ipif_select_source_v6() function.
11434 			 */
11435 			if (inlen != sizeof (uint32_t))
11436 				return (EINVAL);
11437 			error = ip6_set_src_preferences(connp,
11438 			    *(uint32_t *)invalp);
11439 			if (error != 0) {
11440 				*outlenp = 0;
11441 				return (error);
11442 			} else {
11443 				*outlenp = sizeof (uint32_t);
11444 			}
11445 			break;
11446 		}
11447 		case IPV6_V6ONLY:
11448 			if (*i1 < 0 || *i1 > 1) {
11449 				return (EINVAL);
11450 			}
11451 			mutex_enter(&connp->conn_lock);
11452 			connp->conn_ipv6_v6only = *i1;
11453 			mutex_exit(&connp->conn_lock);
11454 			break;
11455 		default:
11456 			return (-EINVAL);
11457 		}
11458 		break;
11459 	default:
11460 		/*
11461 		 * "soft" error (negative)
11462 		 * option not handled at this level
11463 		 * Note: Do not modify *outlenp
11464 		 */
11465 		return (-EINVAL);
11466 	}
11467 	/*
11468 	 * Common case of return from an option that is sizeof (int)
11469 	 */
11470 	*(int *)outvalp = *i1;
11471 	*outlenp = sizeof (int);
11472 	return (0);
11473 }
11474 
11475 /*
11476  * This routine gets default values of certain options whose default
11477  * values are maintained by protocol specific code
11478  */
11479 /* ARGSUSED */
11480 int
11481 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11482 {
11483 	int *i1 = (int *)ptr;
11484 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11485 
11486 	switch (level) {
11487 	case IPPROTO_IP:
11488 		switch (name) {
11489 		case IP_MULTICAST_TTL:
11490 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11491 			return (sizeof (uchar_t));
11492 		case IP_MULTICAST_LOOP:
11493 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11494 			return (sizeof (uchar_t));
11495 		default:
11496 			return (-1);
11497 		}
11498 	case IPPROTO_IPV6:
11499 		switch (name) {
11500 		case IPV6_UNICAST_HOPS:
11501 			*i1 = ipst->ips_ipv6_def_hops;
11502 			return (sizeof (int));
11503 		case IPV6_MULTICAST_HOPS:
11504 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11505 			return (sizeof (int));
11506 		case IPV6_MULTICAST_LOOP:
11507 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11508 			return (sizeof (int));
11509 		case IPV6_V6ONLY:
11510 			*i1 = 1;
11511 			return (sizeof (int));
11512 		default:
11513 			return (-1);
11514 		}
11515 	default:
11516 		return (-1);
11517 	}
11518 	/* NOTREACHED */
11519 }
11520 
11521 /*
11522  * Given a destination address and a pointer to where to put the information
11523  * this routine fills in the mtuinfo.
11524  */
11525 int
11526 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11527     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11528 {
11529 	ire_t *ire;
11530 	ip_stack_t	*ipst = ns->netstack_ip;
11531 
11532 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11533 		return (-1);
11534 
11535 	bzero(mtuinfo, sizeof (*mtuinfo));
11536 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11537 	mtuinfo->ip6m_addr.sin6_port = port;
11538 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11539 
11540 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11541 	if (ire != NULL) {
11542 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11543 		ire_refrele(ire);
11544 	} else {
11545 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11546 	}
11547 	return (sizeof (struct ip6_mtuinfo));
11548 }
11549 
11550 /*
11551  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11552  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11553  * isn't.  This doesn't matter as the error checking is done properly for the
11554  * other MRT options coming in through ip_opt_set.
11555  */
11556 int
11557 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11558 {
11559 	conn_t		*connp = Q_TO_CONN(q);
11560 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11561 
11562 	switch (level) {
11563 	case IPPROTO_IP:
11564 		switch (name) {
11565 		case MRT_VERSION:
11566 		case MRT_ASSERT:
11567 			(void) ip_mrouter_get(name, q, ptr);
11568 			return (sizeof (int));
11569 		case IP_SEC_OPT:
11570 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11571 		case IP_NEXTHOP:
11572 			if (connp->conn_nexthop_set) {
11573 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11574 				return (sizeof (ipaddr_t));
11575 			} else
11576 				return (0);
11577 		case IP_RECVPKTINFO:
11578 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11579 			return (sizeof (int));
11580 		default:
11581 			break;
11582 		}
11583 		break;
11584 	case IPPROTO_IPV6:
11585 		switch (name) {
11586 		case IPV6_SEC_OPT:
11587 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11588 		case IPV6_SRC_PREFERENCES: {
11589 			return (ip6_get_src_preferences(connp,
11590 			    (uint32_t *)ptr));
11591 		}
11592 		case IPV6_V6ONLY:
11593 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11594 			return (sizeof (int));
11595 		case IPV6_PATHMTU:
11596 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11597 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11598 		default:
11599 			break;
11600 		}
11601 		break;
11602 	default:
11603 		break;
11604 	}
11605 	return (-1);
11606 }
11607 
11608 /* Named Dispatch routine to get a current value out of our parameter table. */
11609 /* ARGSUSED */
11610 static int
11611 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11612 {
11613 	ipparam_t *ippa = (ipparam_t *)cp;
11614 
11615 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11616 	return (0);
11617 }
11618 
11619 /* ARGSUSED */
11620 static int
11621 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11622 {
11623 
11624 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11625 	return (0);
11626 }
11627 
11628 /*
11629  * Set ip{,6}_forwarding values.  This means walking through all of the
11630  * ill's and toggling their forwarding values.
11631  */
11632 /* ARGSUSED */
11633 static int
11634 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11635 {
11636 	long new_value;
11637 	int *forwarding_value = (int *)cp;
11638 	ill_t *ill;
11639 	boolean_t isv6;
11640 	ill_walk_context_t ctx;
11641 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11642 
11643 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11644 
11645 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11646 	    new_value < 0 || new_value > 1) {
11647 		return (EINVAL);
11648 	}
11649 
11650 	*forwarding_value = new_value;
11651 
11652 	/*
11653 	 * Regardless of the current value of ip_forwarding, set all per-ill
11654 	 * values of ip_forwarding to the value being set.
11655 	 *
11656 	 * Bring all the ill's up to date with the new global value.
11657 	 */
11658 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11659 
11660 	if (isv6)
11661 		ill = ILL_START_WALK_V6(&ctx, ipst);
11662 	else
11663 		ill = ILL_START_WALK_V4(&ctx, ipst);
11664 
11665 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11666 		(void) ill_forward_set(ill, new_value != 0);
11667 
11668 	rw_exit(&ipst->ips_ill_g_lock);
11669 	return (0);
11670 }
11671 
11672 /*
11673  * Walk through the param array specified registering each element with the
11674  * Named Dispatch handler. This is called only during init. So it is ok
11675  * not to acquire any locks
11676  */
11677 static boolean_t
11678 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11679     ipndp_t *ipnd, size_t ipnd_cnt)
11680 {
11681 	for (; ippa_cnt-- > 0; ippa++) {
11682 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11683 			if (!nd_load(ndp, ippa->ip_param_name,
11684 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11685 				nd_free(ndp);
11686 				return (B_FALSE);
11687 			}
11688 		}
11689 	}
11690 
11691 	for (; ipnd_cnt-- > 0; ipnd++) {
11692 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11693 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11694 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11695 			    ipnd->ip_ndp_data)) {
11696 				nd_free(ndp);
11697 				return (B_FALSE);
11698 			}
11699 		}
11700 	}
11701 
11702 	return (B_TRUE);
11703 }
11704 
11705 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11706 /* ARGSUSED */
11707 static int
11708 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11709 {
11710 	long		new_value;
11711 	ipparam_t	*ippa = (ipparam_t *)cp;
11712 
11713 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11714 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11715 		return (EINVAL);
11716 	}
11717 	ippa->ip_param_value = new_value;
11718 	return (0);
11719 }
11720 
11721 /*
11722  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11723  * When an ipf is passed here for the first time, if
11724  * we already have in-order fragments on the queue, we convert from the fast-
11725  * path reassembly scheme to the hard-case scheme.  From then on, additional
11726  * fragments are reassembled here.  We keep track of the start and end offsets
11727  * of each piece, and the number of holes in the chain.  When the hole count
11728  * goes to zero, we are done!
11729  *
11730  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11731  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11732  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11733  * after the call to ip_reassemble().
11734  */
11735 int
11736 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11737     size_t msg_len)
11738 {
11739 	uint_t	end;
11740 	mblk_t	*next_mp;
11741 	mblk_t	*mp1;
11742 	uint_t	offset;
11743 	boolean_t incr_dups = B_TRUE;
11744 	boolean_t offset_zero_seen = B_FALSE;
11745 	boolean_t pkt_boundary_checked = B_FALSE;
11746 
11747 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11748 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11749 
11750 	/* Add in byte count */
11751 	ipf->ipf_count += msg_len;
11752 	if (ipf->ipf_end) {
11753 		/*
11754 		 * We were part way through in-order reassembly, but now there
11755 		 * is a hole.  We walk through messages already queued, and
11756 		 * mark them for hard case reassembly.  We know that up till
11757 		 * now they were in order starting from offset zero.
11758 		 */
11759 		offset = 0;
11760 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11761 			IP_REASS_SET_START(mp1, offset);
11762 			if (offset == 0) {
11763 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11764 				offset = -ipf->ipf_nf_hdr_len;
11765 			}
11766 			offset += mp1->b_wptr - mp1->b_rptr;
11767 			IP_REASS_SET_END(mp1, offset);
11768 		}
11769 		/* One hole at the end. */
11770 		ipf->ipf_hole_cnt = 1;
11771 		/* Brand it as a hard case, forever. */
11772 		ipf->ipf_end = 0;
11773 	}
11774 	/* Walk through all the new pieces. */
11775 	do {
11776 		end = start + (mp->b_wptr - mp->b_rptr);
11777 		/*
11778 		 * If start is 0, decrease 'end' only for the first mblk of
11779 		 * the fragment. Otherwise 'end' can get wrong value in the
11780 		 * second pass of the loop if first mblk is exactly the
11781 		 * size of ipf_nf_hdr_len.
11782 		 */
11783 		if (start == 0 && !offset_zero_seen) {
11784 			/* First segment */
11785 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11786 			end -= ipf->ipf_nf_hdr_len;
11787 			offset_zero_seen = B_TRUE;
11788 		}
11789 		next_mp = mp->b_cont;
11790 		/*
11791 		 * We are checking to see if there is any interesing data
11792 		 * to process.  If there isn't and the mblk isn't the
11793 		 * one which carries the unfragmentable header then we
11794 		 * drop it.  It's possible to have just the unfragmentable
11795 		 * header come through without any data.  That needs to be
11796 		 * saved.
11797 		 *
11798 		 * If the assert at the top of this function holds then the
11799 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11800 		 * is infrequently traveled enough that the test is left in
11801 		 * to protect against future code changes which break that
11802 		 * invariant.
11803 		 */
11804 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11805 			/* Empty.  Blast it. */
11806 			IP_REASS_SET_START(mp, 0);
11807 			IP_REASS_SET_END(mp, 0);
11808 			/*
11809 			 * If the ipf points to the mblk we are about to free,
11810 			 * update ipf to point to the next mblk (or NULL
11811 			 * if none).
11812 			 */
11813 			if (ipf->ipf_mp->b_cont == mp)
11814 				ipf->ipf_mp->b_cont = next_mp;
11815 			freeb(mp);
11816 			continue;
11817 		}
11818 		mp->b_cont = NULL;
11819 		IP_REASS_SET_START(mp, start);
11820 		IP_REASS_SET_END(mp, end);
11821 		if (!ipf->ipf_tail_mp) {
11822 			ipf->ipf_tail_mp = mp;
11823 			ipf->ipf_mp->b_cont = mp;
11824 			if (start == 0 || !more) {
11825 				ipf->ipf_hole_cnt = 1;
11826 				/*
11827 				 * if the first fragment comes in more than one
11828 				 * mblk, this loop will be executed for each
11829 				 * mblk. Need to adjust hole count so exiting
11830 				 * this routine will leave hole count at 1.
11831 				 */
11832 				if (next_mp)
11833 					ipf->ipf_hole_cnt++;
11834 			} else
11835 				ipf->ipf_hole_cnt = 2;
11836 			continue;
11837 		} else if (ipf->ipf_last_frag_seen && !more &&
11838 		    !pkt_boundary_checked) {
11839 			/*
11840 			 * We check datagram boundary only if this fragment
11841 			 * claims to be the last fragment and we have seen a
11842 			 * last fragment in the past too. We do this only
11843 			 * once for a given fragment.
11844 			 *
11845 			 * start cannot be 0 here as fragments with start=0
11846 			 * and MF=0 gets handled as a complete packet. These
11847 			 * fragments should not reach here.
11848 			 */
11849 
11850 			if (start + msgdsize(mp) !=
11851 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11852 				/*
11853 				 * We have two fragments both of which claim
11854 				 * to be the last fragment but gives conflicting
11855 				 * information about the whole datagram size.
11856 				 * Something fishy is going on. Drop the
11857 				 * fragment and free up the reassembly list.
11858 				 */
11859 				return (IP_REASS_FAILED);
11860 			}
11861 
11862 			/*
11863 			 * We shouldn't come to this code block again for this
11864 			 * particular fragment.
11865 			 */
11866 			pkt_boundary_checked = B_TRUE;
11867 		}
11868 
11869 		/* New stuff at or beyond tail? */
11870 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11871 		if (start >= offset) {
11872 			if (ipf->ipf_last_frag_seen) {
11873 				/* current fragment is beyond last fragment */
11874 				return (IP_REASS_FAILED);
11875 			}
11876 			/* Link it on end. */
11877 			ipf->ipf_tail_mp->b_cont = mp;
11878 			ipf->ipf_tail_mp = mp;
11879 			if (more) {
11880 				if (start != offset)
11881 					ipf->ipf_hole_cnt++;
11882 			} else if (start == offset && next_mp == NULL)
11883 					ipf->ipf_hole_cnt--;
11884 			continue;
11885 		}
11886 		mp1 = ipf->ipf_mp->b_cont;
11887 		offset = IP_REASS_START(mp1);
11888 		/* New stuff at the front? */
11889 		if (start < offset) {
11890 			if (start == 0) {
11891 				if (end >= offset) {
11892 					/* Nailed the hole at the begining. */
11893 					ipf->ipf_hole_cnt--;
11894 				}
11895 			} else if (end < offset) {
11896 				/*
11897 				 * A hole, stuff, and a hole where there used
11898 				 * to be just a hole.
11899 				 */
11900 				ipf->ipf_hole_cnt++;
11901 			}
11902 			mp->b_cont = mp1;
11903 			/* Check for overlap. */
11904 			while (end > offset) {
11905 				if (end < IP_REASS_END(mp1)) {
11906 					mp->b_wptr -= end - offset;
11907 					IP_REASS_SET_END(mp, offset);
11908 					BUMP_MIB(ill->ill_ip_mib,
11909 					    ipIfStatsReasmPartDups);
11910 					break;
11911 				}
11912 				/* Did we cover another hole? */
11913 				if ((mp1->b_cont &&
11914 				    IP_REASS_END(mp1) !=
11915 				    IP_REASS_START(mp1->b_cont) &&
11916 				    end >= IP_REASS_START(mp1->b_cont)) ||
11917 				    (!ipf->ipf_last_frag_seen && !more)) {
11918 					ipf->ipf_hole_cnt--;
11919 				}
11920 				/* Clip out mp1. */
11921 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11922 					/*
11923 					 * After clipping out mp1, this guy
11924 					 * is now hanging off the end.
11925 					 */
11926 					ipf->ipf_tail_mp = mp;
11927 				}
11928 				IP_REASS_SET_START(mp1, 0);
11929 				IP_REASS_SET_END(mp1, 0);
11930 				/* Subtract byte count */
11931 				ipf->ipf_count -= mp1->b_datap->db_lim -
11932 				    mp1->b_datap->db_base;
11933 				freeb(mp1);
11934 				BUMP_MIB(ill->ill_ip_mib,
11935 				    ipIfStatsReasmPartDups);
11936 				mp1 = mp->b_cont;
11937 				if (!mp1)
11938 					break;
11939 				offset = IP_REASS_START(mp1);
11940 			}
11941 			ipf->ipf_mp->b_cont = mp;
11942 			continue;
11943 		}
11944 		/*
11945 		 * The new piece starts somewhere between the start of the head
11946 		 * and before the end of the tail.
11947 		 */
11948 		for (; mp1; mp1 = mp1->b_cont) {
11949 			offset = IP_REASS_END(mp1);
11950 			if (start < offset) {
11951 				if (end <= offset) {
11952 					/* Nothing new. */
11953 					IP_REASS_SET_START(mp, 0);
11954 					IP_REASS_SET_END(mp, 0);
11955 					/* Subtract byte count */
11956 					ipf->ipf_count -= mp->b_datap->db_lim -
11957 					    mp->b_datap->db_base;
11958 					if (incr_dups) {
11959 						ipf->ipf_num_dups++;
11960 						incr_dups = B_FALSE;
11961 					}
11962 					freeb(mp);
11963 					BUMP_MIB(ill->ill_ip_mib,
11964 					    ipIfStatsReasmDuplicates);
11965 					break;
11966 				}
11967 				/*
11968 				 * Trim redundant stuff off beginning of new
11969 				 * piece.
11970 				 */
11971 				IP_REASS_SET_START(mp, offset);
11972 				mp->b_rptr += offset - start;
11973 				BUMP_MIB(ill->ill_ip_mib,
11974 				    ipIfStatsReasmPartDups);
11975 				start = offset;
11976 				if (!mp1->b_cont) {
11977 					/*
11978 					 * After trimming, this guy is now
11979 					 * hanging off the end.
11980 					 */
11981 					mp1->b_cont = mp;
11982 					ipf->ipf_tail_mp = mp;
11983 					if (!more) {
11984 						ipf->ipf_hole_cnt--;
11985 					}
11986 					break;
11987 				}
11988 			}
11989 			if (start >= IP_REASS_START(mp1->b_cont))
11990 				continue;
11991 			/* Fill a hole */
11992 			if (start > offset)
11993 				ipf->ipf_hole_cnt++;
11994 			mp->b_cont = mp1->b_cont;
11995 			mp1->b_cont = mp;
11996 			mp1 = mp->b_cont;
11997 			offset = IP_REASS_START(mp1);
11998 			if (end >= offset) {
11999 				ipf->ipf_hole_cnt--;
12000 				/* Check for overlap. */
12001 				while (end > offset) {
12002 					if (end < IP_REASS_END(mp1)) {
12003 						mp->b_wptr -= end - offset;
12004 						IP_REASS_SET_END(mp, offset);
12005 						/*
12006 						 * TODO we might bump
12007 						 * this up twice if there is
12008 						 * overlap at both ends.
12009 						 */
12010 						BUMP_MIB(ill->ill_ip_mib,
12011 						    ipIfStatsReasmPartDups);
12012 						break;
12013 					}
12014 					/* Did we cover another hole? */
12015 					if ((mp1->b_cont &&
12016 					    IP_REASS_END(mp1)
12017 					    != IP_REASS_START(mp1->b_cont) &&
12018 					    end >=
12019 					    IP_REASS_START(mp1->b_cont)) ||
12020 					    (!ipf->ipf_last_frag_seen &&
12021 					    !more)) {
12022 						ipf->ipf_hole_cnt--;
12023 					}
12024 					/* Clip out mp1. */
12025 					if ((mp->b_cont = mp1->b_cont) ==
12026 					    NULL) {
12027 						/*
12028 						 * After clipping out mp1,
12029 						 * this guy is now hanging
12030 						 * off the end.
12031 						 */
12032 						ipf->ipf_tail_mp = mp;
12033 					}
12034 					IP_REASS_SET_START(mp1, 0);
12035 					IP_REASS_SET_END(mp1, 0);
12036 					/* Subtract byte count */
12037 					ipf->ipf_count -=
12038 					    mp1->b_datap->db_lim -
12039 					    mp1->b_datap->db_base;
12040 					freeb(mp1);
12041 					BUMP_MIB(ill->ill_ip_mib,
12042 					    ipIfStatsReasmPartDups);
12043 					mp1 = mp->b_cont;
12044 					if (!mp1)
12045 						break;
12046 					offset = IP_REASS_START(mp1);
12047 				}
12048 			}
12049 			break;
12050 		}
12051 	} while (start = end, mp = next_mp);
12052 
12053 	/* Fragment just processed could be the last one. Remember this fact */
12054 	if (!more)
12055 		ipf->ipf_last_frag_seen = B_TRUE;
12056 
12057 	/* Still got holes? */
12058 	if (ipf->ipf_hole_cnt)
12059 		return (IP_REASS_PARTIAL);
12060 	/* Clean up overloaded fields to avoid upstream disasters. */
12061 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12062 		IP_REASS_SET_START(mp1, 0);
12063 		IP_REASS_SET_END(mp1, 0);
12064 	}
12065 	return (IP_REASS_COMPLETE);
12066 }
12067 
12068 /*
12069  * ipsec processing for the fast path, used for input UDP Packets
12070  * Returns true if ready for passup to UDP.
12071  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12072  * was an ESP-in-UDP packet, etc.).
12073  */
12074 static boolean_t
12075 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12076     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12077 {
12078 	uint32_t	ill_index;
12079 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12080 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12081 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12082 	udp_t		*udp = connp->conn_udp;
12083 
12084 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12085 	/* The ill_index of the incoming ILL */
12086 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12087 
12088 	/* pass packet up to the transport */
12089 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12090 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12091 		    NULL, mctl_present);
12092 		if (*first_mpp == NULL) {
12093 			return (B_FALSE);
12094 		}
12095 	}
12096 
12097 	/* Initiate IPPF processing for fastpath UDP */
12098 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12099 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12100 		if (*mpp == NULL) {
12101 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12102 			    "deferred/dropped during IPPF processing\n"));
12103 			return (B_FALSE);
12104 		}
12105 	}
12106 	/*
12107 	 * Remove 0-spi if it's 0, or move everything behind
12108 	 * the UDP header over it and forward to ESP via
12109 	 * ip_proto_input().
12110 	 */
12111 	if (udp->udp_nat_t_endpoint) {
12112 		if (mctl_present) {
12113 			/* mctl_present *shouldn't* happen. */
12114 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12115 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12116 			    &ipss->ipsec_dropper);
12117 			*first_mpp = NULL;
12118 			return (B_FALSE);
12119 		}
12120 
12121 		/* "ill" is "recv_ill" in actuality. */
12122 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12123 			return (B_FALSE);
12124 
12125 		/* Else continue like a normal UDP packet. */
12126 	}
12127 
12128 	/*
12129 	 * We make the checks as below since we are in the fast path
12130 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12131 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12132 	 */
12133 	if (connp->conn_recvif || connp->conn_recvslla ||
12134 	    connp->conn_ip_recvpktinfo) {
12135 		if (connp->conn_recvif) {
12136 			in_flags = IPF_RECVIF;
12137 		}
12138 		/*
12139 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12140 		 * so the flag passed to ip_add_info is based on IP version
12141 		 * of connp.
12142 		 */
12143 		if (connp->conn_ip_recvpktinfo) {
12144 			if (connp->conn_af_isv6) {
12145 				/*
12146 				 * V6 only needs index
12147 				 */
12148 				in_flags |= IPF_RECVIF;
12149 			} else {
12150 				/*
12151 				 * V4 needs index + matching address.
12152 				 */
12153 				in_flags |= IPF_RECVADDR;
12154 			}
12155 		}
12156 		if (connp->conn_recvslla) {
12157 			in_flags |= IPF_RECVSLLA;
12158 		}
12159 		/*
12160 		 * since in_flags are being set ill will be
12161 		 * referenced in ip_add_info, so it better not
12162 		 * be NULL.
12163 		 */
12164 		/*
12165 		 * the actual data will be contained in b_cont
12166 		 * upon successful return of the following call.
12167 		 * If the call fails then the original mblk is
12168 		 * returned.
12169 		 */
12170 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12171 		    ipst);
12172 	}
12173 
12174 	return (B_TRUE);
12175 }
12176 
12177 /*
12178  * Fragmentation reassembly.  Each ILL has a hash table for
12179  * queuing packets undergoing reassembly for all IPIFs
12180  * associated with the ILL.  The hash is based on the packet
12181  * IP ident field.  The ILL frag hash table was allocated
12182  * as a timer block at the time the ILL was created.  Whenever
12183  * there is anything on the reassembly queue, the timer will
12184  * be running.  Returns B_TRUE if successful else B_FALSE;
12185  * frees mp on failure.
12186  */
12187 static boolean_t
12188 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12189     uint32_t *cksum_val, uint16_t *cksum_flags)
12190 {
12191 	uint32_t	frag_offset_flags;
12192 	ill_t		*ill = (ill_t *)q->q_ptr;
12193 	mblk_t		*mp = *mpp;
12194 	mblk_t		*t_mp;
12195 	ipaddr_t	dst;
12196 	uint8_t		proto = ipha->ipha_protocol;
12197 	uint32_t	sum_val;
12198 	uint16_t	sum_flags;
12199 	ipf_t		*ipf;
12200 	ipf_t		**ipfp;
12201 	ipfb_t		*ipfb;
12202 	uint16_t	ident;
12203 	uint32_t	offset;
12204 	ipaddr_t	src;
12205 	uint_t		hdr_length;
12206 	uint32_t	end;
12207 	mblk_t		*mp1;
12208 	mblk_t		*tail_mp;
12209 	size_t		count;
12210 	size_t		msg_len;
12211 	uint8_t		ecn_info = 0;
12212 	uint32_t	packet_size;
12213 	boolean_t	pruned = B_FALSE;
12214 	ip_stack_t *ipst = ill->ill_ipst;
12215 
12216 	if (cksum_val != NULL)
12217 		*cksum_val = 0;
12218 	if (cksum_flags != NULL)
12219 		*cksum_flags = 0;
12220 
12221 	/*
12222 	 * Drop the fragmented as early as possible, if
12223 	 * we don't have resource(s) to re-assemble.
12224 	 */
12225 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12226 		freemsg(mp);
12227 		return (B_FALSE);
12228 	}
12229 
12230 	/* Check for fragmentation offset; return if there's none */
12231 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12232 	    (IPH_MF | IPH_OFFSET)) == 0)
12233 		return (B_TRUE);
12234 
12235 	/*
12236 	 * We utilize hardware computed checksum info only for UDP since
12237 	 * IP fragmentation is a normal occurence for the protocol.  In
12238 	 * addition, checksum offload support for IP fragments carrying
12239 	 * UDP payload is commonly implemented across network adapters.
12240 	 */
12241 	ASSERT(ill != NULL);
12242 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12243 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12244 		mblk_t *mp1 = mp->b_cont;
12245 		int32_t len;
12246 
12247 		/* Record checksum information from the packet */
12248 		sum_val = (uint32_t)DB_CKSUM16(mp);
12249 		sum_flags = DB_CKSUMFLAGS(mp);
12250 
12251 		/* IP payload offset from beginning of mblk */
12252 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12253 
12254 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12255 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12256 		    offset >= DB_CKSUMSTART(mp) &&
12257 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12258 			uint32_t adj;
12259 			/*
12260 			 * Partial checksum has been calculated by hardware
12261 			 * and attached to the packet; in addition, any
12262 			 * prepended extraneous data is even byte aligned.
12263 			 * If any such data exists, we adjust the checksum;
12264 			 * this would also handle any postpended data.
12265 			 */
12266 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12267 			    mp, mp1, len, adj);
12268 
12269 			/* One's complement subtract extraneous checksum */
12270 			if (adj >= sum_val)
12271 				sum_val = ~(adj - sum_val) & 0xFFFF;
12272 			else
12273 				sum_val -= adj;
12274 		}
12275 	} else {
12276 		sum_val = 0;
12277 		sum_flags = 0;
12278 	}
12279 
12280 	/* Clear hardware checksumming flag */
12281 	DB_CKSUMFLAGS(mp) = 0;
12282 
12283 	ident = ipha->ipha_ident;
12284 	offset = (frag_offset_flags << 3) & 0xFFFF;
12285 	src = ipha->ipha_src;
12286 	dst = ipha->ipha_dst;
12287 	hdr_length = IPH_HDR_LENGTH(ipha);
12288 	end = ntohs(ipha->ipha_length) - hdr_length;
12289 
12290 	/* If end == 0 then we have a packet with no data, so just free it */
12291 	if (end == 0) {
12292 		freemsg(mp);
12293 		return (B_FALSE);
12294 	}
12295 
12296 	/* Record the ECN field info. */
12297 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12298 	if (offset != 0) {
12299 		/*
12300 		 * If this isn't the first piece, strip the header, and
12301 		 * add the offset to the end value.
12302 		 */
12303 		mp->b_rptr += hdr_length;
12304 		end += offset;
12305 	}
12306 
12307 	msg_len = MBLKSIZE(mp);
12308 	tail_mp = mp;
12309 	while (tail_mp->b_cont != NULL) {
12310 		tail_mp = tail_mp->b_cont;
12311 		msg_len += MBLKSIZE(tail_mp);
12312 	}
12313 
12314 	/* If the reassembly list for this ILL will get too big, prune it */
12315 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12316 	    ipst->ips_ip_reass_queue_bytes) {
12317 		ill_frag_prune(ill,
12318 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12319 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12320 		pruned = B_TRUE;
12321 	}
12322 
12323 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12324 	mutex_enter(&ipfb->ipfb_lock);
12325 
12326 	ipfp = &ipfb->ipfb_ipf;
12327 	/* Try to find an existing fragment queue for this packet. */
12328 	for (;;) {
12329 		ipf = ipfp[0];
12330 		if (ipf != NULL) {
12331 			/*
12332 			 * It has to match on ident and src/dst address.
12333 			 */
12334 			if (ipf->ipf_ident == ident &&
12335 			    ipf->ipf_src == src &&
12336 			    ipf->ipf_dst == dst &&
12337 			    ipf->ipf_protocol == proto) {
12338 				/*
12339 				 * If we have received too many
12340 				 * duplicate fragments for this packet
12341 				 * free it.
12342 				 */
12343 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12344 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12345 					freemsg(mp);
12346 					mutex_exit(&ipfb->ipfb_lock);
12347 					return (B_FALSE);
12348 				}
12349 				/* Found it. */
12350 				break;
12351 			}
12352 			ipfp = &ipf->ipf_hash_next;
12353 			continue;
12354 		}
12355 
12356 		/*
12357 		 * If we pruned the list, do we want to store this new
12358 		 * fragment?. We apply an optimization here based on the
12359 		 * fact that most fragments will be received in order.
12360 		 * So if the offset of this incoming fragment is zero,
12361 		 * it is the first fragment of a new packet. We will
12362 		 * keep it.  Otherwise drop the fragment, as we have
12363 		 * probably pruned the packet already (since the
12364 		 * packet cannot be found).
12365 		 */
12366 		if (pruned && offset != 0) {
12367 			mutex_exit(&ipfb->ipfb_lock);
12368 			freemsg(mp);
12369 			return (B_FALSE);
12370 		}
12371 
12372 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12373 			/*
12374 			 * Too many fragmented packets in this hash
12375 			 * bucket. Free the oldest.
12376 			 */
12377 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12378 		}
12379 
12380 		/* New guy.  Allocate a frag message. */
12381 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12382 		if (mp1 == NULL) {
12383 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12384 			freemsg(mp);
12385 reass_done:
12386 			mutex_exit(&ipfb->ipfb_lock);
12387 			return (B_FALSE);
12388 		}
12389 
12390 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12391 		mp1->b_cont = mp;
12392 
12393 		/* Initialize the fragment header. */
12394 		ipf = (ipf_t *)mp1->b_rptr;
12395 		ipf->ipf_mp = mp1;
12396 		ipf->ipf_ptphn = ipfp;
12397 		ipfp[0] = ipf;
12398 		ipf->ipf_hash_next = NULL;
12399 		ipf->ipf_ident = ident;
12400 		ipf->ipf_protocol = proto;
12401 		ipf->ipf_src = src;
12402 		ipf->ipf_dst = dst;
12403 		ipf->ipf_nf_hdr_len = 0;
12404 		/* Record reassembly start time. */
12405 		ipf->ipf_timestamp = gethrestime_sec();
12406 		/* Record ipf generation and account for frag header */
12407 		ipf->ipf_gen = ill->ill_ipf_gen++;
12408 		ipf->ipf_count = MBLKSIZE(mp1);
12409 		ipf->ipf_last_frag_seen = B_FALSE;
12410 		ipf->ipf_ecn = ecn_info;
12411 		ipf->ipf_num_dups = 0;
12412 		ipfb->ipfb_frag_pkts++;
12413 		ipf->ipf_checksum = 0;
12414 		ipf->ipf_checksum_flags = 0;
12415 
12416 		/* Store checksum value in fragment header */
12417 		if (sum_flags != 0) {
12418 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12419 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12420 			ipf->ipf_checksum = sum_val;
12421 			ipf->ipf_checksum_flags = sum_flags;
12422 		}
12423 
12424 		/*
12425 		 * We handle reassembly two ways.  In the easy case,
12426 		 * where all the fragments show up in order, we do
12427 		 * minimal bookkeeping, and just clip new pieces on
12428 		 * the end.  If we ever see a hole, then we go off
12429 		 * to ip_reassemble which has to mark the pieces and
12430 		 * keep track of the number of holes, etc.  Obviously,
12431 		 * the point of having both mechanisms is so we can
12432 		 * handle the easy case as efficiently as possible.
12433 		 */
12434 		if (offset == 0) {
12435 			/* Easy case, in-order reassembly so far. */
12436 			ipf->ipf_count += msg_len;
12437 			ipf->ipf_tail_mp = tail_mp;
12438 			/*
12439 			 * Keep track of next expected offset in
12440 			 * ipf_end.
12441 			 */
12442 			ipf->ipf_end = end;
12443 			ipf->ipf_nf_hdr_len = hdr_length;
12444 		} else {
12445 			/* Hard case, hole at the beginning. */
12446 			ipf->ipf_tail_mp = NULL;
12447 			/*
12448 			 * ipf_end == 0 means that we have given up
12449 			 * on easy reassembly.
12450 			 */
12451 			ipf->ipf_end = 0;
12452 
12453 			/* Forget checksum offload from now on */
12454 			ipf->ipf_checksum_flags = 0;
12455 
12456 			/*
12457 			 * ipf_hole_cnt is set by ip_reassemble.
12458 			 * ipf_count is updated by ip_reassemble.
12459 			 * No need to check for return value here
12460 			 * as we don't expect reassembly to complete
12461 			 * or fail for the first fragment itself.
12462 			 */
12463 			(void) ip_reassemble(mp, ipf,
12464 			    (frag_offset_flags & IPH_OFFSET) << 3,
12465 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12466 		}
12467 		/* Update per ipfb and ill byte counts */
12468 		ipfb->ipfb_count += ipf->ipf_count;
12469 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12470 		atomic_add_32(&ill->ill_frag_count, ipf->ipf_count);
12471 		/* If the frag timer wasn't already going, start it. */
12472 		mutex_enter(&ill->ill_lock);
12473 		ill_frag_timer_start(ill);
12474 		mutex_exit(&ill->ill_lock);
12475 		goto reass_done;
12476 	}
12477 
12478 	/*
12479 	 * If the packet's flag has changed (it could be coming up
12480 	 * from an interface different than the previous, therefore
12481 	 * possibly different checksum capability), then forget about
12482 	 * any stored checksum states.  Otherwise add the value to
12483 	 * the existing one stored in the fragment header.
12484 	 */
12485 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12486 		sum_val += ipf->ipf_checksum;
12487 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12488 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12489 		ipf->ipf_checksum = sum_val;
12490 	} else if (ipf->ipf_checksum_flags != 0) {
12491 		/* Forget checksum offload from now on */
12492 		ipf->ipf_checksum_flags = 0;
12493 	}
12494 
12495 	/*
12496 	 * We have a new piece of a datagram which is already being
12497 	 * reassembled.  Update the ECN info if all IP fragments
12498 	 * are ECN capable.  If there is one which is not, clear
12499 	 * all the info.  If there is at least one which has CE
12500 	 * code point, IP needs to report that up to transport.
12501 	 */
12502 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12503 		if (ecn_info == IPH_ECN_CE)
12504 			ipf->ipf_ecn = IPH_ECN_CE;
12505 	} else {
12506 		ipf->ipf_ecn = IPH_ECN_NECT;
12507 	}
12508 	if (offset && ipf->ipf_end == offset) {
12509 		/* The new fragment fits at the end */
12510 		ipf->ipf_tail_mp->b_cont = mp;
12511 		/* Update the byte count */
12512 		ipf->ipf_count += msg_len;
12513 		/* Update per ipfb and ill byte counts */
12514 		ipfb->ipfb_count += msg_len;
12515 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12516 		atomic_add_32(&ill->ill_frag_count, msg_len);
12517 		if (frag_offset_flags & IPH_MF) {
12518 			/* More to come. */
12519 			ipf->ipf_end = end;
12520 			ipf->ipf_tail_mp = tail_mp;
12521 			goto reass_done;
12522 		}
12523 	} else {
12524 		/* Go do the hard cases. */
12525 		int ret;
12526 
12527 		if (offset == 0)
12528 			ipf->ipf_nf_hdr_len = hdr_length;
12529 
12530 		/* Save current byte count */
12531 		count = ipf->ipf_count;
12532 		ret = ip_reassemble(mp, ipf,
12533 		    (frag_offset_flags & IPH_OFFSET) << 3,
12534 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12535 		/* Count of bytes added and subtracted (freeb()ed) */
12536 		count = ipf->ipf_count - count;
12537 		if (count) {
12538 			/* Update per ipfb and ill byte counts */
12539 			ipfb->ipfb_count += count;
12540 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12541 			atomic_add_32(&ill->ill_frag_count, count);
12542 		}
12543 		if (ret == IP_REASS_PARTIAL) {
12544 			goto reass_done;
12545 		} else if (ret == IP_REASS_FAILED) {
12546 			/* Reassembly failed. Free up all resources */
12547 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12548 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12549 				IP_REASS_SET_START(t_mp, 0);
12550 				IP_REASS_SET_END(t_mp, 0);
12551 			}
12552 			freemsg(mp);
12553 			goto reass_done;
12554 		}
12555 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12556 	}
12557 	/*
12558 	 * We have completed reassembly.  Unhook the frag header from
12559 	 * the reassembly list.
12560 	 *
12561 	 * Before we free the frag header, record the ECN info
12562 	 * to report back to the transport.
12563 	 */
12564 	ecn_info = ipf->ipf_ecn;
12565 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12566 	ipfp = ipf->ipf_ptphn;
12567 
12568 	/* We need to supply these to caller */
12569 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12570 		sum_val = ipf->ipf_checksum;
12571 	else
12572 		sum_val = 0;
12573 
12574 	mp1 = ipf->ipf_mp;
12575 	count = ipf->ipf_count;
12576 	ipf = ipf->ipf_hash_next;
12577 	if (ipf != NULL)
12578 		ipf->ipf_ptphn = ipfp;
12579 	ipfp[0] = ipf;
12580 	atomic_add_32(&ill->ill_frag_count, -count);
12581 	ASSERT(ipfb->ipfb_count >= count);
12582 	ipfb->ipfb_count -= count;
12583 	ipfb->ipfb_frag_pkts--;
12584 	mutex_exit(&ipfb->ipfb_lock);
12585 	/* Ditch the frag header. */
12586 	mp = mp1->b_cont;
12587 
12588 	freeb(mp1);
12589 
12590 	/* Restore original IP length in header. */
12591 	packet_size = (uint32_t)msgdsize(mp);
12592 	if (packet_size > IP_MAXPACKET) {
12593 		freemsg(mp);
12594 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12595 		return (B_FALSE);
12596 	}
12597 
12598 	if (DB_REF(mp) > 1) {
12599 		mblk_t *mp2 = copymsg(mp);
12600 
12601 		freemsg(mp);
12602 		if (mp2 == NULL) {
12603 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12604 			return (B_FALSE);
12605 		}
12606 		mp = mp2;
12607 	}
12608 	ipha = (ipha_t *)mp->b_rptr;
12609 
12610 	ipha->ipha_length = htons((uint16_t)packet_size);
12611 	/* We're now complete, zip the frag state */
12612 	ipha->ipha_fragment_offset_and_flags = 0;
12613 	/* Record the ECN info. */
12614 	ipha->ipha_type_of_service &= 0xFC;
12615 	ipha->ipha_type_of_service |= ecn_info;
12616 	*mpp = mp;
12617 
12618 	/* Reassembly is successful; return checksum information if needed */
12619 	if (cksum_val != NULL)
12620 		*cksum_val = sum_val;
12621 	if (cksum_flags != NULL)
12622 		*cksum_flags = sum_flags;
12623 
12624 	return (B_TRUE);
12625 }
12626 
12627 /*
12628  * Perform ip header check sum update local options.
12629  * return B_TRUE if all is well, else return B_FALSE and release
12630  * the mp. caller is responsible for decrementing ire ref cnt.
12631  */
12632 static boolean_t
12633 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12634     ip_stack_t *ipst)
12635 {
12636 	mblk_t		*first_mp;
12637 	boolean_t	mctl_present;
12638 	uint16_t	sum;
12639 
12640 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12641 	/*
12642 	 * Don't do the checksum if it has gone through AH/ESP
12643 	 * processing.
12644 	 */
12645 	if (!mctl_present) {
12646 		sum = ip_csum_hdr(ipha);
12647 		if (sum != 0) {
12648 			if (ill != NULL) {
12649 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12650 			} else {
12651 				BUMP_MIB(&ipst->ips_ip_mib,
12652 				    ipIfStatsInCksumErrs);
12653 			}
12654 			freemsg(first_mp);
12655 			return (B_FALSE);
12656 		}
12657 	}
12658 
12659 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12660 		if (mctl_present)
12661 			freeb(first_mp);
12662 		return (B_FALSE);
12663 	}
12664 
12665 	return (B_TRUE);
12666 }
12667 
12668 /*
12669  * All udp packet are delivered to the local host via this routine.
12670  */
12671 void
12672 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12673     ill_t *recv_ill)
12674 {
12675 	uint32_t	sum;
12676 	uint32_t	u1;
12677 	boolean_t	mctl_present;
12678 	conn_t		*connp;
12679 	mblk_t		*first_mp;
12680 	uint16_t	*up;
12681 	ill_t		*ill = (ill_t *)q->q_ptr;
12682 	uint16_t	reass_hck_flags = 0;
12683 	ip_stack_t	*ipst;
12684 
12685 	ASSERT(recv_ill != NULL);
12686 	ipst = recv_ill->ill_ipst;
12687 
12688 #define	rptr    ((uchar_t *)ipha)
12689 
12690 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12691 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12692 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12693 	ASSERT(ill != NULL);
12694 
12695 	/*
12696 	 * FAST PATH for udp packets
12697 	 */
12698 
12699 	/* u1 is # words of IP options */
12700 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12701 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12702 
12703 	/* IP options present */
12704 	if (u1 != 0)
12705 		goto ipoptions;
12706 
12707 	/* Check the IP header checksum.  */
12708 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12709 		/* Clear the IP header h/w cksum flag */
12710 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12711 	} else if (!mctl_present) {
12712 		/*
12713 		 * Don't verify header checksum if this packet is coming
12714 		 * back from AH/ESP as we already did it.
12715 		 */
12716 #define	uph	((uint16_t *)ipha)
12717 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12718 		    uph[6] + uph[7] + uph[8] + uph[9];
12719 #undef	uph
12720 		/* finish doing IP checksum */
12721 		sum = (sum & 0xFFFF) + (sum >> 16);
12722 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12723 		if (sum != 0 && sum != 0xFFFF) {
12724 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12725 			freemsg(first_mp);
12726 			return;
12727 		}
12728 	}
12729 
12730 	/*
12731 	 * Count for SNMP of inbound packets for ire.
12732 	 * if mctl is present this might be a secure packet and
12733 	 * has already been counted for in ip_proto_input().
12734 	 */
12735 	if (!mctl_present) {
12736 		UPDATE_IB_PKT_COUNT(ire);
12737 		ire->ire_last_used_time = lbolt;
12738 	}
12739 
12740 	/* packet part of fragmented IP packet? */
12741 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12742 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12743 		goto fragmented;
12744 	}
12745 
12746 	/* u1 = IP header length (20 bytes) */
12747 	u1 = IP_SIMPLE_HDR_LENGTH;
12748 
12749 	/* packet does not contain complete IP & UDP headers */
12750 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12751 		goto udppullup;
12752 
12753 	/* up points to UDP header */
12754 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12755 #define	iphs    ((uint16_t *)ipha)
12756 
12757 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12758 	if (up[3] != 0) {
12759 		mblk_t *mp1 = mp->b_cont;
12760 		boolean_t cksum_err;
12761 		uint16_t hck_flags = 0;
12762 
12763 		/* Pseudo-header checksum */
12764 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12765 		    iphs[9] + up[2];
12766 
12767 		/*
12768 		 * Revert to software checksum calculation if the interface
12769 		 * isn't capable of checksum offload or if IPsec is present.
12770 		 */
12771 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12772 			hck_flags = DB_CKSUMFLAGS(mp);
12773 
12774 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12775 			IP_STAT(ipst, ip_in_sw_cksum);
12776 
12777 		IP_CKSUM_RECV(hck_flags, u1,
12778 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12779 		    (int32_t)((uchar_t *)up - rptr),
12780 		    mp, mp1, cksum_err);
12781 
12782 		if (cksum_err) {
12783 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12784 			if (hck_flags & HCK_FULLCKSUM)
12785 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12786 			else if (hck_flags & HCK_PARTIALCKSUM)
12787 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12788 			else
12789 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12790 
12791 			freemsg(first_mp);
12792 			return;
12793 		}
12794 	}
12795 
12796 	/* Non-fragmented broadcast or multicast packet? */
12797 	if (ire->ire_type == IRE_BROADCAST)
12798 		goto udpslowpath;
12799 
12800 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12801 	    ire->ire_zoneid, ipst)) != NULL) {
12802 		ASSERT(connp->conn_upq != NULL);
12803 		IP_STAT(ipst, ip_udp_fast_path);
12804 
12805 		if (CONN_UDP_FLOWCTLD(connp)) {
12806 			freemsg(mp);
12807 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12808 		} else {
12809 			if (!mctl_present) {
12810 				BUMP_MIB(ill->ill_ip_mib,
12811 				    ipIfStatsHCInDelivers);
12812 			}
12813 			/*
12814 			 * mp and first_mp can change.
12815 			 */
12816 			if (ip_udp_check(q, connp, recv_ill,
12817 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12818 				/* Send it upstream */
12819 				(connp->conn_recv)(connp, mp, NULL);
12820 			}
12821 		}
12822 		/*
12823 		 * freeb() cannot deal with null mblk being passed
12824 		 * in and first_mp can be set to null in the call
12825 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12826 		 */
12827 		if (mctl_present && first_mp != NULL) {
12828 			freeb(first_mp);
12829 		}
12830 		CONN_DEC_REF(connp);
12831 		return;
12832 	}
12833 
12834 	/*
12835 	 * if we got here we know the packet is not fragmented and
12836 	 * has no options. The classifier could not find a conn_t and
12837 	 * most likely its an icmp packet so send it through slow path.
12838 	 */
12839 
12840 	goto udpslowpath;
12841 
12842 ipoptions:
12843 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12844 		goto slow_done;
12845 	}
12846 
12847 	UPDATE_IB_PKT_COUNT(ire);
12848 	ire->ire_last_used_time = lbolt;
12849 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12850 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12851 fragmented:
12852 		/*
12853 		 * "sum" and "reass_hck_flags" are non-zero if the
12854 		 * reassembled packet has a valid hardware computed
12855 		 * checksum information associated with it.
12856 		 */
12857 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12858 			goto slow_done;
12859 		/*
12860 		 * Make sure that first_mp points back to mp as
12861 		 * the mp we came in with could have changed in
12862 		 * ip_rput_fragment().
12863 		 */
12864 		ASSERT(!mctl_present);
12865 		ipha = (ipha_t *)mp->b_rptr;
12866 		first_mp = mp;
12867 	}
12868 
12869 	/* Now we have a complete datagram, destined for this machine. */
12870 	u1 = IPH_HDR_LENGTH(ipha);
12871 	/* Pull up the UDP header, if necessary. */
12872 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12873 udppullup:
12874 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12875 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12876 			freemsg(first_mp);
12877 			goto slow_done;
12878 		}
12879 		ipha = (ipha_t *)mp->b_rptr;
12880 	}
12881 
12882 	/*
12883 	 * Validate the checksum for the reassembled packet; for the
12884 	 * pullup case we calculate the payload checksum in software.
12885 	 */
12886 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12887 	if (up[3] != 0) {
12888 		boolean_t cksum_err;
12889 
12890 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12891 			IP_STAT(ipst, ip_in_sw_cksum);
12892 
12893 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12894 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12895 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12896 		    iphs[9] + up[2], sum, cksum_err);
12897 
12898 		if (cksum_err) {
12899 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12900 
12901 			if (reass_hck_flags & HCK_FULLCKSUM)
12902 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12903 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12904 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12905 			else
12906 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12907 
12908 			freemsg(first_mp);
12909 			goto slow_done;
12910 		}
12911 	}
12912 udpslowpath:
12913 
12914 	/* Clear hardware checksum flag to be safe */
12915 	DB_CKSUMFLAGS(mp) = 0;
12916 
12917 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12918 	    (ire->ire_type == IRE_BROADCAST),
12919 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12920 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12921 
12922 slow_done:
12923 	IP_STAT(ipst, ip_udp_slow_path);
12924 	return;
12925 
12926 #undef  iphs
12927 #undef  rptr
12928 }
12929 
12930 /* ARGSUSED */
12931 static mblk_t *
12932 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12933     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12934     ill_rx_ring_t *ill_ring)
12935 {
12936 	conn_t		*connp;
12937 	uint32_t	sum;
12938 	uint32_t	u1;
12939 	uint16_t	*up;
12940 	int		offset;
12941 	ssize_t		len;
12942 	mblk_t		*mp1;
12943 	boolean_t	syn_present = B_FALSE;
12944 	tcph_t		*tcph;
12945 	uint_t		ip_hdr_len;
12946 	ill_t		*ill = (ill_t *)q->q_ptr;
12947 	zoneid_t	zoneid = ire->ire_zoneid;
12948 	boolean_t	cksum_err;
12949 	uint16_t	hck_flags = 0;
12950 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12951 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12952 
12953 #define	rptr	((uchar_t *)ipha)
12954 
12955 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12956 	ASSERT(ill != NULL);
12957 
12958 	/*
12959 	 * FAST PATH for tcp packets
12960 	 */
12961 
12962 	/* u1 is # words of IP options */
12963 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12964 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12965 
12966 	/* IP options present */
12967 	if (u1) {
12968 		goto ipoptions;
12969 	} else if (!mctl_present) {
12970 		/* Check the IP header checksum.  */
12971 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12972 			/* Clear the IP header h/w cksum flag */
12973 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12974 		} else if (!mctl_present) {
12975 			/*
12976 			 * Don't verify header checksum if this packet
12977 			 * is coming back from AH/ESP as we already did it.
12978 			 */
12979 #define	uph	((uint16_t *)ipha)
12980 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12981 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12982 #undef	uph
12983 			/* finish doing IP checksum */
12984 			sum = (sum & 0xFFFF) + (sum >> 16);
12985 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12986 			if (sum != 0 && sum != 0xFFFF) {
12987 				BUMP_MIB(ill->ill_ip_mib,
12988 				    ipIfStatsInCksumErrs);
12989 				goto error;
12990 			}
12991 		}
12992 	}
12993 
12994 	if (!mctl_present) {
12995 		UPDATE_IB_PKT_COUNT(ire);
12996 		ire->ire_last_used_time = lbolt;
12997 	}
12998 
12999 	/* packet part of fragmented IP packet? */
13000 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13001 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13002 		goto fragmented;
13003 	}
13004 
13005 	/* u1 = IP header length (20 bytes) */
13006 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13007 
13008 	/* does packet contain IP+TCP headers? */
13009 	len = mp->b_wptr - rptr;
13010 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13011 		IP_STAT(ipst, ip_tcppullup);
13012 		goto tcppullup;
13013 	}
13014 
13015 	/* TCP options present? */
13016 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13017 
13018 	/*
13019 	 * If options need to be pulled up, then goto tcpoptions.
13020 	 * otherwise we are still in the fast path
13021 	 */
13022 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13023 		IP_STAT(ipst, ip_tcpoptions);
13024 		goto tcpoptions;
13025 	}
13026 
13027 	/* multiple mblks of tcp data? */
13028 	if ((mp1 = mp->b_cont) != NULL) {
13029 		/* more then two? */
13030 		if (mp1->b_cont != NULL) {
13031 			IP_STAT(ipst, ip_multipkttcp);
13032 			goto multipkttcp;
13033 		}
13034 		len += mp1->b_wptr - mp1->b_rptr;
13035 	}
13036 
13037 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13038 
13039 	/* part of pseudo checksum */
13040 
13041 	/* TCP datagram length */
13042 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13043 
13044 #define	iphs    ((uint16_t *)ipha)
13045 
13046 #ifdef	_BIG_ENDIAN
13047 	u1 += IPPROTO_TCP;
13048 #else
13049 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13050 #endif
13051 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13052 
13053 	/*
13054 	 * Revert to software checksum calculation if the interface
13055 	 * isn't capable of checksum offload or if IPsec is present.
13056 	 */
13057 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13058 		hck_flags = DB_CKSUMFLAGS(mp);
13059 
13060 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13061 		IP_STAT(ipst, ip_in_sw_cksum);
13062 
13063 	IP_CKSUM_RECV(hck_flags, u1,
13064 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13065 	    (int32_t)((uchar_t *)up - rptr),
13066 	    mp, mp1, cksum_err);
13067 
13068 	if (cksum_err) {
13069 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13070 
13071 		if (hck_flags & HCK_FULLCKSUM)
13072 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13073 		else if (hck_flags & HCK_PARTIALCKSUM)
13074 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13075 		else
13076 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13077 
13078 		goto error;
13079 	}
13080 
13081 try_again:
13082 
13083 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13084 	    zoneid, ipst)) == NULL) {
13085 		/* Send the TH_RST */
13086 		goto no_conn;
13087 	}
13088 
13089 	/*
13090 	 * TCP FAST PATH for AF_INET socket.
13091 	 *
13092 	 * TCP fast path to avoid extra work. An AF_INET socket type
13093 	 * does not have facility to receive extra information via
13094 	 * ip_process or ip_add_info. Also, when the connection was
13095 	 * established, we made a check if this connection is impacted
13096 	 * by any global IPsec policy or per connection policy (a
13097 	 * policy that comes in effect later will not apply to this
13098 	 * connection). Since all this can be determined at the
13099 	 * connection establishment time, a quick check of flags
13100 	 * can avoid extra work.
13101 	 */
13102 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13103 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13104 		ASSERT(first_mp == mp);
13105 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13106 		SET_SQUEUE(mp, tcp_rput_data, connp);
13107 		return (mp);
13108 	}
13109 
13110 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13111 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13112 		if (IPCL_IS_TCP(connp)) {
13113 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13114 			DB_CKSUMSTART(mp) =
13115 			    (intptr_t)ip_squeue_get(ill_ring);
13116 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13117 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13118 				BUMP_MIB(ill->ill_ip_mib,
13119 				    ipIfStatsHCInDelivers);
13120 				SET_SQUEUE(mp, connp->conn_recv, connp);
13121 				return (mp);
13122 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13123 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13124 				BUMP_MIB(ill->ill_ip_mib,
13125 				    ipIfStatsHCInDelivers);
13126 				ip_squeue_enter_unbound++;
13127 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13128 				    connp);
13129 				return (mp);
13130 			}
13131 			syn_present = B_TRUE;
13132 		}
13133 
13134 	}
13135 
13136 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13137 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13138 
13139 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13140 		/* No need to send this packet to TCP */
13141 		if ((flags & TH_RST) || (flags & TH_URG)) {
13142 			CONN_DEC_REF(connp);
13143 			freemsg(first_mp);
13144 			return (NULL);
13145 		}
13146 		if (flags & TH_ACK) {
13147 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13148 			    ipst->ips_netstack->netstack_tcp, connp);
13149 			CONN_DEC_REF(connp);
13150 			return (NULL);
13151 		}
13152 
13153 		CONN_DEC_REF(connp);
13154 		freemsg(first_mp);
13155 		return (NULL);
13156 	}
13157 
13158 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13159 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13160 		    ipha, NULL, mctl_present);
13161 		if (first_mp == NULL) {
13162 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13163 			CONN_DEC_REF(connp);
13164 			return (NULL);
13165 		}
13166 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13167 			ASSERT(syn_present);
13168 			if (mctl_present) {
13169 				ASSERT(first_mp != mp);
13170 				first_mp->b_datap->db_struioflag |=
13171 				    STRUIO_POLICY;
13172 			} else {
13173 				ASSERT(first_mp == mp);
13174 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13175 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13176 			}
13177 		} else {
13178 			/*
13179 			 * Discard first_mp early since we're dealing with a
13180 			 * fully-connected conn_t and tcp doesn't do policy in
13181 			 * this case.
13182 			 */
13183 			if (mctl_present) {
13184 				freeb(first_mp);
13185 				mctl_present = B_FALSE;
13186 			}
13187 			first_mp = mp;
13188 		}
13189 	}
13190 
13191 	/* Initiate IPPF processing for fastpath */
13192 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13193 		uint32_t	ill_index;
13194 
13195 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13196 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13197 		if (mp == NULL) {
13198 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13199 			    "deferred/dropped during IPPF processing\n"));
13200 			CONN_DEC_REF(connp);
13201 			if (mctl_present)
13202 				freeb(first_mp);
13203 			return (NULL);
13204 		} else if (mctl_present) {
13205 			/*
13206 			 * ip_process might return a new mp.
13207 			 */
13208 			ASSERT(first_mp != mp);
13209 			first_mp->b_cont = mp;
13210 		} else {
13211 			first_mp = mp;
13212 		}
13213 
13214 	}
13215 
13216 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13217 		/*
13218 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13219 		 * make sure IPF_RECVIF is passed to ip_add_info.
13220 		 */
13221 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13222 		    IPCL_ZONEID(connp), ipst);
13223 		if (mp == NULL) {
13224 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13225 			CONN_DEC_REF(connp);
13226 			if (mctl_present)
13227 				freeb(first_mp);
13228 			return (NULL);
13229 		} else if (mctl_present) {
13230 			/*
13231 			 * ip_add_info might return a new mp.
13232 			 */
13233 			ASSERT(first_mp != mp);
13234 			first_mp->b_cont = mp;
13235 		} else {
13236 			first_mp = mp;
13237 		}
13238 	}
13239 
13240 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13241 	if (IPCL_IS_TCP(connp)) {
13242 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13243 		return (first_mp);
13244 	} else {
13245 		/* SOCK_RAW, IPPROTO_TCP case */
13246 		(connp->conn_recv)(connp, first_mp, NULL);
13247 		CONN_DEC_REF(connp);
13248 		return (NULL);
13249 	}
13250 
13251 no_conn:
13252 	/* Initiate IPPf processing, if needed. */
13253 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13254 		uint32_t ill_index;
13255 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13256 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13257 		if (first_mp == NULL) {
13258 			return (NULL);
13259 		}
13260 	}
13261 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13262 
13263 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13264 	    ipst->ips_netstack->netstack_tcp, NULL);
13265 	return (NULL);
13266 ipoptions:
13267 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13268 		goto slow_done;
13269 	}
13270 
13271 	UPDATE_IB_PKT_COUNT(ire);
13272 	ire->ire_last_used_time = lbolt;
13273 
13274 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13275 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13276 fragmented:
13277 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13278 			if (mctl_present)
13279 				freeb(first_mp);
13280 			goto slow_done;
13281 		}
13282 		/*
13283 		 * Make sure that first_mp points back to mp as
13284 		 * the mp we came in with could have changed in
13285 		 * ip_rput_fragment().
13286 		 */
13287 		ASSERT(!mctl_present);
13288 		ipha = (ipha_t *)mp->b_rptr;
13289 		first_mp = mp;
13290 	}
13291 
13292 	/* Now we have a complete datagram, destined for this machine. */
13293 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13294 
13295 	len = mp->b_wptr - mp->b_rptr;
13296 	/* Pull up a minimal TCP header, if necessary. */
13297 	if (len < (u1 + 20)) {
13298 tcppullup:
13299 		if (!pullupmsg(mp, u1 + 20)) {
13300 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13301 			goto error;
13302 		}
13303 		ipha = (ipha_t *)mp->b_rptr;
13304 		len = mp->b_wptr - mp->b_rptr;
13305 	}
13306 
13307 	/*
13308 	 * Extract the offset field from the TCP header.  As usual, we
13309 	 * try to help the compiler more than the reader.
13310 	 */
13311 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13312 	if (offset != 5) {
13313 tcpoptions:
13314 		if (offset < 5) {
13315 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13316 			goto error;
13317 		}
13318 		/*
13319 		 * There must be TCP options.
13320 		 * Make sure we can grab them.
13321 		 */
13322 		offset <<= 2;
13323 		offset += u1;
13324 		if (len < offset) {
13325 			if (!pullupmsg(mp, offset)) {
13326 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13327 				goto error;
13328 			}
13329 			ipha = (ipha_t *)mp->b_rptr;
13330 			len = mp->b_wptr - rptr;
13331 		}
13332 	}
13333 
13334 	/* Get the total packet length in len, including headers. */
13335 	if (mp->b_cont) {
13336 multipkttcp:
13337 		len = msgdsize(mp);
13338 	}
13339 
13340 	/*
13341 	 * Check the TCP checksum by pulling together the pseudo-
13342 	 * header checksum, and passing it to ip_csum to be added in
13343 	 * with the TCP datagram.
13344 	 *
13345 	 * Since we are not using the hwcksum if available we must
13346 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13347 	 * If either of these fails along the way the mblk is freed.
13348 	 * If this logic ever changes and mblk is reused to say send
13349 	 * ICMP's back, then this flag may need to be cleared in
13350 	 * other places as well.
13351 	 */
13352 	DB_CKSUMFLAGS(mp) = 0;
13353 
13354 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13355 
13356 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13357 #ifdef	_BIG_ENDIAN
13358 	u1 += IPPROTO_TCP;
13359 #else
13360 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13361 #endif
13362 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13363 	/*
13364 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13365 	 */
13366 	IP_STAT(ipst, ip_in_sw_cksum);
13367 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13368 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13369 		goto error;
13370 	}
13371 
13372 	IP_STAT(ipst, ip_tcp_slow_path);
13373 	goto try_again;
13374 #undef  iphs
13375 #undef  rptr
13376 
13377 error:
13378 	freemsg(first_mp);
13379 slow_done:
13380 	return (NULL);
13381 }
13382 
13383 /* ARGSUSED */
13384 static void
13385 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13386     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13387 {
13388 	conn_t		*connp;
13389 	uint32_t	sum;
13390 	uint32_t	u1;
13391 	ssize_t		len;
13392 	sctp_hdr_t	*sctph;
13393 	zoneid_t	zoneid = ire->ire_zoneid;
13394 	uint32_t	pktsum;
13395 	uint32_t	calcsum;
13396 	uint32_t	ports;
13397 	in6_addr_t	map_src, map_dst;
13398 	ill_t		*ill = (ill_t *)q->q_ptr;
13399 	ip_stack_t	*ipst;
13400 	sctp_stack_t	*sctps;
13401 	boolean_t	sctp_csum_err = B_FALSE;
13402 
13403 	ASSERT(recv_ill != NULL);
13404 	ipst = recv_ill->ill_ipst;
13405 	sctps = ipst->ips_netstack->netstack_sctp;
13406 
13407 #define	rptr	((uchar_t *)ipha)
13408 
13409 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13410 	ASSERT(ill != NULL);
13411 
13412 	/* u1 is # words of IP options */
13413 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13414 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13415 
13416 	/* IP options present */
13417 	if (u1 > 0) {
13418 		goto ipoptions;
13419 	} else {
13420 		/* Check the IP header checksum.  */
13421 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13422 		    !mctl_present) {
13423 #define	uph	((uint16_t *)ipha)
13424 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13425 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13426 #undef	uph
13427 			/* finish doing IP checksum */
13428 			sum = (sum & 0xFFFF) + (sum >> 16);
13429 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13430 			/*
13431 			 * Don't verify header checksum if this packet
13432 			 * is coming back from AH/ESP as we already did it.
13433 			 */
13434 			if (sum != 0 && sum != 0xFFFF) {
13435 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13436 				goto error;
13437 			}
13438 		}
13439 		/*
13440 		 * Since there is no SCTP h/w cksum support yet, just
13441 		 * clear the flag.
13442 		 */
13443 		DB_CKSUMFLAGS(mp) = 0;
13444 	}
13445 
13446 	/*
13447 	 * Don't verify header checksum if this packet is coming
13448 	 * back from AH/ESP as we already did it.
13449 	 */
13450 	if (!mctl_present) {
13451 		UPDATE_IB_PKT_COUNT(ire);
13452 		ire->ire_last_used_time = lbolt;
13453 	}
13454 
13455 	/* packet part of fragmented IP packet? */
13456 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13457 	if (u1 & (IPH_MF | IPH_OFFSET))
13458 		goto fragmented;
13459 
13460 	/* u1 = IP header length (20 bytes) */
13461 	u1 = IP_SIMPLE_HDR_LENGTH;
13462 
13463 find_sctp_client:
13464 	/* Pullup if we don't have the sctp common header. */
13465 	len = MBLKL(mp);
13466 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13467 		if (mp->b_cont == NULL ||
13468 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13469 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13470 			goto error;
13471 		}
13472 		ipha = (ipha_t *)mp->b_rptr;
13473 		len = MBLKL(mp);
13474 	}
13475 
13476 	sctph = (sctp_hdr_t *)(rptr + u1);
13477 #ifdef	DEBUG
13478 	if (!skip_sctp_cksum) {
13479 #endif
13480 		pktsum = sctph->sh_chksum;
13481 		sctph->sh_chksum = 0;
13482 		calcsum = sctp_cksum(mp, u1);
13483 		sctph->sh_chksum = pktsum;
13484 		if (calcsum != pktsum)
13485 			sctp_csum_err = B_TRUE;
13486 #ifdef	DEBUG	/* skip_sctp_cksum */
13487 	}
13488 #endif
13489 	/* get the ports */
13490 	ports = *(uint32_t *)&sctph->sh_sport;
13491 
13492 	IRE_REFRELE(ire);
13493 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13494 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13495 	if (sctp_csum_err) {
13496 		/*
13497 		 * No potential sctp checksum errors go to the Sun
13498 		 * sctp stack however they might be Adler-32 summed
13499 		 * packets a userland stack bound to a raw IP socket
13500 		 * could reasonably use. Note though that Adler-32 is
13501 		 * a long deprecated algorithm and customer sctp
13502 		 * networks should eventually migrate to CRC-32 at
13503 		 * which time this facility should be removed.
13504 		 */
13505 		flags |= IP_FF_SCTP_CSUM_ERR;
13506 		goto no_conn;
13507 	}
13508 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13509 	    sctps)) == NULL) {
13510 		/* Check for raw socket or OOTB handling */
13511 		goto no_conn;
13512 	}
13513 
13514 	/* Found a client; up it goes */
13515 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13516 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13517 	return;
13518 
13519 no_conn:
13520 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13521 	    ports, mctl_present, flags, B_TRUE, zoneid);
13522 	return;
13523 
13524 ipoptions:
13525 	DB_CKSUMFLAGS(mp) = 0;
13526 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13527 		goto slow_done;
13528 
13529 	UPDATE_IB_PKT_COUNT(ire);
13530 	ire->ire_last_used_time = lbolt;
13531 
13532 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13533 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13534 fragmented:
13535 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13536 			goto slow_done;
13537 		/*
13538 		 * Make sure that first_mp points back to mp as
13539 		 * the mp we came in with could have changed in
13540 		 * ip_rput_fragment().
13541 		 */
13542 		ASSERT(!mctl_present);
13543 		ipha = (ipha_t *)mp->b_rptr;
13544 		first_mp = mp;
13545 	}
13546 
13547 	/* Now we have a complete datagram, destined for this machine. */
13548 	u1 = IPH_HDR_LENGTH(ipha);
13549 	goto find_sctp_client;
13550 #undef  iphs
13551 #undef  rptr
13552 
13553 error:
13554 	freemsg(first_mp);
13555 slow_done:
13556 	IRE_REFRELE(ire);
13557 }
13558 
13559 #define	VER_BITS	0xF0
13560 #define	VERSION_6	0x60
13561 
13562 static boolean_t
13563 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13564     ipaddr_t *dstp, ip_stack_t *ipst)
13565 {
13566 	uint_t	opt_len;
13567 	ipha_t *ipha;
13568 	ssize_t len;
13569 	uint_t	pkt_len;
13570 
13571 	ASSERT(ill != NULL);
13572 	IP_STAT(ipst, ip_ipoptions);
13573 	ipha = *iphapp;
13574 
13575 #define	rptr    ((uchar_t *)ipha)
13576 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13577 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13578 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13579 		freemsg(mp);
13580 		return (B_FALSE);
13581 	}
13582 
13583 	/* multiple mblk or too short */
13584 	pkt_len = ntohs(ipha->ipha_length);
13585 
13586 	/* Get the number of words of IP options in the IP header. */
13587 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13588 	if (opt_len) {
13589 		/* IP Options present!  Validate and process. */
13590 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13591 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13592 			goto done;
13593 		}
13594 		/*
13595 		 * Recompute complete header length and make sure we
13596 		 * have access to all of it.
13597 		 */
13598 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13599 		if (len > (mp->b_wptr - rptr)) {
13600 			if (len > pkt_len) {
13601 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13602 				goto done;
13603 			}
13604 			if (!pullupmsg(mp, len)) {
13605 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13606 				goto done;
13607 			}
13608 			ipha = (ipha_t *)mp->b_rptr;
13609 		}
13610 		/*
13611 		 * Go off to ip_rput_options which returns the next hop
13612 		 * destination address, which may have been affected
13613 		 * by source routing.
13614 		 */
13615 		IP_STAT(ipst, ip_opt);
13616 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13617 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13618 			return (B_FALSE);
13619 		}
13620 	}
13621 	*iphapp = ipha;
13622 	return (B_TRUE);
13623 done:
13624 	/* clear b_prev - used by ip_mroute_decap */
13625 	mp->b_prev = NULL;
13626 	freemsg(mp);
13627 	return (B_FALSE);
13628 #undef  rptr
13629 }
13630 
13631 /*
13632  * Deal with the fact that there is no ire for the destination.
13633  */
13634 static ire_t *
13635 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13636 {
13637 	ipha_t	*ipha;
13638 	ill_t	*ill;
13639 	ire_t	*ire;
13640 	ip_stack_t *ipst;
13641 	enum	ire_forward_action ret_action;
13642 
13643 	ipha = (ipha_t *)mp->b_rptr;
13644 	ill = (ill_t *)q->q_ptr;
13645 
13646 	ASSERT(ill != NULL);
13647 	ipst = ill->ill_ipst;
13648 
13649 	/*
13650 	 * No IRE for this destination, so it can't be for us.
13651 	 * Unless we are forwarding, drop the packet.
13652 	 * We have to let source routed packets through
13653 	 * since we don't yet know if they are 'ping -l'
13654 	 * packets i.e. if they will go out over the
13655 	 * same interface as they came in on.
13656 	 */
13657 	if (ll_multicast) {
13658 		freemsg(mp);
13659 		return (NULL);
13660 	}
13661 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13662 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13663 		freemsg(mp);
13664 		return (NULL);
13665 	}
13666 
13667 	/*
13668 	 * Mark this packet as having originated externally.
13669 	 *
13670 	 * For non-forwarding code path, ire_send later double
13671 	 * checks this interface to see if it is still exists
13672 	 * post-ARP resolution.
13673 	 *
13674 	 * Also, IPQOS uses this to differentiate between
13675 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13676 	 * QOS packet processing in ip_wput_attach_llhdr().
13677 	 * The QoS module can mark the b_band for a fastpath message
13678 	 * or the dl_priority field in a unitdata_req header for
13679 	 * CoS marking. This info can only be found in
13680 	 * ip_wput_attach_llhdr().
13681 	 */
13682 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13683 	/*
13684 	 * Clear the indication that this may have a hardware checksum
13685 	 * as we are not using it
13686 	 */
13687 	DB_CKSUMFLAGS(mp) = 0;
13688 
13689 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13690 	    MBLK_GETLABEL(mp), ipst);
13691 
13692 	if (ire == NULL && ret_action == Forward_check_multirt) {
13693 		/* Let ip_newroute handle CGTP  */
13694 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13695 		return (NULL);
13696 	}
13697 
13698 	if (ire != NULL)
13699 		return (ire);
13700 
13701 	mp->b_prev = mp->b_next = 0;
13702 
13703 	if (ret_action == Forward_blackhole) {
13704 		freemsg(mp);
13705 		return (NULL);
13706 	}
13707 	/* send icmp unreachable */
13708 	q = WR(q);
13709 	/* Sent by forwarding path, and router is global zone */
13710 	if (ip_source_routed(ipha, ipst)) {
13711 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13712 		    GLOBAL_ZONEID, ipst);
13713 	} else {
13714 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13715 		    ipst);
13716 	}
13717 
13718 	return (NULL);
13719 
13720 }
13721 
13722 /*
13723  * check ip header length and align it.
13724  */
13725 static boolean_t
13726 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13727 {
13728 	ssize_t len;
13729 	ill_t *ill;
13730 	ipha_t	*ipha;
13731 
13732 	len = MBLKL(mp);
13733 
13734 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13735 		ill = (ill_t *)q->q_ptr;
13736 
13737 		if (!OK_32PTR(mp->b_rptr))
13738 			IP_STAT(ipst, ip_notaligned1);
13739 		else
13740 			IP_STAT(ipst, ip_notaligned2);
13741 		/* Guard against bogus device drivers */
13742 		if (len < 0) {
13743 			/* clear b_prev - used by ip_mroute_decap */
13744 			mp->b_prev = NULL;
13745 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13746 			freemsg(mp);
13747 			return (B_FALSE);
13748 		}
13749 
13750 		if (ip_rput_pullups++ == 0) {
13751 			ipha = (ipha_t *)mp->b_rptr;
13752 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13753 			    "ip_check_and_align_header: %s forced us to "
13754 			    " pullup pkt, hdr len %ld, hdr addr %p",
13755 			    ill->ill_name, len, ipha);
13756 		}
13757 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13758 			/* clear b_prev - used by ip_mroute_decap */
13759 			mp->b_prev = NULL;
13760 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13761 			freemsg(mp);
13762 			return (B_FALSE);
13763 		}
13764 	}
13765 	return (B_TRUE);
13766 }
13767 
13768 ire_t *
13769 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13770 {
13771 	ire_t		*new_ire;
13772 	ill_t		*ire_ill;
13773 	uint_t		ifindex;
13774 	ip_stack_t	*ipst = ill->ill_ipst;
13775 	boolean_t	strict_check = B_FALSE;
13776 
13777 	/*
13778 	 * This packet came in on an interface other than the one associated
13779 	 * with the first ire we found for the destination address. We do
13780 	 * another ire lookup here, using the ingress ill, to see if the
13781 	 * interface is in an interface group.
13782 	 * As long as the ills belong to the same group, we don't consider
13783 	 * them to be arriving on the wrong interface. Thus, if the switch
13784 	 * is doing inbound load spreading, we won't drop packets when the
13785 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13786 	 * for 'usesrc groups' where the destination address may belong to
13787 	 * another interface to allow multipathing to happen.
13788 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13789 	 * where the local address may not be unique. In this case we were
13790 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13791 	 * actually returned. The new lookup, which is more specific, should
13792 	 * only find the IRE_LOCAL associated with the ingress ill if one
13793 	 * exists.
13794 	 */
13795 
13796 	if (ire->ire_ipversion == IPV4_VERSION) {
13797 		if (ipst->ips_ip_strict_dst_multihoming)
13798 			strict_check = B_TRUE;
13799 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13800 		    ill->ill_ipif, ALL_ZONES, NULL,
13801 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13802 	} else {
13803 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13804 		if (ipst->ips_ipv6_strict_dst_multihoming)
13805 			strict_check = B_TRUE;
13806 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13807 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13808 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13809 	}
13810 	/*
13811 	 * If the same ire that was returned in ip_input() is found then this
13812 	 * is an indication that interface groups are in use. The packet
13813 	 * arrived on a different ill in the group than the one associated with
13814 	 * the destination address.  If a different ire was found then the same
13815 	 * IP address must be hosted on multiple ills. This is possible with
13816 	 * unnumbered point2point interfaces. We switch to use this new ire in
13817 	 * order to have accurate interface statistics.
13818 	 */
13819 	if (new_ire != NULL) {
13820 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13821 			ire_refrele(ire);
13822 			ire = new_ire;
13823 		} else {
13824 			ire_refrele(new_ire);
13825 		}
13826 		return (ire);
13827 	} else if ((ire->ire_rfq == NULL) &&
13828 	    (ire->ire_ipversion == IPV4_VERSION)) {
13829 		/*
13830 		 * The best match could have been the original ire which
13831 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13832 		 * the strict multihoming checks are irrelevant as we consider
13833 		 * local addresses hosted on lo0 to be interface agnostic. We
13834 		 * only expect a null ire_rfq on IREs which are associated with
13835 		 * lo0 hence we can return now.
13836 		 */
13837 		return (ire);
13838 	}
13839 
13840 	/*
13841 	 * Chase pointers once and store locally.
13842 	 */
13843 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13844 	    (ill_t *)(ire->ire_rfq->q_ptr);
13845 	ifindex = ill->ill_usesrc_ifindex;
13846 
13847 	/*
13848 	 * Check if it's a legal address on the 'usesrc' interface.
13849 	 */
13850 	if ((ifindex != 0) && (ire_ill != NULL) &&
13851 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13852 		return (ire);
13853 	}
13854 
13855 	/*
13856 	 * If the ip*_strict_dst_multihoming switch is on then we can
13857 	 * only accept this packet if the interface is marked as routing.
13858 	 */
13859 	if (!(strict_check))
13860 		return (ire);
13861 
13862 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13863 	    ILLF_ROUTER) != 0) {
13864 		return (ire);
13865 	}
13866 
13867 	ire_refrele(ire);
13868 	return (NULL);
13869 }
13870 
13871 ire_t *
13872 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13873 {
13874 	ipha_t	*ipha;
13875 	ire_t	*src_ire;
13876 	ill_t	*stq_ill;
13877 	uint_t	hlen;
13878 	uint_t	pkt_len;
13879 	uint32_t sum;
13880 	queue_t	*dev_q;
13881 	ip_stack_t *ipst = ill->ill_ipst;
13882 	mblk_t *fpmp;
13883 	enum	ire_forward_action ret_action;
13884 
13885 	ipha = (ipha_t *)mp->b_rptr;
13886 
13887 	if (ire != NULL &&
13888 	    ire->ire_zoneid != GLOBAL_ZONEID &&
13889 	    ire->ire_zoneid != ALL_ZONES) {
13890 		/*
13891 		 * Should only use IREs that are visible to the global
13892 		 * zone for forwarding.
13893 		 */
13894 		ire_refrele(ire);
13895 		ire = ire_cache_lookup(dst, GLOBAL_ZONEID, NULL, ipst);
13896 	}
13897 
13898 	/*
13899 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13900 	 * The loopback address check for both src and dst has already
13901 	 * been checked in ip_input
13902 	 */
13903 
13904 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13905 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13906 		goto drop;
13907 	}
13908 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13909 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13910 
13911 	if (src_ire != NULL) {
13912 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13913 		ire_refrele(src_ire);
13914 		goto drop;
13915 	}
13916 
13917 	/* No ire cache of nexthop. So first create one  */
13918 	if (ire == NULL) {
13919 
13920 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13921 		    NULL, ipst);
13922 		/*
13923 		 * We only come to ip_fast_forward if ip_cgtp_filter
13924 		 * is not set. So ire_forward() should not return with
13925 		 * Forward_check_multirt as the next action.
13926 		 */
13927 		ASSERT(ret_action != Forward_check_multirt);
13928 		if (ire == NULL) {
13929 			/* An attempt was made to forward the packet */
13930 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13931 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13932 			mp->b_prev = mp->b_next = 0;
13933 			/* send icmp unreachable */
13934 			/* Sent by forwarding path, and router is global zone */
13935 			if (ret_action == Forward_ret_icmp_err) {
13936 				if (ip_source_routed(ipha, ipst)) {
13937 					icmp_unreachable(ill->ill_wq, mp,
13938 					    ICMP_SOURCE_ROUTE_FAILED,
13939 					    GLOBAL_ZONEID, ipst);
13940 				} else {
13941 					icmp_unreachable(ill->ill_wq, mp,
13942 					    ICMP_HOST_UNREACHABLE,
13943 					    GLOBAL_ZONEID, ipst);
13944 				}
13945 			} else {
13946 				freemsg(mp);
13947 			}
13948 			return (NULL);
13949 		}
13950 	}
13951 
13952 	/*
13953 	 * Forwarding fastpath exception case:
13954 	 * If either of the follwoing case is true, we take
13955 	 * the slowpath
13956 	 *	o forwarding is not enabled
13957 	 *	o incoming and outgoing interface are the same, or the same
13958 	 *	  IPMP group
13959 	 *	o corresponding ire is in incomplete state
13960 	 *	o packet needs fragmentation
13961 	 *	o ARP cache is not resolved
13962 	 *
13963 	 * The codeflow from here on is thus:
13964 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13965 	 */
13966 	pkt_len = ntohs(ipha->ipha_length);
13967 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13968 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13969 	    !(ill->ill_flags & ILLF_ROUTER) ||
13970 	    (ill == stq_ill) ||
13971 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13972 	    (ire->ire_nce == NULL) ||
13973 	    (pkt_len > ire->ire_max_frag) ||
13974 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13975 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13976 	    ipha->ipha_ttl <= 1) {
13977 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13978 		    ipha, ill, B_FALSE);
13979 		return (ire);
13980 	}
13981 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13982 
13983 	DTRACE_PROBE4(ip4__forwarding__start,
13984 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13985 
13986 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13987 	    ipst->ips_ipv4firewall_forwarding,
13988 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13989 
13990 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13991 
13992 	if (mp == NULL)
13993 		goto drop;
13994 
13995 	mp->b_datap->db_struioun.cksum.flags = 0;
13996 	/* Adjust the checksum to reflect the ttl decrement. */
13997 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13998 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13999 	ipha->ipha_ttl--;
14000 
14001 	/*
14002 	 * Write the link layer header.  We can do this safely here,
14003 	 * because we have already tested to make sure that the IP
14004 	 * policy is not set, and that we have a fast path destination
14005 	 * header.
14006 	 */
14007 	mp->b_rptr -= hlen;
14008 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14009 
14010 	UPDATE_IB_PKT_COUNT(ire);
14011 	ire->ire_last_used_time = lbolt;
14012 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14013 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14014 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14015 
14016 	dev_q = ire->ire_stq->q_next;
14017 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14018 	    !canputnext(ire->ire_stq)) {
14019 		goto indiscard;
14020 	}
14021 	if (ILL_DLS_CAPABLE(stq_ill)) {
14022 		/*
14023 		 * Send the packet directly to DLD, where it
14024 		 * may be queued depending on the availability
14025 		 * of transmit resources at the media layer.
14026 		 */
14027 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14028 	} else {
14029 		DTRACE_PROBE4(ip4__physical__out__start,
14030 		    ill_t *, NULL, ill_t *, stq_ill,
14031 		    ipha_t *, ipha, mblk_t *, mp);
14032 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14033 		    ipst->ips_ipv4firewall_physical_out,
14034 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14035 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14036 		if (mp == NULL)
14037 			goto drop;
14038 
14039 		DTRACE_IP7(send, mblk_t *, mp, conn_t *, NULL, void_ip_t *,
14040 		    ipha, __dtrace_ipsr_ill_t *, stq_ill, ipha_t *, ipha,
14041 		    ip6_t *, NULL, int, 0);
14042 
14043 		putnext(ire->ire_stq, mp);
14044 	}
14045 	return (ire);
14046 
14047 indiscard:
14048 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14049 drop:
14050 	if (mp != NULL)
14051 		freemsg(mp);
14052 	return (ire);
14053 
14054 }
14055 
14056 /*
14057  * This function is called in the forwarding slowpath, when
14058  * either the ire lacks the link-layer address, or the packet needs
14059  * further processing(eg. fragmentation), before transmission.
14060  */
14061 
14062 static void
14063 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14064     ill_t *ill, boolean_t ll_multicast)
14065 {
14066 	ill_group_t	*ill_group;
14067 	ill_group_t	*ire_group;
14068 	queue_t		*dev_q;
14069 	ire_t		*src_ire;
14070 	ip_stack_t	*ipst = ill->ill_ipst;
14071 
14072 	ASSERT(ire->ire_stq != NULL);
14073 
14074 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14075 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14076 
14077 	if (ll_multicast != 0) {
14078 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14079 		goto drop_pkt;
14080 	}
14081 
14082 	/*
14083 	 * check if ipha_src is a broadcast address. Note that this
14084 	 * check is redundant when we get here from ip_fast_forward()
14085 	 * which has already done this check. However, since we can
14086 	 * also get here from ip_rput_process_broadcast() or, for
14087 	 * for the slow path through ip_fast_forward(), we perform
14088 	 * the check again for code-reusability
14089 	 */
14090 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14091 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14092 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14093 		if (src_ire != NULL)
14094 			ire_refrele(src_ire);
14095 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14096 		ip2dbg(("ip_rput_process_forward: Received packet with"
14097 		    " bad src/dst address on %s\n", ill->ill_name));
14098 		goto drop_pkt;
14099 	}
14100 
14101 	ill_group = ill->ill_group;
14102 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14103 	/*
14104 	 * Check if we want to forward this one at this time.
14105 	 * We allow source routed packets on a host provided that
14106 	 * they go out the same interface or same interface group
14107 	 * as they came in on.
14108 	 *
14109 	 * XXX To be quicker, we may wish to not chase pointers to
14110 	 * get the ILLF_ROUTER flag and instead store the
14111 	 * forwarding policy in the ire.  An unfortunate
14112 	 * side-effect of that would be requiring an ire flush
14113 	 * whenever the ILLF_ROUTER flag changes.
14114 	 */
14115 	if (((ill->ill_flags &
14116 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14117 	    ILLF_ROUTER) == 0) &&
14118 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14119 	    (ill_group != NULL && ill_group == ire_group)))) {
14120 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14121 		if (ip_source_routed(ipha, ipst)) {
14122 			q = WR(q);
14123 			/*
14124 			 * Clear the indication that this may have
14125 			 * hardware checksum as we are not using it.
14126 			 */
14127 			DB_CKSUMFLAGS(mp) = 0;
14128 			/* Sent by forwarding path, and router is global zone */
14129 			icmp_unreachable(q, mp,
14130 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14131 			return;
14132 		}
14133 		goto drop_pkt;
14134 	}
14135 
14136 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14137 
14138 	/* Packet is being forwarded. Turning off hwcksum flag. */
14139 	DB_CKSUMFLAGS(mp) = 0;
14140 	if (ipst->ips_ip_g_send_redirects) {
14141 		/*
14142 		 * Check whether the incoming interface and outgoing
14143 		 * interface is part of the same group. If so,
14144 		 * send redirects.
14145 		 *
14146 		 * Check the source address to see if it originated
14147 		 * on the same logical subnet it is going back out on.
14148 		 * If so, we should be able to send it a redirect.
14149 		 * Avoid sending a redirect if the destination
14150 		 * is directly connected (i.e., ipha_dst is the same
14151 		 * as ire_gateway_addr or the ire_addr of the
14152 		 * nexthop IRE_CACHE ), or if the packet was source
14153 		 * routed out this interface.
14154 		 */
14155 		ipaddr_t src, nhop;
14156 		mblk_t	*mp1;
14157 		ire_t	*nhop_ire = NULL;
14158 
14159 		/*
14160 		 * Check whether ire_rfq and q are from the same ill
14161 		 * or if they are not same, they at least belong
14162 		 * to the same group. If so, send redirects.
14163 		 */
14164 		if ((ire->ire_rfq == q ||
14165 		    (ill_group != NULL && ill_group == ire_group)) &&
14166 		    !ip_source_routed(ipha, ipst)) {
14167 
14168 			nhop = (ire->ire_gateway_addr != 0 ?
14169 			    ire->ire_gateway_addr : ire->ire_addr);
14170 
14171 			if (ipha->ipha_dst == nhop) {
14172 				/*
14173 				 * We avoid sending a redirect if the
14174 				 * destination is directly connected
14175 				 * because it is possible that multiple
14176 				 * IP subnets may have been configured on
14177 				 * the link, and the source may not
14178 				 * be on the same subnet as ip destination,
14179 				 * even though they are on the same
14180 				 * physical link.
14181 				 */
14182 				goto sendit;
14183 			}
14184 
14185 			src = ipha->ipha_src;
14186 
14187 			/*
14188 			 * We look up the interface ire for the nexthop,
14189 			 * to see if ipha_src is in the same subnet
14190 			 * as the nexthop.
14191 			 *
14192 			 * Note that, if, in the future, IRE_CACHE entries
14193 			 * are obsoleted,  this lookup will not be needed,
14194 			 * as the ire passed to this function will be the
14195 			 * same as the nhop_ire computed below.
14196 			 */
14197 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14198 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14199 			    0, NULL, MATCH_IRE_TYPE, ipst);
14200 
14201 			if (nhop_ire != NULL) {
14202 				if ((src & nhop_ire->ire_mask) ==
14203 				    (nhop & nhop_ire->ire_mask)) {
14204 					/*
14205 					 * The source is directly connected.
14206 					 * Just copy the ip header (which is
14207 					 * in the first mblk)
14208 					 */
14209 					mp1 = copyb(mp);
14210 					if (mp1 != NULL) {
14211 						icmp_send_redirect(WR(q), mp1,
14212 						    nhop, ipst);
14213 					}
14214 				}
14215 				ire_refrele(nhop_ire);
14216 			}
14217 		}
14218 	}
14219 sendit:
14220 	dev_q = ire->ire_stq->q_next;
14221 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14222 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14223 		freemsg(mp);
14224 		return;
14225 	}
14226 
14227 	ip_rput_forward(ire, ipha, mp, ill);
14228 	return;
14229 
14230 drop_pkt:
14231 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14232 	freemsg(mp);
14233 }
14234 
14235 ire_t *
14236 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14237     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14238 {
14239 	queue_t		*q;
14240 	uint16_t	hcksumflags;
14241 	ip_stack_t	*ipst = ill->ill_ipst;
14242 
14243 	q = *qp;
14244 
14245 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14246 
14247 	/*
14248 	 * Clear the indication that this may have hardware
14249 	 * checksum as we are not using it for forwarding.
14250 	 */
14251 	hcksumflags = DB_CKSUMFLAGS(mp);
14252 	DB_CKSUMFLAGS(mp) = 0;
14253 
14254 	/*
14255 	 * Directed broadcast forwarding: if the packet came in over a
14256 	 * different interface then it is routed out over we can forward it.
14257 	 */
14258 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14259 		ire_refrele(ire);
14260 		freemsg(mp);
14261 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14262 		return (NULL);
14263 	}
14264 	/*
14265 	 * For multicast we have set dst to be INADDR_BROADCAST
14266 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14267 	 * only for broadcast packets.
14268 	 */
14269 	if (!CLASSD(ipha->ipha_dst)) {
14270 		ire_t *new_ire;
14271 		ipif_t *ipif;
14272 		/*
14273 		 * For ill groups, as the switch duplicates broadcasts
14274 		 * across all the ports, we need to filter out and
14275 		 * send up only one copy. There is one copy for every
14276 		 * broadcast address on each ill. Thus, we look for a
14277 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14278 		 * later to see whether this ill is eligible to receive
14279 		 * them or not. ill_nominate_bcast_rcv() nominates only
14280 		 * one set of IREs for receiving.
14281 		 */
14282 
14283 		ipif = ipif_get_next_ipif(NULL, ill);
14284 		if (ipif == NULL) {
14285 			ire_refrele(ire);
14286 			freemsg(mp);
14287 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14288 			return (NULL);
14289 		}
14290 		new_ire = ire_ctable_lookup(dst, 0, 0,
14291 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14292 		ipif_refrele(ipif);
14293 
14294 		if (new_ire != NULL) {
14295 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14296 				ire_refrele(ire);
14297 				ire_refrele(new_ire);
14298 				freemsg(mp);
14299 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14300 				return (NULL);
14301 			}
14302 			/*
14303 			 * In the special case of multirouted broadcast
14304 			 * packets, we unconditionally need to "gateway"
14305 			 * them to the appropriate interface here.
14306 			 * In the normal case, this cannot happen, because
14307 			 * there is no broadcast IRE tagged with the
14308 			 * RTF_MULTIRT flag.
14309 			 */
14310 			if (new_ire->ire_flags & RTF_MULTIRT) {
14311 				ire_refrele(new_ire);
14312 				if (ire->ire_rfq != NULL) {
14313 					q = ire->ire_rfq;
14314 					*qp = q;
14315 				}
14316 			} else {
14317 				ire_refrele(ire);
14318 				ire = new_ire;
14319 			}
14320 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14321 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14322 				/*
14323 				 * Free the message if
14324 				 * ip_g_forward_directed_bcast is turned
14325 				 * off for non-local broadcast.
14326 				 */
14327 				ire_refrele(ire);
14328 				freemsg(mp);
14329 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14330 				return (NULL);
14331 			}
14332 		} else {
14333 			/*
14334 			 * This CGTP packet successfully passed the
14335 			 * CGTP filter, but the related CGTP
14336 			 * broadcast IRE has not been found,
14337 			 * meaning that the redundant ipif is
14338 			 * probably down. However, if we discarded
14339 			 * this packet, its duplicate would be
14340 			 * filtered out by the CGTP filter so none
14341 			 * of them would get through. So we keep
14342 			 * going with this one.
14343 			 */
14344 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14345 			if (ire->ire_rfq != NULL) {
14346 				q = ire->ire_rfq;
14347 				*qp = q;
14348 			}
14349 		}
14350 	}
14351 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14352 		/*
14353 		 * Verify that there are not more then one
14354 		 * IRE_BROADCAST with this broadcast address which
14355 		 * has ire_stq set.
14356 		 * TODO: simplify, loop over all IRE's
14357 		 */
14358 		ire_t	*ire1;
14359 		int	num_stq = 0;
14360 		mblk_t	*mp1;
14361 
14362 		/* Find the first one with ire_stq set */
14363 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14364 		for (ire1 = ire; ire1 &&
14365 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14366 		    ire1 = ire1->ire_next)
14367 			;
14368 		if (ire1) {
14369 			ire_refrele(ire);
14370 			ire = ire1;
14371 			IRE_REFHOLD(ire);
14372 		}
14373 
14374 		/* Check if there are additional ones with stq set */
14375 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14376 			if (ire->ire_addr != ire1->ire_addr)
14377 				break;
14378 			if (ire1->ire_stq) {
14379 				num_stq++;
14380 				break;
14381 			}
14382 		}
14383 		rw_exit(&ire->ire_bucket->irb_lock);
14384 		if (num_stq == 1 && ire->ire_stq != NULL) {
14385 			ip1dbg(("ip_rput_process_broadcast: directed "
14386 			    "broadcast to 0x%x\n",
14387 			    ntohl(ire->ire_addr)));
14388 			mp1 = copymsg(mp);
14389 			if (mp1) {
14390 				switch (ipha->ipha_protocol) {
14391 				case IPPROTO_UDP:
14392 					ip_udp_input(q, mp1, ipha, ire, ill);
14393 					break;
14394 				default:
14395 					ip_proto_input(q, mp1, ipha, ire, ill,
14396 					    0);
14397 					break;
14398 				}
14399 			}
14400 			/*
14401 			 * Adjust ttl to 2 (1+1 - the forward engine
14402 			 * will decrement it by one.
14403 			 */
14404 			if (ip_csum_hdr(ipha)) {
14405 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14406 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14407 				freemsg(mp);
14408 				ire_refrele(ire);
14409 				return (NULL);
14410 			}
14411 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14412 			ipha->ipha_hdr_checksum = 0;
14413 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14414 			ip_rput_process_forward(q, mp, ire, ipha,
14415 			    ill, ll_multicast);
14416 			ire_refrele(ire);
14417 			return (NULL);
14418 		}
14419 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14420 		    ntohl(ire->ire_addr)));
14421 	}
14422 
14423 
14424 	/* Restore any hardware checksum flags */
14425 	DB_CKSUMFLAGS(mp) = hcksumflags;
14426 	return (ire);
14427 }
14428 
14429 /* ARGSUSED */
14430 static boolean_t
14431 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14432     int *ll_multicast, ipaddr_t *dstp)
14433 {
14434 	ip_stack_t	*ipst = ill->ill_ipst;
14435 
14436 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14437 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14438 	    ntohs(ipha->ipha_length));
14439 
14440 	/*
14441 	 * Forward packets only if we have joined the allmulti
14442 	 * group on this interface.
14443 	 */
14444 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14445 		int retval;
14446 
14447 		/*
14448 		 * Clear the indication that this may have hardware
14449 		 * checksum as we are not using it.
14450 		 */
14451 		DB_CKSUMFLAGS(mp) = 0;
14452 		retval = ip_mforward(ill, ipha, mp);
14453 		/* ip_mforward updates mib variables if needed */
14454 		/* clear b_prev - used by ip_mroute_decap */
14455 		mp->b_prev = NULL;
14456 
14457 		switch (retval) {
14458 		case 0:
14459 			/*
14460 			 * pkt is okay and arrived on phyint.
14461 			 *
14462 			 * If we are running as a multicast router
14463 			 * we need to see all IGMP and/or PIM packets.
14464 			 */
14465 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14466 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14467 				goto done;
14468 			}
14469 			break;
14470 		case -1:
14471 			/* pkt is mal-formed, toss it */
14472 			goto drop_pkt;
14473 		case 1:
14474 			/* pkt is okay and arrived on a tunnel */
14475 			/*
14476 			 * If we are running a multicast router
14477 			 *  we need to see all igmp packets.
14478 			 */
14479 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14480 				*dstp = INADDR_BROADCAST;
14481 				*ll_multicast = 1;
14482 				return (B_FALSE);
14483 			}
14484 
14485 			goto drop_pkt;
14486 		}
14487 	}
14488 
14489 	ILM_WALKER_HOLD(ill);
14490 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14491 		/*
14492 		 * This might just be caused by the fact that
14493 		 * multiple IP Multicast addresses map to the same
14494 		 * link layer multicast - no need to increment counter!
14495 		 */
14496 		ILM_WALKER_RELE(ill);
14497 		freemsg(mp);
14498 		return (B_TRUE);
14499 	}
14500 	ILM_WALKER_RELE(ill);
14501 done:
14502 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14503 	/*
14504 	 * This assumes the we deliver to all streams for multicast
14505 	 * and broadcast packets.
14506 	 */
14507 	*dstp = INADDR_BROADCAST;
14508 	*ll_multicast = 1;
14509 	return (B_FALSE);
14510 drop_pkt:
14511 	ip2dbg(("ip_rput: drop pkt\n"));
14512 	freemsg(mp);
14513 	return (B_TRUE);
14514 }
14515 
14516 /*
14517  * This function is used to both return an indication of whether or not
14518  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14519  * and in doing so, determine whether or not it is broadcast vs multicast.
14520  * For it to be a broadcast packet, we must have the appropriate mblk_t
14521  * hanging off the ill_t.  If this is either not present or doesn't match
14522  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14523  * to be multicast.  Thus NICs that have no broadcast address (or no
14524  * capability for one, such as point to point links) cannot return as
14525  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14526  * the return values simplifies the current use of the return value of this
14527  * function, which is to pass through the multicast/broadcast characteristic
14528  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14529  * changing the return value to some other symbol demands the appropriate
14530  * "translation" when hpe_flags is set prior to calling hook_run() for
14531  * packet events.
14532  */
14533 int
14534 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14535 {
14536 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14537 	mblk_t *bmp;
14538 
14539 	if (ind->dl_group_address) {
14540 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14541 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14542 		    MBLKL(mb) &&
14543 		    (bmp = ill->ill_bcast_mp) != NULL) {
14544 			dl_unitdata_req_t *dlur;
14545 			uint8_t *bphys_addr;
14546 
14547 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14548 			if (ill->ill_sap_length < 0)
14549 				bphys_addr = (uchar_t *)dlur +
14550 				    dlur->dl_dest_addr_offset;
14551 			else
14552 				bphys_addr = (uchar_t *)dlur +
14553 				    dlur->dl_dest_addr_offset +
14554 				    ill->ill_sap_length;
14555 
14556 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14557 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14558 				return (HPE_BROADCAST);
14559 			}
14560 			return (HPE_MULTICAST);
14561 		}
14562 		return (HPE_MULTICAST);
14563 	}
14564 	return (0);
14565 }
14566 
14567 static boolean_t
14568 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14569     int *ll_multicast, mblk_t **mpp)
14570 {
14571 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14572 	boolean_t must_copy = B_FALSE;
14573 	struct iocblk   *iocp;
14574 	ipha_t		*ipha;
14575 	ip_stack_t	*ipst = ill->ill_ipst;
14576 
14577 #define	rptr    ((uchar_t *)ipha)
14578 
14579 	first_mp = *first_mpp;
14580 	mp = *mpp;
14581 
14582 	ASSERT(first_mp == mp);
14583 
14584 	/*
14585 	 * if db_ref > 1 then copymsg and free original. Packet may be
14586 	 * changed and do not want other entity who has a reference to this
14587 	 * message to trip over the changes. This is a blind change because
14588 	 * trying to catch all places that might change packet is too
14589 	 * difficult (since it may be a module above this one)
14590 	 *
14591 	 * This corresponds to the non-fast path case. We walk down the full
14592 	 * chain in this case, and check the db_ref count of all the dblks,
14593 	 * and do a copymsg if required. It is possible that the db_ref counts
14594 	 * of the data blocks in the mblk chain can be different.
14595 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14596 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14597 	 * 'snoop' is running.
14598 	 */
14599 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14600 		if (mp1->b_datap->db_ref > 1) {
14601 			must_copy = B_TRUE;
14602 			break;
14603 		}
14604 	}
14605 
14606 	if (must_copy) {
14607 		mp1 = copymsg(mp);
14608 		if (mp1 == NULL) {
14609 			for (mp1 = mp; mp1 != NULL;
14610 			    mp1 = mp1->b_cont) {
14611 				mp1->b_next = NULL;
14612 				mp1->b_prev = NULL;
14613 			}
14614 			freemsg(mp);
14615 			if (ill != NULL) {
14616 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14617 			} else {
14618 				BUMP_MIB(&ipst->ips_ip_mib,
14619 				    ipIfStatsInDiscards);
14620 			}
14621 			return (B_TRUE);
14622 		}
14623 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14624 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14625 			/* Copy b_prev - used by ip_mroute_decap */
14626 			to_mp->b_prev = from_mp->b_prev;
14627 			from_mp->b_prev = NULL;
14628 		}
14629 		*first_mpp = first_mp = mp1;
14630 		freemsg(mp);
14631 		mp = mp1;
14632 		*mpp = mp1;
14633 	}
14634 
14635 	ipha = (ipha_t *)mp->b_rptr;
14636 
14637 	/*
14638 	 * previous code has a case for M_DATA.
14639 	 * We want to check how that happens.
14640 	 */
14641 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14642 	switch (first_mp->b_datap->db_type) {
14643 	case M_PROTO:
14644 	case M_PCPROTO:
14645 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14646 		    DL_UNITDATA_IND) {
14647 			/* Go handle anything other than data elsewhere. */
14648 			ip_rput_dlpi(q, mp);
14649 			return (B_TRUE);
14650 		}
14651 
14652 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14653 		/* Ditch the DLPI header. */
14654 		mp1 = mp->b_cont;
14655 		ASSERT(first_mp == mp);
14656 		*first_mpp = mp1;
14657 		freeb(mp);
14658 		*mpp = mp1;
14659 		return (B_FALSE);
14660 	case M_IOCACK:
14661 		ip1dbg(("got iocack "));
14662 		iocp = (struct iocblk *)mp->b_rptr;
14663 		switch (iocp->ioc_cmd) {
14664 		case DL_IOC_HDR_INFO:
14665 			ill = (ill_t *)q->q_ptr;
14666 			ill_fastpath_ack(ill, mp);
14667 			return (B_TRUE);
14668 		case SIOCSTUNPARAM:
14669 		case OSIOCSTUNPARAM:
14670 			/* Go through qwriter_ip */
14671 			break;
14672 		case SIOCGTUNPARAM:
14673 		case OSIOCGTUNPARAM:
14674 			ip_rput_other(NULL, q, mp, NULL);
14675 			return (B_TRUE);
14676 		default:
14677 			putnext(q, mp);
14678 			return (B_TRUE);
14679 		}
14680 		/* FALLTHRU */
14681 	case M_ERROR:
14682 	case M_HANGUP:
14683 		/*
14684 		 * Since this is on the ill stream we unconditionally
14685 		 * bump up the refcount
14686 		 */
14687 		ill_refhold(ill);
14688 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14689 		return (B_TRUE);
14690 	case M_CTL:
14691 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14692 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14693 		    IPHADA_M_CTL)) {
14694 			/*
14695 			 * It's an IPsec accelerated packet.
14696 			 * Make sure that the ill from which we received the
14697 			 * packet has enabled IPsec hardware acceleration.
14698 			 */
14699 			if (!(ill->ill_capabilities &
14700 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14701 				/* IPsec kstats: bean counter */
14702 				freemsg(mp);
14703 				return (B_TRUE);
14704 			}
14705 
14706 			/*
14707 			 * Make mp point to the mblk following the M_CTL,
14708 			 * then process according to type of mp.
14709 			 * After this processing, first_mp will point to
14710 			 * the data-attributes and mp to the pkt following
14711 			 * the M_CTL.
14712 			 */
14713 			mp = first_mp->b_cont;
14714 			if (mp == NULL) {
14715 				freemsg(first_mp);
14716 				return (B_TRUE);
14717 			}
14718 			/*
14719 			 * A Hardware Accelerated packet can only be M_DATA
14720 			 * ESP or AH packet.
14721 			 */
14722 			if (mp->b_datap->db_type != M_DATA) {
14723 				/* non-M_DATA IPsec accelerated packet */
14724 				IPSECHW_DEBUG(IPSECHW_PKT,
14725 				    ("non-M_DATA IPsec accelerated pkt\n"));
14726 				freemsg(first_mp);
14727 				return (B_TRUE);
14728 			}
14729 			ipha = (ipha_t *)mp->b_rptr;
14730 			if (ipha->ipha_protocol != IPPROTO_AH &&
14731 			    ipha->ipha_protocol != IPPROTO_ESP) {
14732 				IPSECHW_DEBUG(IPSECHW_PKT,
14733 				    ("non-M_DATA IPsec accelerated pkt\n"));
14734 				freemsg(first_mp);
14735 				return (B_TRUE);
14736 			}
14737 			*mpp = mp;
14738 			return (B_FALSE);
14739 		}
14740 		putnext(q, mp);
14741 		return (B_TRUE);
14742 	case M_IOCNAK:
14743 		ip1dbg(("got iocnak "));
14744 		iocp = (struct iocblk *)mp->b_rptr;
14745 		switch (iocp->ioc_cmd) {
14746 		case SIOCSTUNPARAM:
14747 		case OSIOCSTUNPARAM:
14748 			/*
14749 			 * Since this is on the ill stream we unconditionally
14750 			 * bump up the refcount
14751 			 */
14752 			ill_refhold(ill);
14753 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14754 			return (B_TRUE);
14755 		case DL_IOC_HDR_INFO:
14756 		case SIOCGTUNPARAM:
14757 		case OSIOCGTUNPARAM:
14758 			ip_rput_other(NULL, q, mp, NULL);
14759 			return (B_TRUE);
14760 		default:
14761 			break;
14762 		}
14763 		/* FALLTHRU */
14764 	default:
14765 		putnext(q, mp);
14766 		return (B_TRUE);
14767 	}
14768 }
14769 
14770 /* Read side put procedure.  Packets coming from the wire arrive here. */
14771 void
14772 ip_rput(queue_t *q, mblk_t *mp)
14773 {
14774 	ill_t	*ill;
14775 	union DL_primitives *dl;
14776 
14777 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14778 
14779 	ill = (ill_t *)q->q_ptr;
14780 
14781 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14782 		/*
14783 		 * If things are opening or closing, only accept high-priority
14784 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14785 		 * created; on close, things hanging off the ill may have been
14786 		 * freed already.)
14787 		 */
14788 		dl = (union DL_primitives *)mp->b_rptr;
14789 		if (DB_TYPE(mp) != M_PCPROTO ||
14790 		    dl->dl_primitive == DL_UNITDATA_IND) {
14791 			/*
14792 			 * SIOC[GS]TUNPARAM ioctls can come here.
14793 			 */
14794 			inet_freemsg(mp);
14795 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14796 			    "ip_rput_end: q %p (%S)", q, "uninit");
14797 			return;
14798 		}
14799 	}
14800 
14801 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14802 	    "ip_rput_end: q %p (%S)", q, "end");
14803 
14804 	ip_input(ill, NULL, mp, NULL);
14805 }
14806 
14807 static mblk_t *
14808 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14809 {
14810 	mblk_t *mp1;
14811 	boolean_t adjusted = B_FALSE;
14812 	ip_stack_t *ipst = ill->ill_ipst;
14813 
14814 	IP_STAT(ipst, ip_db_ref);
14815 	/*
14816 	 * The IP_RECVSLLA option depends on having the
14817 	 * link layer header. First check that:
14818 	 * a> the underlying device is of type ether,
14819 	 * since this option is currently supported only
14820 	 * over ethernet.
14821 	 * b> there is enough room to copy over the link
14822 	 * layer header.
14823 	 *
14824 	 * Once the checks are done, adjust rptr so that
14825 	 * the link layer header will be copied via
14826 	 * copymsg. Note that, IFT_ETHER may be returned
14827 	 * by some non-ethernet drivers but in this case
14828 	 * the second check will fail.
14829 	 */
14830 	if (ill->ill_type == IFT_ETHER &&
14831 	    (mp->b_rptr - mp->b_datap->db_base) >=
14832 	    sizeof (struct ether_header)) {
14833 		mp->b_rptr -= sizeof (struct ether_header);
14834 		adjusted = B_TRUE;
14835 	}
14836 	mp1 = copymsg(mp);
14837 
14838 	if (mp1 == NULL) {
14839 		mp->b_next = NULL;
14840 		/* clear b_prev - used by ip_mroute_decap */
14841 		mp->b_prev = NULL;
14842 		freemsg(mp);
14843 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14844 		return (NULL);
14845 	}
14846 
14847 	if (adjusted) {
14848 		/*
14849 		 * Copy is done. Restore the pointer in
14850 		 * the _new_ mblk
14851 		 */
14852 		mp1->b_rptr += sizeof (struct ether_header);
14853 	}
14854 
14855 	/* Copy b_prev - used by ip_mroute_decap */
14856 	mp1->b_prev = mp->b_prev;
14857 	mp->b_prev = NULL;
14858 
14859 	/* preserve the hardware checksum flags and data, if present */
14860 	if (DB_CKSUMFLAGS(mp) != 0) {
14861 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14862 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14863 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14864 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14865 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14866 	}
14867 
14868 	freemsg(mp);
14869 	return (mp1);
14870 }
14871 
14872 /*
14873  * Direct read side procedure capable of dealing with chains. GLDv3 based
14874  * drivers call this function directly with mblk chains while STREAMS
14875  * read side procedure ip_rput() calls this for single packet with ip_ring
14876  * set to NULL to process one packet at a time.
14877  *
14878  * The ill will always be valid if this function is called directly from
14879  * the driver.
14880  *
14881  * If ip_input() is called from GLDv3:
14882  *
14883  *   - This must be a non-VLAN IP stream.
14884  *   - 'mp' is either an untagged or a special priority-tagged packet.
14885  *   - Any VLAN tag that was in the MAC header has been stripped.
14886  *
14887  * If the IP header in packet is not 32-bit aligned, every message in the
14888  * chain will be aligned before further operations. This is required on SPARC
14889  * platform.
14890  */
14891 /* ARGSUSED */
14892 void
14893 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14894     struct mac_header_info_s *mhip)
14895 {
14896 	ipaddr_t		dst = NULL;
14897 	ipaddr_t		prev_dst;
14898 	ire_t			*ire = NULL;
14899 	ipha_t			*ipha;
14900 	uint_t			pkt_len;
14901 	ssize_t			len;
14902 	uint_t			opt_len;
14903 	int			ll_multicast;
14904 	int			cgtp_flt_pkt;
14905 	queue_t			*q = ill->ill_rq;
14906 	squeue_t		*curr_sqp = NULL;
14907 	mblk_t 			*head = NULL;
14908 	mblk_t			*tail = NULL;
14909 	mblk_t			*first_mp;
14910 	mblk_t 			*mp;
14911 	mblk_t			*dmp;
14912 	int			cnt = 0;
14913 	ip_stack_t		*ipst = ill->ill_ipst;
14914 
14915 	ASSERT(mp_chain != NULL);
14916 	ASSERT(ill != NULL);
14917 
14918 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14919 
14920 #define	rptr	((uchar_t *)ipha)
14921 
14922 	while (mp_chain != NULL) {
14923 		first_mp = mp = mp_chain;
14924 		mp_chain = mp_chain->b_next;
14925 		mp->b_next = NULL;
14926 		ll_multicast = 0;
14927 
14928 		/*
14929 		 * We do ire caching from one iteration to
14930 		 * another. In the event the packet chain contains
14931 		 * all packets from the same dst, this caching saves
14932 		 * an ire_cache_lookup for each of the succeeding
14933 		 * packets in a packet chain.
14934 		 */
14935 		prev_dst = dst;
14936 
14937 		/*
14938 		 * if db_ref > 1 then copymsg and free original. Packet
14939 		 * may be changed and we do not want the other entity
14940 		 * who has a reference to this message to trip over the
14941 		 * changes. This is a blind change because trying to
14942 		 * catch all places that might change the packet is too
14943 		 * difficult.
14944 		 *
14945 		 * This corresponds to the fast path case, where we have
14946 		 * a chain of M_DATA mblks.  We check the db_ref count
14947 		 * of only the 1st data block in the mblk chain. There
14948 		 * doesn't seem to be a reason why a device driver would
14949 		 * send up data with varying db_ref counts in the mblk
14950 		 * chain. In any case the Fast path is a private
14951 		 * interface, and our drivers don't do such a thing.
14952 		 * Given the above assumption, there is no need to walk
14953 		 * down the entire mblk chain (which could have a
14954 		 * potential performance problem)
14955 		 */
14956 
14957 		if (DB_REF(mp) > 1) {
14958 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14959 				continue;
14960 		}
14961 
14962 		/*
14963 		 * Check and align the IP header.
14964 		 */
14965 		first_mp = mp;
14966 		if (DB_TYPE(mp) == M_DATA) {
14967 			dmp = mp;
14968 		} else if (DB_TYPE(mp) == M_PROTO &&
14969 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14970 			dmp = mp->b_cont;
14971 		} else {
14972 			dmp = NULL;
14973 		}
14974 		if (dmp != NULL) {
14975 			/*
14976 			 * IP header ptr not aligned?
14977 			 * OR IP header not complete in first mblk
14978 			 */
14979 			if (!OK_32PTR(dmp->b_rptr) ||
14980 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14981 				if (!ip_check_and_align_header(q, dmp, ipst))
14982 					continue;
14983 			}
14984 		}
14985 
14986 		/*
14987 		 * ip_input fast path
14988 		 */
14989 
14990 		/* mblk type is not M_DATA */
14991 		if (DB_TYPE(mp) != M_DATA) {
14992 			if (ip_rput_process_notdata(q, &first_mp, ill,
14993 			    &ll_multicast, &mp))
14994 				continue;
14995 
14996 			/*
14997 			 * The only way we can get here is if we had a
14998 			 * packet that was either a DL_UNITDATA_IND or
14999 			 * an M_CTL for an IPsec accelerated packet.
15000 			 *
15001 			 * In either case, the first_mp will point to
15002 			 * the leading M_PROTO or M_CTL.
15003 			 */
15004 			ASSERT(first_mp != NULL);
15005 		} else if (mhip != NULL) {
15006 			/*
15007 			 * ll_multicast is set here so that it is ready
15008 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15009 			 * manipulates ll_multicast in the same fashion when
15010 			 * called from ip_rput_process_notdata.
15011 			 */
15012 			switch (mhip->mhi_dsttype) {
15013 			case MAC_ADDRTYPE_MULTICAST :
15014 				ll_multicast = HPE_MULTICAST;
15015 				break;
15016 			case MAC_ADDRTYPE_BROADCAST :
15017 				ll_multicast = HPE_BROADCAST;
15018 				break;
15019 			default :
15020 				break;
15021 			}
15022 		}
15023 
15024 		/* Make sure its an M_DATA and that its aligned */
15025 		ASSERT(DB_TYPE(mp) == M_DATA);
15026 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15027 
15028 		ipha = (ipha_t *)mp->b_rptr;
15029 		len = mp->b_wptr - rptr;
15030 		pkt_len = ntohs(ipha->ipha_length);
15031 
15032 		/*
15033 		 * We must count all incoming packets, even if they end
15034 		 * up being dropped later on.
15035 		 */
15036 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15037 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15038 
15039 		/* multiple mblk or too short */
15040 		len -= pkt_len;
15041 		if (len != 0) {
15042 			/*
15043 			 * Make sure we have data length consistent
15044 			 * with the IP header.
15045 			 */
15046 			if (mp->b_cont == NULL) {
15047 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15048 					BUMP_MIB(ill->ill_ip_mib,
15049 					    ipIfStatsInHdrErrors);
15050 					ip2dbg(("ip_input: drop pkt\n"));
15051 					freemsg(mp);
15052 					continue;
15053 				}
15054 				mp->b_wptr = rptr + pkt_len;
15055 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15056 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15057 					BUMP_MIB(ill->ill_ip_mib,
15058 					    ipIfStatsInHdrErrors);
15059 					ip2dbg(("ip_input: drop pkt\n"));
15060 					freemsg(mp);
15061 					continue;
15062 				}
15063 				(void) adjmsg(mp, -len);
15064 				IP_STAT(ipst, ip_multimblk3);
15065 			}
15066 		}
15067 
15068 		/* Obtain the dst of the current packet */
15069 		dst = ipha->ipha_dst;
15070 
15071 		DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL,
15072 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *,
15073 		    ipha, ip6_t *, NULL, int, 0);
15074 
15075 		/*
15076 		 * The following test for loopback is faster than
15077 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15078 		 * operations.
15079 		 * Note that these addresses are always in network byte order
15080 		 */
15081 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15082 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15083 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15084 			freemsg(mp);
15085 			continue;
15086 		}
15087 
15088 		/*
15089 		 * The event for packets being received from a 'physical'
15090 		 * interface is placed after validation of the source and/or
15091 		 * destination address as being local so that packets can be
15092 		 * redirected to loopback addresses using ipnat.
15093 		 */
15094 		DTRACE_PROBE4(ip4__physical__in__start,
15095 		    ill_t *, ill, ill_t *, NULL,
15096 		    ipha_t *, ipha, mblk_t *, first_mp);
15097 
15098 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15099 		    ipst->ips_ipv4firewall_physical_in,
15100 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15101 
15102 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15103 
15104 		if (first_mp == NULL) {
15105 			continue;
15106 		}
15107 		dst = ipha->ipha_dst;
15108 
15109 		/*
15110 		 * Attach any necessary label information to
15111 		 * this packet
15112 		 */
15113 		if (is_system_labeled() &&
15114 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15115 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15116 			freemsg(mp);
15117 			continue;
15118 		}
15119 
15120 		/*
15121 		 * Reuse the cached ire only if the ipha_dst of the previous
15122 		 * packet is the same as the current packet AND it is not
15123 		 * INADDR_ANY.
15124 		 */
15125 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15126 		    (ire != NULL)) {
15127 			ire_refrele(ire);
15128 			ire = NULL;
15129 		}
15130 		opt_len = ipha->ipha_version_and_hdr_length -
15131 		    IP_SIMPLE_HDR_VERSION;
15132 
15133 		/*
15134 		 * Check to see if we can take the fastpath.
15135 		 * That is possible if the following conditions are met
15136 		 *	o Tsol disabled
15137 		 *	o CGTP disabled
15138 		 *	o ipp_action_count is 0
15139 		 *	o no options in the packet
15140 		 *	o not a RSVP packet
15141 		 * 	o not a multicast packet
15142 		 *	o ill not in IP_DHCPINIT_IF mode
15143 		 */
15144 		if (!is_system_labeled() &&
15145 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15146 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15147 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15148 			if (ire == NULL)
15149 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15150 				    ipst);
15151 
15152 			/* incoming packet is for forwarding */
15153 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15154 				ire = ip_fast_forward(ire, dst, ill, mp);
15155 				continue;
15156 			}
15157 			/* incoming packet is for local consumption */
15158 			if (ire->ire_type & IRE_LOCAL)
15159 				goto local;
15160 		}
15161 
15162 		/*
15163 		 * Disable ire caching for anything more complex
15164 		 * than the simple fast path case we checked for above.
15165 		 */
15166 		if (ire != NULL) {
15167 			ire_refrele(ire);
15168 			ire = NULL;
15169 		}
15170 
15171 		/*
15172 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15173 		 * server to unicast DHCP packets to a DHCP client using the
15174 		 * IP address it is offering to the client.  This can be
15175 		 * disabled through the "broadcast bit", but not all DHCP
15176 		 * servers honor that bit.  Therefore, to interoperate with as
15177 		 * many DHCP servers as possible, the DHCP client allows the
15178 		 * server to unicast, but we treat those packets as broadcast
15179 		 * here.  Note that we don't rewrite the packet itself since
15180 		 * (a) that would mess up the checksums and (b) the DHCP
15181 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15182 		 * hand it the packet regardless.
15183 		 */
15184 		if (ill->ill_dhcpinit != 0 &&
15185 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15186 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15187 			udpha_t *udpha;
15188 
15189 			/*
15190 			 * Reload ipha since pullupmsg() can change b_rptr.
15191 			 */
15192 			ipha = (ipha_t *)mp->b_rptr;
15193 			udpha = (udpha_t *)&ipha[1];
15194 
15195 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15196 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15197 				    mblk_t *, mp);
15198 				dst = INADDR_BROADCAST;
15199 			}
15200 		}
15201 
15202 		/* Full-blown slow path */
15203 		if (opt_len != 0) {
15204 			if (len != 0)
15205 				IP_STAT(ipst, ip_multimblk4);
15206 			else
15207 				IP_STAT(ipst, ip_ipoptions);
15208 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15209 			    &dst, ipst))
15210 				continue;
15211 		}
15212 
15213 		/*
15214 		 * Invoke the CGTP (multirouting) filtering module to process
15215 		 * the incoming packet. Packets identified as duplicates
15216 		 * must be discarded. Filtering is active only if the
15217 		 * the ip_cgtp_filter ndd variable is non-zero.
15218 		 */
15219 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15220 		if (ipst->ips_ip_cgtp_filter &&
15221 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15222 			netstackid_t stackid;
15223 
15224 			stackid = ipst->ips_netstack->netstack_stackid;
15225 			cgtp_flt_pkt =
15226 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15227 			    ill->ill_phyint->phyint_ifindex, mp);
15228 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15229 				freemsg(first_mp);
15230 				continue;
15231 			}
15232 		}
15233 
15234 		/*
15235 		 * If rsvpd is running, let RSVP daemon handle its processing
15236 		 * and forwarding of RSVP multicast/unicast packets.
15237 		 * If rsvpd is not running but mrouted is running, RSVP
15238 		 * multicast packets are forwarded as multicast traffic
15239 		 * and RSVP unicast packets are forwarded by unicast router.
15240 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15241 		 * packets are not forwarded, but the unicast packets are
15242 		 * forwarded like unicast traffic.
15243 		 */
15244 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15245 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15246 		    NULL) {
15247 			/* RSVP packet and rsvpd running. Treat as ours */
15248 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15249 			/*
15250 			 * This assumes that we deliver to all streams for
15251 			 * multicast and broadcast packets.
15252 			 * We have to force ll_multicast to 1 to handle the
15253 			 * M_DATA messages passed in from ip_mroute_decap.
15254 			 */
15255 			dst = INADDR_BROADCAST;
15256 			ll_multicast = 1;
15257 		} else if (CLASSD(dst)) {
15258 			/* packet is multicast */
15259 			mp->b_next = NULL;
15260 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15261 			    &ll_multicast, &dst))
15262 				continue;
15263 		}
15264 
15265 		if (ire == NULL) {
15266 			ire = ire_cache_lookup(dst, ALL_ZONES,
15267 			    MBLK_GETLABEL(mp), ipst);
15268 		}
15269 
15270 		if (ire != NULL && ire->ire_stq != NULL &&
15271 		    ire->ire_zoneid != GLOBAL_ZONEID &&
15272 		    ire->ire_zoneid != ALL_ZONES) {
15273 			/*
15274 			 * Should only use IREs that are visible from the
15275 			 * global zone for forwarding.
15276 			 */
15277 			ire_refrele(ire);
15278 			ire = ire_cache_lookup(dst, GLOBAL_ZONEID,
15279 			    MBLK_GETLABEL(mp), ipst);
15280 		}
15281 
15282 		if (ire == NULL) {
15283 			/*
15284 			 * No IRE for this destination, so it can't be for us.
15285 			 * Unless we are forwarding, drop the packet.
15286 			 * We have to let source routed packets through
15287 			 * since we don't yet know if they are 'ping -l'
15288 			 * packets i.e. if they will go out over the
15289 			 * same interface as they came in on.
15290 			 */
15291 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15292 			if (ire == NULL)
15293 				continue;
15294 		}
15295 
15296 		/*
15297 		 * Broadcast IRE may indicate either broadcast or
15298 		 * multicast packet
15299 		 */
15300 		if (ire->ire_type == IRE_BROADCAST) {
15301 			/*
15302 			 * Skip broadcast checks if packet is UDP multicast;
15303 			 * we'd rather not enter ip_rput_process_broadcast()
15304 			 * unless the packet is broadcast for real, since
15305 			 * that routine is a no-op for multicast.
15306 			 */
15307 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15308 			    !CLASSD(ipha->ipha_dst)) {
15309 				ire = ip_rput_process_broadcast(&q, mp,
15310 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15311 				    ll_multicast);
15312 				if (ire == NULL)
15313 					continue;
15314 			}
15315 		} else if (ire->ire_stq != NULL) {
15316 			/* fowarding? */
15317 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15318 			    ll_multicast);
15319 			/* ip_rput_process_forward consumed the packet */
15320 			continue;
15321 		}
15322 
15323 local:
15324 		/*
15325 		 * If the queue in the ire is different to the ingress queue
15326 		 * then we need to check to see if we can accept the packet.
15327 		 * Note that for multicast packets and broadcast packets sent
15328 		 * to a broadcast address which is shared between multiple
15329 		 * interfaces we should not do this since we just got a random
15330 		 * broadcast ire.
15331 		 */
15332 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15333 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15334 			    ill)) == NULL) {
15335 				/* Drop packet */
15336 				BUMP_MIB(ill->ill_ip_mib,
15337 				    ipIfStatsForwProhibits);
15338 				freemsg(mp);
15339 				continue;
15340 			}
15341 			if (ire->ire_rfq != NULL)
15342 				q = ire->ire_rfq;
15343 		}
15344 
15345 		switch (ipha->ipha_protocol) {
15346 		case IPPROTO_TCP:
15347 			ASSERT(first_mp == mp);
15348 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15349 			    mp, 0, q, ip_ring)) != NULL) {
15350 				if (curr_sqp == NULL) {
15351 					curr_sqp = GET_SQUEUE(mp);
15352 					ASSERT(cnt == 0);
15353 					cnt++;
15354 					head = tail = mp;
15355 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15356 					ASSERT(tail != NULL);
15357 					cnt++;
15358 					tail->b_next = mp;
15359 					tail = mp;
15360 				} else {
15361 					/*
15362 					 * A different squeue. Send the
15363 					 * chain for the previous squeue on
15364 					 * its way. This shouldn't happen
15365 					 * often unless interrupt binding
15366 					 * changes.
15367 					 */
15368 					IP_STAT(ipst, ip_input_multi_squeue);
15369 					squeue_enter_chain(curr_sqp, head,
15370 					    tail, cnt, SQTAG_IP_INPUT);
15371 					curr_sqp = GET_SQUEUE(mp);
15372 					head = mp;
15373 					tail = mp;
15374 					cnt = 1;
15375 				}
15376 			}
15377 			continue;
15378 		case IPPROTO_UDP:
15379 			ASSERT(first_mp == mp);
15380 			ip_udp_input(q, mp, ipha, ire, ill);
15381 			continue;
15382 		case IPPROTO_SCTP:
15383 			ASSERT(first_mp == mp);
15384 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15385 			    q, dst);
15386 			/* ire has been released by ip_sctp_input */
15387 			ire = NULL;
15388 			continue;
15389 		default:
15390 			ip_proto_input(q, first_mp, ipha, ire, ill, 0);
15391 			continue;
15392 		}
15393 	}
15394 
15395 	if (ire != NULL)
15396 		ire_refrele(ire);
15397 
15398 	if (head != NULL)
15399 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15400 
15401 	/*
15402 	 * This code is there just to make netperf/ttcp look good.
15403 	 *
15404 	 * Its possible that after being in polling mode (and having cleared
15405 	 * the backlog), squeues have turned the interrupt frequency higher
15406 	 * to improve latency at the expense of more CPU utilization (less
15407 	 * packets per interrupts or more number of interrupts). Workloads
15408 	 * like ttcp/netperf do manage to tickle polling once in a while
15409 	 * but for the remaining time, stay in higher interrupt mode since
15410 	 * their packet arrival rate is pretty uniform and this shows up
15411 	 * as higher CPU utilization. Since people care about CPU utilization
15412 	 * while running netperf/ttcp, turn the interrupt frequency back to
15413 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15414 	 */
15415 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15416 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15417 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15418 			ip_ring->rr_blank(ip_ring->rr_handle,
15419 			    ip_ring->rr_normal_blank_time,
15420 			    ip_ring->rr_normal_pkt_cnt);
15421 		}
15422 		}
15423 
15424 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15425 	    "ip_input_end: q %p (%S)", q, "end");
15426 #undef  rptr
15427 }
15428 
15429 static void
15430 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15431     t_uscalar_t err)
15432 {
15433 	if (dl_err == DL_SYSERR) {
15434 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15435 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15436 		    ill->ill_name, dl_primstr(prim), err);
15437 		return;
15438 	}
15439 
15440 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15441 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15442 	    dl_errstr(dl_err));
15443 }
15444 
15445 /*
15446  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15447  * than DL_UNITDATA_IND messages. If we need to process this message
15448  * exclusively, we call qwriter_ip, in which case we also need to call
15449  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15450  */
15451 void
15452 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15453 {
15454 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15455 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15456 	ill_t		*ill = q->q_ptr;
15457 	t_uscalar_t	prim = dloa->dl_primitive;
15458 	t_uscalar_t	reqprim = DL_PRIM_INVAL;
15459 
15460 	ip1dbg(("ip_rput_dlpi"));
15461 
15462 	/*
15463 	 * If we received an ACK but didn't send a request for it, then it
15464 	 * can't be part of any pending operation; discard up-front.
15465 	 */
15466 	switch (prim) {
15467 	case DL_ERROR_ACK:
15468 		reqprim = dlea->dl_error_primitive;
15469 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK for %s (0x%x): %s "
15470 		    "(0x%x), unix %u\n", ill->ill_name, dl_primstr(reqprim),
15471 		    reqprim, dl_errstr(dlea->dl_errno), dlea->dl_errno,
15472 		    dlea->dl_unix_errno));
15473 		break;
15474 	case DL_OK_ACK:
15475 		reqprim = dloa->dl_correct_primitive;
15476 		break;
15477 	case DL_INFO_ACK:
15478 		reqprim = DL_INFO_REQ;
15479 		break;
15480 	case DL_BIND_ACK:
15481 		reqprim = DL_BIND_REQ;
15482 		break;
15483 	case DL_PHYS_ADDR_ACK:
15484 		reqprim = DL_PHYS_ADDR_REQ;
15485 		break;
15486 	case DL_NOTIFY_ACK:
15487 		reqprim = DL_NOTIFY_REQ;
15488 		break;
15489 	case DL_CONTROL_ACK:
15490 		reqprim = DL_CONTROL_REQ;
15491 		break;
15492 	case DL_CAPABILITY_ACK:
15493 		reqprim = DL_CAPABILITY_REQ;
15494 		break;
15495 	}
15496 
15497 	if (prim != DL_NOTIFY_IND) {
15498 		if (reqprim == DL_PRIM_INVAL ||
15499 		    !ill_dlpi_pending(ill, reqprim)) {
15500 			/* Not a DLPI message we support or expected */
15501 			freemsg(mp);
15502 			return;
15503 		}
15504 		ip1dbg(("ip_rput: received %s for %s\n", dl_primstr(prim),
15505 		    dl_primstr(reqprim)));
15506 	}
15507 
15508 	switch (reqprim) {
15509 	case DL_UNBIND_REQ:
15510 		/*
15511 		 * NOTE: we mark the unbind as complete even if we got a
15512 		 * DL_ERROR_ACK, since there's not much else we can do.
15513 		 */
15514 		mutex_enter(&ill->ill_lock);
15515 		ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15516 		cv_signal(&ill->ill_cv);
15517 		mutex_exit(&ill->ill_lock);
15518 		break;
15519 
15520 	case DL_ENABMULTI_REQ:
15521 		if (prim == DL_OK_ACK) {
15522 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15523 				ill->ill_dlpi_multicast_state = IDS_OK;
15524 		}
15525 		break;
15526 	}
15527 
15528 	/*
15529 	 * The message is one we're waiting for (or DL_NOTIFY_IND), but we
15530 	 * need to become writer to continue to process it.  Because an
15531 	 * exclusive operation doesn't complete until replies to all queued
15532 	 * DLPI messages have been received, we know we're in the middle of an
15533 	 * exclusive operation and pass CUR_OP (except for DL_NOTIFY_IND).
15534 	 *
15535 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15536 	 * Since this is on the ill stream we unconditionally bump up the
15537 	 * refcount without doing ILL_CAN_LOOKUP().
15538 	 */
15539 	ill_refhold(ill);
15540 	if (prim == DL_NOTIFY_IND)
15541 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15542 	else
15543 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15544 }
15545 
15546 /*
15547  * Handling of DLPI messages that require exclusive access to the ipsq.
15548  *
15549  * Need to do ill_pending_mp_release on ioctl completion, which could
15550  * happen here. (along with mi_copy_done)
15551  */
15552 /* ARGSUSED */
15553 static void
15554 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15555 {
15556 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15557 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15558 	int		err = 0;
15559 	ill_t		*ill;
15560 	ipif_t		*ipif = NULL;
15561 	mblk_t		*mp1 = NULL;
15562 	conn_t		*connp = NULL;
15563 	t_uscalar_t	paddrreq;
15564 	mblk_t		*mp_hw;
15565 	boolean_t	success;
15566 	boolean_t	ioctl_aborted = B_FALSE;
15567 	boolean_t	log = B_TRUE;
15568 	ip_stack_t		*ipst;
15569 
15570 	ip1dbg(("ip_rput_dlpi_writer .."));
15571 	ill = (ill_t *)q->q_ptr;
15572 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15573 
15574 	ASSERT(IAM_WRITER_ILL(ill));
15575 
15576 	ipst = ill->ill_ipst;
15577 
15578 	/*
15579 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15580 	 * both are null or non-null. However we can assert that only
15581 	 * after grabbing the ipsq_lock. So we don't make any assertion
15582 	 * here and in other places in the code.
15583 	 */
15584 	ipif = ipsq->ipsq_pending_ipif;
15585 	/*
15586 	 * The current ioctl could have been aborted by the user and a new
15587 	 * ioctl to bring up another ill could have started. We could still
15588 	 * get a response from the driver later.
15589 	 */
15590 	if (ipif != NULL && ipif->ipif_ill != ill)
15591 		ioctl_aborted = B_TRUE;
15592 
15593 	switch (dloa->dl_primitive) {
15594 	case DL_ERROR_ACK:
15595 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15596 		    dl_primstr(dlea->dl_error_primitive)));
15597 
15598 		switch (dlea->dl_error_primitive) {
15599 		case DL_DISABMULTI_REQ:
15600 			if (!ill->ill_isv6)
15601 				ipsq_current_finish(ipsq);
15602 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15603 			break;
15604 		case DL_PROMISCON_REQ:
15605 		case DL_PROMISCOFF_REQ:
15606 		case DL_UNBIND_REQ:
15607 		case DL_ATTACH_REQ:
15608 		case DL_INFO_REQ:
15609 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15610 			break;
15611 		case DL_NOTIFY_REQ:
15612 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15613 			log = B_FALSE;
15614 			break;
15615 		case DL_PHYS_ADDR_REQ:
15616 			/*
15617 			 * For IPv6 only, there are two additional
15618 			 * phys_addr_req's sent to the driver to get the
15619 			 * IPv6 token and lla. This allows IP to acquire
15620 			 * the hardware address format for a given interface
15621 			 * without having built in knowledge of the hardware
15622 			 * address. ill_phys_addr_pend keeps track of the last
15623 			 * DL_PAR sent so we know which response we are
15624 			 * dealing with. ill_dlpi_done will update
15625 			 * ill_phys_addr_pend when it sends the next req.
15626 			 * We don't complete the IOCTL until all three DL_PARs
15627 			 * have been attempted, so set *_len to 0 and break.
15628 			 */
15629 			paddrreq = ill->ill_phys_addr_pend;
15630 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15631 			if (paddrreq == DL_IPV6_TOKEN) {
15632 				ill->ill_token_length = 0;
15633 				log = B_FALSE;
15634 				break;
15635 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15636 				ill->ill_nd_lla_len = 0;
15637 				log = B_FALSE;
15638 				break;
15639 			}
15640 			/*
15641 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15642 			 * We presumably have an IOCTL hanging out waiting
15643 			 * for completion. Find it and complete the IOCTL
15644 			 * with the error noted.
15645 			 * However, ill_dl_phys was called on an ill queue
15646 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15647 			 * set. But the ioctl is known to be pending on ill_wq.
15648 			 */
15649 			if (!ill->ill_ifname_pending)
15650 				break;
15651 			ill->ill_ifname_pending = 0;
15652 			if (!ioctl_aborted)
15653 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15654 			if (mp1 != NULL) {
15655 				/*
15656 				 * This operation (SIOCSLIFNAME) must have
15657 				 * happened on the ill. Assert there is no conn
15658 				 */
15659 				ASSERT(connp == NULL);
15660 				q = ill->ill_wq;
15661 			}
15662 			break;
15663 		case DL_BIND_REQ:
15664 			ill_dlpi_done(ill, DL_BIND_REQ);
15665 			if (ill->ill_ifname_pending)
15666 				break;
15667 			/*
15668 			 * Something went wrong with the bind.  We presumably
15669 			 * have an IOCTL hanging out waiting for completion.
15670 			 * Find it, take down the interface that was coming
15671 			 * up, and complete the IOCTL with the error noted.
15672 			 */
15673 			if (!ioctl_aborted)
15674 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15675 			if (mp1 != NULL) {
15676 				/*
15677 				 * This operation (SIOCSLIFFLAGS) must have
15678 				 * happened from a conn.
15679 				 */
15680 				ASSERT(connp != NULL);
15681 				q = CONNP_TO_WQ(connp);
15682 				if (ill->ill_move_in_progress) {
15683 					ILL_CLEAR_MOVE(ill);
15684 				}
15685 				(void) ipif_down(ipif, NULL, NULL);
15686 				/* error is set below the switch */
15687 			}
15688 			break;
15689 		case DL_ENABMULTI_REQ:
15690 			if (!ill->ill_isv6)
15691 				ipsq_current_finish(ipsq);
15692 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15693 
15694 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15695 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15696 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15697 				ipif_t *ipif;
15698 
15699 				printf("ip: joining multicasts failed (%d)"
15700 				    " on %s - will use link layer "
15701 				    "broadcasts for multicast\n",
15702 				    dlea->dl_errno, ill->ill_name);
15703 
15704 				/*
15705 				 * Set up the multicast mapping alone.
15706 				 * writer, so ok to access ill->ill_ipif
15707 				 * without any lock.
15708 				 */
15709 				ipif = ill->ill_ipif;
15710 				mutex_enter(&ill->ill_phyint->phyint_lock);
15711 				ill->ill_phyint->phyint_flags |=
15712 				    PHYI_MULTI_BCAST;
15713 				mutex_exit(&ill->ill_phyint->phyint_lock);
15714 
15715 				if (!ill->ill_isv6) {
15716 					(void) ipif_arp_setup_multicast(ipif,
15717 					    NULL);
15718 				} else {
15719 					(void) ipif_ndp_setup_multicast(ipif,
15720 					    NULL);
15721 				}
15722 			}
15723 			freemsg(mp);	/* Don't want to pass this up */
15724 			return;
15725 
15726 		case DL_CAPABILITY_REQ:
15727 		case DL_CONTROL_REQ:
15728 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15729 			ill->ill_dlpi_capab_state = IDS_FAILED;
15730 			freemsg(mp);
15731 			return;
15732 		}
15733 		/*
15734 		 * Note the error for IOCTL completion (mp1 is set when
15735 		 * ready to complete ioctl). If ill_ifname_pending_err is
15736 		 * set, an error occured during plumbing (ill_ifname_pending),
15737 		 * so we want to report that error.
15738 		 *
15739 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15740 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15741 		 * expected to get errack'd if the driver doesn't support
15742 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15743 		 * if these error conditions are encountered.
15744 		 */
15745 		if (mp1 != NULL) {
15746 			if (ill->ill_ifname_pending_err != 0)  {
15747 				err = ill->ill_ifname_pending_err;
15748 				ill->ill_ifname_pending_err = 0;
15749 			} else {
15750 				err = dlea->dl_unix_errno ?
15751 				    dlea->dl_unix_errno : ENXIO;
15752 			}
15753 		/*
15754 		 * If we're plumbing an interface and an error hasn't already
15755 		 * been saved, set ill_ifname_pending_err to the error passed
15756 		 * up. Ignore the error if log is B_FALSE (see comment above).
15757 		 */
15758 		} else if (log && ill->ill_ifname_pending &&
15759 		    ill->ill_ifname_pending_err == 0) {
15760 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15761 			    dlea->dl_unix_errno : ENXIO;
15762 		}
15763 
15764 		if (log)
15765 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15766 			    dlea->dl_errno, dlea->dl_unix_errno);
15767 		break;
15768 	case DL_CAPABILITY_ACK:
15769 		/* Call a routine to handle this one. */
15770 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15771 		ill_capability_ack(ill, mp);
15772 
15773 		/*
15774 		 * If the ack is due to renegotiation, we will need to send
15775 		 * a new CAPABILITY_REQ to start the renegotiation.
15776 		 */
15777 		if (ill->ill_capab_reneg) {
15778 			ill->ill_capab_reneg = B_FALSE;
15779 			ill_capability_probe(ill);
15780 		}
15781 		break;
15782 	case DL_CONTROL_ACK:
15783 		/* We treat all of these as "fire and forget" */
15784 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15785 		break;
15786 	case DL_INFO_ACK:
15787 		/* Call a routine to handle this one. */
15788 		ill_dlpi_done(ill, DL_INFO_REQ);
15789 		ip_ll_subnet_defaults(ill, mp);
15790 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15791 		return;
15792 	case DL_BIND_ACK:
15793 		/*
15794 		 * We should have an IOCTL waiting on this unless
15795 		 * sent by ill_dl_phys, in which case just return
15796 		 */
15797 		ill_dlpi_done(ill, DL_BIND_REQ);
15798 		if (ill->ill_ifname_pending)
15799 			break;
15800 
15801 		if (!ioctl_aborted)
15802 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15803 		if (mp1 == NULL)
15804 			break;
15805 		/*
15806 		 * Because mp1 was added by ill_dl_up(), and it always
15807 		 * passes a valid connp, connp must be valid here.
15808 		 */
15809 		ASSERT(connp != NULL);
15810 		q = CONNP_TO_WQ(connp);
15811 
15812 		/*
15813 		 * We are exclusive. So nothing can change even after
15814 		 * we get the pending mp. If need be we can put it back
15815 		 * and restart, as in calling ipif_arp_up()  below.
15816 		 */
15817 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15818 
15819 		mutex_enter(&ill->ill_lock);
15820 		ill->ill_dl_up = 1;
15821 		(void) ill_hook_event_create(ill, 0, NE_UP, NULL, 0);
15822 		mutex_exit(&ill->ill_lock);
15823 
15824 		/*
15825 		 * Now bring up the resolver; when that is complete, we'll
15826 		 * create IREs.  Note that we intentionally mirror what
15827 		 * ipif_up() would have done, because we got here by way of
15828 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15829 		 */
15830 		if (ill->ill_isv6) {
15831 			/*
15832 			 * v6 interfaces.
15833 			 * Unlike ARP which has to do another bind
15834 			 * and attach, once we get here we are
15835 			 * done with NDP. Except in the case of
15836 			 * ILLF_XRESOLV, in which case we send an
15837 			 * AR_INTERFACE_UP to the external resolver.
15838 			 * If all goes well, the ioctl will complete
15839 			 * in ip_rput(). If there's an error, we
15840 			 * complete it here.
15841 			 */
15842 			if ((err = ipif_ndp_up(ipif)) == 0) {
15843 				if (ill->ill_flags & ILLF_XRESOLV) {
15844 					mutex_enter(&connp->conn_lock);
15845 					mutex_enter(&ill->ill_lock);
15846 					success = ipsq_pending_mp_add(
15847 					    connp, ipif, q, mp1, 0);
15848 					mutex_exit(&ill->ill_lock);
15849 					mutex_exit(&connp->conn_lock);
15850 					if (success) {
15851 						err = ipif_resolver_up(ipif,
15852 						    Res_act_initial);
15853 						if (err == EINPROGRESS) {
15854 							freemsg(mp);
15855 							return;
15856 						}
15857 						ASSERT(err != 0);
15858 						mp1 = ipsq_pending_mp_get(ipsq,
15859 						    &connp);
15860 						ASSERT(mp1 != NULL);
15861 					} else {
15862 						/* conn has started closing */
15863 						err = EINTR;
15864 					}
15865 				} else { /* Non XRESOLV interface */
15866 					(void) ipif_resolver_up(ipif,
15867 					    Res_act_initial);
15868 					err = ipif_up_done_v6(ipif);
15869 				}
15870 			}
15871 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15872 			/*
15873 			 * ARP and other v4 external resolvers.
15874 			 * Leave the pending mblk intact so that
15875 			 * the ioctl completes in ip_rput().
15876 			 */
15877 			mutex_enter(&connp->conn_lock);
15878 			mutex_enter(&ill->ill_lock);
15879 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15880 			mutex_exit(&ill->ill_lock);
15881 			mutex_exit(&connp->conn_lock);
15882 			if (success) {
15883 				err = ipif_resolver_up(ipif, Res_act_initial);
15884 				if (err == EINPROGRESS) {
15885 					freemsg(mp);
15886 					return;
15887 				}
15888 				ASSERT(err != 0);
15889 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15890 			} else {
15891 				/* The conn has started closing */
15892 				err = EINTR;
15893 			}
15894 		} else {
15895 			/*
15896 			 * This one is complete. Reply to pending ioctl.
15897 			 */
15898 			(void) ipif_resolver_up(ipif, Res_act_initial);
15899 			err = ipif_up_done(ipif);
15900 		}
15901 
15902 		if ((err == 0) && (ill->ill_up_ipifs)) {
15903 			err = ill_up_ipifs(ill, q, mp1);
15904 			if (err == EINPROGRESS) {
15905 				freemsg(mp);
15906 				return;
15907 			}
15908 		}
15909 
15910 		if (ill->ill_up_ipifs) {
15911 			ill_group_cleanup(ill);
15912 		}
15913 
15914 		break;
15915 	case DL_NOTIFY_IND: {
15916 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15917 		ire_t *ire;
15918 		boolean_t need_ire_walk_v4 = B_FALSE;
15919 		boolean_t need_ire_walk_v6 = B_FALSE;
15920 
15921 		switch (notify->dl_notification) {
15922 		case DL_NOTE_PHYS_ADDR:
15923 			err = ill_set_phys_addr(ill, mp);
15924 			break;
15925 
15926 		case DL_NOTE_FASTPATH_FLUSH:
15927 			ill_fastpath_flush(ill);
15928 			break;
15929 
15930 		case DL_NOTE_SDU_SIZE:
15931 			/*
15932 			 * Change the MTU size of the interface, of all
15933 			 * attached ipif's, and of all relevant ire's.  The
15934 			 * new value's a uint32_t at notify->dl_data.
15935 			 * Mtu change Vs. new ire creation - protocol below.
15936 			 *
15937 			 * a Mark the ipif as IPIF_CHANGING.
15938 			 * b Set the new mtu in the ipif.
15939 			 * c Change the ire_max_frag on all affected ires
15940 			 * d Unmark the IPIF_CHANGING
15941 			 *
15942 			 * To see how the protocol works, assume an interface
15943 			 * route is also being added simultaneously by
15944 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15945 			 * the ire. If the ire is created before step a,
15946 			 * it will be cleaned up by step c. If the ire is
15947 			 * created after step d, it will see the new value of
15948 			 * ipif_mtu. Any attempt to create the ire between
15949 			 * steps a to d will fail because of the IPIF_CHANGING
15950 			 * flag. Note that ire_create() is passed a pointer to
15951 			 * the ipif_mtu, and not the value. During ire_add
15952 			 * under the bucket lock, the ire_max_frag of the
15953 			 * new ire being created is set from the ipif/ire from
15954 			 * which it is being derived.
15955 			 */
15956 			mutex_enter(&ill->ill_lock);
15957 			ill->ill_max_frag = (uint_t)notify->dl_data;
15958 
15959 			/*
15960 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15961 			 * leave it alone
15962 			 */
15963 			if (ill->ill_mtu_userspecified) {
15964 				mutex_exit(&ill->ill_lock);
15965 				break;
15966 			}
15967 			ill->ill_max_mtu = ill->ill_max_frag;
15968 			if (ill->ill_isv6) {
15969 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15970 					ill->ill_max_mtu = IPV6_MIN_MTU;
15971 			} else {
15972 				if (ill->ill_max_mtu < IP_MIN_MTU)
15973 					ill->ill_max_mtu = IP_MIN_MTU;
15974 			}
15975 			for (ipif = ill->ill_ipif; ipif != NULL;
15976 			    ipif = ipif->ipif_next) {
15977 				/*
15978 				 * Don't override the mtu if the user
15979 				 * has explicitly set it.
15980 				 */
15981 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15982 					continue;
15983 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15984 				if (ipif->ipif_isv6)
15985 					ire = ipif_to_ire_v6(ipif);
15986 				else
15987 					ire = ipif_to_ire(ipif);
15988 				if (ire != NULL) {
15989 					ire->ire_max_frag = ipif->ipif_mtu;
15990 					ire_refrele(ire);
15991 				}
15992 				if (ipif->ipif_flags & IPIF_UP) {
15993 					if (ill->ill_isv6)
15994 						need_ire_walk_v6 = B_TRUE;
15995 					else
15996 						need_ire_walk_v4 = B_TRUE;
15997 				}
15998 			}
15999 			mutex_exit(&ill->ill_lock);
16000 			if (need_ire_walk_v4)
16001 				ire_walk_v4(ill_mtu_change, (char *)ill,
16002 				    ALL_ZONES, ipst);
16003 			if (need_ire_walk_v6)
16004 				ire_walk_v6(ill_mtu_change, (char *)ill,
16005 				    ALL_ZONES, ipst);
16006 			break;
16007 		case DL_NOTE_LINK_UP:
16008 		case DL_NOTE_LINK_DOWN: {
16009 			/*
16010 			 * We are writer. ill / phyint / ipsq assocs stable.
16011 			 * The RUNNING flag reflects the state of the link.
16012 			 */
16013 			phyint_t *phyint = ill->ill_phyint;
16014 			uint64_t new_phyint_flags;
16015 			boolean_t changed = B_FALSE;
16016 			boolean_t went_up;
16017 
16018 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16019 			mutex_enter(&phyint->phyint_lock);
16020 			new_phyint_flags = went_up ?
16021 			    phyint->phyint_flags | PHYI_RUNNING :
16022 			    phyint->phyint_flags & ~PHYI_RUNNING;
16023 			if (new_phyint_flags != phyint->phyint_flags) {
16024 				phyint->phyint_flags = new_phyint_flags;
16025 				changed = B_TRUE;
16026 			}
16027 			mutex_exit(&phyint->phyint_lock);
16028 			/*
16029 			 * ill_restart_dad handles the DAD restart and routing
16030 			 * socket notification logic.
16031 			 */
16032 			if (changed) {
16033 				ill_restart_dad(phyint->phyint_illv4, went_up);
16034 				ill_restart_dad(phyint->phyint_illv6, went_up);
16035 			}
16036 			break;
16037 		}
16038 		case DL_NOTE_PROMISC_ON_PHYS:
16039 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16040 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16041 			mutex_enter(&ill->ill_lock);
16042 			ill->ill_promisc_on_phys = B_TRUE;
16043 			mutex_exit(&ill->ill_lock);
16044 			break;
16045 		case DL_NOTE_PROMISC_OFF_PHYS:
16046 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16047 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16048 			mutex_enter(&ill->ill_lock);
16049 			ill->ill_promisc_on_phys = B_FALSE;
16050 			mutex_exit(&ill->ill_lock);
16051 			break;
16052 		case DL_NOTE_CAPAB_RENEG:
16053 			/*
16054 			 * Something changed on the driver side.
16055 			 * It wants us to renegotiate the capabilities
16056 			 * on this ill. One possible cause is the aggregation
16057 			 * interface under us where a port got added or
16058 			 * went away.
16059 			 *
16060 			 * If the capability negotiation is already done
16061 			 * or is in progress, reset the capabilities and
16062 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16063 			 * so that when the ack comes back, we can start
16064 			 * the renegotiation process.
16065 			 *
16066 			 * Note that if ill_capab_reneg is already B_TRUE
16067 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16068 			 * the capability resetting request has been sent
16069 			 * and the renegotiation has not been started yet;
16070 			 * nothing needs to be done in this case.
16071 			 */
16072 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16073 				ill_capability_reset(ill);
16074 				ill->ill_capab_reneg = B_TRUE;
16075 			}
16076 			break;
16077 		default:
16078 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16079 			    "type 0x%x for DL_NOTIFY_IND\n",
16080 			    notify->dl_notification));
16081 			break;
16082 		}
16083 
16084 		/*
16085 		 * As this is an asynchronous operation, we
16086 		 * should not call ill_dlpi_done
16087 		 */
16088 		break;
16089 	}
16090 	case DL_NOTIFY_ACK: {
16091 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16092 
16093 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16094 			ill->ill_note_link = 1;
16095 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16096 		break;
16097 	}
16098 	case DL_PHYS_ADDR_ACK: {
16099 		/*
16100 		 * As part of plumbing the interface via SIOCSLIFNAME,
16101 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16102 		 * whose answers we receive here.  As each answer is received,
16103 		 * we call ill_dlpi_done() to dispatch the next request as
16104 		 * we're processing the current one.  Once all answers have
16105 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16106 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16107 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16108 		 * available, but we know the ioctl is pending on ill_wq.)
16109 		 */
16110 		uint_t paddrlen, paddroff;
16111 
16112 		paddrreq = ill->ill_phys_addr_pend;
16113 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16114 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16115 
16116 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16117 		if (paddrreq == DL_IPV6_TOKEN) {
16118 			/*
16119 			 * bcopy to low-order bits of ill_token
16120 			 *
16121 			 * XXX Temporary hack - currently, all known tokens
16122 			 * are 64 bits, so I'll cheat for the moment.
16123 			 */
16124 			bcopy(mp->b_rptr + paddroff,
16125 			    &ill->ill_token.s6_addr32[2], paddrlen);
16126 			ill->ill_token_length = paddrlen;
16127 			break;
16128 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16129 			ASSERT(ill->ill_nd_lla_mp == NULL);
16130 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16131 			mp = NULL;
16132 			break;
16133 		}
16134 
16135 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16136 		ASSERT(ill->ill_phys_addr_mp == NULL);
16137 		if (!ill->ill_ifname_pending)
16138 			break;
16139 		ill->ill_ifname_pending = 0;
16140 		if (!ioctl_aborted)
16141 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16142 		if (mp1 != NULL) {
16143 			ASSERT(connp == NULL);
16144 			q = ill->ill_wq;
16145 		}
16146 		/*
16147 		 * If any error acks received during the plumbing sequence,
16148 		 * ill_ifname_pending_err will be set. Break out and send up
16149 		 * the error to the pending ioctl.
16150 		 */
16151 		if (ill->ill_ifname_pending_err != 0) {
16152 			err = ill->ill_ifname_pending_err;
16153 			ill->ill_ifname_pending_err = 0;
16154 			break;
16155 		}
16156 
16157 		ill->ill_phys_addr_mp = mp;
16158 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16159 		mp = NULL;
16160 
16161 		/*
16162 		 * If paddrlen is zero, the DLPI provider doesn't support
16163 		 * physical addresses.  The other two tests were historical
16164 		 * workarounds for bugs in our former PPP implementation, but
16165 		 * now other things have grown dependencies on them -- e.g.,
16166 		 * the tun module specifies a dl_addr_length of zero in its
16167 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16168 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16169 		 * but only after careful testing ensures that all dependent
16170 		 * broken DLPI providers have been fixed.
16171 		 */
16172 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16173 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16174 			ill->ill_phys_addr = NULL;
16175 		} else if (paddrlen != ill->ill_phys_addr_length) {
16176 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16177 			    paddrlen, ill->ill_phys_addr_length));
16178 			err = EINVAL;
16179 			break;
16180 		}
16181 
16182 		if (ill->ill_nd_lla_mp == NULL) {
16183 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16184 				err = ENOMEM;
16185 				break;
16186 			}
16187 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16188 		}
16189 
16190 		/*
16191 		 * Set the interface token.  If the zeroth interface address
16192 		 * is unspecified, then set it to the link local address.
16193 		 */
16194 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16195 			(void) ill_setdefaulttoken(ill);
16196 
16197 		ASSERT(ill->ill_ipif->ipif_id == 0);
16198 		if (ipif != NULL &&
16199 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16200 			(void) ipif_setlinklocal(ipif);
16201 		}
16202 		break;
16203 	}
16204 	case DL_OK_ACK:
16205 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16206 		    dl_primstr((int)dloa->dl_correct_primitive),
16207 		    dloa->dl_correct_primitive));
16208 		switch (dloa->dl_correct_primitive) {
16209 		case DL_ENABMULTI_REQ:
16210 		case DL_DISABMULTI_REQ:
16211 			if (!ill->ill_isv6)
16212 				ipsq_current_finish(ipsq);
16213 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16214 			break;
16215 		case DL_PROMISCON_REQ:
16216 		case DL_PROMISCOFF_REQ:
16217 		case DL_UNBIND_REQ:
16218 		case DL_ATTACH_REQ:
16219 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16220 			break;
16221 		}
16222 		break;
16223 	default:
16224 		break;
16225 	}
16226 
16227 	freemsg(mp);
16228 	if (mp1 != NULL) {
16229 		/*
16230 		 * The operation must complete without EINPROGRESS
16231 		 * since ipsq_pending_mp_get() has removed the mblk
16232 		 * from ipsq_pending_mp.  Otherwise, the operation
16233 		 * will be stuck forever in the ipsq.
16234 		 */
16235 		ASSERT(err != EINPROGRESS);
16236 
16237 		switch (ipsq->ipsq_current_ioctl) {
16238 		case 0:
16239 			ipsq_current_finish(ipsq);
16240 			break;
16241 
16242 		case SIOCLIFADDIF:
16243 		case SIOCSLIFNAME:
16244 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16245 			break;
16246 
16247 		default:
16248 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16249 			break;
16250 		}
16251 	}
16252 }
16253 
16254 /*
16255  * ip_rput_other is called by ip_rput to handle messages modifying the global
16256  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16257  */
16258 /* ARGSUSED */
16259 void
16260 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16261 {
16262 	ill_t		*ill;
16263 	struct iocblk	*iocp;
16264 	mblk_t		*mp1;
16265 	conn_t		*connp = NULL;
16266 
16267 	ip1dbg(("ip_rput_other "));
16268 	ill = (ill_t *)q->q_ptr;
16269 	/*
16270 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16271 	 * in which case ipsq is NULL.
16272 	 */
16273 	if (ipsq != NULL) {
16274 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16275 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16276 	}
16277 
16278 	switch (mp->b_datap->db_type) {
16279 	case M_ERROR:
16280 	case M_HANGUP:
16281 		/*
16282 		 * The device has a problem.  We force the ILL down.  It can
16283 		 * be brought up again manually using SIOCSIFFLAGS (via
16284 		 * ifconfig or equivalent).
16285 		 */
16286 		ASSERT(ipsq != NULL);
16287 		if (mp->b_rptr < mp->b_wptr)
16288 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16289 		if (ill->ill_error == 0)
16290 			ill->ill_error = ENXIO;
16291 		if (!ill_down_start(q, mp))
16292 			return;
16293 		ipif_all_down_tail(ipsq, q, mp, NULL);
16294 		break;
16295 	case M_IOCACK:
16296 		iocp = (struct iocblk *)mp->b_rptr;
16297 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16298 		switch (iocp->ioc_cmd) {
16299 		case SIOCSTUNPARAM:
16300 		case OSIOCSTUNPARAM:
16301 			ASSERT(ipsq != NULL);
16302 			/*
16303 			 * Finish socket ioctl passed through to tun.
16304 			 * We should have an IOCTL waiting on this.
16305 			 */
16306 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16307 			if (ill->ill_isv6) {
16308 				struct iftun_req *ta;
16309 
16310 				/*
16311 				 * if a source or destination is
16312 				 * being set, try and set the link
16313 				 * local address for the tunnel
16314 				 */
16315 				ta = (struct iftun_req *)mp->b_cont->
16316 				    b_cont->b_rptr;
16317 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16318 					ipif_set_tun_llink(ill, ta);
16319 				}
16320 
16321 			}
16322 			if (mp1 != NULL) {
16323 				/*
16324 				 * Now copy back the b_next/b_prev used by
16325 				 * mi code for the mi_copy* functions.
16326 				 * See ip_sioctl_tunparam() for the reason.
16327 				 * Also protect against missing b_cont.
16328 				 */
16329 				if (mp->b_cont != NULL) {
16330 					mp->b_cont->b_next =
16331 					    mp1->b_cont->b_next;
16332 					mp->b_cont->b_prev =
16333 					    mp1->b_cont->b_prev;
16334 				}
16335 				inet_freemsg(mp1);
16336 				ASSERT(connp != NULL);
16337 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16338 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16339 			} else {
16340 				ASSERT(connp == NULL);
16341 				putnext(q, mp);
16342 			}
16343 			break;
16344 		case SIOCGTUNPARAM:
16345 		case OSIOCGTUNPARAM:
16346 			/*
16347 			 * This is really M_IOCDATA from the tunnel driver.
16348 			 * convert back and complete the ioctl.
16349 			 * We should have an IOCTL waiting on this.
16350 			 */
16351 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16352 			if (mp1) {
16353 				/*
16354 				 * Now copy back the b_next/b_prev used by
16355 				 * mi code for the mi_copy* functions.
16356 				 * See ip_sioctl_tunparam() for the reason.
16357 				 * Also protect against missing b_cont.
16358 				 */
16359 				if (mp->b_cont != NULL) {
16360 					mp->b_cont->b_next =
16361 					    mp1->b_cont->b_next;
16362 					mp->b_cont->b_prev =
16363 					    mp1->b_cont->b_prev;
16364 				}
16365 				inet_freemsg(mp1);
16366 				if (iocp->ioc_error == 0)
16367 					mp->b_datap->db_type = M_IOCDATA;
16368 				ASSERT(connp != NULL);
16369 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16370 				    iocp->ioc_error, COPYOUT, NULL);
16371 			} else {
16372 				ASSERT(connp == NULL);
16373 				putnext(q, mp);
16374 			}
16375 			break;
16376 		default:
16377 			break;
16378 		}
16379 		break;
16380 	case M_IOCNAK:
16381 		iocp = (struct iocblk *)mp->b_rptr;
16382 
16383 		switch (iocp->ioc_cmd) {
16384 		int mode;
16385 
16386 		case DL_IOC_HDR_INFO:
16387 			/*
16388 			 * If this was the first attempt turn of the
16389 			 * fastpath probing.
16390 			 */
16391 			mutex_enter(&ill->ill_lock);
16392 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16393 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16394 				mutex_exit(&ill->ill_lock);
16395 				ill_fastpath_nack(ill);
16396 				ip1dbg(("ip_rput: DLPI fastpath off on "
16397 				    "interface %s\n",
16398 				    ill->ill_name));
16399 			} else {
16400 				mutex_exit(&ill->ill_lock);
16401 			}
16402 			freemsg(mp);
16403 			break;
16404 		case SIOCSTUNPARAM:
16405 		case OSIOCSTUNPARAM:
16406 			ASSERT(ipsq != NULL);
16407 			/*
16408 			 * Finish socket ioctl passed through to tun
16409 			 * We should have an IOCTL waiting on this.
16410 			 */
16411 			/* FALLTHRU */
16412 		case SIOCGTUNPARAM:
16413 		case OSIOCGTUNPARAM:
16414 			/*
16415 			 * This is really M_IOCDATA from the tunnel driver.
16416 			 * convert back and complete the ioctl.
16417 			 * We should have an IOCTL waiting on this.
16418 			 */
16419 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16420 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16421 				mp1 = ill_pending_mp_get(ill, &connp,
16422 				    iocp->ioc_id);
16423 				mode = COPYOUT;
16424 				ipsq = NULL;
16425 			} else {
16426 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16427 				mode = NO_COPYOUT;
16428 			}
16429 			if (mp1 != NULL) {
16430 				/*
16431 				 * Now copy back the b_next/b_prev used by
16432 				 * mi code for the mi_copy* functions.
16433 				 * See ip_sioctl_tunparam() for the reason.
16434 				 * Also protect against missing b_cont.
16435 				 */
16436 				if (mp->b_cont != NULL) {
16437 					mp->b_cont->b_next =
16438 					    mp1->b_cont->b_next;
16439 					mp->b_cont->b_prev =
16440 					    mp1->b_cont->b_prev;
16441 				}
16442 				inet_freemsg(mp1);
16443 				if (iocp->ioc_error == 0)
16444 					iocp->ioc_error = EINVAL;
16445 				ASSERT(connp != NULL);
16446 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16447 				    iocp->ioc_error, mode, ipsq);
16448 			} else {
16449 				ASSERT(connp == NULL);
16450 				putnext(q, mp);
16451 			}
16452 			break;
16453 		default:
16454 			break;
16455 		}
16456 	default:
16457 		break;
16458 	}
16459 }
16460 
16461 /*
16462  * NOTE : This function does not ire_refrele the ire argument passed in.
16463  *
16464  * IPQoS notes
16465  * IP policy is invoked twice for a forwarded packet, once on the read side
16466  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16467  * enabled. An additional parameter, in_ill, has been added for this purpose.
16468  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16469  * because ip_mroute drops this information.
16470  *
16471  */
16472 void
16473 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16474 {
16475 	uint32_t	old_pkt_len;
16476 	uint32_t	pkt_len;
16477 	queue_t	*q;
16478 	uint32_t	sum;
16479 #define	rptr	((uchar_t *)ipha)
16480 	uint32_t	max_frag;
16481 	uint32_t	ill_index;
16482 	ill_t		*out_ill;
16483 	mib2_ipIfStatsEntry_t *mibptr;
16484 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16485 
16486 	/* Get the ill_index of the incoming ILL */
16487 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16488 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16489 
16490 	/* Initiate Read side IPPF processing */
16491 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16492 		ip_process(IPP_FWD_IN, &mp, ill_index);
16493 		if (mp == NULL) {
16494 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16495 			    "during IPPF processing\n"));
16496 			return;
16497 		}
16498 	}
16499 
16500 	/* Adjust the checksum to reflect the ttl decrement. */
16501 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16502 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16503 
16504 	if (ipha->ipha_ttl-- <= 1) {
16505 		if (ip_csum_hdr(ipha)) {
16506 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16507 			goto drop_pkt;
16508 		}
16509 		/*
16510 		 * Note: ire_stq this will be NULL for multicast
16511 		 * datagrams using the long path through arp (the IRE
16512 		 * is not an IRE_CACHE). This should not cause
16513 		 * problems since we don't generate ICMP errors for
16514 		 * multicast packets.
16515 		 */
16516 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16517 		q = ire->ire_stq;
16518 		if (q != NULL) {
16519 			/* Sent by forwarding path, and router is global zone */
16520 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16521 			    GLOBAL_ZONEID, ipst);
16522 		} else
16523 			freemsg(mp);
16524 		return;
16525 	}
16526 
16527 	/*
16528 	 * Don't forward if the interface is down
16529 	 */
16530 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16531 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16532 		ip2dbg(("ip_rput_forward:interface is down\n"));
16533 		goto drop_pkt;
16534 	}
16535 
16536 	/* Get the ill_index of the outgoing ILL */
16537 	out_ill = ire_to_ill(ire);
16538 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16539 
16540 	DTRACE_PROBE4(ip4__forwarding__start,
16541 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16542 
16543 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16544 	    ipst->ips_ipv4firewall_forwarding,
16545 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16546 
16547 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16548 
16549 	if (mp == NULL)
16550 		return;
16551 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16552 
16553 	if (is_system_labeled()) {
16554 		mblk_t *mp1;
16555 
16556 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16557 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16558 			goto drop_pkt;
16559 		}
16560 		/* Size may have changed */
16561 		mp = mp1;
16562 		ipha = (ipha_t *)mp->b_rptr;
16563 		pkt_len = ntohs(ipha->ipha_length);
16564 	}
16565 
16566 	/* Check if there are options to update */
16567 	if (!IS_SIMPLE_IPH(ipha)) {
16568 		if (ip_csum_hdr(ipha)) {
16569 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16570 			goto drop_pkt;
16571 		}
16572 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16573 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16574 			return;
16575 		}
16576 
16577 		ipha->ipha_hdr_checksum = 0;
16578 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16579 	}
16580 	max_frag = ire->ire_max_frag;
16581 	if (pkt_len > max_frag) {
16582 		/*
16583 		 * It needs fragging on its way out.  We haven't
16584 		 * verified the header checksum yet.  Since we
16585 		 * are going to put a surely good checksum in the
16586 		 * outgoing header, we have to make sure that it
16587 		 * was good coming in.
16588 		 */
16589 		if (ip_csum_hdr(ipha)) {
16590 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16591 			goto drop_pkt;
16592 		}
16593 		/* Initiate Write side IPPF processing */
16594 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16595 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16596 			if (mp == NULL) {
16597 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16598 				    " during IPPF processing\n"));
16599 				return;
16600 			}
16601 		}
16602 		/*
16603 		 * Handle labeled packet resizing.
16604 		 *
16605 		 * If we have added a label, inform ip_wput_frag() of its
16606 		 * effect on the MTU for ICMP messages.
16607 		 */
16608 		if (pkt_len > old_pkt_len) {
16609 			uint32_t secopt_size;
16610 
16611 			secopt_size = pkt_len - old_pkt_len;
16612 			if (secopt_size < max_frag)
16613 				max_frag -= secopt_size;
16614 		}
16615 
16616 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16617 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16618 		return;
16619 	}
16620 
16621 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16622 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16623 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16624 	    ipst->ips_ipv4firewall_physical_out,
16625 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16626 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16627 	if (mp == NULL)
16628 		return;
16629 
16630 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16631 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16632 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16633 	/* ip_xmit_v4 always consumes the packet */
16634 	return;
16635 
16636 drop_pkt:;
16637 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16638 	freemsg(mp);
16639 #undef	rptr
16640 }
16641 
16642 void
16643 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16644 {
16645 	ire_t	*ire;
16646 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16647 
16648 	ASSERT(!ipif->ipif_isv6);
16649 	/*
16650 	 * Find an IRE which matches the destination and the outgoing
16651 	 * queue in the cache table. All we need is an IRE_CACHE which
16652 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16653 	 * then it is enough to have some IRE_CACHE in the group.
16654 	 */
16655 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16656 		dst = ipif->ipif_pp_dst_addr;
16657 
16658 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16659 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16660 	if (ire == NULL) {
16661 		/*
16662 		 * Mark this packet to make it be delivered to
16663 		 * ip_rput_forward after the new ire has been
16664 		 * created.
16665 		 */
16666 		mp->b_prev = NULL;
16667 		mp->b_next = mp;
16668 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16669 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16670 	} else {
16671 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16672 		IRE_REFRELE(ire);
16673 	}
16674 }
16675 
16676 /* Update any source route, record route or timestamp options */
16677 static int
16678 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16679 {
16680 	ipoptp_t	opts;
16681 	uchar_t		*opt;
16682 	uint8_t		optval;
16683 	uint8_t		optlen;
16684 	ipaddr_t	dst;
16685 	uint32_t	ts;
16686 	ire_t		*dst_ire = NULL;
16687 	ire_t		*tmp_ire = NULL;
16688 	timestruc_t	now;
16689 
16690 	ip2dbg(("ip_rput_forward_options\n"));
16691 	dst = ipha->ipha_dst;
16692 	for (optval = ipoptp_first(&opts, ipha);
16693 	    optval != IPOPT_EOL;
16694 	    optval = ipoptp_next(&opts)) {
16695 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16696 		opt = opts.ipoptp_cur;
16697 		optlen = opts.ipoptp_len;
16698 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16699 		    optval, opts.ipoptp_len));
16700 		switch (optval) {
16701 			uint32_t off;
16702 		case IPOPT_SSRR:
16703 		case IPOPT_LSRR:
16704 			/* Check if adminstratively disabled */
16705 			if (!ipst->ips_ip_forward_src_routed) {
16706 				if (ire->ire_stq != NULL) {
16707 					/*
16708 					 * Sent by forwarding path, and router
16709 					 * is global zone
16710 					 */
16711 					icmp_unreachable(ire->ire_stq, mp,
16712 					    ICMP_SOURCE_ROUTE_FAILED,
16713 					    GLOBAL_ZONEID, ipst);
16714 				} else {
16715 					ip0dbg(("ip_rput_forward_options: "
16716 					    "unable to send unreach\n"));
16717 					freemsg(mp);
16718 				}
16719 				return (-1);
16720 			}
16721 
16722 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16723 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16724 			if (dst_ire == NULL) {
16725 				/*
16726 				 * Must be partial since ip_rput_options
16727 				 * checked for strict.
16728 				 */
16729 				break;
16730 			}
16731 			off = opt[IPOPT_OFFSET];
16732 			off--;
16733 		redo_srr:
16734 			if (optlen < IP_ADDR_LEN ||
16735 			    off > optlen - IP_ADDR_LEN) {
16736 				/* End of source route */
16737 				ip1dbg((
16738 				    "ip_rput_forward_options: end of SR\n"));
16739 				ire_refrele(dst_ire);
16740 				break;
16741 			}
16742 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16743 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16744 			    IP_ADDR_LEN);
16745 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16746 			    ntohl(dst)));
16747 
16748 			/*
16749 			 * Check if our address is present more than
16750 			 * once as consecutive hops in source route.
16751 			 */
16752 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16753 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16754 			if (tmp_ire != NULL) {
16755 				ire_refrele(tmp_ire);
16756 				off += IP_ADDR_LEN;
16757 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16758 				goto redo_srr;
16759 			}
16760 			ipha->ipha_dst = dst;
16761 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16762 			ire_refrele(dst_ire);
16763 			break;
16764 		case IPOPT_RR:
16765 			off = opt[IPOPT_OFFSET];
16766 			off--;
16767 			if (optlen < IP_ADDR_LEN ||
16768 			    off > optlen - IP_ADDR_LEN) {
16769 				/* No more room - ignore */
16770 				ip1dbg((
16771 				    "ip_rput_forward_options: end of RR\n"));
16772 				break;
16773 			}
16774 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16775 			    IP_ADDR_LEN);
16776 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16777 			break;
16778 		case IPOPT_TS:
16779 			/* Insert timestamp if there is room */
16780 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16781 			case IPOPT_TS_TSONLY:
16782 				off = IPOPT_TS_TIMELEN;
16783 				break;
16784 			case IPOPT_TS_PRESPEC:
16785 			case IPOPT_TS_PRESPEC_RFC791:
16786 				/* Verify that the address matched */
16787 				off = opt[IPOPT_OFFSET] - 1;
16788 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16789 				dst_ire = ire_ctable_lookup(dst, 0,
16790 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16791 				    MATCH_IRE_TYPE, ipst);
16792 				if (dst_ire == NULL) {
16793 					/* Not for us */
16794 					break;
16795 				}
16796 				ire_refrele(dst_ire);
16797 				/* FALLTHRU */
16798 			case IPOPT_TS_TSANDADDR:
16799 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16800 				break;
16801 			default:
16802 				/*
16803 				 * ip_*put_options should have already
16804 				 * dropped this packet.
16805 				 */
16806 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16807 				    "unknown IT - bug in ip_rput_options?\n");
16808 				return (0);	/* Keep "lint" happy */
16809 			}
16810 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16811 				/* Increase overflow counter */
16812 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16813 				opt[IPOPT_POS_OV_FLG] =
16814 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16815 				    (off << 4));
16816 				break;
16817 			}
16818 			off = opt[IPOPT_OFFSET] - 1;
16819 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16820 			case IPOPT_TS_PRESPEC:
16821 			case IPOPT_TS_PRESPEC_RFC791:
16822 			case IPOPT_TS_TSANDADDR:
16823 				bcopy(&ire->ire_src_addr,
16824 				    (char *)opt + off, IP_ADDR_LEN);
16825 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16826 				/* FALLTHRU */
16827 			case IPOPT_TS_TSONLY:
16828 				off = opt[IPOPT_OFFSET] - 1;
16829 				/* Compute # of milliseconds since midnight */
16830 				gethrestime(&now);
16831 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16832 				    now.tv_nsec / (NANOSEC / MILLISEC);
16833 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16834 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16835 				break;
16836 			}
16837 			break;
16838 		}
16839 	}
16840 	return (0);
16841 }
16842 
16843 /*
16844  * This is called after processing at least one of AH/ESP headers.
16845  *
16846  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16847  * the actual, physical interface on which the packet was received,
16848  * but, when ip_strict_dst_multihoming is set to 1, could be the
16849  * interface which had the ipha_dst configured when the packet went
16850  * through ip_rput. The ill_index corresponding to the recv_ill
16851  * is saved in ipsec_in_rill_index
16852  *
16853  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16854  * cannot assume "ire" points to valid data for any IPv6 cases.
16855  */
16856 void
16857 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16858 {
16859 	mblk_t *mp;
16860 	ipaddr_t dst;
16861 	in6_addr_t *v6dstp;
16862 	ipha_t *ipha;
16863 	ip6_t *ip6h;
16864 	ipsec_in_t *ii;
16865 	boolean_t ill_need_rele = B_FALSE;
16866 	boolean_t rill_need_rele = B_FALSE;
16867 	boolean_t ire_need_rele = B_FALSE;
16868 	netstack_t	*ns;
16869 	ip_stack_t	*ipst;
16870 
16871 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16872 	ASSERT(ii->ipsec_in_ill_index != 0);
16873 	ns = ii->ipsec_in_ns;
16874 	ASSERT(ii->ipsec_in_ns != NULL);
16875 	ipst = ns->netstack_ip;
16876 
16877 	mp = ipsec_mp->b_cont;
16878 	ASSERT(mp != NULL);
16879 
16880 
16881 	if (ill == NULL) {
16882 		ASSERT(recv_ill == NULL);
16883 		/*
16884 		 * We need to get the original queue on which ip_rput_local
16885 		 * or ip_rput_data_v6 was called.
16886 		 */
16887 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16888 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16889 		ill_need_rele = B_TRUE;
16890 
16891 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16892 			recv_ill = ill_lookup_on_ifindex(
16893 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16894 			    NULL, NULL, NULL, NULL, ipst);
16895 			rill_need_rele = B_TRUE;
16896 		} else {
16897 			recv_ill = ill;
16898 		}
16899 
16900 		if ((ill == NULL) || (recv_ill == NULL)) {
16901 			ip0dbg(("ip_fanout_proto_again: interface "
16902 			    "disappeared\n"));
16903 			if (ill != NULL)
16904 				ill_refrele(ill);
16905 			if (recv_ill != NULL)
16906 				ill_refrele(recv_ill);
16907 			freemsg(ipsec_mp);
16908 			return;
16909 		}
16910 	}
16911 
16912 	ASSERT(ill != NULL && recv_ill != NULL);
16913 
16914 	if (mp->b_datap->db_type == M_CTL) {
16915 		/*
16916 		 * AH/ESP is returning the ICMP message after
16917 		 * removing their headers. Fanout again till
16918 		 * it gets to the right protocol.
16919 		 */
16920 		if (ii->ipsec_in_v4) {
16921 			icmph_t *icmph;
16922 			int iph_hdr_length;
16923 			int hdr_length;
16924 
16925 			ipha = (ipha_t *)mp->b_rptr;
16926 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16927 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16928 			ipha = (ipha_t *)&icmph[1];
16929 			hdr_length = IPH_HDR_LENGTH(ipha);
16930 			/*
16931 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16932 			 * Reset the type to M_DATA.
16933 			 */
16934 			mp->b_datap->db_type = M_DATA;
16935 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16936 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16937 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16938 		} else {
16939 			icmp6_t *icmp6;
16940 			int hdr_length;
16941 
16942 			ip6h = (ip6_t *)mp->b_rptr;
16943 			/* Don't call hdr_length_v6() unless you have to. */
16944 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16945 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16946 			else
16947 				hdr_length = IPV6_HDR_LEN;
16948 
16949 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16950 			/*
16951 			 * icmp_inbound_error_fanout_v6 may need to do
16952 			 * pullupmsg.  Reset the type to M_DATA.
16953 			 */
16954 			mp->b_datap->db_type = M_DATA;
16955 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16956 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16957 		}
16958 		if (ill_need_rele)
16959 			ill_refrele(ill);
16960 		if (rill_need_rele)
16961 			ill_refrele(recv_ill);
16962 		return;
16963 	}
16964 
16965 	if (ii->ipsec_in_v4) {
16966 		ipha = (ipha_t *)mp->b_rptr;
16967 		dst = ipha->ipha_dst;
16968 		if (CLASSD(dst)) {
16969 			/*
16970 			 * Multicast has to be delivered to all streams.
16971 			 */
16972 			dst = INADDR_BROADCAST;
16973 		}
16974 
16975 		if (ire == NULL) {
16976 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16977 			    MBLK_GETLABEL(mp), ipst);
16978 			if (ire == NULL) {
16979 				if (ill_need_rele)
16980 					ill_refrele(ill);
16981 				if (rill_need_rele)
16982 					ill_refrele(recv_ill);
16983 				ip1dbg(("ip_fanout_proto_again: "
16984 				    "IRE not found"));
16985 				freemsg(ipsec_mp);
16986 				return;
16987 			}
16988 			ire_need_rele = B_TRUE;
16989 		}
16990 
16991 		switch (ipha->ipha_protocol) {
16992 			case IPPROTO_UDP:
16993 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16994 				    recv_ill);
16995 				if (ire_need_rele)
16996 					ire_refrele(ire);
16997 				break;
16998 			case IPPROTO_TCP:
16999 				if (!ire_need_rele)
17000 					IRE_REFHOLD(ire);
17001 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17002 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17003 				IRE_REFRELE(ire);
17004 				if (mp != NULL)
17005 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17006 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17007 				break;
17008 			case IPPROTO_SCTP:
17009 				if (!ire_need_rele)
17010 					IRE_REFHOLD(ire);
17011 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17012 				    ipsec_mp, 0, ill->ill_rq, dst);
17013 				break;
17014 			default:
17015 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17016 				    recv_ill, 0);
17017 				if (ire_need_rele)
17018 					ire_refrele(ire);
17019 				break;
17020 		}
17021 	} else {
17022 		uint32_t rput_flags = 0;
17023 
17024 		ip6h = (ip6_t *)mp->b_rptr;
17025 		v6dstp = &ip6h->ip6_dst;
17026 		/*
17027 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17028 		 * address.
17029 		 *
17030 		 * Currently, we don't store that state in the IPSEC_IN
17031 		 * message, and we may need to.
17032 		 */
17033 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17034 		    IP6_IN_LLMCAST : 0);
17035 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17036 		    NULL, NULL);
17037 	}
17038 	if (ill_need_rele)
17039 		ill_refrele(ill);
17040 	if (rill_need_rele)
17041 		ill_refrele(recv_ill);
17042 }
17043 
17044 /*
17045  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17046  * returns 'true' if there are still fragments left on the queue, in
17047  * which case we restart the timer.
17048  */
17049 void
17050 ill_frag_timer(void *arg)
17051 {
17052 	ill_t	*ill = (ill_t *)arg;
17053 	boolean_t frag_pending;
17054 	ip_stack_t	*ipst = ill->ill_ipst;
17055 
17056 	mutex_enter(&ill->ill_lock);
17057 	ASSERT(!ill->ill_fragtimer_executing);
17058 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17059 		ill->ill_frag_timer_id = 0;
17060 		mutex_exit(&ill->ill_lock);
17061 		return;
17062 	}
17063 	ill->ill_fragtimer_executing = 1;
17064 	mutex_exit(&ill->ill_lock);
17065 
17066 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17067 
17068 	/*
17069 	 * Restart the timer, if we have fragments pending or if someone
17070 	 * wanted us to be scheduled again.
17071 	 */
17072 	mutex_enter(&ill->ill_lock);
17073 	ill->ill_fragtimer_executing = 0;
17074 	ill->ill_frag_timer_id = 0;
17075 	if (frag_pending || ill->ill_fragtimer_needrestart)
17076 		ill_frag_timer_start(ill);
17077 	mutex_exit(&ill->ill_lock);
17078 }
17079 
17080 void
17081 ill_frag_timer_start(ill_t *ill)
17082 {
17083 	ip_stack_t	*ipst = ill->ill_ipst;
17084 
17085 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17086 
17087 	/* If the ill is closing or opening don't proceed */
17088 	if (ill->ill_state_flags & ILL_CONDEMNED)
17089 		return;
17090 
17091 	if (ill->ill_fragtimer_executing) {
17092 		/*
17093 		 * ill_frag_timer is currently executing. Just record the
17094 		 * the fact that we want the timer to be restarted.
17095 		 * ill_frag_timer will post a timeout before it returns,
17096 		 * ensuring it will be called again.
17097 		 */
17098 		ill->ill_fragtimer_needrestart = 1;
17099 		return;
17100 	}
17101 
17102 	if (ill->ill_frag_timer_id == 0) {
17103 		/*
17104 		 * The timer is neither running nor is the timeout handler
17105 		 * executing. Post a timeout so that ill_frag_timer will be
17106 		 * called
17107 		 */
17108 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17109 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17110 		ill->ill_fragtimer_needrestart = 0;
17111 	}
17112 }
17113 
17114 /*
17115  * This routine is needed for loopback when forwarding multicasts.
17116  *
17117  * IPQoS Notes:
17118  * IPPF processing is done in fanout routines.
17119  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17120  * processing for IPsec packets is done when it comes back in clear.
17121  * NOTE : The callers of this function need to do the ire_refrele for the
17122  *	  ire that is being passed in.
17123  */
17124 void
17125 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17126     ill_t *recv_ill, uint32_t esp_udp_ports)
17127 {
17128 	boolean_t esp_in_udp_packet = (esp_udp_ports != 0);
17129 	ill_t	*ill = (ill_t *)q->q_ptr;
17130 	uint32_t	sum;
17131 	uint32_t	u1;
17132 	uint32_t	u2;
17133 	int		hdr_length;
17134 	boolean_t	mctl_present;
17135 	mblk_t		*first_mp = mp;
17136 	mblk_t		*hada_mp = NULL;
17137 	ipha_t		*inner_ipha;
17138 	ip_stack_t	*ipst;
17139 
17140 	ASSERT(recv_ill != NULL);
17141 	ipst = recv_ill->ill_ipst;
17142 
17143 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17144 	    "ip_rput_locl_start: q %p", q);
17145 
17146 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17147 	ASSERT(ill != NULL);
17148 
17149 
17150 #define	rptr	((uchar_t *)ipha)
17151 #define	iphs	((uint16_t *)ipha)
17152 
17153 	/*
17154 	 * no UDP or TCP packet should come here anymore.
17155 	 */
17156 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17157 	    ipha->ipha_protocol != IPPROTO_UDP);
17158 
17159 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17160 	if (mctl_present &&
17161 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17162 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17163 
17164 		/*
17165 		 * It's an IPsec accelerated packet.
17166 		 * Keep a pointer to the data attributes around until
17167 		 * we allocate the ipsec_info_t.
17168 		 */
17169 		IPSECHW_DEBUG(IPSECHW_PKT,
17170 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17171 		hada_mp = first_mp;
17172 		hada_mp->b_cont = NULL;
17173 		/*
17174 		 * Since it is accelerated, it comes directly from
17175 		 * the ill and the data attributes is followed by
17176 		 * the packet data.
17177 		 */
17178 		ASSERT(mp->b_datap->db_type != M_CTL);
17179 		first_mp = mp;
17180 		mctl_present = B_FALSE;
17181 	}
17182 
17183 	/*
17184 	 * IF M_CTL is not present, then ipsec_in_is_secure
17185 	 * should return B_TRUE. There is a case where loopback
17186 	 * packets has an M_CTL in the front with all the
17187 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17188 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17189 	 * packets never comes here, it is safe to ASSERT the
17190 	 * following.
17191 	 */
17192 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17193 
17194 	/*
17195 	 * Also, we should never have an mctl_present if this is an
17196 	 * ESP-in-UDP packet.
17197 	 */
17198 	ASSERT(!mctl_present || !esp_in_udp_packet);
17199 
17200 
17201 	/* u1 is # words of IP options */
17202 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17203 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17204 
17205 	/*
17206 	 * Don't verify header checksum if we just removed UDP header or
17207 	 * packet is coming back from AH/ESP.
17208 	 */
17209 	if (!esp_in_udp_packet && !mctl_present) {
17210 		if (u1) {
17211 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17212 				if (hada_mp != NULL)
17213 					freemsg(hada_mp);
17214 				return;
17215 			}
17216 		} else {
17217 			/* Check the IP header checksum.  */
17218 #define	uph	((uint16_t *)ipha)
17219 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17220 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17221 #undef  uph
17222 			/* finish doing IP checksum */
17223 			sum = (sum & 0xFFFF) + (sum >> 16);
17224 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17225 			if (sum && sum != 0xFFFF) {
17226 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17227 				goto drop_pkt;
17228 			}
17229 		}
17230 	}
17231 
17232 	/*
17233 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17234 	 * might be called more than once for secure packets, count only
17235 	 * the first time.
17236 	 */
17237 	if (!mctl_present) {
17238 		UPDATE_IB_PKT_COUNT(ire);
17239 		ire->ire_last_used_time = lbolt;
17240 	}
17241 
17242 	/* Check for fragmentation offset. */
17243 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17244 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17245 	if (u1) {
17246 		/*
17247 		 * We re-assemble fragments before we do the AH/ESP
17248 		 * processing. Thus, M_CTL should not be present
17249 		 * while we are re-assembling.
17250 		 */
17251 		ASSERT(!mctl_present);
17252 		ASSERT(first_mp == mp);
17253 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17254 			return;
17255 		}
17256 		/*
17257 		 * Make sure that first_mp points back to mp as
17258 		 * the mp we came in with could have changed in
17259 		 * ip_rput_fragment().
17260 		 */
17261 		ipha = (ipha_t *)mp->b_rptr;
17262 		first_mp = mp;
17263 	}
17264 
17265 	/*
17266 	 * Clear hardware checksumming flag as it is currently only
17267 	 * used by TCP and UDP.
17268 	 */
17269 	DB_CKSUMFLAGS(mp) = 0;
17270 
17271 	/* Now we have a complete datagram, destined for this machine. */
17272 	u1 = IPH_HDR_LENGTH(ipha);
17273 	switch (ipha->ipha_protocol) {
17274 	case IPPROTO_ICMP: {
17275 		ire_t		*ire_zone;
17276 		ilm_t		*ilm;
17277 		mblk_t		*mp1;
17278 		zoneid_t	last_zoneid;
17279 
17280 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17281 			ASSERT(ire->ire_type == IRE_BROADCAST);
17282 			/*
17283 			 * In the multicast case, applications may have joined
17284 			 * the group from different zones, so we need to deliver
17285 			 * the packet to each of them. Loop through the
17286 			 * multicast memberships structures (ilm) on the receive
17287 			 * ill and send a copy of the packet up each matching
17288 			 * one. However, we don't do this for multicasts sent on
17289 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17290 			 * they must stay in the sender's zone.
17291 			 *
17292 			 * ilm_add_v6() ensures that ilms in the same zone are
17293 			 * contiguous in the ill_ilm list. We use this property
17294 			 * to avoid sending duplicates needed when two
17295 			 * applications in the same zone join the same group on
17296 			 * different logical interfaces: we ignore the ilm if
17297 			 * its zoneid is the same as the last matching one.
17298 			 * In addition, the sending of the packet for
17299 			 * ire_zoneid is delayed until all of the other ilms
17300 			 * have been exhausted.
17301 			 */
17302 			last_zoneid = -1;
17303 			ILM_WALKER_HOLD(recv_ill);
17304 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17305 			    ilm = ilm->ilm_next) {
17306 				if ((ilm->ilm_flags & ILM_DELETED) ||
17307 				    ipha->ipha_dst != ilm->ilm_addr ||
17308 				    ilm->ilm_zoneid == last_zoneid ||
17309 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17310 				    ilm->ilm_zoneid == ALL_ZONES ||
17311 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17312 					continue;
17313 				mp1 = ip_copymsg(first_mp);
17314 				if (mp1 == NULL)
17315 					continue;
17316 				icmp_inbound(q, mp1, B_TRUE, ill,
17317 				    0, sum, mctl_present, B_TRUE,
17318 				    recv_ill, ilm->ilm_zoneid);
17319 				last_zoneid = ilm->ilm_zoneid;
17320 			}
17321 			ILM_WALKER_RELE(recv_ill);
17322 		} else if (ire->ire_type == IRE_BROADCAST) {
17323 			/*
17324 			 * In the broadcast case, there may be many zones
17325 			 * which need a copy of the packet delivered to them.
17326 			 * There is one IRE_BROADCAST per broadcast address
17327 			 * and per zone; we walk those using a helper function.
17328 			 * In addition, the sending of the packet for ire is
17329 			 * delayed until all of the other ires have been
17330 			 * processed.
17331 			 */
17332 			IRB_REFHOLD(ire->ire_bucket);
17333 			ire_zone = NULL;
17334 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17335 			    ire)) != NULL) {
17336 				mp1 = ip_copymsg(first_mp);
17337 				if (mp1 == NULL)
17338 					continue;
17339 
17340 				UPDATE_IB_PKT_COUNT(ire_zone);
17341 				ire_zone->ire_last_used_time = lbolt;
17342 				icmp_inbound(q, mp1, B_TRUE, ill,
17343 				    0, sum, mctl_present, B_TRUE,
17344 				    recv_ill, ire_zone->ire_zoneid);
17345 			}
17346 			IRB_REFRELE(ire->ire_bucket);
17347 		}
17348 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17349 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17350 		    ire->ire_zoneid);
17351 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17352 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17353 		return;
17354 	}
17355 	case IPPROTO_IGMP:
17356 		/*
17357 		 * If we are not willing to accept IGMP packets in clear,
17358 		 * then check with global policy.
17359 		 */
17360 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17361 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17362 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17363 			if (first_mp == NULL)
17364 				return;
17365 		}
17366 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17367 			freemsg(first_mp);
17368 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17369 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17370 			return;
17371 		}
17372 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17373 			/* Bad packet - discarded by igmp_input */
17374 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17375 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17376 			if (mctl_present)
17377 				freeb(first_mp);
17378 			return;
17379 		}
17380 		/*
17381 		 * igmp_input() may have returned the pulled up message.
17382 		 * So first_mp and ipha need to be reinitialized.
17383 		 */
17384 		ipha = (ipha_t *)mp->b_rptr;
17385 		if (mctl_present)
17386 			first_mp->b_cont = mp;
17387 		else
17388 			first_mp = mp;
17389 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17390 		    connf_head != NULL) {
17391 			/* No user-level listener for IGMP packets */
17392 			goto drop_pkt;
17393 		}
17394 		/* deliver to local raw users */
17395 		break;
17396 	case IPPROTO_PIM:
17397 		/*
17398 		 * If we are not willing to accept PIM packets in clear,
17399 		 * then check with global policy.
17400 		 */
17401 		if (ipst->ips_pim_accept_clear_messages == 0) {
17402 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17403 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17404 			if (first_mp == NULL)
17405 				return;
17406 		}
17407 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17408 			freemsg(first_mp);
17409 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17410 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17411 			return;
17412 		}
17413 		if (pim_input(q, mp, ill) != 0) {
17414 			/* Bad packet - discarded by pim_input */
17415 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17416 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17417 			if (mctl_present)
17418 				freeb(first_mp);
17419 			return;
17420 		}
17421 
17422 		/*
17423 		 * pim_input() may have pulled up the message so ipha needs to
17424 		 * be reinitialized.
17425 		 */
17426 		ipha = (ipha_t *)mp->b_rptr;
17427 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17428 		    connf_head != NULL) {
17429 			/* No user-level listener for PIM packets */
17430 			goto drop_pkt;
17431 		}
17432 		/* deliver to local raw users */
17433 		break;
17434 	case IPPROTO_ENCAP:
17435 		/*
17436 		 * Handle self-encapsulated packets (IP-in-IP where
17437 		 * the inner addresses == the outer addresses).
17438 		 */
17439 		hdr_length = IPH_HDR_LENGTH(ipha);
17440 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17441 		    mp->b_wptr) {
17442 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17443 			    sizeof (ipha_t) - mp->b_rptr)) {
17444 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17445 				freemsg(first_mp);
17446 				return;
17447 			}
17448 			ipha = (ipha_t *)mp->b_rptr;
17449 		}
17450 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17451 		/*
17452 		 * Check the sanity of the inner IP header.
17453 		 */
17454 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17455 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17456 			freemsg(first_mp);
17457 			return;
17458 		}
17459 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17460 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17461 			freemsg(first_mp);
17462 			return;
17463 		}
17464 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17465 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17466 			ipsec_in_t *ii;
17467 
17468 			/*
17469 			 * Self-encapsulated tunnel packet. Remove
17470 			 * the outer IP header and fanout again.
17471 			 * We also need to make sure that the inner
17472 			 * header is pulled up until options.
17473 			 */
17474 			mp->b_rptr = (uchar_t *)inner_ipha;
17475 			ipha = inner_ipha;
17476 			hdr_length = IPH_HDR_LENGTH(ipha);
17477 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17478 				if (!pullupmsg(mp, (uchar_t *)ipha +
17479 				    + hdr_length - mp->b_rptr)) {
17480 					freemsg(first_mp);
17481 					return;
17482 				}
17483 				ipha = (ipha_t *)mp->b_rptr;
17484 			}
17485 			if (hdr_length > sizeof (ipha_t)) {
17486 				/* We got options on the inner packet. */
17487 				ipaddr_t dst = ipha->ipha_dst;
17488 
17489 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17490 				    -1) {
17491 					/* Bad options! */
17492 					return;
17493 				}
17494 				if (dst != ipha->ipha_dst) {
17495 					/*
17496 					 * Someone put a source-route in
17497 					 * the inside header of a self-
17498 					 * encapsulated packet.  Drop it
17499 					 * with extreme prejudice and let
17500 					 * the sender know.
17501 					 */
17502 					icmp_unreachable(q, first_mp,
17503 					    ICMP_SOURCE_ROUTE_FAILED,
17504 					    recv_ill->ill_zoneid, ipst);
17505 					return;
17506 				}
17507 			}
17508 			if (!mctl_present) {
17509 				ASSERT(first_mp == mp);
17510 				/*
17511 				 * This means that somebody is sending
17512 				 * Self-encapsualted packets without AH/ESP.
17513 				 * If AH/ESP was present, we would have already
17514 				 * allocated the first_mp.
17515 				 *
17516 				 * Send this packet to find a tunnel endpoint.
17517 				 * if I can't find one, an ICMP
17518 				 * PROTOCOL_UNREACHABLE will get sent.
17519 				 */
17520 				goto fanout;
17521 			}
17522 			/*
17523 			 * We generally store the ill_index if we need to
17524 			 * do IPsec processing as we lose the ill queue when
17525 			 * we come back. But in this case, we never should
17526 			 * have to store the ill_index here as it should have
17527 			 * been stored previously when we processed the
17528 			 * AH/ESP header in this routine or for non-ipsec
17529 			 * cases, we still have the queue. But for some bad
17530 			 * packets from the wire, we can get to IPsec after
17531 			 * this and we better store the index for that case.
17532 			 */
17533 			ill = (ill_t *)q->q_ptr;
17534 			ii = (ipsec_in_t *)first_mp->b_rptr;
17535 			ii->ipsec_in_ill_index =
17536 			    ill->ill_phyint->phyint_ifindex;
17537 			ii->ipsec_in_rill_index =
17538 			    recv_ill->ill_phyint->phyint_ifindex;
17539 			if (ii->ipsec_in_decaps) {
17540 				/*
17541 				 * This packet is self-encapsulated multiple
17542 				 * times. We don't want to recurse infinitely.
17543 				 * To keep it simple, drop the packet.
17544 				 */
17545 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17546 				freemsg(first_mp);
17547 				return;
17548 			}
17549 			ii->ipsec_in_decaps = B_TRUE;
17550 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17551 			    ire);
17552 			return;
17553 		}
17554 		break;
17555 	case IPPROTO_AH:
17556 	case IPPROTO_ESP: {
17557 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17558 
17559 		/*
17560 		 * Fast path for AH/ESP. If this is the first time
17561 		 * we are sending a datagram to AH/ESP, allocate
17562 		 * a IPSEC_IN message and prepend it. Otherwise,
17563 		 * just fanout.
17564 		 */
17565 
17566 		int ipsec_rc;
17567 		ipsec_in_t *ii;
17568 		netstack_t *ns = ipst->ips_netstack;
17569 
17570 		IP_STAT(ipst, ipsec_proto_ahesp);
17571 		if (!mctl_present) {
17572 			ASSERT(first_mp == mp);
17573 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17574 			if (first_mp == NULL) {
17575 				ip1dbg(("ip_proto_input: IPSEC_IN "
17576 				    "allocation failure.\n"));
17577 				freemsg(hada_mp); /* okay ifnull */
17578 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17579 				freemsg(mp);
17580 				return;
17581 			}
17582 			/*
17583 			 * Store the ill_index so that when we come back
17584 			 * from IPsec we ride on the same queue.
17585 			 */
17586 			ill = (ill_t *)q->q_ptr;
17587 			ii = (ipsec_in_t *)first_mp->b_rptr;
17588 			ii->ipsec_in_ill_index =
17589 			    ill->ill_phyint->phyint_ifindex;
17590 			ii->ipsec_in_rill_index =
17591 			    recv_ill->ill_phyint->phyint_ifindex;
17592 			first_mp->b_cont = mp;
17593 			/*
17594 			 * Cache hardware acceleration info.
17595 			 */
17596 			if (hada_mp != NULL) {
17597 				IPSECHW_DEBUG(IPSECHW_PKT,
17598 				    ("ip_rput_local: caching data attr.\n"));
17599 				ii->ipsec_in_accelerated = B_TRUE;
17600 				ii->ipsec_in_da = hada_mp;
17601 				hada_mp = NULL;
17602 			}
17603 		} else {
17604 			ii = (ipsec_in_t *)first_mp->b_rptr;
17605 		}
17606 
17607 		ii->ipsec_in_esp_udp_ports = esp_udp_ports;
17608 
17609 		if (!ipsec_loaded(ipss)) {
17610 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17611 			    ire->ire_zoneid, ipst);
17612 			return;
17613 		}
17614 
17615 		ns = ipst->ips_netstack;
17616 		/* select inbound SA and have IPsec process the pkt */
17617 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17618 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17619 			boolean_t esp_in_udp_sa;
17620 			if (esph == NULL)
17621 				return;
17622 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17623 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17624 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17625 			    IPSA_F_NATT) != 0);
17626 			/*
17627 			 * The following is a fancy, but quick, way of saying:
17628 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17629 			 *    OR
17630 			 * ESP SA and ESP-in-UDP packet --> drop
17631 			 */
17632 			if (esp_in_udp_sa != esp_in_udp_packet) {
17633 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17634 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17635 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17636 				    &ns->netstack_ipsec->ipsec_dropper);
17637 				return;
17638 			}
17639 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17640 			    first_mp, esph);
17641 		} else {
17642 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17643 			if (ah == NULL)
17644 				return;
17645 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17646 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17647 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17648 			    first_mp, ah);
17649 		}
17650 
17651 		switch (ipsec_rc) {
17652 		case IPSEC_STATUS_SUCCESS:
17653 			break;
17654 		case IPSEC_STATUS_FAILED:
17655 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17656 			/* FALLTHRU */
17657 		case IPSEC_STATUS_PENDING:
17658 			return;
17659 		}
17660 		/* we're done with IPsec processing, send it up */
17661 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17662 		return;
17663 	}
17664 	default:
17665 		break;
17666 	}
17667 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17668 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17669 		    ire->ire_zoneid));
17670 		goto drop_pkt;
17671 	}
17672 	/*
17673 	 * Handle protocols with which IP is less intimate.  There
17674 	 * can be more than one stream bound to a particular
17675 	 * protocol.  When this is the case, each one gets a copy
17676 	 * of any incoming packets.
17677 	 */
17678 fanout:
17679 	ip_fanout_proto(q, first_mp, ill, ipha,
17680 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17681 	    B_TRUE, recv_ill, ire->ire_zoneid);
17682 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17683 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17684 	return;
17685 
17686 drop_pkt:
17687 	freemsg(first_mp);
17688 	if (hada_mp != NULL)
17689 		freeb(hada_mp);
17690 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17691 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17692 #undef	rptr
17693 #undef  iphs
17694 
17695 }
17696 
17697 /*
17698  * Update any source route, record route or timestamp options.
17699  * Check that we are at end of strict source route.
17700  * The options have already been checked for sanity in ip_rput_options().
17701  */
17702 static boolean_t
17703 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17704     ip_stack_t *ipst)
17705 {
17706 	ipoptp_t	opts;
17707 	uchar_t		*opt;
17708 	uint8_t		optval;
17709 	uint8_t		optlen;
17710 	ipaddr_t	dst;
17711 	uint32_t	ts;
17712 	ire_t		*dst_ire;
17713 	timestruc_t	now;
17714 	zoneid_t	zoneid;
17715 	ill_t		*ill;
17716 
17717 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17718 
17719 	ip2dbg(("ip_rput_local_options\n"));
17720 
17721 	for (optval = ipoptp_first(&opts, ipha);
17722 	    optval != IPOPT_EOL;
17723 	    optval = ipoptp_next(&opts)) {
17724 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17725 		opt = opts.ipoptp_cur;
17726 		optlen = opts.ipoptp_len;
17727 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17728 		    optval, optlen));
17729 		switch (optval) {
17730 			uint32_t off;
17731 		case IPOPT_SSRR:
17732 		case IPOPT_LSRR:
17733 			off = opt[IPOPT_OFFSET];
17734 			off--;
17735 			if (optlen < IP_ADDR_LEN ||
17736 			    off > optlen - IP_ADDR_LEN) {
17737 				/* End of source route */
17738 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17739 				break;
17740 			}
17741 			/*
17742 			 * This will only happen if two consecutive entries
17743 			 * in the source route contains our address or if
17744 			 * it is a packet with a loose source route which
17745 			 * reaches us before consuming the whole source route
17746 			 */
17747 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17748 			if (optval == IPOPT_SSRR) {
17749 				goto bad_src_route;
17750 			}
17751 			/*
17752 			 * Hack: instead of dropping the packet truncate the
17753 			 * source route to what has been used by filling the
17754 			 * rest with IPOPT_NOP.
17755 			 */
17756 			opt[IPOPT_OLEN] = (uint8_t)off;
17757 			while (off < optlen) {
17758 				opt[off++] = IPOPT_NOP;
17759 			}
17760 			break;
17761 		case IPOPT_RR:
17762 			off = opt[IPOPT_OFFSET];
17763 			off--;
17764 			if (optlen < IP_ADDR_LEN ||
17765 			    off > optlen - IP_ADDR_LEN) {
17766 				/* No more room - ignore */
17767 				ip1dbg((
17768 				    "ip_rput_local_options: end of RR\n"));
17769 				break;
17770 			}
17771 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17772 			    IP_ADDR_LEN);
17773 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17774 			break;
17775 		case IPOPT_TS:
17776 			/* Insert timestamp if there is romm */
17777 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17778 			case IPOPT_TS_TSONLY:
17779 				off = IPOPT_TS_TIMELEN;
17780 				break;
17781 			case IPOPT_TS_PRESPEC:
17782 			case IPOPT_TS_PRESPEC_RFC791:
17783 				/* Verify that the address matched */
17784 				off = opt[IPOPT_OFFSET] - 1;
17785 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17786 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17787 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17788 				    ipst);
17789 				if (dst_ire == NULL) {
17790 					/* Not for us */
17791 					break;
17792 				}
17793 				ire_refrele(dst_ire);
17794 				/* FALLTHRU */
17795 			case IPOPT_TS_TSANDADDR:
17796 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17797 				break;
17798 			default:
17799 				/*
17800 				 * ip_*put_options should have already
17801 				 * dropped this packet.
17802 				 */
17803 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17804 				    "unknown IT - bug in ip_rput_options?\n");
17805 				return (B_TRUE);	/* Keep "lint" happy */
17806 			}
17807 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17808 				/* Increase overflow counter */
17809 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17810 				opt[IPOPT_POS_OV_FLG] =
17811 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17812 				    (off << 4));
17813 				break;
17814 			}
17815 			off = opt[IPOPT_OFFSET] - 1;
17816 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17817 			case IPOPT_TS_PRESPEC:
17818 			case IPOPT_TS_PRESPEC_RFC791:
17819 			case IPOPT_TS_TSANDADDR:
17820 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17821 				    IP_ADDR_LEN);
17822 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17823 				/* FALLTHRU */
17824 			case IPOPT_TS_TSONLY:
17825 				off = opt[IPOPT_OFFSET] - 1;
17826 				/* Compute # of milliseconds since midnight */
17827 				gethrestime(&now);
17828 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17829 				    now.tv_nsec / (NANOSEC / MILLISEC);
17830 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17831 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17832 				break;
17833 			}
17834 			break;
17835 		}
17836 	}
17837 	return (B_TRUE);
17838 
17839 bad_src_route:
17840 	q = WR(q);
17841 	if (q->q_next != NULL)
17842 		ill = q->q_ptr;
17843 	else
17844 		ill = NULL;
17845 
17846 	/* make sure we clear any indication of a hardware checksum */
17847 	DB_CKSUMFLAGS(mp) = 0;
17848 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17849 	if (zoneid == ALL_ZONES)
17850 		freemsg(mp);
17851 	else
17852 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17853 	return (B_FALSE);
17854 
17855 }
17856 
17857 /*
17858  * Process IP options in an inbound packet.  If an option affects the
17859  * effective destination address, return the next hop address via dstp.
17860  * Returns -1 if something fails in which case an ICMP error has been sent
17861  * and mp freed.
17862  */
17863 static int
17864 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17865     ip_stack_t *ipst)
17866 {
17867 	ipoptp_t	opts;
17868 	uchar_t		*opt;
17869 	uint8_t		optval;
17870 	uint8_t		optlen;
17871 	ipaddr_t	dst;
17872 	intptr_t	code = 0;
17873 	ire_t		*ire = NULL;
17874 	zoneid_t	zoneid;
17875 	ill_t		*ill;
17876 
17877 	ip2dbg(("ip_rput_options\n"));
17878 	dst = ipha->ipha_dst;
17879 	for (optval = ipoptp_first(&opts, ipha);
17880 	    optval != IPOPT_EOL;
17881 	    optval = ipoptp_next(&opts)) {
17882 		opt = opts.ipoptp_cur;
17883 		optlen = opts.ipoptp_len;
17884 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17885 		    optval, optlen));
17886 		/*
17887 		 * Note: we need to verify the checksum before we
17888 		 * modify anything thus this routine only extracts the next
17889 		 * hop dst from any source route.
17890 		 */
17891 		switch (optval) {
17892 			uint32_t off;
17893 		case IPOPT_SSRR:
17894 		case IPOPT_LSRR:
17895 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17896 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17897 			if (ire == NULL) {
17898 				if (optval == IPOPT_SSRR) {
17899 					ip1dbg(("ip_rput_options: not next"
17900 					    " strict source route 0x%x\n",
17901 					    ntohl(dst)));
17902 					code = (char *)&ipha->ipha_dst -
17903 					    (char *)ipha;
17904 					goto param_prob; /* RouterReq's */
17905 				}
17906 				ip2dbg(("ip_rput_options: "
17907 				    "not next source route 0x%x\n",
17908 				    ntohl(dst)));
17909 				break;
17910 			}
17911 			ire_refrele(ire);
17912 
17913 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17914 				ip1dbg((
17915 				    "ip_rput_options: bad option offset\n"));
17916 				code = (char *)&opt[IPOPT_OLEN] -
17917 				    (char *)ipha;
17918 				goto param_prob;
17919 			}
17920 			off = opt[IPOPT_OFFSET];
17921 			off--;
17922 		redo_srr:
17923 			if (optlen < IP_ADDR_LEN ||
17924 			    off > optlen - IP_ADDR_LEN) {
17925 				/* End of source route */
17926 				ip1dbg(("ip_rput_options: end of SR\n"));
17927 				break;
17928 			}
17929 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17930 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17931 			    ntohl(dst)));
17932 
17933 			/*
17934 			 * Check if our address is present more than
17935 			 * once as consecutive hops in source route.
17936 			 * XXX verify per-interface ip_forwarding
17937 			 * for source route?
17938 			 */
17939 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17940 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17941 
17942 			if (ire != NULL) {
17943 				ire_refrele(ire);
17944 				off += IP_ADDR_LEN;
17945 				goto redo_srr;
17946 			}
17947 
17948 			if (dst == htonl(INADDR_LOOPBACK)) {
17949 				ip1dbg(("ip_rput_options: loopback addr in "
17950 				    "source route!\n"));
17951 				goto bad_src_route;
17952 			}
17953 			/*
17954 			 * For strict: verify that dst is directly
17955 			 * reachable.
17956 			 */
17957 			if (optval == IPOPT_SSRR) {
17958 				ire = ire_ftable_lookup(dst, 0, 0,
17959 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17960 				    MBLK_GETLABEL(mp),
17961 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17962 				if (ire == NULL) {
17963 					ip1dbg(("ip_rput_options: SSRR not "
17964 					    "directly reachable: 0x%x\n",
17965 					    ntohl(dst)));
17966 					goto bad_src_route;
17967 				}
17968 				ire_refrele(ire);
17969 			}
17970 			/*
17971 			 * Defer update of the offset and the record route
17972 			 * until the packet is forwarded.
17973 			 */
17974 			break;
17975 		case IPOPT_RR:
17976 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17977 				ip1dbg((
17978 				    "ip_rput_options: bad option offset\n"));
17979 				code = (char *)&opt[IPOPT_OLEN] -
17980 				    (char *)ipha;
17981 				goto param_prob;
17982 			}
17983 			break;
17984 		case IPOPT_TS:
17985 			/*
17986 			 * Verify that length >= 5 and that there is either
17987 			 * room for another timestamp or that the overflow
17988 			 * counter is not maxed out.
17989 			 */
17990 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17991 			if (optlen < IPOPT_MINLEN_IT) {
17992 				goto param_prob;
17993 			}
17994 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17995 				ip1dbg((
17996 				    "ip_rput_options: bad option offset\n"));
17997 				code = (char *)&opt[IPOPT_OFFSET] -
17998 				    (char *)ipha;
17999 				goto param_prob;
18000 			}
18001 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18002 			case IPOPT_TS_TSONLY:
18003 				off = IPOPT_TS_TIMELEN;
18004 				break;
18005 			case IPOPT_TS_TSANDADDR:
18006 			case IPOPT_TS_PRESPEC:
18007 			case IPOPT_TS_PRESPEC_RFC791:
18008 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18009 				break;
18010 			default:
18011 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18012 				    (char *)ipha;
18013 				goto param_prob;
18014 			}
18015 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18016 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18017 				/*
18018 				 * No room and the overflow counter is 15
18019 				 * already.
18020 				 */
18021 				goto param_prob;
18022 			}
18023 			break;
18024 		}
18025 	}
18026 
18027 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18028 		*dstp = dst;
18029 		return (0);
18030 	}
18031 
18032 	ip1dbg(("ip_rput_options: error processing IP options."));
18033 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18034 
18035 param_prob:
18036 	q = WR(q);
18037 	if (q->q_next != NULL)
18038 		ill = q->q_ptr;
18039 	else
18040 		ill = NULL;
18041 
18042 	/* make sure we clear any indication of a hardware checksum */
18043 	DB_CKSUMFLAGS(mp) = 0;
18044 	/* Don't know whether this is for non-global or global/forwarding */
18045 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18046 	if (zoneid == ALL_ZONES)
18047 		freemsg(mp);
18048 	else
18049 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18050 	return (-1);
18051 
18052 bad_src_route:
18053 	q = WR(q);
18054 	if (q->q_next != NULL)
18055 		ill = q->q_ptr;
18056 	else
18057 		ill = NULL;
18058 
18059 	/* make sure we clear any indication of a hardware checksum */
18060 	DB_CKSUMFLAGS(mp) = 0;
18061 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18062 	if (zoneid == ALL_ZONES)
18063 		freemsg(mp);
18064 	else
18065 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18066 	return (-1);
18067 }
18068 
18069 /*
18070  * IP & ICMP info in >=14 msg's ...
18071  *  - ip fixed part (mib2_ip_t)
18072  *  - icmp fixed part (mib2_icmp_t)
18073  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18074  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18075  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18076  *  - ipRouteAttributeTable (ip 102)	labeled routes
18077  *  - ip multicast membership (ip_member_t)
18078  *  - ip multicast source filtering (ip_grpsrc_t)
18079  *  - igmp fixed part (struct igmpstat)
18080  *  - multicast routing stats (struct mrtstat)
18081  *  - multicast routing vifs (array of struct vifctl)
18082  *  - multicast routing routes (array of struct mfcctl)
18083  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18084  *					One per ill plus one generic
18085  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18086  *					One per ill plus one generic
18087  *  - ipv6RouteEntry			all IPv6 IREs
18088  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18089  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18090  *  - ipv6AddrEntry			all IPv6 ipifs
18091  *  - ipv6 multicast membership (ipv6_member_t)
18092  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18093  *
18094  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18095  *
18096  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18097  * already filled in by the caller.
18098  * Return value of 0 indicates that no messages were sent and caller
18099  * should free mpctl.
18100  */
18101 int
18102 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18103 {
18104 	ip_stack_t *ipst;
18105 	sctp_stack_t *sctps;
18106 
18107 	if (q->q_next != NULL) {
18108 		ipst = ILLQ_TO_IPST(q);
18109 	} else {
18110 		ipst = CONNQ_TO_IPST(q);
18111 	}
18112 	ASSERT(ipst != NULL);
18113 	sctps = ipst->ips_netstack->netstack_sctp;
18114 
18115 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18116 		return (0);
18117 	}
18118 
18119 	/*
18120 	 * For the purposes of the (broken) packet shell use
18121 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18122 	 * to make TCP and UDP appear first in the list of mib items.
18123 	 * TBD: We could expand this and use it in netstat so that
18124 	 * the kernel doesn't have to produce large tables (connections,
18125 	 * routes, etc) when netstat only wants the statistics or a particular
18126 	 * table.
18127 	 */
18128 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18129 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18130 			return (1);
18131 		}
18132 	}
18133 
18134 	if (level != MIB2_TCP) {
18135 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18136 			return (1);
18137 		}
18138 	}
18139 
18140 	if (level != MIB2_UDP) {
18141 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18142 			return (1);
18143 		}
18144 	}
18145 
18146 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18147 	    ipst)) == NULL) {
18148 		return (1);
18149 	}
18150 
18151 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18152 		return (1);
18153 	}
18154 
18155 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18156 		return (1);
18157 	}
18158 
18159 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18160 		return (1);
18161 	}
18162 
18163 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18164 		return (1);
18165 	}
18166 
18167 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18168 		return (1);
18169 	}
18170 
18171 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18172 		return (1);
18173 	}
18174 
18175 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18176 		return (1);
18177 	}
18178 
18179 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18180 		return (1);
18181 	}
18182 
18183 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18184 		return (1);
18185 	}
18186 
18187 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18188 		return (1);
18189 	}
18190 
18191 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18192 		return (1);
18193 	}
18194 
18195 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18196 		return (1);
18197 	}
18198 
18199 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18200 		return (1);
18201 	}
18202 
18203 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18204 		return (1);
18205 	}
18206 
18207 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18208 	if (mpctl == NULL) {
18209 		return (1);
18210 	}
18211 
18212 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18213 		return (1);
18214 	}
18215 	freemsg(mpctl);
18216 	return (1);
18217 }
18218 
18219 
18220 /* Get global (legacy) IPv4 statistics */
18221 static mblk_t *
18222 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18223     ip_stack_t *ipst)
18224 {
18225 	mib2_ip_t		old_ip_mib;
18226 	struct opthdr		*optp;
18227 	mblk_t			*mp2ctl;
18228 
18229 	/*
18230 	 * make a copy of the original message
18231 	 */
18232 	mp2ctl = copymsg(mpctl);
18233 
18234 	/* fixed length IP structure... */
18235 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18236 	optp->level = MIB2_IP;
18237 	optp->name = 0;
18238 	SET_MIB(old_ip_mib.ipForwarding,
18239 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18240 	SET_MIB(old_ip_mib.ipDefaultTTL,
18241 	    (uint32_t)ipst->ips_ip_def_ttl);
18242 	SET_MIB(old_ip_mib.ipReasmTimeout,
18243 	    ipst->ips_ip_g_frag_timeout);
18244 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18245 	    sizeof (mib2_ipAddrEntry_t));
18246 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18247 	    sizeof (mib2_ipRouteEntry_t));
18248 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18249 	    sizeof (mib2_ipNetToMediaEntry_t));
18250 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18251 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18252 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18253 	    sizeof (mib2_ipAttributeEntry_t));
18254 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18255 
18256 	/*
18257 	 * Grab the statistics from the new IP MIB
18258 	 */
18259 	SET_MIB(old_ip_mib.ipInReceives,
18260 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18261 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18262 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18263 	SET_MIB(old_ip_mib.ipForwDatagrams,
18264 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18265 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18266 	    ipmib->ipIfStatsInUnknownProtos);
18267 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18268 	SET_MIB(old_ip_mib.ipInDelivers,
18269 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18270 	SET_MIB(old_ip_mib.ipOutRequests,
18271 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18272 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18273 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18274 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18275 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18276 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18277 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18278 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18279 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18280 
18281 	/* ipRoutingDiscards is not being used */
18282 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18283 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18284 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18285 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18286 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18287 	    ipmib->ipIfStatsReasmDuplicates);
18288 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18289 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18290 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18291 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18292 	SET_MIB(old_ip_mib.rawipInOverflows,
18293 	    ipmib->rawipIfStatsInOverflows);
18294 
18295 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18296 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18297 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18298 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18299 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18300 	    ipmib->ipIfStatsOutSwitchIPVersion);
18301 
18302 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18303 	    (int)sizeof (old_ip_mib))) {
18304 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18305 		    (uint_t)sizeof (old_ip_mib)));
18306 	}
18307 
18308 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18309 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18310 	    (int)optp->level, (int)optp->name, (int)optp->len));
18311 	qreply(q, mpctl);
18312 	return (mp2ctl);
18313 }
18314 
18315 /* Per interface IPv4 statistics */
18316 static mblk_t *
18317 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18318 {
18319 	struct opthdr		*optp;
18320 	mblk_t			*mp2ctl;
18321 	ill_t			*ill;
18322 	ill_walk_context_t	ctx;
18323 	mblk_t			*mp_tail = NULL;
18324 	mib2_ipIfStatsEntry_t	global_ip_mib;
18325 
18326 	/*
18327 	 * Make a copy of the original message
18328 	 */
18329 	mp2ctl = copymsg(mpctl);
18330 
18331 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18332 	optp->level = MIB2_IP;
18333 	optp->name = MIB2_IP_TRAFFIC_STATS;
18334 	/* Include "unknown interface" ip_mib */
18335 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18336 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18337 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18338 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18339 	    (ipst->ips_ip_g_forward ? 1 : 2));
18340 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18341 	    (uint32_t)ipst->ips_ip_def_ttl);
18342 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18343 	    sizeof (mib2_ipIfStatsEntry_t));
18344 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18345 	    sizeof (mib2_ipAddrEntry_t));
18346 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18347 	    sizeof (mib2_ipRouteEntry_t));
18348 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18349 	    sizeof (mib2_ipNetToMediaEntry_t));
18350 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18351 	    sizeof (ip_member_t));
18352 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18353 	    sizeof (ip_grpsrc_t));
18354 
18355 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18356 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18357 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18358 		    "failed to allocate %u bytes\n",
18359 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18360 	}
18361 
18362 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18363 
18364 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18365 	ill = ILL_START_WALK_V4(&ctx, ipst);
18366 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18367 		ill->ill_ip_mib->ipIfStatsIfIndex =
18368 		    ill->ill_phyint->phyint_ifindex;
18369 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18370 		    (ipst->ips_ip_g_forward ? 1 : 2));
18371 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18372 		    (uint32_t)ipst->ips_ip_def_ttl);
18373 
18374 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18375 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18376 		    (char *)ill->ill_ip_mib,
18377 		    (int)sizeof (*ill->ill_ip_mib))) {
18378 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18379 			    "failed to allocate %u bytes\n",
18380 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18381 		}
18382 	}
18383 	rw_exit(&ipst->ips_ill_g_lock);
18384 
18385 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18386 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18387 	    "level %d, name %d, len %d\n",
18388 	    (int)optp->level, (int)optp->name, (int)optp->len));
18389 	qreply(q, mpctl);
18390 
18391 	if (mp2ctl == NULL)
18392 		return (NULL);
18393 
18394 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18395 }
18396 
18397 /* Global IPv4 ICMP statistics */
18398 static mblk_t *
18399 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18400 {
18401 	struct opthdr		*optp;
18402 	mblk_t			*mp2ctl;
18403 
18404 	/*
18405 	 * Make a copy of the original message
18406 	 */
18407 	mp2ctl = copymsg(mpctl);
18408 
18409 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18410 	optp->level = MIB2_ICMP;
18411 	optp->name = 0;
18412 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18413 	    (int)sizeof (ipst->ips_icmp_mib))) {
18414 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18415 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18416 	}
18417 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18418 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18419 	    (int)optp->level, (int)optp->name, (int)optp->len));
18420 	qreply(q, mpctl);
18421 	return (mp2ctl);
18422 }
18423 
18424 /* Global IPv4 IGMP statistics */
18425 static mblk_t *
18426 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18427 {
18428 	struct opthdr		*optp;
18429 	mblk_t			*mp2ctl;
18430 
18431 	/*
18432 	 * make a copy of the original message
18433 	 */
18434 	mp2ctl = copymsg(mpctl);
18435 
18436 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18437 	optp->level = EXPER_IGMP;
18438 	optp->name = 0;
18439 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18440 	    (int)sizeof (ipst->ips_igmpstat))) {
18441 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18442 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18443 	}
18444 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18445 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18446 	    (int)optp->level, (int)optp->name, (int)optp->len));
18447 	qreply(q, mpctl);
18448 	return (mp2ctl);
18449 }
18450 
18451 /* Global IPv4 Multicast Routing statistics */
18452 static mblk_t *
18453 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18454 {
18455 	struct opthdr		*optp;
18456 	mblk_t			*mp2ctl;
18457 
18458 	/*
18459 	 * make a copy of the original message
18460 	 */
18461 	mp2ctl = copymsg(mpctl);
18462 
18463 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18464 	optp->level = EXPER_DVMRP;
18465 	optp->name = 0;
18466 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18467 		ip0dbg(("ip_mroute_stats: failed\n"));
18468 	}
18469 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18470 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18471 	    (int)optp->level, (int)optp->name, (int)optp->len));
18472 	qreply(q, mpctl);
18473 	return (mp2ctl);
18474 }
18475 
18476 /* IPv4 address information */
18477 static mblk_t *
18478 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18479 {
18480 	struct opthdr		*optp;
18481 	mblk_t			*mp2ctl;
18482 	mblk_t			*mp_tail = NULL;
18483 	ill_t			*ill;
18484 	ipif_t			*ipif;
18485 	uint_t			bitval;
18486 	mib2_ipAddrEntry_t	mae;
18487 	zoneid_t		zoneid;
18488 	ill_walk_context_t ctx;
18489 
18490 	/*
18491 	 * make a copy of the original message
18492 	 */
18493 	mp2ctl = copymsg(mpctl);
18494 
18495 	/* ipAddrEntryTable */
18496 
18497 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18498 	optp->level = MIB2_IP;
18499 	optp->name = MIB2_IP_ADDR;
18500 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18501 
18502 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18503 	ill = ILL_START_WALK_V4(&ctx, ipst);
18504 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18505 		for (ipif = ill->ill_ipif; ipif != NULL;
18506 		    ipif = ipif->ipif_next) {
18507 			if (ipif->ipif_zoneid != zoneid &&
18508 			    ipif->ipif_zoneid != ALL_ZONES)
18509 				continue;
18510 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18511 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18512 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18513 
18514 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18515 			    OCTET_LENGTH);
18516 			mae.ipAdEntIfIndex.o_length =
18517 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18518 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18519 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18520 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18521 			mae.ipAdEntInfo.ae_subnet_len =
18522 			    ip_mask_to_plen(ipif->ipif_net_mask);
18523 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18524 			for (bitval = 1;
18525 			    bitval &&
18526 			    !(bitval & ipif->ipif_brd_addr);
18527 			    bitval <<= 1)
18528 				noop;
18529 			mae.ipAdEntBcastAddr = bitval;
18530 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18531 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18532 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18533 			mae.ipAdEntInfo.ae_broadcast_addr =
18534 			    ipif->ipif_brd_addr;
18535 			mae.ipAdEntInfo.ae_pp_dst_addr =
18536 			    ipif->ipif_pp_dst_addr;
18537 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18538 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18539 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18540 
18541 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18542 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18543 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18544 				    "allocate %u bytes\n",
18545 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18546 			}
18547 		}
18548 	}
18549 	rw_exit(&ipst->ips_ill_g_lock);
18550 
18551 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18552 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18553 	    (int)optp->level, (int)optp->name, (int)optp->len));
18554 	qreply(q, mpctl);
18555 	return (mp2ctl);
18556 }
18557 
18558 /* IPv6 address information */
18559 static mblk_t *
18560 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18561 {
18562 	struct opthdr		*optp;
18563 	mblk_t			*mp2ctl;
18564 	mblk_t			*mp_tail = NULL;
18565 	ill_t			*ill;
18566 	ipif_t			*ipif;
18567 	mib2_ipv6AddrEntry_t	mae6;
18568 	zoneid_t		zoneid;
18569 	ill_walk_context_t	ctx;
18570 
18571 	/*
18572 	 * make a copy of the original message
18573 	 */
18574 	mp2ctl = copymsg(mpctl);
18575 
18576 	/* ipv6AddrEntryTable */
18577 
18578 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18579 	optp->level = MIB2_IP6;
18580 	optp->name = MIB2_IP6_ADDR;
18581 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18582 
18583 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18584 	ill = ILL_START_WALK_V6(&ctx, ipst);
18585 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18586 		for (ipif = ill->ill_ipif; ipif != NULL;
18587 		    ipif = ipif->ipif_next) {
18588 			if (ipif->ipif_zoneid != zoneid &&
18589 			    ipif->ipif_zoneid != ALL_ZONES)
18590 				continue;
18591 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18592 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18593 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18594 
18595 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18596 			    OCTET_LENGTH);
18597 			mae6.ipv6AddrIfIndex.o_length =
18598 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18599 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18600 			mae6.ipv6AddrPfxLength =
18601 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18602 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18603 			mae6.ipv6AddrInfo.ae_subnet_len =
18604 			    mae6.ipv6AddrPfxLength;
18605 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18606 
18607 			/* Type: stateless(1), stateful(2), unknown(3) */
18608 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18609 				mae6.ipv6AddrType = 1;
18610 			else
18611 				mae6.ipv6AddrType = 2;
18612 			/* Anycast: true(1), false(2) */
18613 			if (ipif->ipif_flags & IPIF_ANYCAST)
18614 				mae6.ipv6AddrAnycastFlag = 1;
18615 			else
18616 				mae6.ipv6AddrAnycastFlag = 2;
18617 
18618 			/*
18619 			 * Address status: preferred(1), deprecated(2),
18620 			 * invalid(3), inaccessible(4), unknown(5)
18621 			 */
18622 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18623 				mae6.ipv6AddrStatus = 3;
18624 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18625 				mae6.ipv6AddrStatus = 2;
18626 			else
18627 				mae6.ipv6AddrStatus = 1;
18628 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18629 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18630 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18631 			    ipif->ipif_v6pp_dst_addr;
18632 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18633 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18634 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18635 			mae6.ipv6AddrIdentifier = ill->ill_token;
18636 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18637 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18638 			mae6.ipv6AddrRetransmitTime =
18639 			    ill->ill_reachable_retrans_time;
18640 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18641 			    (char *)&mae6,
18642 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18643 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18644 				    "allocate %u bytes\n",
18645 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18646 			}
18647 		}
18648 	}
18649 	rw_exit(&ipst->ips_ill_g_lock);
18650 
18651 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18652 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18653 	    (int)optp->level, (int)optp->name, (int)optp->len));
18654 	qreply(q, mpctl);
18655 	return (mp2ctl);
18656 }
18657 
18658 /* IPv4 multicast group membership. */
18659 static mblk_t *
18660 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18661 {
18662 	struct opthdr		*optp;
18663 	mblk_t			*mp2ctl;
18664 	ill_t			*ill;
18665 	ipif_t			*ipif;
18666 	ilm_t			*ilm;
18667 	ip_member_t		ipm;
18668 	mblk_t			*mp_tail = NULL;
18669 	ill_walk_context_t	ctx;
18670 	zoneid_t		zoneid;
18671 
18672 	/*
18673 	 * make a copy of the original message
18674 	 */
18675 	mp2ctl = copymsg(mpctl);
18676 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18677 
18678 	/* ipGroupMember table */
18679 	optp = (struct opthdr *)&mpctl->b_rptr[
18680 	    sizeof (struct T_optmgmt_ack)];
18681 	optp->level = MIB2_IP;
18682 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18683 
18684 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18685 	ill = ILL_START_WALK_V4(&ctx, ipst);
18686 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18687 		ILM_WALKER_HOLD(ill);
18688 		for (ipif = ill->ill_ipif; ipif != NULL;
18689 		    ipif = ipif->ipif_next) {
18690 			if (ipif->ipif_zoneid != zoneid &&
18691 			    ipif->ipif_zoneid != ALL_ZONES)
18692 				continue;	/* not this zone */
18693 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18694 			    OCTET_LENGTH);
18695 			ipm.ipGroupMemberIfIndex.o_length =
18696 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18697 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18698 				ASSERT(ilm->ilm_ipif != NULL);
18699 				ASSERT(ilm->ilm_ill == NULL);
18700 				if (ilm->ilm_ipif != ipif)
18701 					continue;
18702 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18703 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18704 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18705 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18706 				    (char *)&ipm, (int)sizeof (ipm))) {
18707 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18708 					    "failed to allocate %u bytes\n",
18709 					    (uint_t)sizeof (ipm)));
18710 				}
18711 			}
18712 		}
18713 		ILM_WALKER_RELE(ill);
18714 	}
18715 	rw_exit(&ipst->ips_ill_g_lock);
18716 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18717 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18718 	    (int)optp->level, (int)optp->name, (int)optp->len));
18719 	qreply(q, mpctl);
18720 	return (mp2ctl);
18721 }
18722 
18723 /* IPv6 multicast group membership. */
18724 static mblk_t *
18725 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18726 {
18727 	struct opthdr		*optp;
18728 	mblk_t			*mp2ctl;
18729 	ill_t			*ill;
18730 	ilm_t			*ilm;
18731 	ipv6_member_t		ipm6;
18732 	mblk_t			*mp_tail = NULL;
18733 	ill_walk_context_t	ctx;
18734 	zoneid_t		zoneid;
18735 
18736 	/*
18737 	 * make a copy of the original message
18738 	 */
18739 	mp2ctl = copymsg(mpctl);
18740 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18741 
18742 	/* ip6GroupMember table */
18743 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18744 	optp->level = MIB2_IP6;
18745 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18746 
18747 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18748 	ill = ILL_START_WALK_V6(&ctx, ipst);
18749 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18750 		ILM_WALKER_HOLD(ill);
18751 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18752 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18753 			ASSERT(ilm->ilm_ipif == NULL);
18754 			ASSERT(ilm->ilm_ill != NULL);
18755 			if (ilm->ilm_zoneid != zoneid)
18756 				continue;	/* not this zone */
18757 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18758 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18759 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18760 			if (!snmp_append_data2(mpctl->b_cont,
18761 			    &mp_tail,
18762 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18763 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18764 				    "failed to allocate %u bytes\n",
18765 				    (uint_t)sizeof (ipm6)));
18766 			}
18767 		}
18768 		ILM_WALKER_RELE(ill);
18769 	}
18770 	rw_exit(&ipst->ips_ill_g_lock);
18771 
18772 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18773 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18774 	    (int)optp->level, (int)optp->name, (int)optp->len));
18775 	qreply(q, mpctl);
18776 	return (mp2ctl);
18777 }
18778 
18779 /* IP multicast filtered sources */
18780 static mblk_t *
18781 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18782 {
18783 	struct opthdr		*optp;
18784 	mblk_t			*mp2ctl;
18785 	ill_t			*ill;
18786 	ipif_t			*ipif;
18787 	ilm_t			*ilm;
18788 	ip_grpsrc_t		ips;
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 	/* ipGroupSource table */
18802 	optp = (struct opthdr *)&mpctl->b_rptr[
18803 	    sizeof (struct T_optmgmt_ack)];
18804 	optp->level = MIB2_IP;
18805 	optp->name = EXPER_IP_GROUP_SOURCES;
18806 
18807 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18808 	ill = ILL_START_WALK_V4(&ctx, ipst);
18809 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18810 		ILM_WALKER_HOLD(ill);
18811 		for (ipif = ill->ill_ipif; ipif != NULL;
18812 		    ipif = ipif->ipif_next) {
18813 			if (ipif->ipif_zoneid != zoneid)
18814 				continue;	/* not this zone */
18815 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18816 			    OCTET_LENGTH);
18817 			ips.ipGroupSourceIfIndex.o_length =
18818 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18819 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18820 				ASSERT(ilm->ilm_ipif != NULL);
18821 				ASSERT(ilm->ilm_ill == NULL);
18822 				sl = ilm->ilm_filter;
18823 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18824 					continue;
18825 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18826 				for (i = 0; i < sl->sl_numsrc; i++) {
18827 					if (!IN6_IS_ADDR_V4MAPPED(
18828 					    &sl->sl_addr[i]))
18829 						continue;
18830 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18831 					    ips.ipGroupSourceAddress);
18832 					if (snmp_append_data2(mpctl->b_cont,
18833 					    &mp_tail, (char *)&ips,
18834 					    (int)sizeof (ips)) == 0) {
18835 						ip1dbg(("ip_snmp_get_mib2_"
18836 						    "ip_group_src: failed to "
18837 						    "allocate %u bytes\n",
18838 						    (uint_t)sizeof (ips)));
18839 					}
18840 				}
18841 			}
18842 		}
18843 		ILM_WALKER_RELE(ill);
18844 	}
18845 	rw_exit(&ipst->ips_ill_g_lock);
18846 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18847 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18848 	    (int)optp->level, (int)optp->name, (int)optp->len));
18849 	qreply(q, mpctl);
18850 	return (mp2ctl);
18851 }
18852 
18853 /* IPv6 multicast filtered sources. */
18854 static mblk_t *
18855 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18856 {
18857 	struct opthdr		*optp;
18858 	mblk_t			*mp2ctl;
18859 	ill_t			*ill;
18860 	ilm_t			*ilm;
18861 	ipv6_grpsrc_t		ips6;
18862 	mblk_t			*mp_tail = NULL;
18863 	ill_walk_context_t	ctx;
18864 	zoneid_t		zoneid;
18865 	int			i;
18866 	slist_t			*sl;
18867 
18868 	/*
18869 	 * make a copy of the original message
18870 	 */
18871 	mp2ctl = copymsg(mpctl);
18872 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18873 
18874 	/* ip6GroupMember table */
18875 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18876 	optp->level = MIB2_IP6;
18877 	optp->name = EXPER_IP6_GROUP_SOURCES;
18878 
18879 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18880 	ill = ILL_START_WALK_V6(&ctx, ipst);
18881 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18882 		ILM_WALKER_HOLD(ill);
18883 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18884 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18885 			ASSERT(ilm->ilm_ipif == NULL);
18886 			ASSERT(ilm->ilm_ill != NULL);
18887 			sl = ilm->ilm_filter;
18888 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18889 				continue;
18890 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18891 			for (i = 0; i < sl->sl_numsrc; i++) {
18892 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18893 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18894 				    (char *)&ips6, (int)sizeof (ips6))) {
18895 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18896 					    "group_src: failed to allocate "
18897 					    "%u bytes\n",
18898 					    (uint_t)sizeof (ips6)));
18899 				}
18900 			}
18901 		}
18902 		ILM_WALKER_RELE(ill);
18903 	}
18904 	rw_exit(&ipst->ips_ill_g_lock);
18905 
18906 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18907 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18908 	    (int)optp->level, (int)optp->name, (int)optp->len));
18909 	qreply(q, mpctl);
18910 	return (mp2ctl);
18911 }
18912 
18913 /* Multicast routing virtual interface table. */
18914 static mblk_t *
18915 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18916 {
18917 	struct opthdr		*optp;
18918 	mblk_t			*mp2ctl;
18919 
18920 	/*
18921 	 * make a copy of the original message
18922 	 */
18923 	mp2ctl = copymsg(mpctl);
18924 
18925 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18926 	optp->level = EXPER_DVMRP;
18927 	optp->name = EXPER_DVMRP_VIF;
18928 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18929 		ip0dbg(("ip_mroute_vif: failed\n"));
18930 	}
18931 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18932 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18933 	    (int)optp->level, (int)optp->name, (int)optp->len));
18934 	qreply(q, mpctl);
18935 	return (mp2ctl);
18936 }
18937 
18938 /* Multicast routing table. */
18939 static mblk_t *
18940 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18941 {
18942 	struct opthdr		*optp;
18943 	mblk_t			*mp2ctl;
18944 
18945 	/*
18946 	 * make a copy of the original message
18947 	 */
18948 	mp2ctl = copymsg(mpctl);
18949 
18950 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18951 	optp->level = EXPER_DVMRP;
18952 	optp->name = EXPER_DVMRP_MRT;
18953 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18954 		ip0dbg(("ip_mroute_mrt: failed\n"));
18955 	}
18956 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18957 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18958 	    (int)optp->level, (int)optp->name, (int)optp->len));
18959 	qreply(q, mpctl);
18960 	return (mp2ctl);
18961 }
18962 
18963 /*
18964  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18965  * in one IRE walk.
18966  */
18967 static mblk_t *
18968 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18969 {
18970 	struct opthdr	*optp;
18971 	mblk_t		*mp2ctl;	/* Returned */
18972 	mblk_t		*mp3ctl;	/* nettomedia */
18973 	mblk_t		*mp4ctl;	/* routeattrs */
18974 	iproutedata_t	ird;
18975 	zoneid_t	zoneid;
18976 
18977 	/*
18978 	 * make copies of the original message
18979 	 *	- mp2ctl is returned unchanged to the caller for his use
18980 	 *	- mpctl is sent upstream as ipRouteEntryTable
18981 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18982 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18983 	 */
18984 	mp2ctl = copymsg(mpctl);
18985 	mp3ctl = copymsg(mpctl);
18986 	mp4ctl = copymsg(mpctl);
18987 	if (mp3ctl == NULL || mp4ctl == NULL) {
18988 		freemsg(mp4ctl);
18989 		freemsg(mp3ctl);
18990 		freemsg(mp2ctl);
18991 		freemsg(mpctl);
18992 		return (NULL);
18993 	}
18994 
18995 	bzero(&ird, sizeof (ird));
18996 
18997 	ird.ird_route.lp_head = mpctl->b_cont;
18998 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18999 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19000 
19001 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19002 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19003 
19004 	/* ipRouteEntryTable in mpctl */
19005 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19006 	optp->level = MIB2_IP;
19007 	optp->name = MIB2_IP_ROUTE;
19008 	optp->len = msgdsize(ird.ird_route.lp_head);
19009 	ip3dbg(("ip_snmp_get_mib2_ip_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 	/* ipNetToMediaEntryTable in mp3ctl */
19014 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19015 	optp->level = MIB2_IP;
19016 	optp->name = MIB2_IP_MEDIA;
19017 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19018 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19019 	    (int)optp->level, (int)optp->name, (int)optp->len));
19020 	qreply(q, mp3ctl);
19021 
19022 	/* ipRouteAttributeTable in mp4ctl */
19023 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19024 	optp->level = MIB2_IP;
19025 	optp->name = EXPER_IP_RTATTR;
19026 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19027 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19028 	    (int)optp->level, (int)optp->name, (int)optp->len));
19029 	if (optp->len == 0)
19030 		freemsg(mp4ctl);
19031 	else
19032 		qreply(q, mp4ctl);
19033 
19034 	return (mp2ctl);
19035 }
19036 
19037 /*
19038  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19039  * ipv6NetToMediaEntryTable in an NDP walk.
19040  */
19041 static mblk_t *
19042 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19043 {
19044 	struct opthdr	*optp;
19045 	mblk_t		*mp2ctl;	/* Returned */
19046 	mblk_t		*mp3ctl;	/* nettomedia */
19047 	mblk_t		*mp4ctl;	/* routeattrs */
19048 	iproutedata_t	ird;
19049 	zoneid_t	zoneid;
19050 
19051 	/*
19052 	 * make copies of the original message
19053 	 *	- mp2ctl is returned unchanged to the caller for his use
19054 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19055 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19056 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19057 	 */
19058 	mp2ctl = copymsg(mpctl);
19059 	mp3ctl = copymsg(mpctl);
19060 	mp4ctl = copymsg(mpctl);
19061 	if (mp3ctl == NULL || mp4ctl == NULL) {
19062 		freemsg(mp4ctl);
19063 		freemsg(mp3ctl);
19064 		freemsg(mp2ctl);
19065 		freemsg(mpctl);
19066 		return (NULL);
19067 	}
19068 
19069 	bzero(&ird, sizeof (ird));
19070 
19071 	ird.ird_route.lp_head = mpctl->b_cont;
19072 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19073 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19074 
19075 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19076 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19077 
19078 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19079 	optp->level = MIB2_IP6;
19080 	optp->name = MIB2_IP6_ROUTE;
19081 	optp->len = msgdsize(ird.ird_route.lp_head);
19082 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19083 	    (int)optp->level, (int)optp->name, (int)optp->len));
19084 	qreply(q, mpctl);
19085 
19086 	/* ipv6NetToMediaEntryTable in mp3ctl */
19087 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19088 
19089 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19090 	optp->level = MIB2_IP6;
19091 	optp->name = MIB2_IP6_MEDIA;
19092 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19093 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19094 	    (int)optp->level, (int)optp->name, (int)optp->len));
19095 	qreply(q, mp3ctl);
19096 
19097 	/* ipv6RouteAttributeTable in mp4ctl */
19098 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19099 	optp->level = MIB2_IP6;
19100 	optp->name = EXPER_IP_RTATTR;
19101 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19102 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19103 	    (int)optp->level, (int)optp->name, (int)optp->len));
19104 	if (optp->len == 0)
19105 		freemsg(mp4ctl);
19106 	else
19107 		qreply(q, mp4ctl);
19108 
19109 	return (mp2ctl);
19110 }
19111 
19112 /*
19113  * IPv6 mib: One per ill
19114  */
19115 static mblk_t *
19116 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19117 {
19118 	struct opthdr		*optp;
19119 	mblk_t			*mp2ctl;
19120 	ill_t			*ill;
19121 	ill_walk_context_t	ctx;
19122 	mblk_t			*mp_tail = NULL;
19123 
19124 	/*
19125 	 * Make a copy of the original message
19126 	 */
19127 	mp2ctl = copymsg(mpctl);
19128 
19129 	/* fixed length IPv6 structure ... */
19130 
19131 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19132 	optp->level = MIB2_IP6;
19133 	optp->name = 0;
19134 	/* Include "unknown interface" ip6_mib */
19135 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19136 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19137 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19138 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19139 	    ipst->ips_ipv6_forward ? 1 : 2);
19140 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19141 	    ipst->ips_ipv6_def_hops);
19142 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19143 	    sizeof (mib2_ipIfStatsEntry_t));
19144 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19145 	    sizeof (mib2_ipv6AddrEntry_t));
19146 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19147 	    sizeof (mib2_ipv6RouteEntry_t));
19148 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19149 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19150 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19151 	    sizeof (ipv6_member_t));
19152 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19153 	    sizeof (ipv6_grpsrc_t));
19154 
19155 	/*
19156 	 * Synchronize 64- and 32-bit counters
19157 	 */
19158 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19159 	    ipIfStatsHCInReceives);
19160 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19161 	    ipIfStatsHCInDelivers);
19162 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19163 	    ipIfStatsHCOutRequests);
19164 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19165 	    ipIfStatsHCOutForwDatagrams);
19166 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19167 	    ipIfStatsHCOutMcastPkts);
19168 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19169 	    ipIfStatsHCInMcastPkts);
19170 
19171 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19172 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19173 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19174 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19175 	}
19176 
19177 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19178 	ill = ILL_START_WALK_V6(&ctx, ipst);
19179 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19180 		ill->ill_ip_mib->ipIfStatsIfIndex =
19181 		    ill->ill_phyint->phyint_ifindex;
19182 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19183 		    ipst->ips_ipv6_forward ? 1 : 2);
19184 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19185 		    ill->ill_max_hops);
19186 
19187 		/*
19188 		 * Synchronize 64- and 32-bit counters
19189 		 */
19190 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19191 		    ipIfStatsHCInReceives);
19192 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19193 		    ipIfStatsHCInDelivers);
19194 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19195 		    ipIfStatsHCOutRequests);
19196 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19197 		    ipIfStatsHCOutForwDatagrams);
19198 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19199 		    ipIfStatsHCOutMcastPkts);
19200 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19201 		    ipIfStatsHCInMcastPkts);
19202 
19203 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19204 		    (char *)ill->ill_ip_mib,
19205 		    (int)sizeof (*ill->ill_ip_mib))) {
19206 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19207 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19208 		}
19209 	}
19210 	rw_exit(&ipst->ips_ill_g_lock);
19211 
19212 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19213 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19214 	    (int)optp->level, (int)optp->name, (int)optp->len));
19215 	qreply(q, mpctl);
19216 	return (mp2ctl);
19217 }
19218 
19219 /*
19220  * ICMPv6 mib: One per ill
19221  */
19222 static mblk_t *
19223 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19224 {
19225 	struct opthdr		*optp;
19226 	mblk_t			*mp2ctl;
19227 	ill_t			*ill;
19228 	ill_walk_context_t	ctx;
19229 	mblk_t			*mp_tail = NULL;
19230 	/*
19231 	 * Make a copy of the original message
19232 	 */
19233 	mp2ctl = copymsg(mpctl);
19234 
19235 	/* fixed length ICMPv6 structure ... */
19236 
19237 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19238 	optp->level = MIB2_ICMP6;
19239 	optp->name = 0;
19240 	/* Include "unknown interface" icmp6_mib */
19241 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19242 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19243 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19244 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19245 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19246 	    (char *)&ipst->ips_icmp6_mib,
19247 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19248 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19249 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19250 	}
19251 
19252 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19253 	ill = ILL_START_WALK_V6(&ctx, ipst);
19254 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19255 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19256 		    ill->ill_phyint->phyint_ifindex;
19257 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19258 		    (char *)ill->ill_icmp6_mib,
19259 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19260 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19261 			    "%u bytes\n",
19262 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19263 		}
19264 	}
19265 	rw_exit(&ipst->ips_ill_g_lock);
19266 
19267 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19268 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19269 	    (int)optp->level, (int)optp->name, (int)optp->len));
19270 	qreply(q, mpctl);
19271 	return (mp2ctl);
19272 }
19273 
19274 /*
19275  * ire_walk routine to create both ipRouteEntryTable and
19276  * ipRouteAttributeTable in one IRE walk
19277  */
19278 static void
19279 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19280 {
19281 	ill_t				*ill;
19282 	ipif_t				*ipif;
19283 	mib2_ipRouteEntry_t		*re;
19284 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19285 	ipaddr_t			gw_addr;
19286 	tsol_ire_gw_secattr_t		*attrp;
19287 	tsol_gc_t			*gc = NULL;
19288 	tsol_gcgrp_t			*gcgrp = NULL;
19289 	uint_t				sacnt = 0;
19290 	int				i;
19291 
19292 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19293 
19294 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19295 		return;
19296 
19297 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19298 		mutex_enter(&attrp->igsa_lock);
19299 		if ((gc = attrp->igsa_gc) != NULL) {
19300 			gcgrp = gc->gc_grp;
19301 			ASSERT(gcgrp != NULL);
19302 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19303 			sacnt = 1;
19304 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19305 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19306 			gc = gcgrp->gcgrp_head;
19307 			sacnt = gcgrp->gcgrp_count;
19308 		}
19309 		mutex_exit(&attrp->igsa_lock);
19310 
19311 		/* do nothing if there's no gc to report */
19312 		if (gc == NULL) {
19313 			ASSERT(sacnt == 0);
19314 			if (gcgrp != NULL) {
19315 				/* we might as well drop the lock now */
19316 				rw_exit(&gcgrp->gcgrp_rwlock);
19317 				gcgrp = NULL;
19318 			}
19319 			attrp = NULL;
19320 		}
19321 
19322 		ASSERT(gc == NULL || (gcgrp != NULL &&
19323 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19324 	}
19325 	ASSERT(sacnt == 0 || gc != NULL);
19326 
19327 	if (sacnt != 0 &&
19328 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19329 		kmem_free(re, sizeof (*re));
19330 		rw_exit(&gcgrp->gcgrp_rwlock);
19331 		return;
19332 	}
19333 
19334 	/*
19335 	 * Return all IRE types for route table... let caller pick and choose
19336 	 */
19337 	re->ipRouteDest = ire->ire_addr;
19338 	ipif = ire->ire_ipif;
19339 	re->ipRouteIfIndex.o_length = 0;
19340 	if (ire->ire_type == IRE_CACHE) {
19341 		ill = (ill_t *)ire->ire_stq->q_ptr;
19342 		re->ipRouteIfIndex.o_length =
19343 		    ill->ill_name_length == 0 ? 0 :
19344 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19345 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19346 		    re->ipRouteIfIndex.o_length);
19347 	} else if (ipif != NULL) {
19348 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19349 		re->ipRouteIfIndex.o_length =
19350 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19351 	}
19352 	re->ipRouteMetric1 = -1;
19353 	re->ipRouteMetric2 = -1;
19354 	re->ipRouteMetric3 = -1;
19355 	re->ipRouteMetric4 = -1;
19356 
19357 	gw_addr = ire->ire_gateway_addr;
19358 
19359 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19360 		re->ipRouteNextHop = ire->ire_src_addr;
19361 	else
19362 		re->ipRouteNextHop = gw_addr;
19363 	/* indirect(4), direct(3), or invalid(2) */
19364 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19365 		re->ipRouteType = 2;
19366 	else
19367 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19368 	re->ipRouteProto = -1;
19369 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19370 	re->ipRouteMask = ire->ire_mask;
19371 	re->ipRouteMetric5 = -1;
19372 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19373 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19374 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19375 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19376 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19377 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19378 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19379 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19380 
19381 	if (ire->ire_flags & RTF_DYNAMIC) {
19382 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19383 	} else {
19384 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19385 	}
19386 
19387 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19388 	    (char *)re, (int)sizeof (*re))) {
19389 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19390 		    (uint_t)sizeof (*re)));
19391 	}
19392 
19393 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19394 		iaeptr->iae_routeidx = ird->ird_idx;
19395 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19396 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19397 	}
19398 
19399 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19400 	    (char *)iae, sacnt * sizeof (*iae))) {
19401 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19402 		    (unsigned)(sacnt * sizeof (*iae))));
19403 	}
19404 
19405 	/* bump route index for next pass */
19406 	ird->ird_idx++;
19407 
19408 	kmem_free(re, sizeof (*re));
19409 	if (sacnt != 0)
19410 		kmem_free(iae, sacnt * sizeof (*iae));
19411 
19412 	if (gcgrp != NULL)
19413 		rw_exit(&gcgrp->gcgrp_rwlock);
19414 }
19415 
19416 /*
19417  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19418  */
19419 static void
19420 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19421 {
19422 	ill_t				*ill;
19423 	ipif_t				*ipif;
19424 	mib2_ipv6RouteEntry_t		*re;
19425 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19426 	in6_addr_t			gw_addr_v6;
19427 	tsol_ire_gw_secattr_t		*attrp;
19428 	tsol_gc_t			*gc = NULL;
19429 	tsol_gcgrp_t			*gcgrp = NULL;
19430 	uint_t				sacnt = 0;
19431 	int				i;
19432 
19433 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19434 
19435 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19436 		return;
19437 
19438 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19439 		mutex_enter(&attrp->igsa_lock);
19440 		if ((gc = attrp->igsa_gc) != NULL) {
19441 			gcgrp = gc->gc_grp;
19442 			ASSERT(gcgrp != NULL);
19443 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19444 			sacnt = 1;
19445 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19446 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19447 			gc = gcgrp->gcgrp_head;
19448 			sacnt = gcgrp->gcgrp_count;
19449 		}
19450 		mutex_exit(&attrp->igsa_lock);
19451 
19452 		/* do nothing if there's no gc to report */
19453 		if (gc == NULL) {
19454 			ASSERT(sacnt == 0);
19455 			if (gcgrp != NULL) {
19456 				/* we might as well drop the lock now */
19457 				rw_exit(&gcgrp->gcgrp_rwlock);
19458 				gcgrp = NULL;
19459 			}
19460 			attrp = NULL;
19461 		}
19462 
19463 		ASSERT(gc == NULL || (gcgrp != NULL &&
19464 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19465 	}
19466 	ASSERT(sacnt == 0 || gc != NULL);
19467 
19468 	if (sacnt != 0 &&
19469 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19470 		kmem_free(re, sizeof (*re));
19471 		rw_exit(&gcgrp->gcgrp_rwlock);
19472 		return;
19473 	}
19474 
19475 	/*
19476 	 * Return all IRE types for route table... let caller pick and choose
19477 	 */
19478 	re->ipv6RouteDest = ire->ire_addr_v6;
19479 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19480 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19481 	re->ipv6RouteIfIndex.o_length = 0;
19482 	ipif = ire->ire_ipif;
19483 	if (ire->ire_type == IRE_CACHE) {
19484 		ill = (ill_t *)ire->ire_stq->q_ptr;
19485 		re->ipv6RouteIfIndex.o_length =
19486 		    ill->ill_name_length == 0 ? 0 :
19487 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19488 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19489 		    re->ipv6RouteIfIndex.o_length);
19490 	} else if (ipif != NULL) {
19491 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19492 		re->ipv6RouteIfIndex.o_length =
19493 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19494 	}
19495 
19496 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19497 
19498 	mutex_enter(&ire->ire_lock);
19499 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19500 	mutex_exit(&ire->ire_lock);
19501 
19502 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19503 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19504 	else
19505 		re->ipv6RouteNextHop = gw_addr_v6;
19506 
19507 	/* remote(4), local(3), or discard(2) */
19508 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19509 		re->ipv6RouteType = 2;
19510 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19511 		re->ipv6RouteType = 3;
19512 	else
19513 		re->ipv6RouteType = 4;
19514 
19515 	re->ipv6RouteProtocol	= -1;
19516 	re->ipv6RoutePolicy	= 0;
19517 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19518 	re->ipv6RouteNextHopRDI	= 0;
19519 	re->ipv6RouteWeight	= 0;
19520 	re->ipv6RouteMetric	= 0;
19521 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19522 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19523 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19524 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19525 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19526 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19527 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19528 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19529 
19530 	if (ire->ire_flags & RTF_DYNAMIC) {
19531 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19532 	} else {
19533 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19534 	}
19535 
19536 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19537 	    (char *)re, (int)sizeof (*re))) {
19538 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19539 		    (uint_t)sizeof (*re)));
19540 	}
19541 
19542 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19543 		iaeptr->iae_routeidx = ird->ird_idx;
19544 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19545 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19546 	}
19547 
19548 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19549 	    (char *)iae, sacnt * sizeof (*iae))) {
19550 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19551 		    (unsigned)(sacnt * sizeof (*iae))));
19552 	}
19553 
19554 	/* bump route index for next pass */
19555 	ird->ird_idx++;
19556 
19557 	kmem_free(re, sizeof (*re));
19558 	if (sacnt != 0)
19559 		kmem_free(iae, sacnt * sizeof (*iae));
19560 
19561 	if (gcgrp != NULL)
19562 		rw_exit(&gcgrp->gcgrp_rwlock);
19563 }
19564 
19565 /*
19566  * ndp_walk routine to create ipv6NetToMediaEntryTable
19567  */
19568 static int
19569 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19570 {
19571 	ill_t				*ill;
19572 	mib2_ipv6NetToMediaEntry_t	ntme;
19573 	dl_unitdata_req_t		*dl;
19574 
19575 	ill = nce->nce_ill;
19576 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19577 		return (0);
19578 
19579 	/*
19580 	 * Neighbor cache entry attached to IRE with on-link
19581 	 * destination.
19582 	 */
19583 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19584 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19585 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19586 	    (nce->nce_res_mp != NULL)) {
19587 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19588 		ntme.ipv6NetToMediaPhysAddress.o_length =
19589 		    dl->dl_dest_addr_length;
19590 	} else {
19591 		ntme.ipv6NetToMediaPhysAddress.o_length =
19592 		    ill->ill_phys_addr_length;
19593 	}
19594 	if (nce->nce_res_mp != NULL) {
19595 		bcopy((char *)nce->nce_res_mp->b_rptr +
19596 		    NCE_LL_ADDR_OFFSET(ill),
19597 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19598 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19599 	} else {
19600 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19601 		    ill->ill_phys_addr_length);
19602 	}
19603 	/*
19604 	 * Note: Returns ND_* states. Should be:
19605 	 * reachable(1), stale(2), delay(3), probe(4),
19606 	 * invalid(5), unknown(6)
19607 	 */
19608 	ntme.ipv6NetToMediaState = nce->nce_state;
19609 	ntme.ipv6NetToMediaLastUpdated = 0;
19610 
19611 	/* other(1), dynamic(2), static(3), local(4) */
19612 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19613 		ntme.ipv6NetToMediaType = 4;
19614 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19615 		ntme.ipv6NetToMediaType = 1;
19616 	} else {
19617 		ntme.ipv6NetToMediaType = 2;
19618 	}
19619 
19620 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19621 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19622 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19623 		    (uint_t)sizeof (ntme)));
19624 	}
19625 	return (0);
19626 }
19627 
19628 /*
19629  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19630  */
19631 /* ARGSUSED */
19632 int
19633 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19634 {
19635 	switch (level) {
19636 	case MIB2_IP:
19637 	case MIB2_ICMP:
19638 		switch (name) {
19639 		default:
19640 			break;
19641 		}
19642 		return (1);
19643 	default:
19644 		return (1);
19645 	}
19646 }
19647 
19648 /*
19649  * When there exists both a 64- and 32-bit counter of a particular type
19650  * (i.e., InReceives), only the 64-bit counters are added.
19651  */
19652 void
19653 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19654 {
19655 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19656 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19657 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19658 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19659 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19660 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19661 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19662 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19663 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19664 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19665 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19666 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19667 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19668 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19669 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19670 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19671 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19672 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19673 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19674 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19675 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19676 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19677 	    o2->ipIfStatsInWrongIPVersion);
19678 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19679 	    o2->ipIfStatsInWrongIPVersion);
19680 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19681 	    o2->ipIfStatsOutSwitchIPVersion);
19682 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19683 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19684 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19685 	    o2->ipIfStatsHCInForwDatagrams);
19686 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19687 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19688 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19689 	    o2->ipIfStatsHCOutForwDatagrams);
19690 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19691 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19692 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19693 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19694 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19695 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19696 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19697 	    o2->ipIfStatsHCOutMcastOctets);
19698 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19699 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19700 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19701 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19702 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19703 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19704 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19705 }
19706 
19707 void
19708 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19709 {
19710 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19711 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19712 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19713 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19714 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19715 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19716 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19717 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19718 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19719 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19720 	    o2->ipv6IfIcmpInRouterSolicits);
19721 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19722 	    o2->ipv6IfIcmpInRouterAdvertisements);
19723 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19724 	    o2->ipv6IfIcmpInNeighborSolicits);
19725 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19726 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19727 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19728 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19729 	    o2->ipv6IfIcmpInGroupMembQueries);
19730 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19731 	    o2->ipv6IfIcmpInGroupMembResponses);
19732 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19733 	    o2->ipv6IfIcmpInGroupMembReductions);
19734 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19735 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19736 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19737 	    o2->ipv6IfIcmpOutDestUnreachs);
19738 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19739 	    o2->ipv6IfIcmpOutAdminProhibs);
19740 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19741 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19742 	    o2->ipv6IfIcmpOutParmProblems);
19743 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19744 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19745 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19746 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19747 	    o2->ipv6IfIcmpOutRouterSolicits);
19748 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19749 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19750 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19751 	    o2->ipv6IfIcmpOutNeighborSolicits);
19752 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19753 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19754 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19755 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19756 	    o2->ipv6IfIcmpOutGroupMembQueries);
19757 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19758 	    o2->ipv6IfIcmpOutGroupMembResponses);
19759 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19760 	    o2->ipv6IfIcmpOutGroupMembReductions);
19761 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19762 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19763 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19764 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19765 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19766 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19767 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19768 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19769 	    o2->ipv6IfIcmpInGroupMembTotal);
19770 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19771 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19772 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19773 	    o2->ipv6IfIcmpInGroupMembBadReports);
19774 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19775 	    o2->ipv6IfIcmpInGroupMembOurReports);
19776 }
19777 
19778 /*
19779  * Called before the options are updated to check if this packet will
19780  * be source routed from here.
19781  * This routine assumes that the options are well formed i.e. that they
19782  * have already been checked.
19783  */
19784 static boolean_t
19785 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19786 {
19787 	ipoptp_t	opts;
19788 	uchar_t		*opt;
19789 	uint8_t		optval;
19790 	uint8_t		optlen;
19791 	ipaddr_t	dst;
19792 	ire_t		*ire;
19793 
19794 	if (IS_SIMPLE_IPH(ipha)) {
19795 		ip2dbg(("not source routed\n"));
19796 		return (B_FALSE);
19797 	}
19798 	dst = ipha->ipha_dst;
19799 	for (optval = ipoptp_first(&opts, ipha);
19800 	    optval != IPOPT_EOL;
19801 	    optval = ipoptp_next(&opts)) {
19802 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19803 		opt = opts.ipoptp_cur;
19804 		optlen = opts.ipoptp_len;
19805 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19806 		    optval, optlen));
19807 		switch (optval) {
19808 			uint32_t off;
19809 		case IPOPT_SSRR:
19810 		case IPOPT_LSRR:
19811 			/*
19812 			 * If dst is one of our addresses and there are some
19813 			 * entries left in the source route return (true).
19814 			 */
19815 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19816 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19817 			if (ire == NULL) {
19818 				ip2dbg(("ip_source_routed: not next"
19819 				    " source route 0x%x\n",
19820 				    ntohl(dst)));
19821 				return (B_FALSE);
19822 			}
19823 			ire_refrele(ire);
19824 			off = opt[IPOPT_OFFSET];
19825 			off--;
19826 			if (optlen < IP_ADDR_LEN ||
19827 			    off > optlen - IP_ADDR_LEN) {
19828 				/* End of source route */
19829 				ip1dbg(("ip_source_routed: end of SR\n"));
19830 				return (B_FALSE);
19831 			}
19832 			return (B_TRUE);
19833 		}
19834 	}
19835 	ip2dbg(("not source routed\n"));
19836 	return (B_FALSE);
19837 }
19838 
19839 /*
19840  * Check if the packet contains any source route.
19841  */
19842 static boolean_t
19843 ip_source_route_included(ipha_t *ipha)
19844 {
19845 	ipoptp_t	opts;
19846 	uint8_t		optval;
19847 
19848 	if (IS_SIMPLE_IPH(ipha))
19849 		return (B_FALSE);
19850 	for (optval = ipoptp_first(&opts, ipha);
19851 	    optval != IPOPT_EOL;
19852 	    optval = ipoptp_next(&opts)) {
19853 		switch (optval) {
19854 		case IPOPT_SSRR:
19855 		case IPOPT_LSRR:
19856 			return (B_TRUE);
19857 		}
19858 	}
19859 	return (B_FALSE);
19860 }
19861 
19862 /*
19863  * Called when the IRE expiration timer fires.
19864  */
19865 void
19866 ip_trash_timer_expire(void *args)
19867 {
19868 	int			flush_flag = 0;
19869 	ire_expire_arg_t	iea;
19870 	ip_stack_t		*ipst = (ip_stack_t *)args;
19871 
19872 	iea.iea_ipst = ipst;	/* No netstack_hold */
19873 
19874 	/*
19875 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19876 	 * This lock makes sure that a new invocation of this function
19877 	 * that occurs due to an almost immediate timer firing will not
19878 	 * progress beyond this point until the current invocation is done
19879 	 */
19880 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19881 	ipst->ips_ip_ire_expire_id = 0;
19882 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19883 
19884 	/* Periodic timer */
19885 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19886 	    ipst->ips_ip_ire_arp_interval) {
19887 		/*
19888 		 * Remove all IRE_CACHE entries since they might
19889 		 * contain arp information.
19890 		 */
19891 		flush_flag |= FLUSH_ARP_TIME;
19892 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19893 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19894 	}
19895 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19896 	    ipst->ips_ip_ire_redir_interval) {
19897 		/* Remove all redirects */
19898 		flush_flag |= FLUSH_REDIRECT_TIME;
19899 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19900 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19901 	}
19902 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19903 	    ipst->ips_ip_ire_pathmtu_interval) {
19904 		/* Increase path mtu */
19905 		flush_flag |= FLUSH_MTU_TIME;
19906 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19907 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19908 	}
19909 
19910 	/*
19911 	 * Optimize for the case when there are no redirects in the
19912 	 * ftable, that is, no need to walk the ftable in that case.
19913 	 */
19914 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19915 		iea.iea_flush_flag = flush_flag;
19916 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19917 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19918 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19919 		    NULL, ALL_ZONES, ipst);
19920 	}
19921 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19922 	    ipst->ips_ip_redirect_cnt > 0) {
19923 		iea.iea_flush_flag = flush_flag;
19924 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19925 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19926 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19927 	}
19928 	if (flush_flag & FLUSH_MTU_TIME) {
19929 		/*
19930 		 * Walk all IPv6 IRE's and update them
19931 		 * Note that ARP and redirect timers are not
19932 		 * needed since NUD handles stale entries.
19933 		 */
19934 		flush_flag = FLUSH_MTU_TIME;
19935 		iea.iea_flush_flag = flush_flag;
19936 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19937 		    ALL_ZONES, ipst);
19938 	}
19939 
19940 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19941 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19942 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19943 
19944 	/*
19945 	 * Hold the lock to serialize timeout calls and prevent
19946 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19947 	 * for the timer to fire and a new invocation of this function
19948 	 * to start before the return value of timeout has been stored
19949 	 * in ip_ire_expire_id by the current invocation.
19950 	 */
19951 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19952 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19953 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19954 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19955 }
19956 
19957 /*
19958  * Called by the memory allocator subsystem directly, when the system
19959  * is running low on memory.
19960  */
19961 /* ARGSUSED */
19962 void
19963 ip_trash_ire_reclaim(void *args)
19964 {
19965 	netstack_handle_t nh;
19966 	netstack_t *ns;
19967 
19968 	netstack_next_init(&nh);
19969 	while ((ns = netstack_next(&nh)) != NULL) {
19970 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19971 		netstack_rele(ns);
19972 	}
19973 	netstack_next_fini(&nh);
19974 }
19975 
19976 static void
19977 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19978 {
19979 	ire_cache_count_t icc;
19980 	ire_cache_reclaim_t icr;
19981 	ncc_cache_count_t ncc;
19982 	nce_cache_reclaim_t ncr;
19983 	uint_t delete_cnt;
19984 	/*
19985 	 * Memory reclaim call back.
19986 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19987 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19988 	 * entries, determine what fraction to free for
19989 	 * each category of IRE_CACHE entries giving absolute priority
19990 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19991 	 * entry will be freed unless all offlink entries are freed).
19992 	 */
19993 	icc.icc_total = 0;
19994 	icc.icc_unused = 0;
19995 	icc.icc_offlink = 0;
19996 	icc.icc_pmtu = 0;
19997 	icc.icc_onlink = 0;
19998 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19999 
20000 	/*
20001 	 * Free NCEs for IPv6 like the onlink ires.
20002 	 */
20003 	ncc.ncc_total = 0;
20004 	ncc.ncc_host = 0;
20005 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20006 
20007 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20008 	    icc.icc_pmtu + icc.icc_onlink);
20009 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20010 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20011 	if (delete_cnt == 0)
20012 		return;
20013 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20014 	/* Always delete all unused offlink entries */
20015 	icr.icr_ipst = ipst;
20016 	icr.icr_unused = 1;
20017 	if (delete_cnt <= icc.icc_unused) {
20018 		/*
20019 		 * Only need to free unused entries.  In other words,
20020 		 * there are enough unused entries to free to meet our
20021 		 * target number of freed ire cache entries.
20022 		 */
20023 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20024 		ncr.ncr_host = 0;
20025 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20026 		/*
20027 		 * Only need to free unused entries, plus a fraction of offlink
20028 		 * entries.  It follows from the first if statement that
20029 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20030 		 */
20031 		delete_cnt -= icc.icc_unused;
20032 		/* Round up # deleted by truncating fraction */
20033 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20034 		icr.icr_pmtu = icr.icr_onlink = 0;
20035 		ncr.ncr_host = 0;
20036 	} else if (delete_cnt <=
20037 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20038 		/*
20039 		 * Free all unused and offlink entries, plus a fraction of
20040 		 * pmtu entries.  It follows from the previous if statement
20041 		 * that icc_pmtu is non-zero, and that
20042 		 * delete_cnt != icc_unused + icc_offlink.
20043 		 */
20044 		icr.icr_offlink = 1;
20045 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20046 		/* Round up # deleted by truncating fraction */
20047 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20048 		icr.icr_onlink = 0;
20049 		ncr.ncr_host = 0;
20050 	} else {
20051 		/*
20052 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20053 		 * of onlink entries.  If we're here, then we know that
20054 		 * icc_onlink is non-zero, and that
20055 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20056 		 */
20057 		icr.icr_offlink = icr.icr_pmtu = 1;
20058 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20059 		    icc.icc_pmtu;
20060 		/* Round up # deleted by truncating fraction */
20061 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20062 		/* Using the same delete fraction as for onlink IREs */
20063 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20064 	}
20065 #ifdef DEBUG
20066 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20067 	    "fractions %d/%d/%d/%d\n",
20068 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20069 	    icc.icc_unused, icc.icc_offlink,
20070 	    icc.icc_pmtu, icc.icc_onlink,
20071 	    icr.icr_unused, icr.icr_offlink,
20072 	    icr.icr_pmtu, icr.icr_onlink));
20073 #endif
20074 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20075 	if (ncr.ncr_host != 0)
20076 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20077 		    (uchar_t *)&ncr, ipst);
20078 #ifdef DEBUG
20079 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20080 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20081 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20082 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20083 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20084 	    icc.icc_pmtu, icc.icc_onlink));
20085 #endif
20086 }
20087 
20088 /*
20089  * ip_unbind is called when a copy of an unbind request is received from the
20090  * upper level protocol.  We remove this conn from any fanout hash list it is
20091  * on, and zero out the bind information.  No reply is expected up above.
20092  */
20093 mblk_t *
20094 ip_unbind(queue_t *q, mblk_t *mp)
20095 {
20096 	conn_t	*connp = Q_TO_CONN(q);
20097 
20098 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20099 
20100 	if (is_system_labeled() && connp->conn_anon_port) {
20101 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20102 		    connp->conn_mlp_type, connp->conn_ulp,
20103 		    ntohs(connp->conn_lport), B_FALSE);
20104 		connp->conn_anon_port = 0;
20105 	}
20106 	connp->conn_mlp_type = mlptSingle;
20107 
20108 	ipcl_hash_remove(connp);
20109 
20110 	ASSERT(mp->b_cont == NULL);
20111 	/*
20112 	 * Convert mp into a T_OK_ACK
20113 	 */
20114 	mp = mi_tpi_ok_ack_alloc(mp);
20115 
20116 	/*
20117 	 * should not happen in practice... T_OK_ACK is smaller than the
20118 	 * original message.
20119 	 */
20120 	if (mp == NULL)
20121 		return (NULL);
20122 
20123 	return (mp);
20124 }
20125 
20126 /*
20127  * Write side put procedure.  Outbound data, IOCTLs, responses from
20128  * resolvers, etc, come down through here.
20129  *
20130  * arg2 is always a queue_t *.
20131  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20132  * the zoneid.
20133  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20134  */
20135 void
20136 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20137 {
20138 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20139 }
20140 
20141 void
20142 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20143     ip_opt_info_t *infop)
20144 {
20145 	conn_t		*connp = NULL;
20146 	queue_t		*q = (queue_t *)arg2;
20147 	ipha_t		*ipha;
20148 #define	rptr	((uchar_t *)ipha)
20149 	ire_t		*ire = NULL;
20150 	ire_t		*sctp_ire = NULL;
20151 	uint32_t	v_hlen_tos_len;
20152 	ipaddr_t	dst;
20153 	mblk_t		*first_mp = NULL;
20154 	boolean_t	mctl_present;
20155 	ipsec_out_t	*io;
20156 	int		match_flags;
20157 	ill_t		*attach_ill = NULL;
20158 					/* Bind to IPIF_NOFAILOVER ill etc. */
20159 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20160 	ipif_t		*dst_ipif;
20161 	boolean_t	multirt_need_resolve = B_FALSE;
20162 	mblk_t		*copy_mp = NULL;
20163 	int		err;
20164 	zoneid_t	zoneid;
20165 	boolean_t	need_decref = B_FALSE;
20166 	boolean_t	ignore_dontroute = B_FALSE;
20167 	boolean_t	ignore_nexthop = B_FALSE;
20168 	boolean_t	ip_nexthop = B_FALSE;
20169 	ipaddr_t	nexthop_addr;
20170 	ip_stack_t	*ipst;
20171 
20172 #ifdef	_BIG_ENDIAN
20173 #define	V_HLEN	(v_hlen_tos_len >> 24)
20174 #else
20175 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20176 #endif
20177 
20178 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20179 	    "ip_wput_start: q %p", q);
20180 
20181 	/*
20182 	 * ip_wput fast path
20183 	 */
20184 
20185 	/* is packet from ARP ? */
20186 	if (q->q_next != NULL) {
20187 		zoneid = (zoneid_t)(uintptr_t)arg;
20188 		goto qnext;
20189 	}
20190 
20191 	connp = (conn_t *)arg;
20192 	ASSERT(connp != NULL);
20193 	zoneid = connp->conn_zoneid;
20194 	ipst = connp->conn_netstack->netstack_ip;
20195 
20196 	/* is queue flow controlled? */
20197 	if ((q->q_first != NULL || connp->conn_draining) &&
20198 	    (caller == IP_WPUT)) {
20199 		ASSERT(!need_decref);
20200 		(void) putq(q, mp);
20201 		return;
20202 	}
20203 
20204 	/* Multidata transmit? */
20205 	if (DB_TYPE(mp) == M_MULTIDATA) {
20206 		/*
20207 		 * We should never get here, since all Multidata messages
20208 		 * originating from tcp should have been directed over to
20209 		 * tcp_multisend() in the first place.
20210 		 */
20211 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20212 		freemsg(mp);
20213 		return;
20214 	} else if (DB_TYPE(mp) != M_DATA)
20215 		goto notdata;
20216 
20217 	if (mp->b_flag & MSGHASREF) {
20218 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20219 		mp->b_flag &= ~MSGHASREF;
20220 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20221 		need_decref = B_TRUE;
20222 	}
20223 	ipha = (ipha_t *)mp->b_rptr;
20224 
20225 	/* is IP header non-aligned or mblk smaller than basic IP header */
20226 #ifndef SAFETY_BEFORE_SPEED
20227 	if (!OK_32PTR(rptr) ||
20228 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20229 		goto hdrtoosmall;
20230 #endif
20231 
20232 	ASSERT(OK_32PTR(ipha));
20233 
20234 	/*
20235 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20236 	 * wrong version, we'll catch it again in ip_output_v6.
20237 	 *
20238 	 * Note that this is *only* locally-generated output here, and never
20239 	 * forwarded data, and that we need to deal only with transports that
20240 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20241 	 * label.)
20242 	 */
20243 	if (is_system_labeled() &&
20244 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20245 	    !connp->conn_ulp_labeled) {
20246 		err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20247 		    connp->conn_mac_exempt, ipst);
20248 		ipha = (ipha_t *)mp->b_rptr;
20249 		if (err != 0) {
20250 			first_mp = mp;
20251 			if (err == EINVAL)
20252 				goto icmp_parameter_problem;
20253 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20254 			goto discard_pkt;
20255 		}
20256 	}
20257 
20258 	ASSERT(infop != NULL);
20259 
20260 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20261 		/*
20262 		 * IP_PKTINFO ancillary option is present.
20263 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20264 		 * allows using address of any zone as the source address.
20265 		 */
20266 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20267 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20268 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20269 		if (ire == NULL)
20270 			goto drop_pkt;
20271 		ire_refrele(ire);
20272 		ire = NULL;
20273 	}
20274 
20275 	/*
20276 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20277 	 * passed in IP_PKTINFO.
20278 	 */
20279 	if (infop->ip_opt_ill_index != 0 &&
20280 	    connp->conn_outgoing_ill == NULL &&
20281 	    connp->conn_nofailover_ill == NULL) {
20282 
20283 		xmit_ill = ill_lookup_on_ifindex(
20284 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20285 		    ipst);
20286 
20287 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20288 			goto drop_pkt;
20289 		/*
20290 		 * check that there is an ipif belonging
20291 		 * to our zone. IPCL_ZONEID is not used because
20292 		 * IP_ALLZONES option is valid only when the ill is
20293 		 * accessible from all zones i.e has a valid ipif in
20294 		 * all zones.
20295 		 */
20296 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20297 			goto drop_pkt;
20298 		}
20299 	}
20300 
20301 	/*
20302 	 * If there is a policy, try to attach an ipsec_out in
20303 	 * the front. At the end, first_mp either points to a
20304 	 * M_DATA message or IPSEC_OUT message linked to a
20305 	 * M_DATA message. We have to do it now as we might
20306 	 * lose the "conn" if we go through ip_newroute.
20307 	 */
20308 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20309 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20310 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20311 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20312 			if (need_decref)
20313 				CONN_DEC_REF(connp);
20314 			return;
20315 		} else {
20316 			ASSERT(mp->b_datap->db_type == M_CTL);
20317 			first_mp = mp;
20318 			mp = mp->b_cont;
20319 			mctl_present = B_TRUE;
20320 		}
20321 	} else {
20322 		first_mp = mp;
20323 		mctl_present = B_FALSE;
20324 	}
20325 
20326 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20327 
20328 	/* is wrong version or IP options present */
20329 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20330 		goto version_hdrlen_check;
20331 	dst = ipha->ipha_dst;
20332 
20333 	if (connp->conn_nofailover_ill != NULL) {
20334 		attach_ill = conn_get_held_ill(connp,
20335 		    &connp->conn_nofailover_ill, &err);
20336 		if (err == ILL_LOOKUP_FAILED) {
20337 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20338 			if (need_decref)
20339 				CONN_DEC_REF(connp);
20340 			freemsg(first_mp);
20341 			return;
20342 		}
20343 	}
20344 
20345 	/* If IP_BOUND_IF has been set, use that ill. */
20346 	if (connp->conn_outgoing_ill != NULL) {
20347 		xmit_ill = conn_get_held_ill(connp,
20348 		    &connp->conn_outgoing_ill, &err);
20349 		if (err == ILL_LOOKUP_FAILED)
20350 			goto drop_pkt;
20351 
20352 		goto send_from_ill;
20353 	}
20354 
20355 	/* is packet multicast? */
20356 	if (CLASSD(dst))
20357 		goto multicast;
20358 
20359 	/*
20360 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20361 	 * takes precedence over conn_dontroute and conn_nexthop_set
20362 	 */
20363 	if (xmit_ill != NULL)
20364 		goto send_from_ill;
20365 
20366 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20367 		/*
20368 		 * If the destination is a broadcast, local, or loopback
20369 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20370 		 * standard path.
20371 		 */
20372 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20373 		if ((ire == NULL) || (ire->ire_type &
20374 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20375 			if (ire != NULL) {
20376 				ire_refrele(ire);
20377 				/* No more access to ire */
20378 				ire = NULL;
20379 			}
20380 			/*
20381 			 * bypass routing checks and go directly to interface.
20382 			 */
20383 			if (connp->conn_dontroute)
20384 				goto dontroute;
20385 
20386 			ASSERT(connp->conn_nexthop_set);
20387 			ip_nexthop = B_TRUE;
20388 			nexthop_addr = connp->conn_nexthop_v4;
20389 			goto send_from_ill;
20390 		}
20391 
20392 		/* Must be a broadcast, a loopback or a local ire */
20393 		ire_refrele(ire);
20394 		/* No more access to ire */
20395 		ire = NULL;
20396 	}
20397 
20398 	if (attach_ill != NULL)
20399 		goto send_from_ill;
20400 
20401 	/*
20402 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20403 	 * this for the tcp global queue and listen end point
20404 	 * as it does not really have a real destination to
20405 	 * talk to.  This is also true for SCTP.
20406 	 */
20407 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20408 	    !connp->conn_fully_bound) {
20409 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20410 		if (ire == NULL)
20411 			goto noirefound;
20412 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20413 		    "ip_wput_end: q %p (%S)", q, "end");
20414 
20415 		/*
20416 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20417 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20418 		 */
20419 		if (ire->ire_flags & RTF_MULTIRT) {
20420 
20421 			/*
20422 			 * Force the TTL of multirouted packets if required.
20423 			 * The TTL of such packets is bounded by the
20424 			 * ip_multirt_ttl ndd variable.
20425 			 */
20426 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20427 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20428 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20429 				    "(was %d), dst 0x%08x\n",
20430 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20431 				    ntohl(ire->ire_addr)));
20432 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20433 			}
20434 			/*
20435 			 * We look at this point if there are pending
20436 			 * unresolved routes. ire_multirt_resolvable()
20437 			 * checks in O(n) that all IRE_OFFSUBNET ire
20438 			 * entries for the packet's destination and
20439 			 * flagged RTF_MULTIRT are currently resolved.
20440 			 * If some remain unresolved, we make a copy
20441 			 * of the current message. It will be used
20442 			 * to initiate additional route resolutions.
20443 			 */
20444 			multirt_need_resolve =
20445 			    ire_multirt_need_resolve(ire->ire_addr,
20446 			    MBLK_GETLABEL(first_mp), ipst);
20447 			ip2dbg(("ip_wput[TCP]: ire %p, "
20448 			    "multirt_need_resolve %d, first_mp %p\n",
20449 			    (void *)ire, multirt_need_resolve,
20450 			    (void *)first_mp));
20451 			if (multirt_need_resolve) {
20452 				copy_mp = copymsg(first_mp);
20453 				if (copy_mp != NULL) {
20454 					MULTIRT_DEBUG_TAG(copy_mp);
20455 				}
20456 			}
20457 		}
20458 
20459 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20460 
20461 		/*
20462 		 * Try to resolve another multiroute if
20463 		 * ire_multirt_need_resolve() deemed it necessary.
20464 		 */
20465 		if (copy_mp != NULL)
20466 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20467 		if (need_decref)
20468 			CONN_DEC_REF(connp);
20469 		return;
20470 	}
20471 
20472 	/*
20473 	 * Access to conn_ire_cache. (protected by conn_lock)
20474 	 *
20475 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20476 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20477 	 * send a packet or two with the IRE_CACHE that is going away.
20478 	 * Access to the ire requires an ire refhold on the ire prior to
20479 	 * its use since an interface unplumb thread may delete the cached
20480 	 * ire and release the refhold at any time.
20481 	 *
20482 	 * Caching an ire in the conn_ire_cache
20483 	 *
20484 	 * o Caching an ire pointer in the conn requires a strict check for
20485 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20486 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20487 	 * in the conn is done after making sure under the bucket lock that the
20488 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20489 	 * caching an ire after the unplumb thread has cleaned up the conn.
20490 	 * If the conn does not send a packet subsequently the unplumb thread
20491 	 * will be hanging waiting for the ire count to drop to zero.
20492 	 *
20493 	 * o We also need to atomically test for a null conn_ire_cache and
20494 	 * set the conn_ire_cache under the the protection of the conn_lock
20495 	 * to avoid races among concurrent threads trying to simultaneously
20496 	 * cache an ire in the conn_ire_cache.
20497 	 */
20498 	mutex_enter(&connp->conn_lock);
20499 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20500 
20501 	if (ire != NULL && ire->ire_addr == dst &&
20502 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20503 
20504 		IRE_REFHOLD(ire);
20505 		mutex_exit(&connp->conn_lock);
20506 
20507 	} else {
20508 		boolean_t cached = B_FALSE;
20509 		connp->conn_ire_cache = NULL;
20510 		mutex_exit(&connp->conn_lock);
20511 		/* Release the old ire */
20512 		if (ire != NULL && sctp_ire == NULL)
20513 			IRE_REFRELE_NOTR(ire);
20514 
20515 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20516 		if (ire == NULL)
20517 			goto noirefound;
20518 		IRE_REFHOLD_NOTR(ire);
20519 
20520 		mutex_enter(&connp->conn_lock);
20521 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20522 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20523 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20524 				if (connp->conn_ulp == IPPROTO_TCP)
20525 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20526 				connp->conn_ire_cache = ire;
20527 				cached = B_TRUE;
20528 			}
20529 			rw_exit(&ire->ire_bucket->irb_lock);
20530 		}
20531 		mutex_exit(&connp->conn_lock);
20532 
20533 		/*
20534 		 * We can continue to use the ire but since it was
20535 		 * not cached, we should drop the extra reference.
20536 		 */
20537 		if (!cached)
20538 			IRE_REFRELE_NOTR(ire);
20539 	}
20540 
20541 
20542 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20543 	    "ip_wput_end: q %p (%S)", q, "end");
20544 
20545 	/*
20546 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20547 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20548 	 */
20549 	if (ire->ire_flags & RTF_MULTIRT) {
20550 
20551 		/*
20552 		 * Force the TTL of multirouted packets if required.
20553 		 * The TTL of such packets is bounded by the
20554 		 * ip_multirt_ttl ndd variable.
20555 		 */
20556 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20557 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20558 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20559 			    "(was %d), dst 0x%08x\n",
20560 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20561 			    ntohl(ire->ire_addr)));
20562 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20563 		}
20564 
20565 		/*
20566 		 * At this point, we check to see if there are any pending
20567 		 * unresolved routes. ire_multirt_resolvable()
20568 		 * checks in O(n) that all IRE_OFFSUBNET ire
20569 		 * entries for the packet's destination and
20570 		 * flagged RTF_MULTIRT are currently resolved.
20571 		 * If some remain unresolved, we make a copy
20572 		 * of the current message. It will be used
20573 		 * to initiate additional route resolutions.
20574 		 */
20575 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20576 		    MBLK_GETLABEL(first_mp), ipst);
20577 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20578 		    "multirt_need_resolve %d, first_mp %p\n",
20579 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20580 		if (multirt_need_resolve) {
20581 			copy_mp = copymsg(first_mp);
20582 			if (copy_mp != NULL) {
20583 				MULTIRT_DEBUG_TAG(copy_mp);
20584 			}
20585 		}
20586 	}
20587 
20588 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20589 
20590 	/*
20591 	 * Try to resolve another multiroute if
20592 	 * ire_multirt_resolvable() deemed it necessary
20593 	 */
20594 	if (copy_mp != NULL)
20595 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20596 	if (need_decref)
20597 		CONN_DEC_REF(connp);
20598 	return;
20599 
20600 qnext:
20601 	/*
20602 	 * Upper Level Protocols pass down complete IP datagrams
20603 	 * as M_DATA messages.	Everything else is a sideshow.
20604 	 *
20605 	 * 1) We could be re-entering ip_wput because of ip_neworute
20606 	 *    in which case we could have a IPSEC_OUT message. We
20607 	 *    need to pass through ip_wput like other datagrams and
20608 	 *    hence cannot branch to ip_wput_nondata.
20609 	 *
20610 	 * 2) ARP, AH, ESP, and other clients who are on the module
20611 	 *    instance of IP stream, give us something to deal with.
20612 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20613 	 *
20614 	 * 3) ICMP replies also could come here.
20615 	 */
20616 	ipst = ILLQ_TO_IPST(q);
20617 
20618 	if (DB_TYPE(mp) != M_DATA) {
20619 notdata:
20620 		if (DB_TYPE(mp) == M_CTL) {
20621 			/*
20622 			 * M_CTL messages are used by ARP, AH and ESP to
20623 			 * communicate with IP. We deal with IPSEC_IN and
20624 			 * IPSEC_OUT here. ip_wput_nondata handles other
20625 			 * cases.
20626 			 */
20627 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20628 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20629 				first_mp = mp->b_cont;
20630 				first_mp->b_flag &= ~MSGHASREF;
20631 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20632 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20633 				CONN_DEC_REF(connp);
20634 				connp = NULL;
20635 			}
20636 			if (ii->ipsec_info_type == IPSEC_IN) {
20637 				/*
20638 				 * Either this message goes back to
20639 				 * IPsec for further processing or to
20640 				 * ULP after policy checks.
20641 				 */
20642 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20643 				return;
20644 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20645 				io = (ipsec_out_t *)ii;
20646 				if (io->ipsec_out_proc_begin) {
20647 					/*
20648 					 * IPsec processing has already started.
20649 					 * Complete it.
20650 					 * IPQoS notes: We don't care what is
20651 					 * in ipsec_out_ill_index since this
20652 					 * won't be processed for IPQoS policies
20653 					 * in ipsec_out_process.
20654 					 */
20655 					ipsec_out_process(q, mp, NULL,
20656 					    io->ipsec_out_ill_index);
20657 					return;
20658 				} else {
20659 					connp = (q->q_next != NULL) ?
20660 					    NULL : Q_TO_CONN(q);
20661 					first_mp = mp;
20662 					mp = mp->b_cont;
20663 					mctl_present = B_TRUE;
20664 				}
20665 				zoneid = io->ipsec_out_zoneid;
20666 				ASSERT(zoneid != ALL_ZONES);
20667 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20668 				/*
20669 				 * It's an IPsec control message requesting
20670 				 * an SADB update to be sent to the IPsec
20671 				 * hardware acceleration capable ills.
20672 				 */
20673 				ipsec_ctl_t *ipsec_ctl =
20674 				    (ipsec_ctl_t *)mp->b_rptr;
20675 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20676 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20677 				mblk_t *cmp = mp->b_cont;
20678 
20679 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20680 				ASSERT(cmp != NULL);
20681 
20682 				freeb(mp);
20683 				ill_ipsec_capab_send_all(satype, cmp, sa,
20684 				    ipst->ips_netstack);
20685 				return;
20686 			} else {
20687 				/*
20688 				 * This must be ARP or special TSOL signaling.
20689 				 */
20690 				ip_wput_nondata(NULL, q, mp, NULL);
20691 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20692 				    "ip_wput_end: q %p (%S)", q, "nondata");
20693 				return;
20694 			}
20695 		} else {
20696 			/*
20697 			 * This must be non-(ARP/AH/ESP) messages.
20698 			 */
20699 			ASSERT(!need_decref);
20700 			ip_wput_nondata(NULL, q, mp, NULL);
20701 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20702 			    "ip_wput_end: q %p (%S)", q, "nondata");
20703 			return;
20704 		}
20705 	} else {
20706 		first_mp = mp;
20707 		mctl_present = B_FALSE;
20708 	}
20709 
20710 	ASSERT(first_mp != NULL);
20711 	/*
20712 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20713 	 * to make sure that this packet goes out on the same interface it
20714 	 * came in. We handle that here.
20715 	 */
20716 	if (mctl_present) {
20717 		uint_t ifindex;
20718 
20719 		io = (ipsec_out_t *)first_mp->b_rptr;
20720 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20721 			/*
20722 			 * We may have lost the conn context if we are
20723 			 * coming here from ip_newroute(). Copy the
20724 			 * nexthop information.
20725 			 */
20726 			if (io->ipsec_out_ip_nexthop) {
20727 				ip_nexthop = B_TRUE;
20728 				nexthop_addr = io->ipsec_out_nexthop_addr;
20729 
20730 				ipha = (ipha_t *)mp->b_rptr;
20731 				dst = ipha->ipha_dst;
20732 				goto send_from_ill;
20733 			} else {
20734 				ASSERT(io->ipsec_out_ill_index != 0);
20735 				ifindex = io->ipsec_out_ill_index;
20736 				attach_ill = ill_lookup_on_ifindex(ifindex,
20737 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20738 				if (attach_ill == NULL) {
20739 					ASSERT(xmit_ill == NULL);
20740 					ip1dbg(("ip_output: bad ifindex for "
20741 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20742 					    ifindex));
20743 					freemsg(first_mp);
20744 					BUMP_MIB(&ipst->ips_ip_mib,
20745 					    ipIfStatsOutDiscards);
20746 					ASSERT(!need_decref);
20747 					return;
20748 				}
20749 			}
20750 		}
20751 	}
20752 
20753 	ASSERT(xmit_ill == NULL);
20754 
20755 	/* We have a complete IP datagram heading outbound. */
20756 	ipha = (ipha_t *)mp->b_rptr;
20757 
20758 #ifndef SPEED_BEFORE_SAFETY
20759 	/*
20760 	 * Make sure we have a full-word aligned message and that at least
20761 	 * a simple IP header is accessible in the first message.  If not,
20762 	 * try a pullup.  For labeled systems we need to always take this
20763 	 * path as M_CTLs are "notdata" but have trailing data to process.
20764 	 */
20765 	if (!OK_32PTR(rptr) ||
20766 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20767 hdrtoosmall:
20768 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20769 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20770 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20771 			if (first_mp == NULL)
20772 				first_mp = mp;
20773 			goto discard_pkt;
20774 		}
20775 
20776 		/* This function assumes that mp points to an IPv4 packet. */
20777 		if (is_system_labeled() && q->q_next == NULL &&
20778 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20779 		    !connp->conn_ulp_labeled) {
20780 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20781 			    connp->conn_mac_exempt, ipst);
20782 			ipha = (ipha_t *)mp->b_rptr;
20783 			if (first_mp != NULL)
20784 				first_mp->b_cont = mp;
20785 			if (err != 0) {
20786 				if (first_mp == NULL)
20787 					first_mp = mp;
20788 				if (err == EINVAL)
20789 					goto icmp_parameter_problem;
20790 				ip2dbg(("ip_wput: label check failed (%d)\n",
20791 				    err));
20792 				goto discard_pkt;
20793 			}
20794 		}
20795 
20796 		ipha = (ipha_t *)mp->b_rptr;
20797 		if (first_mp == NULL) {
20798 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20799 			/*
20800 			 * If we got here because of "goto hdrtoosmall"
20801 			 * We need to attach a IPSEC_OUT.
20802 			 */
20803 			if (connp->conn_out_enforce_policy) {
20804 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20805 				    NULL, ipha->ipha_protocol,
20806 				    ipst->ips_netstack)) == NULL)) {
20807 					BUMP_MIB(&ipst->ips_ip_mib,
20808 					    ipIfStatsOutDiscards);
20809 					if (need_decref)
20810 						CONN_DEC_REF(connp);
20811 					return;
20812 				} else {
20813 					ASSERT(mp->b_datap->db_type == M_CTL);
20814 					first_mp = mp;
20815 					mp = mp->b_cont;
20816 					mctl_present = B_TRUE;
20817 				}
20818 			} else {
20819 				first_mp = mp;
20820 				mctl_present = B_FALSE;
20821 			}
20822 		}
20823 	}
20824 #endif
20825 
20826 	/* Most of the code below is written for speed, not readability */
20827 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20828 
20829 	/*
20830 	 * If ip_newroute() fails, we're going to need a full
20831 	 * header for the icmp wraparound.
20832 	 */
20833 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20834 		uint_t	v_hlen;
20835 version_hdrlen_check:
20836 		ASSERT(first_mp != NULL);
20837 		v_hlen = V_HLEN;
20838 		/*
20839 		 * siphon off IPv6 packets coming down from transport
20840 		 * layer modules here.
20841 		 * Note: high-order bit carries NUD reachability confirmation
20842 		 */
20843 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20844 			/*
20845 			 * FIXME: assume that callers of ip_output* call
20846 			 * the right version?
20847 			 */
20848 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20849 			ASSERT(xmit_ill == NULL);
20850 			if (attach_ill != NULL)
20851 				ill_refrele(attach_ill);
20852 			if (need_decref)
20853 				mp->b_flag |= MSGHASREF;
20854 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20855 			return;
20856 		}
20857 
20858 		if ((v_hlen >> 4) != IP_VERSION) {
20859 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20860 			    "ip_wput_end: q %p (%S)", q, "badvers");
20861 			goto discard_pkt;
20862 		}
20863 		/*
20864 		 * Is the header length at least 20 bytes?
20865 		 *
20866 		 * Are there enough bytes accessible in the header?  If
20867 		 * not, try a pullup.
20868 		 */
20869 		v_hlen &= 0xF;
20870 		v_hlen <<= 2;
20871 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20872 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20873 			    "ip_wput_end: q %p (%S)", q, "badlen");
20874 			goto discard_pkt;
20875 		}
20876 		if (v_hlen > (mp->b_wptr - rptr)) {
20877 			if (!pullupmsg(mp, v_hlen)) {
20878 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20879 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20880 				goto discard_pkt;
20881 			}
20882 			ipha = (ipha_t *)mp->b_rptr;
20883 		}
20884 		/*
20885 		 * Move first entry from any source route into ipha_dst and
20886 		 * verify the options
20887 		 */
20888 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20889 		    zoneid, ipst)) {
20890 			ASSERT(xmit_ill == NULL);
20891 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20892 			if (attach_ill != NULL)
20893 				ill_refrele(attach_ill);
20894 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20895 			    "ip_wput_end: q %p (%S)", q, "badopts");
20896 			if (need_decref)
20897 				CONN_DEC_REF(connp);
20898 			return;
20899 		}
20900 	}
20901 	dst = ipha->ipha_dst;
20902 
20903 	/*
20904 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20905 	 * we have to run the packet through ip_newroute which will take
20906 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20907 	 * a resolver, or assigning a default gateway, etc.
20908 	 */
20909 	if (CLASSD(dst)) {
20910 		ipif_t	*ipif;
20911 		uint32_t setsrc = 0;
20912 
20913 multicast:
20914 		ASSERT(first_mp != NULL);
20915 		ip2dbg(("ip_wput: CLASSD\n"));
20916 		if (connp == NULL) {
20917 			/*
20918 			 * Use the first good ipif on the ill.
20919 			 * XXX Should this ever happen? (Appears
20920 			 * to show up with just ppp and no ethernet due
20921 			 * to in.rdisc.)
20922 			 * However, ire_send should be able to
20923 			 * call ip_wput_ire directly.
20924 			 *
20925 			 * XXX Also, this can happen for ICMP and other packets
20926 			 * with multicast source addresses.  Perhaps we should
20927 			 * fix things so that we drop the packet in question,
20928 			 * but for now, just run with it.
20929 			 */
20930 			ill_t *ill = (ill_t *)q->q_ptr;
20931 
20932 			/*
20933 			 * Don't honor attach_if for this case. If ill
20934 			 * is part of the group, ipif could belong to
20935 			 * any ill and we cannot maintain attach_ill
20936 			 * and ipif_ill same anymore and the assert
20937 			 * below would fail.
20938 			 */
20939 			if (mctl_present && io->ipsec_out_attach_if) {
20940 				io->ipsec_out_ill_index = 0;
20941 				io->ipsec_out_attach_if = B_FALSE;
20942 				ASSERT(attach_ill != NULL);
20943 				ill_refrele(attach_ill);
20944 				attach_ill = NULL;
20945 			}
20946 
20947 			ASSERT(attach_ill == NULL);
20948 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20949 			if (ipif == NULL) {
20950 				if (need_decref)
20951 					CONN_DEC_REF(connp);
20952 				freemsg(first_mp);
20953 				return;
20954 			}
20955 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20956 			    ntohl(dst), ill->ill_name));
20957 		} else {
20958 			/*
20959 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20960 			 * and IP_MULTICAST_IF.  The block comment above this
20961 			 * function explains the locking mechanism used here.
20962 			 */
20963 			if (xmit_ill == NULL) {
20964 				xmit_ill = conn_get_held_ill(connp,
20965 				    &connp->conn_outgoing_ill, &err);
20966 				if (err == ILL_LOOKUP_FAILED) {
20967 					ip1dbg(("ip_wput: No ill for "
20968 					    "IP_BOUND_IF\n"));
20969 					BUMP_MIB(&ipst->ips_ip_mib,
20970 					    ipIfStatsOutNoRoutes);
20971 					goto drop_pkt;
20972 				}
20973 			}
20974 
20975 			if (xmit_ill == NULL) {
20976 				ipif = conn_get_held_ipif(connp,
20977 				    &connp->conn_multicast_ipif, &err);
20978 				if (err == IPIF_LOOKUP_FAILED) {
20979 					ip1dbg(("ip_wput: No ipif for "
20980 					    "multicast\n"));
20981 					BUMP_MIB(&ipst->ips_ip_mib,
20982 					    ipIfStatsOutNoRoutes);
20983 					goto drop_pkt;
20984 				}
20985 			}
20986 			if (xmit_ill != NULL) {
20987 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20988 				if (ipif == NULL) {
20989 					ip1dbg(("ip_wput: No ipif for "
20990 					    "xmit_ill\n"));
20991 					BUMP_MIB(&ipst->ips_ip_mib,
20992 					    ipIfStatsOutNoRoutes);
20993 					goto drop_pkt;
20994 				}
20995 			} else if (ipif == NULL || ipif->ipif_isv6) {
20996 				/*
20997 				 * We must do this ipif determination here
20998 				 * else we could pass through ip_newroute
20999 				 * and come back here without the conn context.
21000 				 *
21001 				 * Note: we do late binding i.e. we bind to
21002 				 * the interface when the first packet is sent.
21003 				 * For performance reasons we do not rebind on
21004 				 * each packet but keep the binding until the
21005 				 * next IP_MULTICAST_IF option.
21006 				 *
21007 				 * conn_multicast_{ipif,ill} are shared between
21008 				 * IPv4 and IPv6 and AF_INET6 sockets can
21009 				 * send both IPv4 and IPv6 packets. Hence
21010 				 * we have to check that "isv6" matches above.
21011 				 */
21012 				if (ipif != NULL)
21013 					ipif_refrele(ipif);
21014 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21015 				if (ipif == NULL) {
21016 					ip1dbg(("ip_wput: No ipif for "
21017 					    "multicast\n"));
21018 					BUMP_MIB(&ipst->ips_ip_mib,
21019 					    ipIfStatsOutNoRoutes);
21020 					goto drop_pkt;
21021 				}
21022 				err = conn_set_held_ipif(connp,
21023 				    &connp->conn_multicast_ipif, ipif);
21024 				if (err == IPIF_LOOKUP_FAILED) {
21025 					ipif_refrele(ipif);
21026 					ip1dbg(("ip_wput: No ipif for "
21027 					    "multicast\n"));
21028 					BUMP_MIB(&ipst->ips_ip_mib,
21029 					    ipIfStatsOutNoRoutes);
21030 					goto drop_pkt;
21031 				}
21032 			}
21033 		}
21034 		ASSERT(!ipif->ipif_isv6);
21035 		/*
21036 		 * As we may lose the conn by the time we reach ip_wput_ire,
21037 		 * we copy conn_multicast_loop and conn_dontroute on to an
21038 		 * ipsec_out. In case if this datagram goes out secure,
21039 		 * we need the ill_index also. Copy that also into the
21040 		 * ipsec_out.
21041 		 */
21042 		if (mctl_present) {
21043 			io = (ipsec_out_t *)first_mp->b_rptr;
21044 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21045 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21046 		} else {
21047 			ASSERT(mp == first_mp);
21048 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21049 			    BPRI_HI)) == NULL) {
21050 				ipif_refrele(ipif);
21051 				first_mp = mp;
21052 				goto discard_pkt;
21053 			}
21054 			first_mp->b_datap->db_type = M_CTL;
21055 			first_mp->b_wptr += sizeof (ipsec_info_t);
21056 			/* ipsec_out_secure is B_FALSE now */
21057 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21058 			io = (ipsec_out_t *)first_mp->b_rptr;
21059 			io->ipsec_out_type = IPSEC_OUT;
21060 			io->ipsec_out_len = sizeof (ipsec_out_t);
21061 			io->ipsec_out_use_global_policy = B_TRUE;
21062 			io->ipsec_out_ns = ipst->ips_netstack;
21063 			first_mp->b_cont = mp;
21064 			mctl_present = B_TRUE;
21065 		}
21066 		if (attach_ill != NULL) {
21067 			ASSERT(attach_ill == ipif->ipif_ill);
21068 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21069 
21070 			/*
21071 			 * Check if we need an ire that will not be
21072 			 * looked up by anybody else i.e. HIDDEN.
21073 			 */
21074 			if (ill_is_probeonly(attach_ill)) {
21075 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21076 			}
21077 			io->ipsec_out_ill_index =
21078 			    attach_ill->ill_phyint->phyint_ifindex;
21079 			io->ipsec_out_attach_if = B_TRUE;
21080 		} else {
21081 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21082 			io->ipsec_out_ill_index =
21083 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21084 		}
21085 		if (connp != NULL) {
21086 			io->ipsec_out_multicast_loop =
21087 			    connp->conn_multicast_loop;
21088 			io->ipsec_out_dontroute = connp->conn_dontroute;
21089 			io->ipsec_out_zoneid = connp->conn_zoneid;
21090 		}
21091 		/*
21092 		 * If the application uses IP_MULTICAST_IF with
21093 		 * different logical addresses of the same ILL, we
21094 		 * need to make sure that the soruce address of
21095 		 * the packet matches the logical IP address used
21096 		 * in the option. We do it by initializing ipha_src
21097 		 * here. This should keep IPsec also happy as
21098 		 * when we return from IPsec processing, we don't
21099 		 * have to worry about getting the right address on
21100 		 * the packet. Thus it is sufficient to look for
21101 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21102 		 * MATCH_IRE_IPIF.
21103 		 *
21104 		 * NOTE : We need to do it for non-secure case also as
21105 		 * this might go out secure if there is a global policy
21106 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21107 		 * address, the source should be initialized already and
21108 		 * hence we won't be initializing here.
21109 		 *
21110 		 * As we do not have the ire yet, it is possible that
21111 		 * we set the source address here and then later discover
21112 		 * that the ire implies the source address to be assigned
21113 		 * through the RTF_SETSRC flag.
21114 		 * In that case, the setsrc variable will remind us
21115 		 * that overwritting the source address by the one
21116 		 * of the RTF_SETSRC-flagged ire is allowed.
21117 		 */
21118 		if (ipha->ipha_src == INADDR_ANY &&
21119 		    (connp == NULL || !connp->conn_unspec_src)) {
21120 			ipha->ipha_src = ipif->ipif_src_addr;
21121 			setsrc = RTF_SETSRC;
21122 		}
21123 		/*
21124 		 * Find an IRE which matches the destination and the outgoing
21125 		 * queue (i.e. the outgoing interface.)
21126 		 * For loopback use a unicast IP address for
21127 		 * the ire lookup.
21128 		 */
21129 		if (IS_LOOPBACK(ipif->ipif_ill))
21130 			dst = ipif->ipif_lcl_addr;
21131 
21132 		/*
21133 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21134 		 * We don't need to lookup ire in ctable as the packet
21135 		 * needs to be sent to the destination through the specified
21136 		 * ill irrespective of ires in the cache table.
21137 		 */
21138 		ire = NULL;
21139 		if (xmit_ill == NULL) {
21140 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21141 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21142 		}
21143 
21144 		/*
21145 		 * refrele attach_ill as its not needed anymore.
21146 		 */
21147 		if (attach_ill != NULL) {
21148 			ill_refrele(attach_ill);
21149 			attach_ill = NULL;
21150 		}
21151 
21152 		if (ire == NULL) {
21153 			/*
21154 			 * Multicast loopback and multicast forwarding is
21155 			 * done in ip_wput_ire.
21156 			 *
21157 			 * Mark this packet to make it be delivered to
21158 			 * ip_wput_ire after the new ire has been
21159 			 * created.
21160 			 *
21161 			 * The call to ip_newroute_ipif takes into account
21162 			 * the setsrc reminder. In any case, we take care
21163 			 * of the RTF_MULTIRT flag.
21164 			 */
21165 			mp->b_prev = mp->b_next = NULL;
21166 			if (xmit_ill == NULL ||
21167 			    xmit_ill->ill_ipif_up_count > 0) {
21168 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21169 				    setsrc | RTF_MULTIRT, zoneid, infop);
21170 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21171 				    "ip_wput_end: q %p (%S)", q, "noire");
21172 			} else {
21173 				freemsg(first_mp);
21174 			}
21175 			ipif_refrele(ipif);
21176 			if (xmit_ill != NULL)
21177 				ill_refrele(xmit_ill);
21178 			if (need_decref)
21179 				CONN_DEC_REF(connp);
21180 			return;
21181 		}
21182 
21183 		ipif_refrele(ipif);
21184 		ipif = NULL;
21185 		ASSERT(xmit_ill == NULL);
21186 
21187 		/*
21188 		 * Honor the RTF_SETSRC flag for multicast packets,
21189 		 * if allowed by the setsrc reminder.
21190 		 */
21191 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21192 			ipha->ipha_src = ire->ire_src_addr;
21193 		}
21194 
21195 		/*
21196 		 * Unconditionally force the TTL to 1 for
21197 		 * multirouted multicast packets:
21198 		 * multirouted multicast should not cross
21199 		 * multicast routers.
21200 		 */
21201 		if (ire->ire_flags & RTF_MULTIRT) {
21202 			if (ipha->ipha_ttl > 1) {
21203 				ip2dbg(("ip_wput: forcing multicast "
21204 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21205 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21206 				ipha->ipha_ttl = 1;
21207 			}
21208 		}
21209 	} else {
21210 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21211 		if ((ire != NULL) && (ire->ire_type &
21212 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21213 			ignore_dontroute = B_TRUE;
21214 			ignore_nexthop = B_TRUE;
21215 		}
21216 		if (ire != NULL) {
21217 			ire_refrele(ire);
21218 			ire = NULL;
21219 		}
21220 		/*
21221 		 * Guard against coming in from arp in which case conn is NULL.
21222 		 * Also guard against non M_DATA with dontroute set but
21223 		 * destined to local, loopback or broadcast addresses.
21224 		 */
21225 		if (connp != NULL && connp->conn_dontroute &&
21226 		    !ignore_dontroute) {
21227 dontroute:
21228 			/*
21229 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21230 			 * routing protocols from seeing false direct
21231 			 * connectivity.
21232 			 */
21233 			ipha->ipha_ttl = 1;
21234 
21235 			/* If suitable ipif not found, drop packet */
21236 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21237 			if (dst_ipif == NULL) {
21238 noroute:
21239 				ip1dbg(("ip_wput: no route for dst using"
21240 				    " SO_DONTROUTE\n"));
21241 				BUMP_MIB(&ipst->ips_ip_mib,
21242 				    ipIfStatsOutNoRoutes);
21243 				mp->b_prev = mp->b_next = NULL;
21244 				if (first_mp == NULL)
21245 					first_mp = mp;
21246 				goto drop_pkt;
21247 			} else {
21248 				/*
21249 				 * If suitable ipif has been found, set
21250 				 * xmit_ill to the corresponding
21251 				 * ipif_ill because we'll be using the
21252 				 * send_from_ill logic below.
21253 				 */
21254 				ASSERT(xmit_ill == NULL);
21255 				xmit_ill = dst_ipif->ipif_ill;
21256 				mutex_enter(&xmit_ill->ill_lock);
21257 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21258 					mutex_exit(&xmit_ill->ill_lock);
21259 					xmit_ill = NULL;
21260 					ipif_refrele(dst_ipif);
21261 					goto noroute;
21262 				}
21263 				ill_refhold_locked(xmit_ill);
21264 				mutex_exit(&xmit_ill->ill_lock);
21265 				ipif_refrele(dst_ipif);
21266 			}
21267 		}
21268 		/*
21269 		 * If we are bound to IPIF_NOFAILOVER address, look for
21270 		 * an IRE_CACHE matching the ill.
21271 		 */
21272 send_from_ill:
21273 		if (attach_ill != NULL) {
21274 			ipif_t	*attach_ipif;
21275 
21276 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21277 
21278 			/*
21279 			 * Check if we need an ire that will not be
21280 			 * looked up by anybody else i.e. HIDDEN.
21281 			 */
21282 			if (ill_is_probeonly(attach_ill)) {
21283 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21284 			}
21285 
21286 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21287 			if (attach_ipif == NULL) {
21288 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21289 				goto discard_pkt;
21290 			}
21291 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21292 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21293 			ipif_refrele(attach_ipif);
21294 		} else if (xmit_ill != NULL) {
21295 			ipif_t *ipif;
21296 
21297 			/*
21298 			 * Mark this packet as originated locally
21299 			 */
21300 			mp->b_prev = mp->b_next = NULL;
21301 
21302 			/*
21303 			 * Could be SO_DONTROUTE case also.
21304 			 * Verify that at least one ipif is up on the ill.
21305 			 */
21306 			if (xmit_ill->ill_ipif_up_count == 0) {
21307 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21308 				    xmit_ill->ill_name));
21309 				goto drop_pkt;
21310 			}
21311 
21312 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21313 			if (ipif == NULL) {
21314 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21315 				    xmit_ill->ill_name));
21316 				goto drop_pkt;
21317 			}
21318 
21319 			/*
21320 			 * Look for a ire that is part of the group,
21321 			 * if found use it else call ip_newroute_ipif.
21322 			 * IPCL_ZONEID is not used for matching because
21323 			 * IP_ALLZONES option is valid only when the
21324 			 * ill is accessible from all zones i.e has a
21325 			 * valid ipif in all zones.
21326 			 */
21327 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21328 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21329 			    MBLK_GETLABEL(mp), match_flags, ipst);
21330 			/*
21331 			 * If an ire exists use it or else create
21332 			 * an ire but don't add it to the cache.
21333 			 * Adding an ire may cause issues with
21334 			 * asymmetric routing.
21335 			 * In case of multiroute always act as if
21336 			 * ire does not exist.
21337 			 */
21338 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21339 				if (ire != NULL)
21340 					ire_refrele(ire);
21341 				ip_newroute_ipif(q, first_mp, ipif,
21342 				    dst, connp, 0, zoneid, infop);
21343 				ipif_refrele(ipif);
21344 				ip1dbg(("ip_output: xmit_ill via %s\n",
21345 				    xmit_ill->ill_name));
21346 				ill_refrele(xmit_ill);
21347 				if (need_decref)
21348 					CONN_DEC_REF(connp);
21349 				return;
21350 			}
21351 			ipif_refrele(ipif);
21352 		} else if (ip_nexthop || (connp != NULL &&
21353 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21354 			if (!ip_nexthop) {
21355 				ip_nexthop = B_TRUE;
21356 				nexthop_addr = connp->conn_nexthop_v4;
21357 			}
21358 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21359 			    MATCH_IRE_GW;
21360 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21361 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21362 		} else {
21363 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21364 			    ipst);
21365 		}
21366 		if (!ire) {
21367 			/*
21368 			 * Make sure we don't load spread if this
21369 			 * is IPIF_NOFAILOVER case.
21370 			 */
21371 			if ((attach_ill != NULL) ||
21372 			    (ip_nexthop && !ignore_nexthop)) {
21373 				if (mctl_present) {
21374 					io = (ipsec_out_t *)first_mp->b_rptr;
21375 					ASSERT(first_mp->b_datap->db_type ==
21376 					    M_CTL);
21377 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21378 				} else {
21379 					ASSERT(mp == first_mp);
21380 					first_mp = allocb(
21381 					    sizeof (ipsec_info_t), BPRI_HI);
21382 					if (first_mp == NULL) {
21383 						first_mp = mp;
21384 						goto discard_pkt;
21385 					}
21386 					first_mp->b_datap->db_type = M_CTL;
21387 					first_mp->b_wptr +=
21388 					    sizeof (ipsec_info_t);
21389 					/* ipsec_out_secure is B_FALSE now */
21390 					bzero(first_mp->b_rptr,
21391 					    sizeof (ipsec_info_t));
21392 					io = (ipsec_out_t *)first_mp->b_rptr;
21393 					io->ipsec_out_type = IPSEC_OUT;
21394 					io->ipsec_out_len =
21395 					    sizeof (ipsec_out_t);
21396 					io->ipsec_out_use_global_policy =
21397 					    B_TRUE;
21398 					io->ipsec_out_ns = ipst->ips_netstack;
21399 					first_mp->b_cont = mp;
21400 					mctl_present = B_TRUE;
21401 				}
21402 				if (attach_ill != NULL) {
21403 					io->ipsec_out_ill_index = attach_ill->
21404 					    ill_phyint->phyint_ifindex;
21405 					io->ipsec_out_attach_if = B_TRUE;
21406 				} else {
21407 					io->ipsec_out_ip_nexthop = ip_nexthop;
21408 					io->ipsec_out_nexthop_addr =
21409 					    nexthop_addr;
21410 				}
21411 			}
21412 noirefound:
21413 			/*
21414 			 * Mark this packet as having originated on
21415 			 * this machine.  This will be noted in
21416 			 * ire_add_then_send, which needs to know
21417 			 * whether to run it back through ip_wput or
21418 			 * ip_rput following successful resolution.
21419 			 */
21420 			mp->b_prev = NULL;
21421 			mp->b_next = NULL;
21422 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21423 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21424 			    "ip_wput_end: q %p (%S)", q, "newroute");
21425 			if (attach_ill != NULL)
21426 				ill_refrele(attach_ill);
21427 			if (xmit_ill != NULL)
21428 				ill_refrele(xmit_ill);
21429 			if (need_decref)
21430 				CONN_DEC_REF(connp);
21431 			return;
21432 		}
21433 	}
21434 
21435 	/* We now know where we are going with it. */
21436 
21437 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21438 	    "ip_wput_end: q %p (%S)", q, "end");
21439 
21440 	/*
21441 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21442 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21443 	 */
21444 	if (ire->ire_flags & RTF_MULTIRT) {
21445 		/*
21446 		 * Force the TTL of multirouted packets if required.
21447 		 * The TTL of such packets is bounded by the
21448 		 * ip_multirt_ttl ndd variable.
21449 		 */
21450 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21451 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21452 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21453 			    "(was %d), dst 0x%08x\n",
21454 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21455 			    ntohl(ire->ire_addr)));
21456 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21457 		}
21458 		/*
21459 		 * At this point, we check to see if there are any pending
21460 		 * unresolved routes. ire_multirt_resolvable()
21461 		 * checks in O(n) that all IRE_OFFSUBNET ire
21462 		 * entries for the packet's destination and
21463 		 * flagged RTF_MULTIRT are currently resolved.
21464 		 * If some remain unresolved, we make a copy
21465 		 * of the current message. It will be used
21466 		 * to initiate additional route resolutions.
21467 		 */
21468 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21469 		    MBLK_GETLABEL(first_mp), ipst);
21470 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21471 		    "multirt_need_resolve %d, first_mp %p\n",
21472 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21473 		if (multirt_need_resolve) {
21474 			copy_mp = copymsg(first_mp);
21475 			if (copy_mp != NULL) {
21476 				MULTIRT_DEBUG_TAG(copy_mp);
21477 			}
21478 		}
21479 	}
21480 
21481 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21482 	/*
21483 	 * Try to resolve another multiroute if
21484 	 * ire_multirt_resolvable() deemed it necessary.
21485 	 * At this point, we need to distinguish
21486 	 * multicasts from other packets. For multicasts,
21487 	 * we call ip_newroute_ipif() and request that both
21488 	 * multirouting and setsrc flags are checked.
21489 	 */
21490 	if (copy_mp != NULL) {
21491 		if (CLASSD(dst)) {
21492 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21493 			if (ipif) {
21494 				ASSERT(infop->ip_opt_ill_index == 0);
21495 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21496 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21497 				ipif_refrele(ipif);
21498 			} else {
21499 				MULTIRT_DEBUG_UNTAG(copy_mp);
21500 				freemsg(copy_mp);
21501 				copy_mp = NULL;
21502 			}
21503 		} else {
21504 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21505 		}
21506 	}
21507 	if (attach_ill != NULL)
21508 		ill_refrele(attach_ill);
21509 	if (xmit_ill != NULL)
21510 		ill_refrele(xmit_ill);
21511 	if (need_decref)
21512 		CONN_DEC_REF(connp);
21513 	return;
21514 
21515 icmp_parameter_problem:
21516 	/* could not have originated externally */
21517 	ASSERT(mp->b_prev == NULL);
21518 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21519 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21520 		/* it's the IP header length that's in trouble */
21521 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21522 		first_mp = NULL;
21523 	}
21524 
21525 discard_pkt:
21526 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21527 drop_pkt:
21528 	ip1dbg(("ip_wput: dropped packet\n"));
21529 	if (ire != NULL)
21530 		ire_refrele(ire);
21531 	if (need_decref)
21532 		CONN_DEC_REF(connp);
21533 	freemsg(first_mp);
21534 	if (attach_ill != NULL)
21535 		ill_refrele(attach_ill);
21536 	if (xmit_ill != NULL)
21537 		ill_refrele(xmit_ill);
21538 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21539 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21540 }
21541 
21542 /*
21543  * If this is a conn_t queue, then we pass in the conn. This includes the
21544  * zoneid.
21545  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21546  * in which case we use the global zoneid since those are all part of
21547  * the global zone.
21548  */
21549 void
21550 ip_wput(queue_t *q, mblk_t *mp)
21551 {
21552 	if (CONN_Q(q))
21553 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21554 	else
21555 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21556 }
21557 
21558 /*
21559  *
21560  * The following rules must be observed when accessing any ipif or ill
21561  * that has been cached in the conn. Typically conn_nofailover_ill,
21562  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21563  *
21564  * Access: The ipif or ill pointed to from the conn can be accessed under
21565  * the protection of the conn_lock or after it has been refheld under the
21566  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21567  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21568  * The reason for this is that a concurrent unplumb could actually be
21569  * cleaning up these cached pointers by walking the conns and might have
21570  * finished cleaning up the conn in question. The macros check that an
21571  * unplumb has not yet started on the ipif or ill.
21572  *
21573  * Caching: An ipif or ill pointer may be cached in the conn only after
21574  * making sure that an unplumb has not started. So the caching is done
21575  * while holding both the conn_lock and the ill_lock and after using the
21576  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21577  * flag before starting the cleanup of conns.
21578  *
21579  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21580  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21581  * or a reference to the ipif or a reference to an ire that references the
21582  * ipif. An ipif does not change its ill except for failover/failback. Since
21583  * failover/failback happens only after bringing down the ipif and making sure
21584  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21585  * the above holds.
21586  */
21587 ipif_t *
21588 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21589 {
21590 	ipif_t	*ipif;
21591 	ill_t	*ill;
21592 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21593 
21594 	*err = 0;
21595 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21596 	mutex_enter(&connp->conn_lock);
21597 	ipif = *ipifp;
21598 	if (ipif != NULL) {
21599 		ill = ipif->ipif_ill;
21600 		mutex_enter(&ill->ill_lock);
21601 		if (IPIF_CAN_LOOKUP(ipif)) {
21602 			ipif_refhold_locked(ipif);
21603 			mutex_exit(&ill->ill_lock);
21604 			mutex_exit(&connp->conn_lock);
21605 			rw_exit(&ipst->ips_ill_g_lock);
21606 			return (ipif);
21607 		} else {
21608 			*err = IPIF_LOOKUP_FAILED;
21609 		}
21610 		mutex_exit(&ill->ill_lock);
21611 	}
21612 	mutex_exit(&connp->conn_lock);
21613 	rw_exit(&ipst->ips_ill_g_lock);
21614 	return (NULL);
21615 }
21616 
21617 ill_t *
21618 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21619 {
21620 	ill_t	*ill;
21621 
21622 	*err = 0;
21623 	mutex_enter(&connp->conn_lock);
21624 	ill = *illp;
21625 	if (ill != NULL) {
21626 		mutex_enter(&ill->ill_lock);
21627 		if (ILL_CAN_LOOKUP(ill)) {
21628 			ill_refhold_locked(ill);
21629 			mutex_exit(&ill->ill_lock);
21630 			mutex_exit(&connp->conn_lock);
21631 			return (ill);
21632 		} else {
21633 			*err = ILL_LOOKUP_FAILED;
21634 		}
21635 		mutex_exit(&ill->ill_lock);
21636 	}
21637 	mutex_exit(&connp->conn_lock);
21638 	return (NULL);
21639 }
21640 
21641 static int
21642 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21643 {
21644 	ill_t	*ill;
21645 
21646 	ill = ipif->ipif_ill;
21647 	mutex_enter(&connp->conn_lock);
21648 	mutex_enter(&ill->ill_lock);
21649 	if (IPIF_CAN_LOOKUP(ipif)) {
21650 		*ipifp = ipif;
21651 		mutex_exit(&ill->ill_lock);
21652 		mutex_exit(&connp->conn_lock);
21653 		return (0);
21654 	}
21655 	mutex_exit(&ill->ill_lock);
21656 	mutex_exit(&connp->conn_lock);
21657 	return (IPIF_LOOKUP_FAILED);
21658 }
21659 
21660 /*
21661  * This is called if the outbound datagram needs fragmentation.
21662  *
21663  * NOTE : This function does not ire_refrele the ire argument passed in.
21664  */
21665 static void
21666 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21667     ip_stack_t *ipst)
21668 {
21669 	ipha_t		*ipha;
21670 	mblk_t		*mp;
21671 	uint32_t	v_hlen_tos_len;
21672 	uint32_t	max_frag;
21673 	uint32_t	frag_flag;
21674 	boolean_t	dont_use;
21675 
21676 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21677 		mp = ipsec_mp->b_cont;
21678 	} else {
21679 		mp = ipsec_mp;
21680 	}
21681 
21682 	ipha = (ipha_t *)mp->b_rptr;
21683 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21684 
21685 #ifdef	_BIG_ENDIAN
21686 #define	V_HLEN	(v_hlen_tos_len >> 24)
21687 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21688 #else
21689 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21690 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21691 #endif
21692 
21693 #ifndef SPEED_BEFORE_SAFETY
21694 	/*
21695 	 * Check that ipha_length is consistent with
21696 	 * the mblk length
21697 	 */
21698 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21699 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21700 		    LENGTH, msgdsize(mp)));
21701 		freemsg(ipsec_mp);
21702 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21703 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21704 		    "packet length mismatch");
21705 		return;
21706 	}
21707 #endif
21708 	/*
21709 	 * Don't use frag_flag if pre-built packet or source
21710 	 * routed or if multicast (since multicast packets do not solicit
21711 	 * ICMP "packet too big" messages). Get the values of
21712 	 * max_frag and frag_flag atomically by acquiring the
21713 	 * ire_lock.
21714 	 */
21715 	mutex_enter(&ire->ire_lock);
21716 	max_frag = ire->ire_max_frag;
21717 	frag_flag = ire->ire_frag_flag;
21718 	mutex_exit(&ire->ire_lock);
21719 
21720 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21721 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21722 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21723 
21724 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21725 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21726 }
21727 
21728 /*
21729  * Used for deciding the MSS size for the upper layer. Thus
21730  * we need to check the outbound policy values in the conn.
21731  */
21732 int
21733 conn_ipsec_length(conn_t *connp)
21734 {
21735 	ipsec_latch_t *ipl;
21736 
21737 	ipl = connp->conn_latch;
21738 	if (ipl == NULL)
21739 		return (0);
21740 
21741 	if (ipl->ipl_out_policy == NULL)
21742 		return (0);
21743 
21744 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21745 }
21746 
21747 /*
21748  * Returns an estimate of the IPsec headers size. This is used if
21749  * we don't want to call into IPsec to get the exact size.
21750  */
21751 int
21752 ipsec_out_extra_length(mblk_t *ipsec_mp)
21753 {
21754 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21755 	ipsec_action_t *a;
21756 
21757 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21758 	if (!io->ipsec_out_secure)
21759 		return (0);
21760 
21761 	a = io->ipsec_out_act;
21762 
21763 	if (a == NULL) {
21764 		ASSERT(io->ipsec_out_policy != NULL);
21765 		a = io->ipsec_out_policy->ipsp_act;
21766 	}
21767 	ASSERT(a != NULL);
21768 
21769 	return (a->ipa_ovhd);
21770 }
21771 
21772 /*
21773  * Returns an estimate of the IPsec headers size. This is used if
21774  * we don't want to call into IPsec to get the exact size.
21775  */
21776 int
21777 ipsec_in_extra_length(mblk_t *ipsec_mp)
21778 {
21779 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21780 	ipsec_action_t *a;
21781 
21782 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21783 
21784 	a = ii->ipsec_in_action;
21785 	return (a == NULL ? 0 : a->ipa_ovhd);
21786 }
21787 
21788 /*
21789  * If there are any source route options, return the true final
21790  * destination. Otherwise, return the destination.
21791  */
21792 ipaddr_t
21793 ip_get_dst(ipha_t *ipha)
21794 {
21795 	ipoptp_t	opts;
21796 	uchar_t		*opt;
21797 	uint8_t		optval;
21798 	uint8_t		optlen;
21799 	ipaddr_t	dst;
21800 	uint32_t off;
21801 
21802 	dst = ipha->ipha_dst;
21803 
21804 	if (IS_SIMPLE_IPH(ipha))
21805 		return (dst);
21806 
21807 	for (optval = ipoptp_first(&opts, ipha);
21808 	    optval != IPOPT_EOL;
21809 	    optval = ipoptp_next(&opts)) {
21810 		opt = opts.ipoptp_cur;
21811 		optlen = opts.ipoptp_len;
21812 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21813 		switch (optval) {
21814 		case IPOPT_SSRR:
21815 		case IPOPT_LSRR:
21816 			off = opt[IPOPT_OFFSET];
21817 			/*
21818 			 * If one of the conditions is true, it means
21819 			 * end of options and dst already has the right
21820 			 * value.
21821 			 */
21822 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21823 				off = optlen - IP_ADDR_LEN;
21824 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21825 			}
21826 			return (dst);
21827 		default:
21828 			break;
21829 		}
21830 	}
21831 
21832 	return (dst);
21833 }
21834 
21835 mblk_t *
21836 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21837     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21838 {
21839 	ipsec_out_t	*io;
21840 	mblk_t		*first_mp;
21841 	boolean_t policy_present;
21842 	ip_stack_t	*ipst;
21843 	ipsec_stack_t	*ipss;
21844 
21845 	ASSERT(ire != NULL);
21846 	ipst = ire->ire_ipst;
21847 	ipss = ipst->ips_netstack->netstack_ipsec;
21848 
21849 	first_mp = mp;
21850 	if (mp->b_datap->db_type == M_CTL) {
21851 		io = (ipsec_out_t *)first_mp->b_rptr;
21852 		/*
21853 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21854 		 *
21855 		 * 1) There is per-socket policy (including cached global
21856 		 *    policy) or a policy on the IP-in-IP tunnel.
21857 		 * 2) There is no per-socket policy, but it is
21858 		 *    a multicast packet that needs to go out
21859 		 *    on a specific interface. This is the case
21860 		 *    where (ip_wput and ip_wput_multicast) attaches
21861 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21862 		 *
21863 		 * In case (2) we check with global policy to
21864 		 * see if there is a match and set the ill_index
21865 		 * appropriately so that we can lookup the ire
21866 		 * properly in ip_wput_ipsec_out.
21867 		 */
21868 
21869 		/*
21870 		 * ipsec_out_use_global_policy is set to B_FALSE
21871 		 * in ipsec_in_to_out(). Refer to that function for
21872 		 * details.
21873 		 */
21874 		if ((io->ipsec_out_latch == NULL) &&
21875 		    (io->ipsec_out_use_global_policy)) {
21876 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21877 			    ire, connp, unspec_src, zoneid));
21878 		}
21879 		if (!io->ipsec_out_secure) {
21880 			/*
21881 			 * If this is not a secure packet, drop
21882 			 * the IPSEC_OUT mp and treat it as a clear
21883 			 * packet. This happens when we are sending
21884 			 * a ICMP reply back to a clear packet. See
21885 			 * ipsec_in_to_out() for details.
21886 			 */
21887 			mp = first_mp->b_cont;
21888 			freeb(first_mp);
21889 		}
21890 		return (mp);
21891 	}
21892 	/*
21893 	 * See whether we need to attach a global policy here. We
21894 	 * don't depend on the conn (as it could be null) for deciding
21895 	 * what policy this datagram should go through because it
21896 	 * should have happened in ip_wput if there was some
21897 	 * policy. This normally happens for connections which are not
21898 	 * fully bound preventing us from caching policies in
21899 	 * ip_bind. Packets coming from the TCP listener/global queue
21900 	 * - which are non-hard_bound - could also be affected by
21901 	 * applying policy here.
21902 	 *
21903 	 * If this packet is coming from tcp global queue or listener,
21904 	 * we will be applying policy here.  This may not be *right*
21905 	 * if these packets are coming from the detached connection as
21906 	 * it could have gone in clear before. This happens only if a
21907 	 * TCP connection started when there is no policy and somebody
21908 	 * added policy before it became detached. Thus packets of the
21909 	 * detached connection could go out secure and the other end
21910 	 * would drop it because it will be expecting in clear. The
21911 	 * converse is not true i.e if somebody starts a TCP
21912 	 * connection and deletes the policy, all the packets will
21913 	 * still go out with the policy that existed before deleting
21914 	 * because ip_unbind sends up policy information which is used
21915 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21916 	 * TCP to attach a dummy IPSEC_OUT and set
21917 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21918 	 * affect performance for normal cases, we are not doing it.
21919 	 * Thus, set policy before starting any TCP connections.
21920 	 *
21921 	 * NOTE - We might apply policy even for a hard bound connection
21922 	 * - for which we cached policy in ip_bind - if somebody added
21923 	 * global policy after we inherited the policy in ip_bind.
21924 	 * This means that the packets that were going out in clear
21925 	 * previously would start going secure and hence get dropped
21926 	 * on the other side. To fix this, TCP attaches a dummy
21927 	 * ipsec_out and make sure that we don't apply global policy.
21928 	 */
21929 	if (ipha != NULL)
21930 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21931 	else
21932 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21933 	if (!policy_present)
21934 		return (mp);
21935 
21936 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21937 	    zoneid));
21938 }
21939 
21940 ire_t *
21941 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21942 {
21943 	ipaddr_t addr;
21944 	ire_t *save_ire;
21945 	irb_t *irb;
21946 	ill_group_t *illgrp;
21947 	int	err;
21948 
21949 	save_ire = ire;
21950 	addr = ire->ire_addr;
21951 
21952 	ASSERT(ire->ire_type == IRE_BROADCAST);
21953 
21954 	illgrp = connp->conn_outgoing_ill->ill_group;
21955 	if (illgrp == NULL) {
21956 		*conn_outgoing_ill = conn_get_held_ill(connp,
21957 		    &connp->conn_outgoing_ill, &err);
21958 		if (err == ILL_LOOKUP_FAILED) {
21959 			ire_refrele(save_ire);
21960 			return (NULL);
21961 		}
21962 		return (save_ire);
21963 	}
21964 	/*
21965 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21966 	 * If it is part of the group, we need to send on the ire
21967 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21968 	 * to this group. This is okay as IP_BOUND_IF really means
21969 	 * any ill in the group. We depend on the fact that the
21970 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21971 	 * if such an ire exists. This is possible only if you have
21972 	 * at least one ill in the group that has not failed.
21973 	 *
21974 	 * First get to the ire that matches the address and group.
21975 	 *
21976 	 * We don't look for an ire with a matching zoneid because a given zone
21977 	 * won't always have broadcast ires on all ills in the group.
21978 	 */
21979 	irb = ire->ire_bucket;
21980 	rw_enter(&irb->irb_lock, RW_READER);
21981 	if (ire->ire_marks & IRE_MARK_NORECV) {
21982 		/*
21983 		 * If the current zone only has an ire broadcast for this
21984 		 * address marked NORECV, the ire we want is ahead in the
21985 		 * bucket, so we look it up deliberately ignoring the zoneid.
21986 		 */
21987 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21988 			if (ire->ire_addr != addr)
21989 				continue;
21990 			/* skip over deleted ires */
21991 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21992 				continue;
21993 		}
21994 	}
21995 	while (ire != NULL) {
21996 		/*
21997 		 * If a new interface is coming up, we could end up
21998 		 * seeing the loopback ire and the non-loopback ire
21999 		 * may not have been added yet. So check for ire_stq
22000 		 */
22001 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22002 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22003 			break;
22004 		}
22005 		ire = ire->ire_next;
22006 	}
22007 	if (ire != NULL && ire->ire_addr == addr &&
22008 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22009 		IRE_REFHOLD(ire);
22010 		rw_exit(&irb->irb_lock);
22011 		ire_refrele(save_ire);
22012 		*conn_outgoing_ill = ire_to_ill(ire);
22013 		/*
22014 		 * Refhold the ill to make the conn_outgoing_ill
22015 		 * independent of the ire. ip_wput_ire goes in a loop
22016 		 * and may refrele the ire. Since we have an ire at this
22017 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22018 		 */
22019 		ill_refhold(*conn_outgoing_ill);
22020 		return (ire);
22021 	}
22022 	rw_exit(&irb->irb_lock);
22023 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22024 	/*
22025 	 * If we can't find a suitable ire, return the original ire.
22026 	 */
22027 	return (save_ire);
22028 }
22029 
22030 /*
22031  * This function does the ire_refrele of the ire passed in as the
22032  * argument. As this function looks up more ires i.e broadcast ires,
22033  * it needs to REFRELE them. Currently, for simplicity we don't
22034  * differentiate the one passed in and looked up here. We always
22035  * REFRELE.
22036  * IPQoS Notes:
22037  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22038  * IPsec packets are done in ipsec_out_process.
22039  *
22040  */
22041 void
22042 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22043     zoneid_t zoneid)
22044 {
22045 	ipha_t		*ipha;
22046 #define	rptr	((uchar_t *)ipha)
22047 	queue_t		*stq;
22048 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22049 	uint32_t	v_hlen_tos_len;
22050 	uint32_t	ttl_protocol;
22051 	ipaddr_t	src;
22052 	ipaddr_t	dst;
22053 	uint32_t	cksum;
22054 	ipaddr_t	orig_src;
22055 	ire_t		*ire1;
22056 	mblk_t		*next_mp;
22057 	uint_t		hlen;
22058 	uint16_t	*up;
22059 	uint32_t	max_frag = ire->ire_max_frag;
22060 	ill_t		*ill = ire_to_ill(ire);
22061 	int		clusterwide;
22062 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22063 	int		ipsec_len;
22064 	mblk_t		*first_mp;
22065 	ipsec_out_t	*io;
22066 	boolean_t	conn_dontroute;		/* conn value for multicast */
22067 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22068 	boolean_t	multicast_forward;	/* Should we forward ? */
22069 	boolean_t	unspec_src;
22070 	ill_t		*conn_outgoing_ill = NULL;
22071 	ill_t		*ire_ill;
22072 	ill_t		*ire1_ill;
22073 	ill_t		*out_ill;
22074 	uint32_t 	ill_index = 0;
22075 	boolean_t	multirt_send = B_FALSE;
22076 	int		err;
22077 	ipxmit_state_t	pktxmit_state;
22078 	ip_stack_t	*ipst = ire->ire_ipst;
22079 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22080 
22081 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22082 	    "ip_wput_ire_start: q %p", q);
22083 
22084 	multicast_forward = B_FALSE;
22085 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22086 
22087 	if (ire->ire_flags & RTF_MULTIRT) {
22088 		/*
22089 		 * Multirouting case. The bucket where ire is stored
22090 		 * probably holds other RTF_MULTIRT flagged ire
22091 		 * to the destination. In this call to ip_wput_ire,
22092 		 * we attempt to send the packet through all
22093 		 * those ires. Thus, we first ensure that ire is the
22094 		 * first RTF_MULTIRT ire in the bucket,
22095 		 * before walking the ire list.
22096 		 */
22097 		ire_t *first_ire;
22098 		irb_t *irb = ire->ire_bucket;
22099 		ASSERT(irb != NULL);
22100 
22101 		/* Make sure we do not omit any multiroute ire. */
22102 		IRB_REFHOLD(irb);
22103 		for (first_ire = irb->irb_ire;
22104 		    first_ire != NULL;
22105 		    first_ire = first_ire->ire_next) {
22106 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22107 			    (first_ire->ire_addr == ire->ire_addr) &&
22108 			    !(first_ire->ire_marks &
22109 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22110 				break;
22111 			}
22112 		}
22113 
22114 		if ((first_ire != NULL) && (first_ire != ire)) {
22115 			IRE_REFHOLD(first_ire);
22116 			ire_refrele(ire);
22117 			ire = first_ire;
22118 			ill = ire_to_ill(ire);
22119 		}
22120 		IRB_REFRELE(irb);
22121 	}
22122 
22123 	/*
22124 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22125 	 * for performance we don't grab the mutexs in the fastpath
22126 	 */
22127 	if ((connp != NULL) &&
22128 	    (ire->ire_type == IRE_BROADCAST) &&
22129 	    ((connp->conn_nofailover_ill != NULL) ||
22130 	    (connp->conn_outgoing_ill != NULL))) {
22131 		/*
22132 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22133 		 * option. So, see if this endpoint is bound to a
22134 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22135 		 * that if the interface is failed, we will still send
22136 		 * the packet on the same ill which is what we want.
22137 		 */
22138 		conn_outgoing_ill = conn_get_held_ill(connp,
22139 		    &connp->conn_nofailover_ill, &err);
22140 		if (err == ILL_LOOKUP_FAILED) {
22141 			ire_refrele(ire);
22142 			freemsg(mp);
22143 			return;
22144 		}
22145 		if (conn_outgoing_ill == NULL) {
22146 			/*
22147 			 * Choose a good ill in the group to send the
22148 			 * packets on.
22149 			 */
22150 			ire = conn_set_outgoing_ill(connp, ire,
22151 			    &conn_outgoing_ill);
22152 			if (ire == NULL) {
22153 				freemsg(mp);
22154 				return;
22155 			}
22156 		}
22157 	}
22158 
22159 	if (mp->b_datap->db_type != M_CTL) {
22160 		ipha = (ipha_t *)mp->b_rptr;
22161 	} else {
22162 		io = (ipsec_out_t *)mp->b_rptr;
22163 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22164 		ASSERT(zoneid == io->ipsec_out_zoneid);
22165 		ASSERT(zoneid != ALL_ZONES);
22166 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22167 		dst = ipha->ipha_dst;
22168 		/*
22169 		 * For the multicast case, ipsec_out carries conn_dontroute and
22170 		 * conn_multicast_loop as conn may not be available here. We
22171 		 * need this for multicast loopback and forwarding which is done
22172 		 * later in the code.
22173 		 */
22174 		if (CLASSD(dst)) {
22175 			conn_dontroute = io->ipsec_out_dontroute;
22176 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22177 			/*
22178 			 * If conn_dontroute is not set or conn_multicast_loop
22179 			 * is set, we need to do forwarding/loopback. For
22180 			 * datagrams from ip_wput_multicast, conn_dontroute is
22181 			 * set to B_TRUE and conn_multicast_loop is set to
22182 			 * B_FALSE so that we neither do forwarding nor
22183 			 * loopback.
22184 			 */
22185 			if (!conn_dontroute || conn_multicast_loop)
22186 				multicast_forward = B_TRUE;
22187 		}
22188 	}
22189 
22190 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22191 	    ire->ire_zoneid != ALL_ZONES) {
22192 		/*
22193 		 * When a zone sends a packet to another zone, we try to deliver
22194 		 * the packet under the same conditions as if the destination
22195 		 * was a real node on the network. To do so, we look for a
22196 		 * matching route in the forwarding table.
22197 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22198 		 * ip_newroute() does.
22199 		 * Note that IRE_LOCAL are special, since they are used
22200 		 * when the zoneid doesn't match in some cases. This means that
22201 		 * we need to handle ipha_src differently since ire_src_addr
22202 		 * belongs to the receiving zone instead of the sending zone.
22203 		 * When ip_restrict_interzone_loopback is set, then
22204 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22205 		 * for loopback between zones when the logical "Ethernet" would
22206 		 * have looped them back.
22207 		 */
22208 		ire_t *src_ire;
22209 
22210 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22211 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22212 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22213 		if (src_ire != NULL &&
22214 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22215 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22216 		    ire_local_same_ill_group(ire, src_ire))) {
22217 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22218 				ipha->ipha_src = src_ire->ire_src_addr;
22219 			ire_refrele(src_ire);
22220 		} else {
22221 			ire_refrele(ire);
22222 			if (conn_outgoing_ill != NULL)
22223 				ill_refrele(conn_outgoing_ill);
22224 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22225 			if (src_ire != NULL) {
22226 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22227 					ire_refrele(src_ire);
22228 					freemsg(mp);
22229 					return;
22230 				}
22231 				ire_refrele(src_ire);
22232 			}
22233 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22234 				/* Failed */
22235 				freemsg(mp);
22236 				return;
22237 			}
22238 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22239 			    ipst);
22240 			return;
22241 		}
22242 	}
22243 
22244 	if (mp->b_datap->db_type == M_CTL ||
22245 	    ipss->ipsec_outbound_v4_policy_present) {
22246 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22247 		    unspec_src, zoneid);
22248 		if (mp == NULL) {
22249 			ire_refrele(ire);
22250 			if (conn_outgoing_ill != NULL)
22251 				ill_refrele(conn_outgoing_ill);
22252 			return;
22253 		}
22254 		/*
22255 		 * Trusted Extensions supports all-zones interfaces, so
22256 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22257 		 * the global zone.
22258 		 */
22259 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22260 			io = (ipsec_out_t *)mp->b_rptr;
22261 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22262 			zoneid = io->ipsec_out_zoneid;
22263 		}
22264 	}
22265 
22266 	first_mp = mp;
22267 	ipsec_len = 0;
22268 
22269 	if (first_mp->b_datap->db_type == M_CTL) {
22270 		io = (ipsec_out_t *)first_mp->b_rptr;
22271 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22272 		mp = first_mp->b_cont;
22273 		ipsec_len = ipsec_out_extra_length(first_mp);
22274 		ASSERT(ipsec_len >= 0);
22275 		/* We already picked up the zoneid from the M_CTL above */
22276 		ASSERT(zoneid == io->ipsec_out_zoneid);
22277 		ASSERT(zoneid != ALL_ZONES);
22278 
22279 		/*
22280 		 * Drop M_CTL here if IPsec processing is not needed.
22281 		 * (Non-IPsec use of M_CTL extracted any information it
22282 		 * needed above).
22283 		 */
22284 		if (ipsec_len == 0) {
22285 			freeb(first_mp);
22286 			first_mp = mp;
22287 		}
22288 	}
22289 
22290 	/*
22291 	 * Fast path for ip_wput_ire
22292 	 */
22293 
22294 	ipha = (ipha_t *)mp->b_rptr;
22295 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22296 	dst = ipha->ipha_dst;
22297 
22298 	/*
22299 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22300 	 * if the socket is a SOCK_RAW type. The transport checksum should
22301 	 * be provided in the pre-built packet, so we don't need to compute it.
22302 	 * Also, other application set flags, like DF, should not be altered.
22303 	 * Other transport MUST pass down zero.
22304 	 */
22305 	ip_hdr_included = ipha->ipha_ident;
22306 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22307 
22308 	if (CLASSD(dst)) {
22309 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22310 		    ntohl(dst),
22311 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22312 		    ntohl(ire->ire_addr)));
22313 	}
22314 
22315 /* Macros to extract header fields from data already in registers */
22316 #ifdef	_BIG_ENDIAN
22317 #define	V_HLEN	(v_hlen_tos_len >> 24)
22318 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22319 #define	PROTO	(ttl_protocol & 0xFF)
22320 #else
22321 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22322 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22323 #define	PROTO	(ttl_protocol >> 8)
22324 #endif
22325 
22326 
22327 	orig_src = src = ipha->ipha_src;
22328 	/* (The loop back to "another" is explained down below.) */
22329 another:;
22330 	/*
22331 	 * Assign an ident value for this packet.  We assign idents on
22332 	 * a per destination basis out of the IRE.  There could be
22333 	 * other threads targeting the same destination, so we have to
22334 	 * arrange for a atomic increment.  Note that we use a 32-bit
22335 	 * atomic add because it has better performance than its
22336 	 * 16-bit sibling.
22337 	 *
22338 	 * If running in cluster mode and if the source address
22339 	 * belongs to a replicated service then vector through
22340 	 * cl_inet_ipident vector to allocate ip identifier
22341 	 * NOTE: This is a contract private interface with the
22342 	 * clustering group.
22343 	 */
22344 	clusterwide = 0;
22345 	if (cl_inet_ipident) {
22346 		ASSERT(cl_inet_isclusterwide);
22347 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22348 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22349 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22350 			    AF_INET, (uint8_t *)(uintptr_t)src,
22351 			    (uint8_t *)(uintptr_t)dst);
22352 			clusterwide = 1;
22353 		}
22354 	}
22355 	if (!clusterwide) {
22356 		ipha->ipha_ident =
22357 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22358 	}
22359 
22360 #ifndef _BIG_ENDIAN
22361 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22362 #endif
22363 
22364 	/*
22365 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22366 	 * This is needed to obey conn_unspec_src when packets go through
22367 	 * ip_newroute + arp.
22368 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22369 	 */
22370 	if (src == INADDR_ANY && !unspec_src) {
22371 		/*
22372 		 * Assign the appropriate source address from the IRE if none
22373 		 * was specified.
22374 		 */
22375 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22376 
22377 		/*
22378 		 * With IP multipathing, broadcast packets are sent on the ire
22379 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22380 		 * the group. However, this ire might not be in the same zone so
22381 		 * we can't always use its source address. We look for a
22382 		 * broadcast ire in the same group and in the right zone.
22383 		 */
22384 		if (ire->ire_type == IRE_BROADCAST &&
22385 		    ire->ire_zoneid != zoneid) {
22386 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22387 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22388 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22389 			if (src_ire != NULL) {
22390 				src = src_ire->ire_src_addr;
22391 				ire_refrele(src_ire);
22392 			} else {
22393 				ire_refrele(ire);
22394 				if (conn_outgoing_ill != NULL)
22395 					ill_refrele(conn_outgoing_ill);
22396 				freemsg(first_mp);
22397 				if (ill != NULL) {
22398 					BUMP_MIB(ill->ill_ip_mib,
22399 					    ipIfStatsOutDiscards);
22400 				} else {
22401 					BUMP_MIB(&ipst->ips_ip_mib,
22402 					    ipIfStatsOutDiscards);
22403 				}
22404 				return;
22405 			}
22406 		} else {
22407 			src = ire->ire_src_addr;
22408 		}
22409 
22410 		if (connp == NULL) {
22411 			ip1dbg(("ip_wput_ire: no connp and no src "
22412 			    "address for dst 0x%x, using src 0x%x\n",
22413 			    ntohl(dst),
22414 			    ntohl(src)));
22415 		}
22416 		ipha->ipha_src = src;
22417 	}
22418 	stq = ire->ire_stq;
22419 
22420 	/*
22421 	 * We only allow ire chains for broadcasts since there will
22422 	 * be multiple IRE_CACHE entries for the same multicast
22423 	 * address (one per ipif).
22424 	 */
22425 	next_mp = NULL;
22426 
22427 	/* broadcast packet */
22428 	if (ire->ire_type == IRE_BROADCAST)
22429 		goto broadcast;
22430 
22431 	/* loopback ? */
22432 	if (stq == NULL)
22433 		goto nullstq;
22434 
22435 	/* The ill_index for outbound ILL */
22436 	ill_index = Q_TO_INDEX(stq);
22437 
22438 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22439 	ttl_protocol = ((uint16_t *)ipha)[4];
22440 
22441 	/* pseudo checksum (do it in parts for IP header checksum) */
22442 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22443 
22444 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22445 		queue_t *dev_q = stq->q_next;
22446 
22447 		/* flow controlled */
22448 		if ((dev_q->q_next || dev_q->q_first) &&
22449 		    !canput(dev_q))
22450 			goto blocked;
22451 		if ((PROTO == IPPROTO_UDP) &&
22452 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22453 			hlen = (V_HLEN & 0xF) << 2;
22454 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22455 			if (*up != 0) {
22456 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22457 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22458 				/* Software checksum? */
22459 				if (DB_CKSUMFLAGS(mp) == 0) {
22460 					IP_STAT(ipst, ip_out_sw_cksum);
22461 					IP_STAT_UPDATE(ipst,
22462 					    ip_udp_out_sw_cksum_bytes,
22463 					    LENGTH - hlen);
22464 				}
22465 			}
22466 		}
22467 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22468 		hlen = (V_HLEN & 0xF) << 2;
22469 		if (PROTO == IPPROTO_TCP) {
22470 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22471 			/*
22472 			 * The packet header is processed once and for all, even
22473 			 * in the multirouting case. We disable hardware
22474 			 * checksum if the packet is multirouted, as it will be
22475 			 * replicated via several interfaces, and not all of
22476 			 * them may have this capability.
22477 			 */
22478 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22479 			    LENGTH, max_frag, ipsec_len, cksum);
22480 			/* Software checksum? */
22481 			if (DB_CKSUMFLAGS(mp) == 0) {
22482 				IP_STAT(ipst, ip_out_sw_cksum);
22483 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22484 				    LENGTH - hlen);
22485 			}
22486 		} else {
22487 			sctp_hdr_t	*sctph;
22488 
22489 			ASSERT(PROTO == IPPROTO_SCTP);
22490 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22491 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22492 			/*
22493 			 * Zero out the checksum field to ensure proper
22494 			 * checksum calculation.
22495 			 */
22496 			sctph->sh_chksum = 0;
22497 #ifdef	DEBUG
22498 			if (!skip_sctp_cksum)
22499 #endif
22500 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22501 		}
22502 	}
22503 
22504 	/*
22505 	 * If this is a multicast packet and originated from ip_wput
22506 	 * we need to do loopback and forwarding checks. If it comes
22507 	 * from ip_wput_multicast, we SHOULD not do this.
22508 	 */
22509 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22510 
22511 	/* checksum */
22512 	cksum += ttl_protocol;
22513 
22514 	/* fragment the packet */
22515 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22516 		goto fragmentit;
22517 	/*
22518 	 * Don't use frag_flag if packet is pre-built or source
22519 	 * routed or if multicast (since multicast packets do
22520 	 * not solicit ICMP "packet too big" messages).
22521 	 */
22522 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22523 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22524 	    !ip_source_route_included(ipha)) &&
22525 	    !CLASSD(ipha->ipha_dst))
22526 		ipha->ipha_fragment_offset_and_flags |=
22527 		    htons(ire->ire_frag_flag);
22528 
22529 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22530 		/* calculate IP header checksum */
22531 		cksum += ipha->ipha_ident;
22532 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22533 		cksum += ipha->ipha_fragment_offset_and_flags;
22534 
22535 		/* IP options present */
22536 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22537 		if (hlen)
22538 			goto checksumoptions;
22539 
22540 		/* calculate hdr checksum */
22541 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22542 		cksum = ~(cksum + (cksum >> 16));
22543 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22544 	}
22545 	if (ipsec_len != 0) {
22546 		/*
22547 		 * We will do the rest of the processing after
22548 		 * we come back from IPsec in ip_wput_ipsec_out().
22549 		 */
22550 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22551 
22552 		io = (ipsec_out_t *)first_mp->b_rptr;
22553 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22554 		    ill_phyint->phyint_ifindex;
22555 
22556 		ipsec_out_process(q, first_mp, ire, ill_index);
22557 		ire_refrele(ire);
22558 		if (conn_outgoing_ill != NULL)
22559 			ill_refrele(conn_outgoing_ill);
22560 		return;
22561 	}
22562 
22563 	/*
22564 	 * In most cases, the emission loop below is entered only
22565 	 * once. Only in the case where the ire holds the
22566 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22567 	 * flagged ires in the bucket, and send the packet
22568 	 * through all crossed RTF_MULTIRT routes.
22569 	 */
22570 	if (ire->ire_flags & RTF_MULTIRT) {
22571 		multirt_send = B_TRUE;
22572 	}
22573 	do {
22574 		if (multirt_send) {
22575 			irb_t *irb;
22576 			/*
22577 			 * We are in a multiple send case, need to get
22578 			 * the next ire and make a duplicate of the packet.
22579 			 * ire1 holds here the next ire to process in the
22580 			 * bucket. If multirouting is expected,
22581 			 * any non-RTF_MULTIRT ire that has the
22582 			 * right destination address is ignored.
22583 			 */
22584 			irb = ire->ire_bucket;
22585 			ASSERT(irb != NULL);
22586 
22587 			IRB_REFHOLD(irb);
22588 			for (ire1 = ire->ire_next;
22589 			    ire1 != NULL;
22590 			    ire1 = ire1->ire_next) {
22591 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22592 					continue;
22593 				if (ire1->ire_addr != ire->ire_addr)
22594 					continue;
22595 				if (ire1->ire_marks &
22596 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22597 					continue;
22598 
22599 				/* Got one */
22600 				IRE_REFHOLD(ire1);
22601 				break;
22602 			}
22603 			IRB_REFRELE(irb);
22604 
22605 			if (ire1 != NULL) {
22606 				next_mp = copyb(mp);
22607 				if ((next_mp == NULL) ||
22608 				    ((mp->b_cont != NULL) &&
22609 				    ((next_mp->b_cont =
22610 				    dupmsg(mp->b_cont)) == NULL))) {
22611 					freemsg(next_mp);
22612 					next_mp = NULL;
22613 					ire_refrele(ire1);
22614 					ire1 = NULL;
22615 				}
22616 			}
22617 
22618 			/* Last multiroute ire; don't loop anymore. */
22619 			if (ire1 == NULL) {
22620 				multirt_send = B_FALSE;
22621 			}
22622 		}
22623 
22624 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22625 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22626 		    mblk_t *, mp);
22627 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22628 		    ipst->ips_ipv4firewall_physical_out,
22629 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22630 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22631 		if (mp == NULL)
22632 			goto release_ire_and_ill;
22633 
22634 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22635 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22636 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22637 		if ((pktxmit_state == SEND_FAILED) ||
22638 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22639 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22640 			    "- packet dropped\n"));
22641 release_ire_and_ill:
22642 			ire_refrele(ire);
22643 			if (next_mp != NULL) {
22644 				freemsg(next_mp);
22645 				ire_refrele(ire1);
22646 			}
22647 			if (conn_outgoing_ill != NULL)
22648 				ill_refrele(conn_outgoing_ill);
22649 			return;
22650 		}
22651 
22652 		if (CLASSD(dst)) {
22653 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22654 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22655 			    LENGTH);
22656 		}
22657 
22658 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22659 		    "ip_wput_ire_end: q %p (%S)",
22660 		    q, "last copy out");
22661 		IRE_REFRELE(ire);
22662 
22663 		if (multirt_send) {
22664 			ASSERT(ire1);
22665 			/*
22666 			 * Proceed with the next RTF_MULTIRT ire,
22667 			 * Also set up the send-to queue accordingly.
22668 			 */
22669 			ire = ire1;
22670 			ire1 = NULL;
22671 			stq = ire->ire_stq;
22672 			mp = next_mp;
22673 			next_mp = NULL;
22674 			ipha = (ipha_t *)mp->b_rptr;
22675 			ill_index = Q_TO_INDEX(stq);
22676 			ill = (ill_t *)stq->q_ptr;
22677 		}
22678 	} while (multirt_send);
22679 	if (conn_outgoing_ill != NULL)
22680 		ill_refrele(conn_outgoing_ill);
22681 	return;
22682 
22683 	/*
22684 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22685 	 */
22686 broadcast:
22687 	{
22688 		/*
22689 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22690 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22691 		 * can be overridden stack-wide through the ip_broadcast_ttl
22692 		 * ndd tunable, or on a per-connection basis through the
22693 		 * IP_BROADCAST_TTL socket option.
22694 		 *
22695 		 * In the event that we are replying to incoming ICMP packets,
22696 		 * connp could be NULL.
22697 		 */
22698 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22699 		if (connp != NULL) {
22700 			if (connp->conn_dontroute)
22701 				ipha->ipha_ttl = 1;
22702 			else if (connp->conn_broadcast_ttl != 0)
22703 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22704 		}
22705 
22706 		/*
22707 		 * Note that we are not doing a IRB_REFHOLD here.
22708 		 * Actually we don't care if the list changes i.e
22709 		 * if somebody deletes an IRE from the list while
22710 		 * we drop the lock, the next time we come around
22711 		 * ire_next will be NULL and hence we won't send
22712 		 * out multiple copies which is fine.
22713 		 */
22714 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22715 		ire1 = ire->ire_next;
22716 		if (conn_outgoing_ill != NULL) {
22717 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22718 				ASSERT(ire1 == ire->ire_next);
22719 				if (ire1 != NULL && ire1->ire_addr == dst) {
22720 					ire_refrele(ire);
22721 					ire = ire1;
22722 					IRE_REFHOLD(ire);
22723 					ire1 = ire->ire_next;
22724 					continue;
22725 				}
22726 				rw_exit(&ire->ire_bucket->irb_lock);
22727 				/* Did not find a matching ill */
22728 				ip1dbg(("ip_wput_ire: broadcast with no "
22729 				    "matching IP_BOUND_IF ill %s dst %x\n",
22730 				    conn_outgoing_ill->ill_name, dst));
22731 				freemsg(first_mp);
22732 				if (ire != NULL)
22733 					ire_refrele(ire);
22734 				ill_refrele(conn_outgoing_ill);
22735 				return;
22736 			}
22737 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22738 			/*
22739 			 * If the next IRE has the same address and is not one
22740 			 * of the two copies that we need to send, try to see
22741 			 * whether this copy should be sent at all. This
22742 			 * assumes that we insert loopbacks first and then
22743 			 * non-loopbacks. This is acheived by inserting the
22744 			 * loopback always before non-loopback.
22745 			 * This is used to send a single copy of a broadcast
22746 			 * packet out all physical interfaces that have an
22747 			 * matching IRE_BROADCAST while also looping
22748 			 * back one copy (to ip_wput_local) for each
22749 			 * matching physical interface. However, we avoid
22750 			 * sending packets out different logical that match by
22751 			 * having ipif_up/ipif_down supress duplicate
22752 			 * IRE_BROADCASTS.
22753 			 *
22754 			 * This feature is currently used to get broadcasts
22755 			 * sent to multiple interfaces, when the broadcast
22756 			 * address being used applies to multiple interfaces.
22757 			 * For example, a whole net broadcast will be
22758 			 * replicated on every connected subnet of
22759 			 * the target net.
22760 			 *
22761 			 * Each zone has its own set of IRE_BROADCASTs, so that
22762 			 * we're able to distribute inbound packets to multiple
22763 			 * zones who share a broadcast address. We avoid looping
22764 			 * back outbound packets in different zones but on the
22765 			 * same ill, as the application would see duplicates.
22766 			 *
22767 			 * If the interfaces are part of the same group,
22768 			 * we would want to send only one copy out for
22769 			 * whole group.
22770 			 *
22771 			 * This logic assumes that ire_add_v4() groups the
22772 			 * IRE_BROADCAST entries so that those with the same
22773 			 * ire_addr and ill_group are kept together.
22774 			 */
22775 			ire_ill = ire->ire_ipif->ipif_ill;
22776 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22777 				if (ire_ill->ill_group != NULL &&
22778 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22779 					/*
22780 					 * If the current zone only has an ire
22781 					 * broadcast for this address marked
22782 					 * NORECV, the ire we want is ahead in
22783 					 * the bucket, so we look it up
22784 					 * deliberately ignoring the zoneid.
22785 					 */
22786 					for (ire1 = ire->ire_bucket->irb_ire;
22787 					    ire1 != NULL;
22788 					    ire1 = ire1->ire_next) {
22789 						ire1_ill =
22790 						    ire1->ire_ipif->ipif_ill;
22791 						if (ire1->ire_addr != dst)
22792 							continue;
22793 						/* skip over the current ire */
22794 						if (ire1 == ire)
22795 							continue;
22796 						/* skip over deleted ires */
22797 						if (ire1->ire_marks &
22798 						    IRE_MARK_CONDEMNED)
22799 							continue;
22800 						/*
22801 						 * non-loopback ire in our
22802 						 * group: use it for the next
22803 						 * pass in the loop
22804 						 */
22805 						if (ire1->ire_stq != NULL &&
22806 						    ire1_ill->ill_group ==
22807 						    ire_ill->ill_group)
22808 							break;
22809 					}
22810 				}
22811 			} else {
22812 				while (ire1 != NULL && ire1->ire_addr == dst) {
22813 					ire1_ill = ire1->ire_ipif->ipif_ill;
22814 					/*
22815 					 * We can have two broadcast ires on the
22816 					 * same ill in different zones; here
22817 					 * we'll send a copy of the packet on
22818 					 * each ill and the fanout code will
22819 					 * call conn_wantpacket() to check that
22820 					 * the zone has the broadcast address
22821 					 * configured on the ill. If the two
22822 					 * ires are in the same group we only
22823 					 * send one copy up.
22824 					 */
22825 					if (ire1_ill != ire_ill &&
22826 					    (ire1_ill->ill_group == NULL ||
22827 					    ire_ill->ill_group == NULL ||
22828 					    ire1_ill->ill_group !=
22829 					    ire_ill->ill_group)) {
22830 						break;
22831 					}
22832 					ire1 = ire1->ire_next;
22833 				}
22834 			}
22835 		}
22836 		ASSERT(multirt_send == B_FALSE);
22837 		if (ire1 != NULL && ire1->ire_addr == dst) {
22838 			if ((ire->ire_flags & RTF_MULTIRT) &&
22839 			    (ire1->ire_flags & RTF_MULTIRT)) {
22840 				/*
22841 				 * We are in the multirouting case.
22842 				 * The message must be sent at least
22843 				 * on both ires. These ires have been
22844 				 * inserted AFTER the standard ones
22845 				 * in ip_rt_add(). There are thus no
22846 				 * other ire entries for the destination
22847 				 * address in the rest of the bucket
22848 				 * that do not have the RTF_MULTIRT
22849 				 * flag. We don't process a copy
22850 				 * of the message here. This will be
22851 				 * done in the final sending loop.
22852 				 */
22853 				multirt_send = B_TRUE;
22854 			} else {
22855 				next_mp = ip_copymsg(first_mp);
22856 				if (next_mp != NULL)
22857 					IRE_REFHOLD(ire1);
22858 			}
22859 		}
22860 		rw_exit(&ire->ire_bucket->irb_lock);
22861 	}
22862 
22863 	if (stq) {
22864 		/*
22865 		 * A non-NULL send-to queue means this packet is going
22866 		 * out of this machine.
22867 		 */
22868 		out_ill = (ill_t *)stq->q_ptr;
22869 
22870 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22871 		ttl_protocol = ((uint16_t *)ipha)[4];
22872 		/*
22873 		 * We accumulate the pseudo header checksum in cksum.
22874 		 * This is pretty hairy code, so watch close.  One
22875 		 * thing to keep in mind is that UDP and TCP have
22876 		 * stored their respective datagram lengths in their
22877 		 * checksum fields.  This lines things up real nice.
22878 		 */
22879 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22880 		    (src >> 16) + (src & 0xFFFF);
22881 		/*
22882 		 * We assume the udp checksum field contains the
22883 		 * length, so to compute the pseudo header checksum,
22884 		 * all we need is the protocol number and src/dst.
22885 		 */
22886 		/* Provide the checksums for UDP and TCP. */
22887 		if ((PROTO == IPPROTO_TCP) &&
22888 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22889 			/* hlen gets the number of uchar_ts in the IP header */
22890 			hlen = (V_HLEN & 0xF) << 2;
22891 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22892 			IP_STAT(ipst, ip_out_sw_cksum);
22893 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22894 			    LENGTH - hlen);
22895 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22896 		} else if (PROTO == IPPROTO_SCTP &&
22897 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22898 			sctp_hdr_t	*sctph;
22899 
22900 			hlen = (V_HLEN & 0xF) << 2;
22901 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22902 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22903 			sctph->sh_chksum = 0;
22904 #ifdef	DEBUG
22905 			if (!skip_sctp_cksum)
22906 #endif
22907 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22908 		} else {
22909 			queue_t *dev_q = stq->q_next;
22910 
22911 			if ((dev_q->q_next || dev_q->q_first) &&
22912 			    !canput(dev_q)) {
22913 blocked:
22914 				ipha->ipha_ident = ip_hdr_included;
22915 				/*
22916 				 * If we don't have a conn to apply
22917 				 * backpressure, free the message.
22918 				 * In the ire_send path, we don't know
22919 				 * the position to requeue the packet. Rather
22920 				 * than reorder packets, we just drop this
22921 				 * packet.
22922 				 */
22923 				if (ipst->ips_ip_output_queue &&
22924 				    connp != NULL &&
22925 				    caller != IRE_SEND) {
22926 					if (caller == IP_WSRV) {
22927 						connp->conn_did_putbq = 1;
22928 						(void) putbq(connp->conn_wq,
22929 						    first_mp);
22930 						conn_drain_insert(connp);
22931 						/*
22932 						 * This is the service thread,
22933 						 * and the queue is already
22934 						 * noenabled. The check for
22935 						 * canput and the putbq is not
22936 						 * atomic. So we need to check
22937 						 * again.
22938 						 */
22939 						if (canput(stq->q_next))
22940 							connp->conn_did_putbq
22941 							    = 0;
22942 						IP_STAT(ipst, ip_conn_flputbq);
22943 					} else {
22944 						/*
22945 						 * We are not the service proc.
22946 						 * ip_wsrv will be scheduled or
22947 						 * is already running.
22948 						 */
22949 						(void) putq(connp->conn_wq,
22950 						    first_mp);
22951 					}
22952 				} else {
22953 					out_ill = (ill_t *)stq->q_ptr;
22954 					BUMP_MIB(out_ill->ill_ip_mib,
22955 					    ipIfStatsOutDiscards);
22956 					freemsg(first_mp);
22957 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22958 					    "ip_wput_ire_end: q %p (%S)",
22959 					    q, "discard");
22960 				}
22961 				ire_refrele(ire);
22962 				if (next_mp) {
22963 					ire_refrele(ire1);
22964 					freemsg(next_mp);
22965 				}
22966 				if (conn_outgoing_ill != NULL)
22967 					ill_refrele(conn_outgoing_ill);
22968 				return;
22969 			}
22970 			if ((PROTO == IPPROTO_UDP) &&
22971 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22972 				/*
22973 				 * hlen gets the number of uchar_ts in the
22974 				 * IP header
22975 				 */
22976 				hlen = (V_HLEN & 0xF) << 2;
22977 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22978 				max_frag = ire->ire_max_frag;
22979 				if (*up != 0) {
22980 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22981 					    up, PROTO, hlen, LENGTH, max_frag,
22982 					    ipsec_len, cksum);
22983 					/* Software checksum? */
22984 					if (DB_CKSUMFLAGS(mp) == 0) {
22985 						IP_STAT(ipst, ip_out_sw_cksum);
22986 						IP_STAT_UPDATE(ipst,
22987 						    ip_udp_out_sw_cksum_bytes,
22988 						    LENGTH - hlen);
22989 					}
22990 				}
22991 			}
22992 		}
22993 		/*
22994 		 * Need to do this even when fragmenting. The local
22995 		 * loopback can be done without computing checksums
22996 		 * but forwarding out other interface must be done
22997 		 * after the IP checksum (and ULP checksums) have been
22998 		 * computed.
22999 		 *
23000 		 * NOTE : multicast_forward is set only if this packet
23001 		 * originated from ip_wput. For packets originating from
23002 		 * ip_wput_multicast, it is not set.
23003 		 */
23004 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23005 multi_loopback:
23006 			ip2dbg(("ip_wput: multicast, loop %d\n",
23007 			    conn_multicast_loop));
23008 
23009 			/*  Forget header checksum offload */
23010 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23011 
23012 			/*
23013 			 * Local loopback of multicasts?  Check the
23014 			 * ill.
23015 			 *
23016 			 * Note that the loopback function will not come
23017 			 * in through ip_rput - it will only do the
23018 			 * client fanout thus we need to do an mforward
23019 			 * as well.  The is different from the BSD
23020 			 * logic.
23021 			 */
23022 			if (ill != NULL) {
23023 				ilm_t	*ilm;
23024 
23025 				ILM_WALKER_HOLD(ill);
23026 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23027 				    ALL_ZONES);
23028 				ILM_WALKER_RELE(ill);
23029 				if (ilm != NULL) {
23030 					/*
23031 					 * Pass along the virtual output q.
23032 					 * ip_wput_local() will distribute the
23033 					 * packet to all the matching zones,
23034 					 * except the sending zone when
23035 					 * IP_MULTICAST_LOOP is false.
23036 					 */
23037 					ip_multicast_loopback(q, ill, first_mp,
23038 					    conn_multicast_loop ? 0 :
23039 					    IP_FF_NO_MCAST_LOOP, zoneid);
23040 				}
23041 			}
23042 			if (ipha->ipha_ttl == 0) {
23043 				/*
23044 				 * 0 => only to this host i.e. we are
23045 				 * done. We are also done if this was the
23046 				 * loopback interface since it is sufficient
23047 				 * to loopback one copy of a multicast packet.
23048 				 */
23049 				freemsg(first_mp);
23050 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23051 				    "ip_wput_ire_end: q %p (%S)",
23052 				    q, "loopback");
23053 				ire_refrele(ire);
23054 				if (conn_outgoing_ill != NULL)
23055 					ill_refrele(conn_outgoing_ill);
23056 				return;
23057 			}
23058 			/*
23059 			 * ILLF_MULTICAST is checked in ip_newroute
23060 			 * i.e. we don't need to check it here since
23061 			 * all IRE_CACHEs come from ip_newroute.
23062 			 * For multicast traffic, SO_DONTROUTE is interpreted
23063 			 * to mean only send the packet out the interface
23064 			 * (optionally specified with IP_MULTICAST_IF)
23065 			 * and do not forward it out additional interfaces.
23066 			 * RSVP and the rsvp daemon is an example of a
23067 			 * protocol and user level process that
23068 			 * handles it's own routing. Hence, it uses the
23069 			 * SO_DONTROUTE option to accomplish this.
23070 			 */
23071 
23072 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23073 			    ill != NULL) {
23074 				/* Unconditionally redo the checksum */
23075 				ipha->ipha_hdr_checksum = 0;
23076 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23077 
23078 				/*
23079 				 * If this needs to go out secure, we need
23080 				 * to wait till we finish the IPsec
23081 				 * processing.
23082 				 */
23083 				if (ipsec_len == 0 &&
23084 				    ip_mforward(ill, ipha, mp)) {
23085 					freemsg(first_mp);
23086 					ip1dbg(("ip_wput: mforward failed\n"));
23087 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23088 					    "ip_wput_ire_end: q %p (%S)",
23089 					    q, "mforward failed");
23090 					ire_refrele(ire);
23091 					if (conn_outgoing_ill != NULL)
23092 						ill_refrele(conn_outgoing_ill);
23093 					return;
23094 				}
23095 			}
23096 		}
23097 		max_frag = ire->ire_max_frag;
23098 		cksum += ttl_protocol;
23099 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23100 			/* No fragmentation required for this one. */
23101 			/*
23102 			 * Don't use frag_flag if packet is pre-built or source
23103 			 * routed or if multicast (since multicast packets do
23104 			 * not solicit ICMP "packet too big" messages).
23105 			 */
23106 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23107 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23108 			    !ip_source_route_included(ipha)) &&
23109 			    !CLASSD(ipha->ipha_dst))
23110 				ipha->ipha_fragment_offset_and_flags |=
23111 				    htons(ire->ire_frag_flag);
23112 
23113 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23114 				/* Complete the IP header checksum. */
23115 				cksum += ipha->ipha_ident;
23116 				cksum += (v_hlen_tos_len >> 16)+
23117 				    (v_hlen_tos_len & 0xFFFF);
23118 				cksum += ipha->ipha_fragment_offset_and_flags;
23119 				hlen = (V_HLEN & 0xF) -
23120 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23121 				if (hlen) {
23122 checksumoptions:
23123 					/*
23124 					 * Account for the IP Options in the IP
23125 					 * header checksum.
23126 					 */
23127 					up = (uint16_t *)(rptr+
23128 					    IP_SIMPLE_HDR_LENGTH);
23129 					do {
23130 						cksum += up[0];
23131 						cksum += up[1];
23132 						up += 2;
23133 					} while (--hlen);
23134 				}
23135 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23136 				cksum = ~(cksum + (cksum >> 16));
23137 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23138 			}
23139 			if (ipsec_len != 0) {
23140 				ipsec_out_process(q, first_mp, ire, ill_index);
23141 				if (!next_mp) {
23142 					ire_refrele(ire);
23143 					if (conn_outgoing_ill != NULL)
23144 						ill_refrele(conn_outgoing_ill);
23145 					return;
23146 				}
23147 				goto next;
23148 			}
23149 
23150 			/*
23151 			 * multirt_send has already been handled
23152 			 * for broadcast, but not yet for multicast
23153 			 * or IP options.
23154 			 */
23155 			if (next_mp == NULL) {
23156 				if (ire->ire_flags & RTF_MULTIRT) {
23157 					multirt_send = B_TRUE;
23158 				}
23159 			}
23160 
23161 			/*
23162 			 * In most cases, the emission loop below is
23163 			 * entered only once. Only in the case where
23164 			 * the ire holds the RTF_MULTIRT flag, do we loop
23165 			 * to process all RTF_MULTIRT ires in the bucket,
23166 			 * and send the packet through all crossed
23167 			 * RTF_MULTIRT routes.
23168 			 */
23169 			do {
23170 				if (multirt_send) {
23171 					irb_t *irb;
23172 
23173 					irb = ire->ire_bucket;
23174 					ASSERT(irb != NULL);
23175 					/*
23176 					 * We are in a multiple send case,
23177 					 * need to get the next IRE and make
23178 					 * a duplicate of the packet.
23179 					 */
23180 					IRB_REFHOLD(irb);
23181 					for (ire1 = ire->ire_next;
23182 					    ire1 != NULL;
23183 					    ire1 = ire1->ire_next) {
23184 						if (!(ire1->ire_flags &
23185 						    RTF_MULTIRT)) {
23186 							continue;
23187 						}
23188 						if (ire1->ire_addr !=
23189 						    ire->ire_addr) {
23190 							continue;
23191 						}
23192 						if (ire1->ire_marks &
23193 						    (IRE_MARK_CONDEMNED|
23194 						    IRE_MARK_HIDDEN)) {
23195 							continue;
23196 						}
23197 
23198 						/* Got one */
23199 						IRE_REFHOLD(ire1);
23200 						break;
23201 					}
23202 					IRB_REFRELE(irb);
23203 
23204 					if (ire1 != NULL) {
23205 						next_mp = copyb(mp);
23206 						if ((next_mp == NULL) ||
23207 						    ((mp->b_cont != NULL) &&
23208 						    ((next_mp->b_cont =
23209 						    dupmsg(mp->b_cont))
23210 						    == NULL))) {
23211 							freemsg(next_mp);
23212 							next_mp = NULL;
23213 							ire_refrele(ire1);
23214 							ire1 = NULL;
23215 						}
23216 					}
23217 
23218 					/*
23219 					 * Last multiroute ire; don't loop
23220 					 * anymore. The emission is over
23221 					 * and next_mp is NULL.
23222 					 */
23223 					if (ire1 == NULL) {
23224 						multirt_send = B_FALSE;
23225 					}
23226 				}
23227 
23228 				out_ill = ire_to_ill(ire);
23229 				DTRACE_PROBE4(ip4__physical__out__start,
23230 				    ill_t *, NULL,
23231 				    ill_t *, out_ill,
23232 				    ipha_t *, ipha, mblk_t *, mp);
23233 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23234 				    ipst->ips_ipv4firewall_physical_out,
23235 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23236 				DTRACE_PROBE1(ip4__physical__out__end,
23237 				    mblk_t *, mp);
23238 				if (mp == NULL)
23239 					goto release_ire_and_ill_2;
23240 
23241 				ASSERT(ipsec_len == 0);
23242 				mp->b_prev =
23243 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23244 				DTRACE_PROBE2(ip__xmit__2,
23245 				    mblk_t *, mp, ire_t *, ire);
23246 				pktxmit_state = ip_xmit_v4(mp, ire,
23247 				    NULL, B_TRUE);
23248 				if ((pktxmit_state == SEND_FAILED) ||
23249 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23250 release_ire_and_ill_2:
23251 					if (next_mp) {
23252 						freemsg(next_mp);
23253 						ire_refrele(ire1);
23254 					}
23255 					ire_refrele(ire);
23256 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23257 					    "ip_wput_ire_end: q %p (%S)",
23258 					    q, "discard MDATA");
23259 					if (conn_outgoing_ill != NULL)
23260 						ill_refrele(conn_outgoing_ill);
23261 					return;
23262 				}
23263 
23264 				if (CLASSD(dst)) {
23265 					BUMP_MIB(out_ill->ill_ip_mib,
23266 					    ipIfStatsHCOutMcastPkts);
23267 					UPDATE_MIB(out_ill->ill_ip_mib,
23268 					    ipIfStatsHCOutMcastOctets,
23269 					    LENGTH);
23270 				} else if (ire->ire_type == IRE_BROADCAST) {
23271 					BUMP_MIB(out_ill->ill_ip_mib,
23272 					    ipIfStatsHCOutBcastPkts);
23273 				}
23274 
23275 				if (multirt_send) {
23276 					/*
23277 					 * We are in a multiple send case,
23278 					 * need to re-enter the sending loop
23279 					 * using the next ire.
23280 					 */
23281 					ire_refrele(ire);
23282 					ire = ire1;
23283 					stq = ire->ire_stq;
23284 					mp = next_mp;
23285 					next_mp = NULL;
23286 					ipha = (ipha_t *)mp->b_rptr;
23287 					ill_index = Q_TO_INDEX(stq);
23288 				}
23289 			} while (multirt_send);
23290 
23291 			if (!next_mp) {
23292 				/*
23293 				 * Last copy going out (the ultra-common
23294 				 * case).  Note that we intentionally replicate
23295 				 * the putnext rather than calling it before
23296 				 * the next_mp check in hopes of a little
23297 				 * tail-call action out of the compiler.
23298 				 */
23299 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23300 				    "ip_wput_ire_end: q %p (%S)",
23301 				    q, "last copy out(1)");
23302 				ire_refrele(ire);
23303 				if (conn_outgoing_ill != NULL)
23304 					ill_refrele(conn_outgoing_ill);
23305 				return;
23306 			}
23307 			/* More copies going out below. */
23308 		} else {
23309 			int offset;
23310 fragmentit:
23311 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23312 			/*
23313 			 * If this would generate a icmp_frag_needed message,
23314 			 * we need to handle it before we do the IPsec
23315 			 * processing. Otherwise, we need to strip the IPsec
23316 			 * headers before we send up the message to the ULPs
23317 			 * which becomes messy and difficult.
23318 			 */
23319 			if (ipsec_len != 0) {
23320 				if ((max_frag < (unsigned int)(LENGTH +
23321 				    ipsec_len)) && (offset & IPH_DF)) {
23322 					out_ill = (ill_t *)stq->q_ptr;
23323 					BUMP_MIB(out_ill->ill_ip_mib,
23324 					    ipIfStatsOutFragFails);
23325 					BUMP_MIB(out_ill->ill_ip_mib,
23326 					    ipIfStatsOutFragReqds);
23327 					ipha->ipha_hdr_checksum = 0;
23328 					ipha->ipha_hdr_checksum =
23329 					    (uint16_t)ip_csum_hdr(ipha);
23330 					icmp_frag_needed(ire->ire_stq, first_mp,
23331 					    max_frag, zoneid, ipst);
23332 					if (!next_mp) {
23333 						ire_refrele(ire);
23334 						if (conn_outgoing_ill != NULL) {
23335 							ill_refrele(
23336 							    conn_outgoing_ill);
23337 						}
23338 						return;
23339 					}
23340 				} else {
23341 					/*
23342 					 * This won't cause a icmp_frag_needed
23343 					 * message. to be generated. Send it on
23344 					 * the wire. Note that this could still
23345 					 * cause fragmentation and all we
23346 					 * do is the generation of the message
23347 					 * to the ULP if needed before IPsec.
23348 					 */
23349 					if (!next_mp) {
23350 						ipsec_out_process(q, first_mp,
23351 						    ire, ill_index);
23352 						TRACE_2(TR_FAC_IP,
23353 						    TR_IP_WPUT_IRE_END,
23354 						    "ip_wput_ire_end: q %p "
23355 						    "(%S)", q,
23356 						    "last ipsec_out_process");
23357 						ire_refrele(ire);
23358 						if (conn_outgoing_ill != NULL) {
23359 							ill_refrele(
23360 							    conn_outgoing_ill);
23361 						}
23362 						return;
23363 					}
23364 					ipsec_out_process(q, first_mp,
23365 					    ire, ill_index);
23366 				}
23367 			} else {
23368 				/*
23369 				 * Initiate IPPF processing. For
23370 				 * fragmentable packets we finish
23371 				 * all QOS packet processing before
23372 				 * calling:
23373 				 * ip_wput_ire_fragmentit->ip_wput_frag
23374 				 */
23375 
23376 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23377 					ip_process(IPP_LOCAL_OUT, &mp,
23378 					    ill_index);
23379 					if (mp == NULL) {
23380 						out_ill = (ill_t *)stq->q_ptr;
23381 						BUMP_MIB(out_ill->ill_ip_mib,
23382 						    ipIfStatsOutDiscards);
23383 						if (next_mp != NULL) {
23384 							freemsg(next_mp);
23385 							ire_refrele(ire1);
23386 						}
23387 						ire_refrele(ire);
23388 						TRACE_2(TR_FAC_IP,
23389 						    TR_IP_WPUT_IRE_END,
23390 						    "ip_wput_ire: q %p (%S)",
23391 						    q, "discard MDATA");
23392 						if (conn_outgoing_ill != NULL) {
23393 							ill_refrele(
23394 							    conn_outgoing_ill);
23395 						}
23396 						return;
23397 					}
23398 				}
23399 				if (!next_mp) {
23400 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23401 					    "ip_wput_ire_end: q %p (%S)",
23402 					    q, "last fragmentation");
23403 					ip_wput_ire_fragmentit(mp, ire,
23404 					    zoneid, ipst);
23405 					ire_refrele(ire);
23406 					if (conn_outgoing_ill != NULL)
23407 						ill_refrele(conn_outgoing_ill);
23408 					return;
23409 				}
23410 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23411 			}
23412 		}
23413 	} else {
23414 nullstq:
23415 		/* A NULL stq means the destination address is local. */
23416 		UPDATE_OB_PKT_COUNT(ire);
23417 		ire->ire_last_used_time = lbolt;
23418 		ASSERT(ire->ire_ipif != NULL);
23419 		if (!next_mp) {
23420 			/*
23421 			 * Is there an "in" and "out" for traffic local
23422 			 * to a host (loopback)?  The code in Solaris doesn't
23423 			 * explicitly draw a line in its code for in vs out,
23424 			 * so we've had to draw a line in the sand: ip_wput_ire
23425 			 * is considered to be the "output" side and
23426 			 * ip_wput_local to be the "input" side.
23427 			 */
23428 			out_ill = ire_to_ill(ire);
23429 
23430 			/*
23431 			 * DTrace this as ip:::send.  A blocked packet will
23432 			 * fire the send probe, but not the receive probe.
23433 			 */
23434 			DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23435 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23436 			    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23437 
23438 			DTRACE_PROBE4(ip4__loopback__out__start,
23439 			    ill_t *, NULL, ill_t *, out_ill,
23440 			    ipha_t *, ipha, mblk_t *, first_mp);
23441 
23442 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23443 			    ipst->ips_ipv4firewall_loopback_out,
23444 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23445 
23446 			DTRACE_PROBE1(ip4__loopback__out_end,
23447 			    mblk_t *, first_mp);
23448 
23449 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23450 			    "ip_wput_ire_end: q %p (%S)",
23451 			    q, "local address");
23452 
23453 			if (first_mp != NULL)
23454 				ip_wput_local(q, out_ill, ipha,
23455 				    first_mp, ire, 0, ire->ire_zoneid);
23456 			ire_refrele(ire);
23457 			if (conn_outgoing_ill != NULL)
23458 				ill_refrele(conn_outgoing_ill);
23459 			return;
23460 		}
23461 
23462 		out_ill = ire_to_ill(ire);
23463 
23464 		/*
23465 		 * DTrace this as ip:::send.  A blocked packet will fire the
23466 		 * send probe, but not the receive probe.
23467 		 */
23468 		DTRACE_IP7(send, mblk_t *, first_mp, conn_t *, NULL,
23469 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
23470 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
23471 
23472 		DTRACE_PROBE4(ip4__loopback__out__start,
23473 		    ill_t *, NULL, ill_t *, out_ill,
23474 		    ipha_t *, ipha, mblk_t *, first_mp);
23475 
23476 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23477 		    ipst->ips_ipv4firewall_loopback_out,
23478 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23479 
23480 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23481 
23482 		if (first_mp != NULL)
23483 			ip_wput_local(q, out_ill, ipha,
23484 			    first_mp, ire, 0, ire->ire_zoneid);
23485 	}
23486 next:
23487 	/*
23488 	 * More copies going out to additional interfaces.
23489 	 * ire1 has already been held. We don't need the
23490 	 * "ire" anymore.
23491 	 */
23492 	ire_refrele(ire);
23493 	ire = ire1;
23494 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23495 	mp = next_mp;
23496 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23497 	ill = ire_to_ill(ire);
23498 	first_mp = mp;
23499 	if (ipsec_len != 0) {
23500 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23501 		mp = mp->b_cont;
23502 	}
23503 	dst = ire->ire_addr;
23504 	ipha = (ipha_t *)mp->b_rptr;
23505 	/*
23506 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23507 	 * Restore ipha_ident "no checksum" flag.
23508 	 */
23509 	src = orig_src;
23510 	ipha->ipha_ident = ip_hdr_included;
23511 	goto another;
23512 
23513 #undef	rptr
23514 #undef	Q_TO_INDEX
23515 }
23516 
23517 /*
23518  * Routine to allocate a message that is used to notify the ULP about MDT.
23519  * The caller may provide a pointer to the link-layer MDT capabilities,
23520  * or NULL if MDT is to be disabled on the stream.
23521  */
23522 mblk_t *
23523 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23524 {
23525 	mblk_t *mp;
23526 	ip_mdt_info_t *mdti;
23527 	ill_mdt_capab_t *idst;
23528 
23529 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23530 		DB_TYPE(mp) = M_CTL;
23531 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23532 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23533 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23534 		idst = &(mdti->mdt_capab);
23535 
23536 		/*
23537 		 * If the caller provides us with the capability, copy
23538 		 * it over into our notification message; otherwise
23539 		 * we zero out the capability portion.
23540 		 */
23541 		if (isrc != NULL)
23542 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23543 		else
23544 			bzero((caddr_t)idst, sizeof (*idst));
23545 	}
23546 	return (mp);
23547 }
23548 
23549 /*
23550  * Routine which determines whether MDT can be enabled on the destination
23551  * IRE and IPC combination, and if so, allocates and returns the MDT
23552  * notification mblk that may be used by ULP.  We also check if we need to
23553  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23554  * MDT usage in the past have been lifted.  This gets called during IP
23555  * and ULP binding.
23556  */
23557 mblk_t *
23558 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23559     ill_mdt_capab_t *mdt_cap)
23560 {
23561 	mblk_t *mp;
23562 	boolean_t rc = B_FALSE;
23563 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23564 
23565 	ASSERT(dst_ire != NULL);
23566 	ASSERT(connp != NULL);
23567 	ASSERT(mdt_cap != NULL);
23568 
23569 	/*
23570 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23571 	 * Multidata, which is handled in tcp_multisend().  This
23572 	 * is the reason why we do all these checks here, to ensure
23573 	 * that we don't enable Multidata for the cases which we
23574 	 * can't handle at the moment.
23575 	 */
23576 	do {
23577 		/* Only do TCP at the moment */
23578 		if (connp->conn_ulp != IPPROTO_TCP)
23579 			break;
23580 
23581 		/*
23582 		 * IPsec outbound policy present?  Note that we get here
23583 		 * after calling ipsec_conn_cache_policy() where the global
23584 		 * policy checking is performed.  conn_latch will be
23585 		 * non-NULL as long as there's a policy defined,
23586 		 * i.e. conn_out_enforce_policy may be NULL in such case
23587 		 * when the connection is non-secure, and hence we check
23588 		 * further if the latch refers to an outbound policy.
23589 		 */
23590 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23591 			break;
23592 
23593 		/* CGTP (multiroute) is enabled? */
23594 		if (dst_ire->ire_flags & RTF_MULTIRT)
23595 			break;
23596 
23597 		/* Outbound IPQoS enabled? */
23598 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23599 			/*
23600 			 * In this case, we disable MDT for this and all
23601 			 * future connections going over the interface.
23602 			 */
23603 			mdt_cap->ill_mdt_on = 0;
23604 			break;
23605 		}
23606 
23607 		/* socket option(s) present? */
23608 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23609 			break;
23610 
23611 		rc = B_TRUE;
23612 	/* CONSTCOND */
23613 	} while (0);
23614 
23615 	/* Remember the result */
23616 	connp->conn_mdt_ok = rc;
23617 
23618 	if (!rc)
23619 		return (NULL);
23620 	else if (!mdt_cap->ill_mdt_on) {
23621 		/*
23622 		 * If MDT has been previously turned off in the past, and we
23623 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23624 		 * then enable it for this interface.
23625 		 */
23626 		mdt_cap->ill_mdt_on = 1;
23627 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23628 		    "interface %s\n", ill_name));
23629 	}
23630 
23631 	/* Allocate the MDT info mblk */
23632 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23633 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23634 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23635 		return (NULL);
23636 	}
23637 	return (mp);
23638 }
23639 
23640 /*
23641  * Routine to allocate a message that is used to notify the ULP about LSO.
23642  * The caller may provide a pointer to the link-layer LSO capabilities,
23643  * or NULL if LSO is to be disabled on the stream.
23644  */
23645 mblk_t *
23646 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23647 {
23648 	mblk_t *mp;
23649 	ip_lso_info_t *lsoi;
23650 	ill_lso_capab_t *idst;
23651 
23652 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23653 		DB_TYPE(mp) = M_CTL;
23654 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23655 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23656 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23657 		idst = &(lsoi->lso_capab);
23658 
23659 		/*
23660 		 * If the caller provides us with the capability, copy
23661 		 * it over into our notification message; otherwise
23662 		 * we zero out the capability portion.
23663 		 */
23664 		if (isrc != NULL)
23665 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23666 		else
23667 			bzero((caddr_t)idst, sizeof (*idst));
23668 	}
23669 	return (mp);
23670 }
23671 
23672 /*
23673  * Routine which determines whether LSO can be enabled on the destination
23674  * IRE and IPC combination, and if so, allocates and returns the LSO
23675  * notification mblk that may be used by ULP.  We also check if we need to
23676  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23677  * LSO usage in the past have been lifted.  This gets called during IP
23678  * and ULP binding.
23679  */
23680 mblk_t *
23681 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23682     ill_lso_capab_t *lso_cap)
23683 {
23684 	mblk_t *mp;
23685 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23686 
23687 	ASSERT(dst_ire != NULL);
23688 	ASSERT(connp != NULL);
23689 	ASSERT(lso_cap != NULL);
23690 
23691 	connp->conn_lso_ok = B_TRUE;
23692 
23693 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23694 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23695 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23696 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23697 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23698 		connp->conn_lso_ok = B_FALSE;
23699 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23700 			/*
23701 			 * Disable LSO for this and all future connections going
23702 			 * over the interface.
23703 			 */
23704 			lso_cap->ill_lso_on = 0;
23705 		}
23706 	}
23707 
23708 	if (!connp->conn_lso_ok)
23709 		return (NULL);
23710 	else if (!lso_cap->ill_lso_on) {
23711 		/*
23712 		 * If LSO has been previously turned off in the past, and we
23713 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23714 		 * then enable it for this interface.
23715 		 */
23716 		lso_cap->ill_lso_on = 1;
23717 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23718 		    ill_name));
23719 	}
23720 
23721 	/* Allocate the LSO info mblk */
23722 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23723 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23724 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23725 
23726 	return (mp);
23727 }
23728 
23729 /*
23730  * Create destination address attribute, and fill it with the physical
23731  * destination address and SAP taken from the template DL_UNITDATA_REQ
23732  * message block.
23733  */
23734 boolean_t
23735 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23736 {
23737 	dl_unitdata_req_t *dlurp;
23738 	pattr_t *pa;
23739 	pattrinfo_t pa_info;
23740 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23741 	uint_t das_len, das_off;
23742 
23743 	ASSERT(dlmp != NULL);
23744 
23745 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23746 	das_len = dlurp->dl_dest_addr_length;
23747 	das_off = dlurp->dl_dest_addr_offset;
23748 
23749 	pa_info.type = PATTR_DSTADDRSAP;
23750 	pa_info.len = sizeof (**das) + das_len - 1;
23751 
23752 	/* create and associate the attribute */
23753 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23754 	if (pa != NULL) {
23755 		ASSERT(*das != NULL);
23756 		(*das)->addr_is_group = 0;
23757 		(*das)->addr_len = (uint8_t)das_len;
23758 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23759 	}
23760 
23761 	return (pa != NULL);
23762 }
23763 
23764 /*
23765  * Create hardware checksum attribute and fill it with the values passed.
23766  */
23767 boolean_t
23768 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23769     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23770 {
23771 	pattr_t *pa;
23772 	pattrinfo_t pa_info;
23773 
23774 	ASSERT(mmd != NULL);
23775 
23776 	pa_info.type = PATTR_HCKSUM;
23777 	pa_info.len = sizeof (pattr_hcksum_t);
23778 
23779 	/* create and associate the attribute */
23780 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23781 	if (pa != NULL) {
23782 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23783 
23784 		hck->hcksum_start_offset = start_offset;
23785 		hck->hcksum_stuff_offset = stuff_offset;
23786 		hck->hcksum_end_offset = end_offset;
23787 		hck->hcksum_flags = flags;
23788 	}
23789 	return (pa != NULL);
23790 }
23791 
23792 /*
23793  * Create zerocopy attribute and fill it with the specified flags
23794  */
23795 boolean_t
23796 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23797 {
23798 	pattr_t *pa;
23799 	pattrinfo_t pa_info;
23800 
23801 	ASSERT(mmd != NULL);
23802 	pa_info.type = PATTR_ZCOPY;
23803 	pa_info.len = sizeof (pattr_zcopy_t);
23804 
23805 	/* create and associate the attribute */
23806 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23807 	if (pa != NULL) {
23808 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23809 
23810 		zcopy->zcopy_flags = flags;
23811 	}
23812 	return (pa != NULL);
23813 }
23814 
23815 /*
23816  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23817  * block chain. We could rewrite to handle arbitrary message block chains but
23818  * that would make the code complicated and slow. Right now there three
23819  * restrictions:
23820  *
23821  *   1. The first message block must contain the complete IP header and
23822  *	at least 1 byte of payload data.
23823  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23824  *	so that we can use a single Multidata message.
23825  *   3. No frag must be distributed over two or more message blocks so
23826  *	that we don't need more than two packet descriptors per frag.
23827  *
23828  * The above restrictions allow us to support userland applications (which
23829  * will send down a single message block) and NFS over UDP (which will
23830  * send down a chain of at most three message blocks).
23831  *
23832  * We also don't use MDT for payloads with less than or equal to
23833  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23834  */
23835 boolean_t
23836 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23837 {
23838 	int	blocks;
23839 	ssize_t	total, missing, size;
23840 
23841 	ASSERT(mp != NULL);
23842 	ASSERT(hdr_len > 0);
23843 
23844 	size = MBLKL(mp) - hdr_len;
23845 	if (size <= 0)
23846 		return (B_FALSE);
23847 
23848 	/* The first mblk contains the header and some payload. */
23849 	blocks = 1;
23850 	total = size;
23851 	size %= len;
23852 	missing = (size == 0) ? 0 : (len - size);
23853 	mp = mp->b_cont;
23854 
23855 	while (mp != NULL) {
23856 		/*
23857 		 * Give up if we encounter a zero length message block.
23858 		 * In practice, this should rarely happen and therefore
23859 		 * not worth the trouble of freeing and re-linking the
23860 		 * mblk from the chain to handle such case.
23861 		 */
23862 		if ((size = MBLKL(mp)) == 0)
23863 			return (B_FALSE);
23864 
23865 		/* Too many payload buffers for a single Multidata message? */
23866 		if (++blocks > MULTIDATA_MAX_PBUFS)
23867 			return (B_FALSE);
23868 
23869 		total += size;
23870 		/* Is a frag distributed over two or more message blocks? */
23871 		if (missing > size)
23872 			return (B_FALSE);
23873 		size -= missing;
23874 
23875 		size %= len;
23876 		missing = (size == 0) ? 0 : (len - size);
23877 
23878 		mp = mp->b_cont;
23879 	}
23880 
23881 	return (total > ip_wput_frag_mdt_min);
23882 }
23883 
23884 /*
23885  * Outbound IPv4 fragmentation routine using MDT.
23886  */
23887 static void
23888 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23889     uint32_t frag_flag, int offset)
23890 {
23891 	ipha_t		*ipha_orig;
23892 	int		i1, ip_data_end;
23893 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23894 	mblk_t		*hdr_mp, *md_mp = NULL;
23895 	unsigned char	*hdr_ptr, *pld_ptr;
23896 	multidata_t	*mmd;
23897 	ip_pdescinfo_t	pdi;
23898 	ill_t		*ill;
23899 	ip_stack_t	*ipst = ire->ire_ipst;
23900 
23901 	ASSERT(DB_TYPE(mp) == M_DATA);
23902 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23903 
23904 	ill = ire_to_ill(ire);
23905 	ASSERT(ill != NULL);
23906 
23907 	ipha_orig = (ipha_t *)mp->b_rptr;
23908 	mp->b_rptr += sizeof (ipha_t);
23909 
23910 	/* Calculate how many packets we will send out */
23911 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23912 	pkts = (i1 + len - 1) / len;
23913 	ASSERT(pkts > 1);
23914 
23915 	/* Allocate a message block which will hold all the IP Headers. */
23916 	wroff = ipst->ips_ip_wroff_extra;
23917 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23918 
23919 	i1 = pkts * hdr_chunk_len;
23920 	/*
23921 	 * Create the header buffer, Multidata and destination address
23922 	 * and SAP attribute that should be associated with it.
23923 	 */
23924 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23925 	    ((hdr_mp->b_wptr += i1),
23926 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23927 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23928 		freemsg(mp);
23929 		if (md_mp == NULL) {
23930 			freemsg(hdr_mp);
23931 		} else {
23932 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23933 			freemsg(md_mp);
23934 		}
23935 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23936 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23937 		return;
23938 	}
23939 	IP_STAT(ipst, ip_frag_mdt_allocd);
23940 
23941 	/*
23942 	 * Add a payload buffer to the Multidata; this operation must not
23943 	 * fail, or otherwise our logic in this routine is broken.  There
23944 	 * is no memory allocation done by the routine, so any returned
23945 	 * failure simply tells us that we've done something wrong.
23946 	 *
23947 	 * A failure tells us that either we're adding the same payload
23948 	 * buffer more than once, or we're trying to add more buffers than
23949 	 * allowed.  None of the above cases should happen, and we panic
23950 	 * because either there's horrible heap corruption, and/or
23951 	 * programming mistake.
23952 	 */
23953 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23954 		goto pbuf_panic;
23955 
23956 	hdr_ptr = hdr_mp->b_rptr;
23957 	pld_ptr = mp->b_rptr;
23958 
23959 	/* Establish the ending byte offset, based on the starting offset. */
23960 	offset <<= 3;
23961 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23962 	    IP_SIMPLE_HDR_LENGTH;
23963 
23964 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23965 
23966 	while (pld_ptr < mp->b_wptr) {
23967 		ipha_t		*ipha;
23968 		uint16_t	offset_and_flags;
23969 		uint16_t	ip_len;
23970 		int		error;
23971 
23972 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23973 		ipha = (ipha_t *)(hdr_ptr + wroff);
23974 		ASSERT(OK_32PTR(ipha));
23975 		*ipha = *ipha_orig;
23976 
23977 		if (ip_data_end - offset > len) {
23978 			offset_and_flags = IPH_MF;
23979 		} else {
23980 			/*
23981 			 * Last frag. Set len to the length of this last piece.
23982 			 */
23983 			len = ip_data_end - offset;
23984 			/* A frag of a frag might have IPH_MF non-zero */
23985 			offset_and_flags =
23986 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23987 			    IPH_MF;
23988 		}
23989 		offset_and_flags |= (uint16_t)(offset >> 3);
23990 		offset_and_flags |= (uint16_t)frag_flag;
23991 		/* Store the offset and flags in the IP header. */
23992 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23993 
23994 		/* Store the length in the IP header. */
23995 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23996 		ipha->ipha_length = htons(ip_len);
23997 
23998 		/*
23999 		 * Set the IP header checksum.  Note that mp is just
24000 		 * the header, so this is easy to pass to ip_csum.
24001 		 */
24002 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24003 
24004 		DTRACE_IP7(send, mblk_t *, md_mp, conn_t *, NULL, void_ip_t *,
24005 		    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *,
24006 		    NULL, int, 0);
24007 
24008 		/*
24009 		 * Record offset and size of header and data of the next packet
24010 		 * in the multidata message.
24011 		 */
24012 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24013 		PDESC_PLD_INIT(&pdi);
24014 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24015 		ASSERT(i1 > 0);
24016 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24017 		if (i1 == len) {
24018 			pld_ptr += len;
24019 		} else {
24020 			i1 = len - i1;
24021 			mp = mp->b_cont;
24022 			ASSERT(mp != NULL);
24023 			ASSERT(MBLKL(mp) >= i1);
24024 			/*
24025 			 * Attach the next payload message block to the
24026 			 * multidata message.
24027 			 */
24028 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24029 				goto pbuf_panic;
24030 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24031 			pld_ptr = mp->b_rptr + i1;
24032 		}
24033 
24034 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24035 		    KM_NOSLEEP)) == NULL) {
24036 			/*
24037 			 * Any failure other than ENOMEM indicates that we
24038 			 * have passed in invalid pdesc info or parameters
24039 			 * to mmd_addpdesc, which must not happen.
24040 			 *
24041 			 * EINVAL is a result of failure on boundary checks
24042 			 * against the pdesc info contents.  It should not
24043 			 * happen, and we panic because either there's
24044 			 * horrible heap corruption, and/or programming
24045 			 * mistake.
24046 			 */
24047 			if (error != ENOMEM) {
24048 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24049 				    "pdesc logic error detected for "
24050 				    "mmd %p pinfo %p (%d)\n",
24051 				    (void *)mmd, (void *)&pdi, error);
24052 				/* NOTREACHED */
24053 			}
24054 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24055 			/* Free unattached payload message blocks as well */
24056 			md_mp->b_cont = mp->b_cont;
24057 			goto free_mmd;
24058 		}
24059 
24060 		/* Advance fragment offset. */
24061 		offset += len;
24062 
24063 		/* Advance to location for next header in the buffer. */
24064 		hdr_ptr += hdr_chunk_len;
24065 
24066 		/* Did we reach the next payload message block? */
24067 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24068 			mp = mp->b_cont;
24069 			/*
24070 			 * Attach the next message block with payload
24071 			 * data to the multidata message.
24072 			 */
24073 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24074 				goto pbuf_panic;
24075 			pld_ptr = mp->b_rptr;
24076 		}
24077 	}
24078 
24079 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24080 	ASSERT(mp->b_wptr == pld_ptr);
24081 
24082 	/* Update IP statistics */
24083 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24084 
24085 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24086 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24087 
24088 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24089 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24090 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24091 
24092 	if (pkt_type == OB_PKT) {
24093 		ire->ire_ob_pkt_count += pkts;
24094 		if (ire->ire_ipif != NULL)
24095 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24096 	} else {
24097 		/* The type is IB_PKT in the forwarding path. */
24098 		ire->ire_ib_pkt_count += pkts;
24099 		ASSERT(!IRE_IS_LOCAL(ire));
24100 		if (ire->ire_type & IRE_BROADCAST) {
24101 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24102 		} else {
24103 			UPDATE_MIB(ill->ill_ip_mib,
24104 			    ipIfStatsHCOutForwDatagrams, pkts);
24105 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24106 		}
24107 	}
24108 	ire->ire_last_used_time = lbolt;
24109 	/* Send it down */
24110 	putnext(ire->ire_stq, md_mp);
24111 	return;
24112 
24113 pbuf_panic:
24114 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24115 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24116 	    pbuf_idx);
24117 	/* NOTREACHED */
24118 }
24119 
24120 /*
24121  * Outbound IP fragmentation routine.
24122  *
24123  * NOTE : This routine does not ire_refrele the ire that is passed in
24124  * as the argument.
24125  */
24126 static void
24127 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24128     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24129 {
24130 	int		i1;
24131 	mblk_t		*ll_hdr_mp;
24132 	int 		ll_hdr_len;
24133 	int		hdr_len;
24134 	mblk_t		*hdr_mp;
24135 	ipha_t		*ipha;
24136 	int		ip_data_end;
24137 	int		len;
24138 	mblk_t		*mp = mp_orig, *mp1;
24139 	int		offset;
24140 	queue_t		*q;
24141 	uint32_t	v_hlen_tos_len;
24142 	mblk_t		*first_mp;
24143 	boolean_t	mctl_present;
24144 	ill_t		*ill;
24145 	ill_t		*out_ill;
24146 	mblk_t		*xmit_mp;
24147 	mblk_t		*carve_mp;
24148 	ire_t		*ire1 = NULL;
24149 	ire_t		*save_ire = NULL;
24150 	mblk_t  	*next_mp = NULL;
24151 	boolean_t	last_frag = B_FALSE;
24152 	boolean_t	multirt_send = B_FALSE;
24153 	ire_t		*first_ire = NULL;
24154 	irb_t		*irb = NULL;
24155 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24156 
24157 	ill = ire_to_ill(ire);
24158 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24159 
24160 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24161 
24162 	if (max_frag == 0) {
24163 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24164 		    " -  dropping packet\n"));
24165 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24166 		freemsg(mp);
24167 		return;
24168 	}
24169 
24170 	/*
24171 	 * IPsec does not allow hw accelerated packets to be fragmented
24172 	 * This check is made in ip_wput_ipsec_out prior to coming here
24173 	 * via ip_wput_ire_fragmentit.
24174 	 *
24175 	 * If at this point we have an ire whose ARP request has not
24176 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24177 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24178 	 * This packet and all fragmentable packets for this ire will
24179 	 * continue to get dropped while ire_nce->nce_state remains in
24180 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24181 	 * ND_REACHABLE, all subsquent large packets for this ire will
24182 	 * get fragemented and sent out by this function.
24183 	 */
24184 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24185 		/* If nce_state is ND_INITIAL, trigger ARP query */
24186 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24187 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24188 		    " -  dropping packet\n"));
24189 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24190 		freemsg(mp);
24191 		return;
24192 	}
24193 
24194 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24195 	    "ip_wput_frag_start:");
24196 
24197 	if (mp->b_datap->db_type == M_CTL) {
24198 		first_mp = mp;
24199 		mp_orig = mp = mp->b_cont;
24200 		mctl_present = B_TRUE;
24201 	} else {
24202 		first_mp = mp;
24203 		mctl_present = B_FALSE;
24204 	}
24205 
24206 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24207 	ipha = (ipha_t *)mp->b_rptr;
24208 
24209 	/*
24210 	 * If the Don't Fragment flag is on, generate an ICMP destination
24211 	 * unreachable, fragmentation needed.
24212 	 */
24213 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24214 	if (offset & IPH_DF) {
24215 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24216 		if (is_system_labeled()) {
24217 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24218 			    ire->ire_max_frag - max_frag, AF_INET);
24219 		}
24220 		/*
24221 		 * Need to compute hdr checksum if called from ip_wput_ire.
24222 		 * Note that ip_rput_forward verifies the checksum before
24223 		 * calling this routine so in that case this is a noop.
24224 		 */
24225 		ipha->ipha_hdr_checksum = 0;
24226 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24227 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24228 		    ipst);
24229 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24230 		    "ip_wput_frag_end:(%S)",
24231 		    "don't fragment");
24232 		return;
24233 	}
24234 	/*
24235 	 * Labeled systems adjust max_frag if they add a label
24236 	 * to send the correct path mtu.  We need the real mtu since we
24237 	 * are fragmenting the packet after label adjustment.
24238 	 */
24239 	if (is_system_labeled())
24240 		max_frag = ire->ire_max_frag;
24241 	if (mctl_present)
24242 		freeb(first_mp);
24243 	/*
24244 	 * Establish the starting offset.  May not be zero if we are fragging
24245 	 * a fragment that is being forwarded.
24246 	 */
24247 	offset = offset & IPH_OFFSET;
24248 
24249 	/* TODO why is this test needed? */
24250 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24251 	if (((max_frag - LENGTH) & ~7) < 8) {
24252 		/* TODO: notify ulp somehow */
24253 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24254 		freemsg(mp);
24255 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24256 		    "ip_wput_frag_end:(%S)",
24257 		    "len < 8");
24258 		return;
24259 	}
24260 
24261 	hdr_len = (V_HLEN & 0xF) << 2;
24262 
24263 	ipha->ipha_hdr_checksum = 0;
24264 
24265 	/*
24266 	 * Establish the number of bytes maximum per frag, after putting
24267 	 * in the header.
24268 	 */
24269 	len = (max_frag - hdr_len) & ~7;
24270 
24271 	/* Check if we can use MDT to send out the frags. */
24272 	ASSERT(!IRE_IS_LOCAL(ire));
24273 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24274 	    ipst->ips_ip_multidata_outbound &&
24275 	    !(ire->ire_flags & RTF_MULTIRT) &&
24276 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24277 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24278 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24279 		ASSERT(ill->ill_mdt_capab != NULL);
24280 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24281 			/*
24282 			 * If MDT has been previously turned off in the past,
24283 			 * and we currently can do MDT (due to IPQoS policy
24284 			 * removal, etc.) then enable it for this interface.
24285 			 */
24286 			ill->ill_mdt_capab->ill_mdt_on = 1;
24287 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24288 			    ill->ill_name));
24289 		}
24290 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24291 		    offset);
24292 		return;
24293 	}
24294 
24295 	/* Get a copy of the header for the trailing frags */
24296 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24297 	if (!hdr_mp) {
24298 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24299 		freemsg(mp);
24300 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24301 		    "ip_wput_frag_end:(%S)",
24302 		    "couldn't copy hdr");
24303 		return;
24304 	}
24305 	if (DB_CRED(mp) != NULL)
24306 		mblk_setcred(hdr_mp, DB_CRED(mp));
24307 
24308 	/* Store the starting offset, with the MoreFrags flag. */
24309 	i1 = offset | IPH_MF | frag_flag;
24310 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24311 
24312 	/* Establish the ending byte offset, based on the starting offset. */
24313 	offset <<= 3;
24314 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24315 
24316 	/* Store the length of the first fragment in the IP header. */
24317 	i1 = len + hdr_len;
24318 	ASSERT(i1 <= IP_MAXPACKET);
24319 	ipha->ipha_length = htons((uint16_t)i1);
24320 
24321 	/*
24322 	 * Compute the IP header checksum for the first frag.  We have to
24323 	 * watch out that we stop at the end of the header.
24324 	 */
24325 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24326 
24327 	/*
24328 	 * Now carve off the first frag.  Note that this will include the
24329 	 * original IP header.
24330 	 */
24331 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24332 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24333 		freeb(hdr_mp);
24334 		freemsg(mp_orig);
24335 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24336 		    "ip_wput_frag_end:(%S)",
24337 		    "couldn't carve first");
24338 		return;
24339 	}
24340 
24341 	/*
24342 	 * Multirouting case. Each fragment is replicated
24343 	 * via all non-condemned RTF_MULTIRT routes
24344 	 * currently resolved.
24345 	 * We ensure that first_ire is the first RTF_MULTIRT
24346 	 * ire in the bucket.
24347 	 */
24348 	if (ire->ire_flags & RTF_MULTIRT) {
24349 		irb = ire->ire_bucket;
24350 		ASSERT(irb != NULL);
24351 
24352 		multirt_send = B_TRUE;
24353 
24354 		/* Make sure we do not omit any multiroute ire. */
24355 		IRB_REFHOLD(irb);
24356 		for (first_ire = irb->irb_ire;
24357 		    first_ire != NULL;
24358 		    first_ire = first_ire->ire_next) {
24359 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24360 			    (first_ire->ire_addr == ire->ire_addr) &&
24361 			    !(first_ire->ire_marks &
24362 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24363 				break;
24364 			}
24365 		}
24366 
24367 		if (first_ire != NULL) {
24368 			if (first_ire != ire) {
24369 				IRE_REFHOLD(first_ire);
24370 				/*
24371 				 * Do not release the ire passed in
24372 				 * as the argument.
24373 				 */
24374 				ire = first_ire;
24375 			} else {
24376 				first_ire = NULL;
24377 			}
24378 		}
24379 		IRB_REFRELE(irb);
24380 
24381 		/*
24382 		 * Save the first ire; we will need to restore it
24383 		 * for the trailing frags.
24384 		 * We REFHOLD save_ire, as each iterated ire will be
24385 		 * REFRELEd.
24386 		 */
24387 		save_ire = ire;
24388 		IRE_REFHOLD(save_ire);
24389 	}
24390 
24391 	/*
24392 	 * First fragment emission loop.
24393 	 * In most cases, the emission loop below is entered only
24394 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24395 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24396 	 * bucket, and send the fragment through all crossed
24397 	 * RTF_MULTIRT routes.
24398 	 */
24399 	do {
24400 		if (ire->ire_flags & RTF_MULTIRT) {
24401 			/*
24402 			 * We are in a multiple send case, need to get
24403 			 * the next ire and make a copy of the packet.
24404 			 * ire1 holds here the next ire to process in the
24405 			 * bucket. If multirouting is expected,
24406 			 * any non-RTF_MULTIRT ire that has the
24407 			 * right destination address is ignored.
24408 			 *
24409 			 * We have to take into account the MTU of
24410 			 * each walked ire. max_frag is set by the
24411 			 * the caller and generally refers to
24412 			 * the primary ire entry. Here we ensure that
24413 			 * no route with a lower MTU will be used, as
24414 			 * fragments are carved once for all ires,
24415 			 * then replicated.
24416 			 */
24417 			ASSERT(irb != NULL);
24418 			IRB_REFHOLD(irb);
24419 			for (ire1 = ire->ire_next;
24420 			    ire1 != NULL;
24421 			    ire1 = ire1->ire_next) {
24422 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24423 					continue;
24424 				if (ire1->ire_addr != ire->ire_addr)
24425 					continue;
24426 				if (ire1->ire_marks &
24427 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24428 					continue;
24429 				/*
24430 				 * Ensure we do not exceed the MTU
24431 				 * of the next route.
24432 				 */
24433 				if (ire1->ire_max_frag < max_frag) {
24434 					ip_multirt_bad_mtu(ire1, max_frag);
24435 					continue;
24436 				}
24437 
24438 				/* Got one. */
24439 				IRE_REFHOLD(ire1);
24440 				break;
24441 			}
24442 			IRB_REFRELE(irb);
24443 
24444 			if (ire1 != NULL) {
24445 				next_mp = copyb(mp);
24446 				if ((next_mp == NULL) ||
24447 				    ((mp->b_cont != NULL) &&
24448 				    ((next_mp->b_cont =
24449 				    dupmsg(mp->b_cont)) == NULL))) {
24450 					freemsg(next_mp);
24451 					next_mp = NULL;
24452 					ire_refrele(ire1);
24453 					ire1 = NULL;
24454 				}
24455 			}
24456 
24457 			/* Last multiroute ire; don't loop anymore. */
24458 			if (ire1 == NULL) {
24459 				multirt_send = B_FALSE;
24460 			}
24461 		}
24462 
24463 		ll_hdr_len = 0;
24464 		LOCK_IRE_FP_MP(ire);
24465 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24466 		if (ll_hdr_mp != NULL) {
24467 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24468 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24469 		} else {
24470 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24471 		}
24472 
24473 		/* If there is a transmit header, get a copy for this frag. */
24474 		/*
24475 		 * TODO: should check db_ref before calling ip_carve_mp since
24476 		 * it might give us a dup.
24477 		 */
24478 		if (!ll_hdr_mp) {
24479 			/* No xmit header. */
24480 			xmit_mp = mp;
24481 
24482 		/* We have a link-layer header that can fit in our mblk. */
24483 		} else if (mp->b_datap->db_ref == 1 &&
24484 		    ll_hdr_len != 0 &&
24485 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24486 			/* M_DATA fastpath */
24487 			mp->b_rptr -= ll_hdr_len;
24488 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24489 			xmit_mp = mp;
24490 
24491 		/* Corner case if copyb has failed */
24492 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24493 			UNLOCK_IRE_FP_MP(ire);
24494 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24495 			freeb(hdr_mp);
24496 			freemsg(mp);
24497 			freemsg(mp_orig);
24498 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24499 			    "ip_wput_frag_end:(%S)",
24500 			    "discard");
24501 
24502 			if (multirt_send) {
24503 				ASSERT(ire1);
24504 				ASSERT(next_mp);
24505 
24506 				freemsg(next_mp);
24507 				ire_refrele(ire1);
24508 			}
24509 			if (save_ire != NULL)
24510 				IRE_REFRELE(save_ire);
24511 
24512 			if (first_ire != NULL)
24513 				ire_refrele(first_ire);
24514 			return;
24515 
24516 		/*
24517 		 * Case of res_mp OR the fastpath mp can't fit
24518 		 * in the mblk
24519 		 */
24520 		} else {
24521 			xmit_mp->b_cont = mp;
24522 			if (DB_CRED(mp) != NULL)
24523 				mblk_setcred(xmit_mp, DB_CRED(mp));
24524 			/*
24525 			 * Get priority marking, if any.
24526 			 * We propagate the CoS marking from the
24527 			 * original packet that went to QoS processing
24528 			 * in ip_wput_ire to the newly carved mp.
24529 			 */
24530 			if (DB_TYPE(xmit_mp) == M_DATA)
24531 				xmit_mp->b_band = mp->b_band;
24532 		}
24533 		UNLOCK_IRE_FP_MP(ire);
24534 
24535 		q = ire->ire_stq;
24536 		out_ill = (ill_t *)q->q_ptr;
24537 
24538 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24539 
24540 		DTRACE_PROBE4(ip4__physical__out__start,
24541 		    ill_t *, NULL, ill_t *, out_ill,
24542 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24543 
24544 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24545 		    ipst->ips_ipv4firewall_physical_out,
24546 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24547 
24548 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24549 
24550 		if (xmit_mp != NULL) {
24551 			DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *, NULL,
24552 			    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
24553 			    ipha_t *, ipha, ip6_t *, NULL, int, 0);
24554 
24555 			putnext(q, xmit_mp);
24556 
24557 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24558 			UPDATE_MIB(out_ill->ill_ip_mib,
24559 			    ipIfStatsHCOutOctets, i1);
24560 
24561 			if (pkt_type != OB_PKT) {
24562 				/*
24563 				 * Update the packet count and MIB stats
24564 				 * of trailing RTF_MULTIRT ires.
24565 				 */
24566 				UPDATE_OB_PKT_COUNT(ire);
24567 				BUMP_MIB(out_ill->ill_ip_mib,
24568 				    ipIfStatsOutFragReqds);
24569 			}
24570 		}
24571 
24572 		if (multirt_send) {
24573 			/*
24574 			 * We are in a multiple send case; look for
24575 			 * the next ire and re-enter the loop.
24576 			 */
24577 			ASSERT(ire1);
24578 			ASSERT(next_mp);
24579 			/* REFRELE the current ire before looping */
24580 			ire_refrele(ire);
24581 			ire = ire1;
24582 			ire1 = NULL;
24583 			mp = next_mp;
24584 			next_mp = NULL;
24585 		}
24586 	} while (multirt_send);
24587 
24588 	ASSERT(ire1 == NULL);
24589 
24590 	/* Restore the original ire; we need it for the trailing frags */
24591 	if (save_ire != NULL) {
24592 		/* REFRELE the last iterated ire */
24593 		ire_refrele(ire);
24594 		/* save_ire has been REFHOLDed */
24595 		ire = save_ire;
24596 		save_ire = NULL;
24597 		q = ire->ire_stq;
24598 	}
24599 
24600 	if (pkt_type == OB_PKT) {
24601 		UPDATE_OB_PKT_COUNT(ire);
24602 	} else {
24603 		out_ill = (ill_t *)q->q_ptr;
24604 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24605 		UPDATE_IB_PKT_COUNT(ire);
24606 	}
24607 
24608 	/* Advance the offset to the second frag starting point. */
24609 	offset += len;
24610 	/*
24611 	 * Update hdr_len from the copied header - there might be less options
24612 	 * in the later fragments.
24613 	 */
24614 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24615 	/* Loop until done. */
24616 	for (;;) {
24617 		uint16_t	offset_and_flags;
24618 		uint16_t	ip_len;
24619 
24620 		if (ip_data_end - offset > len) {
24621 			/*
24622 			 * Carve off the appropriate amount from the original
24623 			 * datagram.
24624 			 */
24625 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24626 				mp = NULL;
24627 				break;
24628 			}
24629 			/*
24630 			 * More frags after this one.  Get another copy
24631 			 * of the header.
24632 			 */
24633 			if (carve_mp->b_datap->db_ref == 1 &&
24634 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24635 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24636 				/* Inline IP header */
24637 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24638 				    hdr_mp->b_rptr;
24639 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24640 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24641 				mp = carve_mp;
24642 			} else {
24643 				if (!(mp = copyb(hdr_mp))) {
24644 					freemsg(carve_mp);
24645 					break;
24646 				}
24647 				/* Get priority marking, if any. */
24648 				mp->b_band = carve_mp->b_band;
24649 				mp->b_cont = carve_mp;
24650 			}
24651 			ipha = (ipha_t *)mp->b_rptr;
24652 			offset_and_flags = IPH_MF;
24653 		} else {
24654 			/*
24655 			 * Last frag.  Consume the header. Set len to
24656 			 * the length of this last piece.
24657 			 */
24658 			len = ip_data_end - offset;
24659 
24660 			/*
24661 			 * Carve off the appropriate amount from the original
24662 			 * datagram.
24663 			 */
24664 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24665 				mp = NULL;
24666 				break;
24667 			}
24668 			if (carve_mp->b_datap->db_ref == 1 &&
24669 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24670 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24671 				/* Inline IP header */
24672 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24673 				    hdr_mp->b_rptr;
24674 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24675 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24676 				mp = carve_mp;
24677 				freeb(hdr_mp);
24678 				hdr_mp = mp;
24679 			} else {
24680 				mp = hdr_mp;
24681 				/* Get priority marking, if any. */
24682 				mp->b_band = carve_mp->b_band;
24683 				mp->b_cont = carve_mp;
24684 			}
24685 			ipha = (ipha_t *)mp->b_rptr;
24686 			/* A frag of a frag might have IPH_MF non-zero */
24687 			offset_and_flags =
24688 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24689 			    IPH_MF;
24690 		}
24691 		offset_and_flags |= (uint16_t)(offset >> 3);
24692 		offset_and_flags |= (uint16_t)frag_flag;
24693 		/* Store the offset and flags in the IP header. */
24694 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24695 
24696 		/* Store the length in the IP header. */
24697 		ip_len = (uint16_t)(len + hdr_len);
24698 		ipha->ipha_length = htons(ip_len);
24699 
24700 		/*
24701 		 * Set the IP header checksum.	Note that mp is just
24702 		 * the header, so this is easy to pass to ip_csum.
24703 		 */
24704 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24705 
24706 		/* Attach a transmit header, if any, and ship it. */
24707 		if (pkt_type == OB_PKT) {
24708 			UPDATE_OB_PKT_COUNT(ire);
24709 		} else {
24710 			out_ill = (ill_t *)q->q_ptr;
24711 			BUMP_MIB(out_ill->ill_ip_mib,
24712 			    ipIfStatsHCOutForwDatagrams);
24713 			UPDATE_IB_PKT_COUNT(ire);
24714 		}
24715 
24716 		if (ire->ire_flags & RTF_MULTIRT) {
24717 			irb = ire->ire_bucket;
24718 			ASSERT(irb != NULL);
24719 
24720 			multirt_send = B_TRUE;
24721 
24722 			/*
24723 			 * Save the original ire; we will need to restore it
24724 			 * for the tailing frags.
24725 			 */
24726 			save_ire = ire;
24727 			IRE_REFHOLD(save_ire);
24728 		}
24729 		/*
24730 		 * Emission loop for this fragment, similar
24731 		 * to what is done for the first fragment.
24732 		 */
24733 		do {
24734 			if (multirt_send) {
24735 				/*
24736 				 * We are in a multiple send case, need to get
24737 				 * the next ire and make a copy of the packet.
24738 				 */
24739 				ASSERT(irb != NULL);
24740 				IRB_REFHOLD(irb);
24741 				for (ire1 = ire->ire_next;
24742 				    ire1 != NULL;
24743 				    ire1 = ire1->ire_next) {
24744 					if (!(ire1->ire_flags & RTF_MULTIRT))
24745 						continue;
24746 					if (ire1->ire_addr != ire->ire_addr)
24747 						continue;
24748 					if (ire1->ire_marks &
24749 					    (IRE_MARK_CONDEMNED|
24750 					    IRE_MARK_HIDDEN)) {
24751 						continue;
24752 					}
24753 					/*
24754 					 * Ensure we do not exceed the MTU
24755 					 * of the next route.
24756 					 */
24757 					if (ire1->ire_max_frag < max_frag) {
24758 						ip_multirt_bad_mtu(ire1,
24759 						    max_frag);
24760 						continue;
24761 					}
24762 
24763 					/* Got one. */
24764 					IRE_REFHOLD(ire1);
24765 					break;
24766 				}
24767 				IRB_REFRELE(irb);
24768 
24769 				if (ire1 != NULL) {
24770 					next_mp = copyb(mp);
24771 					if ((next_mp == NULL) ||
24772 					    ((mp->b_cont != NULL) &&
24773 					    ((next_mp->b_cont =
24774 					    dupmsg(mp->b_cont)) == NULL))) {
24775 						freemsg(next_mp);
24776 						next_mp = NULL;
24777 						ire_refrele(ire1);
24778 						ire1 = NULL;
24779 					}
24780 				}
24781 
24782 				/* Last multiroute ire; don't loop anymore. */
24783 				if (ire1 == NULL) {
24784 					multirt_send = B_FALSE;
24785 				}
24786 			}
24787 
24788 			/* Update transmit header */
24789 			ll_hdr_len = 0;
24790 			LOCK_IRE_FP_MP(ire);
24791 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24792 			if (ll_hdr_mp != NULL) {
24793 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24794 				ll_hdr_len = MBLKL(ll_hdr_mp);
24795 			} else {
24796 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24797 			}
24798 
24799 			if (!ll_hdr_mp) {
24800 				xmit_mp = mp;
24801 
24802 			/*
24803 			 * We have link-layer header that can fit in
24804 			 * our mblk.
24805 			 */
24806 			} else if (mp->b_datap->db_ref == 1 &&
24807 			    ll_hdr_len != 0 &&
24808 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24809 				/* M_DATA fastpath */
24810 				mp->b_rptr -= ll_hdr_len;
24811 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24812 				    ll_hdr_len);
24813 				xmit_mp = mp;
24814 
24815 			/*
24816 			 * Case of res_mp OR the fastpath mp can't fit
24817 			 * in the mblk
24818 			 */
24819 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24820 				xmit_mp->b_cont = mp;
24821 				if (DB_CRED(mp) != NULL)
24822 					mblk_setcred(xmit_mp, DB_CRED(mp));
24823 				/* Get priority marking, if any. */
24824 				if (DB_TYPE(xmit_mp) == M_DATA)
24825 					xmit_mp->b_band = mp->b_band;
24826 
24827 			/* Corner case if copyb failed */
24828 			} else {
24829 				/*
24830 				 * Exit both the replication and
24831 				 * fragmentation loops.
24832 				 */
24833 				UNLOCK_IRE_FP_MP(ire);
24834 				goto drop_pkt;
24835 			}
24836 			UNLOCK_IRE_FP_MP(ire);
24837 
24838 			mp1 = mp;
24839 			out_ill = (ill_t *)q->q_ptr;
24840 
24841 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24842 
24843 			DTRACE_PROBE4(ip4__physical__out__start,
24844 			    ill_t *, NULL, ill_t *, out_ill,
24845 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24846 
24847 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24848 			    ipst->ips_ipv4firewall_physical_out,
24849 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24850 
24851 			DTRACE_PROBE1(ip4__physical__out__end,
24852 			    mblk_t *, xmit_mp);
24853 
24854 			if (mp != mp1 && hdr_mp == mp1)
24855 				hdr_mp = mp;
24856 			if (mp != mp1 && mp_orig == mp1)
24857 				mp_orig = mp;
24858 
24859 			if (xmit_mp != NULL) {
24860 				DTRACE_IP7(send, mblk_t *, xmit_mp, conn_t *,
24861 				    NULL, void_ip_t *, ipha,
24862 				    __dtrace_ipsr_ill_t *, out_ill, ipha_t *,
24863 				    ipha, ip6_t *, NULL, int, 0);
24864 
24865 				putnext(q, xmit_mp);
24866 
24867 				BUMP_MIB(out_ill->ill_ip_mib,
24868 				    ipIfStatsHCOutTransmits);
24869 				UPDATE_MIB(out_ill->ill_ip_mib,
24870 				    ipIfStatsHCOutOctets, ip_len);
24871 
24872 				if (pkt_type != OB_PKT) {
24873 					/*
24874 					 * Update the packet count of trailing
24875 					 * RTF_MULTIRT ires.
24876 					 */
24877 					UPDATE_OB_PKT_COUNT(ire);
24878 				}
24879 			}
24880 
24881 			/* All done if we just consumed the hdr_mp. */
24882 			if (mp == hdr_mp) {
24883 				last_frag = B_TRUE;
24884 				BUMP_MIB(out_ill->ill_ip_mib,
24885 				    ipIfStatsOutFragOKs);
24886 			}
24887 
24888 			if (multirt_send) {
24889 				/*
24890 				 * We are in a multiple send case; look for
24891 				 * the next ire and re-enter the loop.
24892 				 */
24893 				ASSERT(ire1);
24894 				ASSERT(next_mp);
24895 				/* REFRELE the current ire before looping */
24896 				ire_refrele(ire);
24897 				ire = ire1;
24898 				ire1 = NULL;
24899 				q = ire->ire_stq;
24900 				mp = next_mp;
24901 				next_mp = NULL;
24902 			}
24903 		} while (multirt_send);
24904 		/*
24905 		 * Restore the original ire; we need it for the
24906 		 * trailing frags
24907 		 */
24908 		if (save_ire != NULL) {
24909 			ASSERT(ire1 == NULL);
24910 			/* REFRELE the last iterated ire */
24911 			ire_refrele(ire);
24912 			/* save_ire has been REFHOLDed */
24913 			ire = save_ire;
24914 			q = ire->ire_stq;
24915 			save_ire = NULL;
24916 		}
24917 
24918 		if (last_frag) {
24919 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24920 			    "ip_wput_frag_end:(%S)",
24921 			    "consumed hdr_mp");
24922 
24923 			if (first_ire != NULL)
24924 				ire_refrele(first_ire);
24925 			return;
24926 		}
24927 		/* Otherwise, advance and loop. */
24928 		offset += len;
24929 	}
24930 
24931 drop_pkt:
24932 	/* Clean up following allocation failure. */
24933 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24934 	freemsg(mp);
24935 	if (mp != hdr_mp)
24936 		freeb(hdr_mp);
24937 	if (mp != mp_orig)
24938 		freemsg(mp_orig);
24939 
24940 	if (save_ire != NULL)
24941 		IRE_REFRELE(save_ire);
24942 	if (first_ire != NULL)
24943 		ire_refrele(first_ire);
24944 
24945 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24946 	    "ip_wput_frag_end:(%S)",
24947 	    "end--alloc failure");
24948 }
24949 
24950 /*
24951  * Copy the header plus those options which have the copy bit set
24952  */
24953 static mblk_t *
24954 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24955 {
24956 	mblk_t	*mp;
24957 	uchar_t	*up;
24958 
24959 	/*
24960 	 * Quick check if we need to look for options without the copy bit
24961 	 * set
24962 	 */
24963 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24964 	if (!mp)
24965 		return (mp);
24966 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24967 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24968 		bcopy(rptr, mp->b_rptr, hdr_len);
24969 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24970 		return (mp);
24971 	}
24972 	up  = mp->b_rptr;
24973 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24974 	up += IP_SIMPLE_HDR_LENGTH;
24975 	rptr += IP_SIMPLE_HDR_LENGTH;
24976 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24977 	while (hdr_len > 0) {
24978 		uint32_t optval;
24979 		uint32_t optlen;
24980 
24981 		optval = *rptr;
24982 		if (optval == IPOPT_EOL)
24983 			break;
24984 		if (optval == IPOPT_NOP)
24985 			optlen = 1;
24986 		else
24987 			optlen = rptr[1];
24988 		if (optval & IPOPT_COPY) {
24989 			bcopy(rptr, up, optlen);
24990 			up += optlen;
24991 		}
24992 		rptr += optlen;
24993 		hdr_len -= optlen;
24994 	}
24995 	/*
24996 	 * Make sure that we drop an even number of words by filling
24997 	 * with EOL to the next word boundary.
24998 	 */
24999 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
25000 	    hdr_len & 0x3; hdr_len++)
25001 		*up++ = IPOPT_EOL;
25002 	mp->b_wptr = up;
25003 	/* Update header length */
25004 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
25005 	return (mp);
25006 }
25007 
25008 /*
25009  * Delivery to local recipients including fanout to multiple recipients.
25010  * Does not do checksumming of UDP/TCP.
25011  * Note: q should be the read side queue for either the ill or conn.
25012  * Note: rq should be the read side q for the lower (ill) stream.
25013  * We don't send packets to IPPF processing, thus the last argument
25014  * to all the fanout calls are B_FALSE.
25015  */
25016 void
25017 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25018     int fanout_flags, zoneid_t zoneid)
25019 {
25020 	uint32_t	protocol;
25021 	mblk_t		*first_mp;
25022 	boolean_t	mctl_present;
25023 	int		ire_type;
25024 #define	rptr	((uchar_t *)ipha)
25025 	ip_stack_t	*ipst = ill->ill_ipst;
25026 
25027 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25028 	    "ip_wput_local_start: q %p", q);
25029 
25030 	if (ire != NULL) {
25031 		ire_type = ire->ire_type;
25032 	} else {
25033 		/*
25034 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25035 		 * packet is not multicast, we can't tell the ire type.
25036 		 */
25037 		ASSERT(CLASSD(ipha->ipha_dst));
25038 		ire_type = IRE_BROADCAST;
25039 	}
25040 
25041 	first_mp = mp;
25042 	if (first_mp->b_datap->db_type == M_CTL) {
25043 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25044 		if (!io->ipsec_out_secure) {
25045 			/*
25046 			 * This ipsec_out_t was allocated in ip_wput
25047 			 * for multicast packets to store the ill_index.
25048 			 * As this is being delivered locally, we don't
25049 			 * need this anymore.
25050 			 */
25051 			mp = first_mp->b_cont;
25052 			freeb(first_mp);
25053 			first_mp = mp;
25054 			mctl_present = B_FALSE;
25055 		} else {
25056 			/*
25057 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25058 			 * security properties for the looped-back packet.
25059 			 */
25060 			mctl_present = B_TRUE;
25061 			mp = first_mp->b_cont;
25062 			ASSERT(mp != NULL);
25063 			ipsec_out_to_in(first_mp);
25064 		}
25065 	} else {
25066 		mctl_present = B_FALSE;
25067 	}
25068 
25069 	DTRACE_PROBE4(ip4__loopback__in__start,
25070 	    ill_t *, ill, ill_t *, NULL,
25071 	    ipha_t *, ipha, mblk_t *, first_mp);
25072 
25073 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25074 	    ipst->ips_ipv4firewall_loopback_in,
25075 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25076 
25077 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25078 
25079 	if (first_mp == NULL)
25080 		return;
25081 
25082 	DTRACE_IP7(receive, mblk_t *, first_mp, conn_t *, NULL, void_ip_t *,
25083 	    ipha, __dtrace_ipsr_ill_t *, ill, ipha_t *, ipha, ip6_t *, NULL,
25084 	    int, 1);
25085 
25086 	ipst->ips_loopback_packets++;
25087 
25088 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25089 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25090 	if (!IS_SIMPLE_IPH(ipha)) {
25091 		ip_wput_local_options(ipha, ipst);
25092 	}
25093 
25094 	protocol = ipha->ipha_protocol;
25095 	switch (protocol) {
25096 	case IPPROTO_ICMP: {
25097 		ire_t		*ire_zone;
25098 		ilm_t		*ilm;
25099 		mblk_t		*mp1;
25100 		zoneid_t	last_zoneid;
25101 
25102 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25103 			ASSERT(ire_type == IRE_BROADCAST);
25104 			/*
25105 			 * In the multicast case, applications may have joined
25106 			 * the group from different zones, so we need to deliver
25107 			 * the packet to each of them. Loop through the
25108 			 * multicast memberships structures (ilm) on the receive
25109 			 * ill and send a copy of the packet up each matching
25110 			 * one. However, we don't do this for multicasts sent on
25111 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25112 			 * they must stay in the sender's zone.
25113 			 *
25114 			 * ilm_add_v6() ensures that ilms in the same zone are
25115 			 * contiguous in the ill_ilm list. We use this property
25116 			 * to avoid sending duplicates needed when two
25117 			 * applications in the same zone join the same group on
25118 			 * different logical interfaces: we ignore the ilm if
25119 			 * it's zoneid is the same as the last matching one.
25120 			 * In addition, the sending of the packet for
25121 			 * ire_zoneid is delayed until all of the other ilms
25122 			 * have been exhausted.
25123 			 */
25124 			last_zoneid = -1;
25125 			ILM_WALKER_HOLD(ill);
25126 			for (ilm = ill->ill_ilm; ilm != NULL;
25127 			    ilm = ilm->ilm_next) {
25128 				if ((ilm->ilm_flags & ILM_DELETED) ||
25129 				    ipha->ipha_dst != ilm->ilm_addr ||
25130 				    ilm->ilm_zoneid == last_zoneid ||
25131 				    ilm->ilm_zoneid == zoneid ||
25132 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25133 					continue;
25134 				mp1 = ip_copymsg(first_mp);
25135 				if (mp1 == NULL)
25136 					continue;
25137 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25138 				    mctl_present, B_FALSE, ill,
25139 				    ilm->ilm_zoneid);
25140 				last_zoneid = ilm->ilm_zoneid;
25141 			}
25142 			ILM_WALKER_RELE(ill);
25143 			/*
25144 			 * Loopback case: the sending endpoint has
25145 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25146 			 * dispatch the multicast packet to the sending zone.
25147 			 */
25148 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25149 				freemsg(first_mp);
25150 				return;
25151 			}
25152 		} else if (ire_type == IRE_BROADCAST) {
25153 			/*
25154 			 * In the broadcast case, there may be many zones
25155 			 * which need a copy of the packet delivered to them.
25156 			 * There is one IRE_BROADCAST per broadcast address
25157 			 * and per zone; we walk those using a helper function.
25158 			 * In addition, the sending of the packet for zoneid is
25159 			 * delayed until all of the other ires have been
25160 			 * processed.
25161 			 */
25162 			IRB_REFHOLD(ire->ire_bucket);
25163 			ire_zone = NULL;
25164 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25165 			    ire)) != NULL) {
25166 				mp1 = ip_copymsg(first_mp);
25167 				if (mp1 == NULL)
25168 					continue;
25169 
25170 				UPDATE_IB_PKT_COUNT(ire_zone);
25171 				ire_zone->ire_last_used_time = lbolt;
25172 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25173 				    mctl_present, B_FALSE, ill,
25174 				    ire_zone->ire_zoneid);
25175 			}
25176 			IRB_REFRELE(ire->ire_bucket);
25177 		}
25178 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25179 		    0, mctl_present, B_FALSE, ill, zoneid);
25180 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25181 		    "ip_wput_local_end: q %p (%S)",
25182 		    q, "icmp");
25183 		return;
25184 	}
25185 	case IPPROTO_IGMP:
25186 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25187 			/* Bad packet - discarded by igmp_input */
25188 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25189 			    "ip_wput_local_end: q %p (%S)",
25190 			    q, "igmp_input--bad packet");
25191 			if (mctl_present)
25192 				freeb(first_mp);
25193 			return;
25194 		}
25195 		/*
25196 		 * igmp_input() may have returned the pulled up message.
25197 		 * So first_mp and ipha need to be reinitialized.
25198 		 */
25199 		ipha = (ipha_t *)mp->b_rptr;
25200 		if (mctl_present)
25201 			first_mp->b_cont = mp;
25202 		else
25203 			first_mp = mp;
25204 		/* deliver to local raw users */
25205 		break;
25206 	case IPPROTO_ENCAP:
25207 		/*
25208 		 * This case is covered by either ip_fanout_proto, or by
25209 		 * the above security processing for self-tunneled packets.
25210 		 */
25211 		break;
25212 	case IPPROTO_UDP: {
25213 		uint16_t	*up;
25214 		uint32_t	ports;
25215 
25216 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25217 		    UDP_PORTS_OFFSET);
25218 		/* Force a 'valid' checksum. */
25219 		up[3] = 0;
25220 
25221 		ports = *(uint32_t *)up;
25222 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25223 		    (ire_type == IRE_BROADCAST),
25224 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25225 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25226 		    ill, zoneid);
25227 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25228 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25229 		return;
25230 	}
25231 	case IPPROTO_TCP: {
25232 
25233 		/*
25234 		 * For TCP, discard broadcast packets.
25235 		 */
25236 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25237 			freemsg(first_mp);
25238 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25239 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25240 			return;
25241 		}
25242 
25243 		if (mp->b_datap->db_type == M_DATA) {
25244 			/*
25245 			 * M_DATA mblk, so init mblk (chain) for no struio().
25246 			 */
25247 			mblk_t	*mp1 = mp;
25248 
25249 			do {
25250 				mp1->b_datap->db_struioflag = 0;
25251 			} while ((mp1 = mp1->b_cont) != NULL);
25252 		}
25253 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25254 		    <= mp->b_wptr);
25255 		ip_fanout_tcp(q, first_mp, ill, ipha,
25256 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25257 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25258 		    mctl_present, B_FALSE, zoneid);
25259 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25260 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25261 		return;
25262 	}
25263 	case IPPROTO_SCTP:
25264 	{
25265 		uint32_t	ports;
25266 
25267 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25268 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25269 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25270 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25271 		return;
25272 	}
25273 
25274 	default:
25275 		break;
25276 	}
25277 	/*
25278 	 * Find a client for some other protocol.  We give
25279 	 * copies to multiple clients, if more than one is
25280 	 * bound.
25281 	 */
25282 	ip_fanout_proto(q, first_mp, ill, ipha,
25283 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25284 	    mctl_present, B_FALSE, ill, zoneid);
25285 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25286 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25287 #undef	rptr
25288 }
25289 
25290 /*
25291  * Update any source route, record route, or timestamp options.
25292  * Check that we are at end of strict source route.
25293  * The options have been sanity checked by ip_wput_options().
25294  */
25295 static void
25296 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25297 {
25298 	ipoptp_t	opts;
25299 	uchar_t		*opt;
25300 	uint8_t		optval;
25301 	uint8_t		optlen;
25302 	ipaddr_t	dst;
25303 	uint32_t	ts;
25304 	ire_t		*ire;
25305 	timestruc_t	now;
25306 
25307 	ip2dbg(("ip_wput_local_options\n"));
25308 	for (optval = ipoptp_first(&opts, ipha);
25309 	    optval != IPOPT_EOL;
25310 	    optval = ipoptp_next(&opts)) {
25311 		opt = opts.ipoptp_cur;
25312 		optlen = opts.ipoptp_len;
25313 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25314 		switch (optval) {
25315 			uint32_t off;
25316 		case IPOPT_SSRR:
25317 		case IPOPT_LSRR:
25318 			off = opt[IPOPT_OFFSET];
25319 			off--;
25320 			if (optlen < IP_ADDR_LEN ||
25321 			    off > optlen - IP_ADDR_LEN) {
25322 				/* End of source route */
25323 				break;
25324 			}
25325 			/*
25326 			 * This will only happen if two consecutive entries
25327 			 * in the source route contains our address or if
25328 			 * it is a packet with a loose source route which
25329 			 * reaches us before consuming the whole source route
25330 			 */
25331 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25332 			if (optval == IPOPT_SSRR) {
25333 				return;
25334 			}
25335 			/*
25336 			 * Hack: instead of dropping the packet truncate the
25337 			 * source route to what has been used by filling the
25338 			 * rest with IPOPT_NOP.
25339 			 */
25340 			opt[IPOPT_OLEN] = (uint8_t)off;
25341 			while (off < optlen) {
25342 				opt[off++] = IPOPT_NOP;
25343 			}
25344 			break;
25345 		case IPOPT_RR:
25346 			off = opt[IPOPT_OFFSET];
25347 			off--;
25348 			if (optlen < IP_ADDR_LEN ||
25349 			    off > optlen - IP_ADDR_LEN) {
25350 				/* No more room - ignore */
25351 				ip1dbg((
25352 				    "ip_wput_forward_options: end of RR\n"));
25353 				break;
25354 			}
25355 			dst = htonl(INADDR_LOOPBACK);
25356 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25357 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25358 			break;
25359 		case IPOPT_TS:
25360 			/* Insert timestamp if there is romm */
25361 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25362 			case IPOPT_TS_TSONLY:
25363 				off = IPOPT_TS_TIMELEN;
25364 				break;
25365 			case IPOPT_TS_PRESPEC:
25366 			case IPOPT_TS_PRESPEC_RFC791:
25367 				/* Verify that the address matched */
25368 				off = opt[IPOPT_OFFSET] - 1;
25369 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25370 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25371 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25372 				    ipst);
25373 				if (ire == NULL) {
25374 					/* Not for us */
25375 					break;
25376 				}
25377 				ire_refrele(ire);
25378 				/* FALLTHRU */
25379 			case IPOPT_TS_TSANDADDR:
25380 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25381 				break;
25382 			default:
25383 				/*
25384 				 * ip_*put_options should have already
25385 				 * dropped this packet.
25386 				 */
25387 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25388 				    "unknown IT - bug in ip_wput_options?\n");
25389 				return;	/* Keep "lint" happy */
25390 			}
25391 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25392 				/* Increase overflow counter */
25393 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25394 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25395 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25396 				    (off << 4);
25397 				break;
25398 			}
25399 			off = opt[IPOPT_OFFSET] - 1;
25400 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25401 			case IPOPT_TS_PRESPEC:
25402 			case IPOPT_TS_PRESPEC_RFC791:
25403 			case IPOPT_TS_TSANDADDR:
25404 				dst = htonl(INADDR_LOOPBACK);
25405 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25406 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25407 				/* FALLTHRU */
25408 			case IPOPT_TS_TSONLY:
25409 				off = opt[IPOPT_OFFSET] - 1;
25410 				/* Compute # of milliseconds since midnight */
25411 				gethrestime(&now);
25412 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25413 				    now.tv_nsec / (NANOSEC / MILLISEC);
25414 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25415 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25416 				break;
25417 			}
25418 			break;
25419 		}
25420 	}
25421 }
25422 
25423 /*
25424  * Send out a multicast packet on interface ipif.
25425  * The sender does not have an conn.
25426  * Caller verifies that this isn't a PHYI_LOOPBACK.
25427  */
25428 void
25429 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25430 {
25431 	ipha_t	*ipha;
25432 	ire_t	*ire;
25433 	ipaddr_t	dst;
25434 	mblk_t		*first_mp;
25435 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25436 
25437 	/* igmp_sendpkt always allocates a ipsec_out_t */
25438 	ASSERT(mp->b_datap->db_type == M_CTL);
25439 	ASSERT(!ipif->ipif_isv6);
25440 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25441 
25442 	first_mp = mp;
25443 	mp = first_mp->b_cont;
25444 	ASSERT(mp->b_datap->db_type == M_DATA);
25445 	ipha = (ipha_t *)mp->b_rptr;
25446 
25447 	/*
25448 	 * Find an IRE which matches the destination and the outgoing
25449 	 * queue (i.e. the outgoing interface.)
25450 	 */
25451 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25452 		dst = ipif->ipif_pp_dst_addr;
25453 	else
25454 		dst = ipha->ipha_dst;
25455 	/*
25456 	 * The source address has already been initialized by the
25457 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25458 	 * be sufficient rather than MATCH_IRE_IPIF.
25459 	 *
25460 	 * This function is used for sending IGMP packets. We need
25461 	 * to make sure that we send the packet out of the interface
25462 	 * (ipif->ipif_ill) where we joined the group. This is to
25463 	 * prevent from switches doing IGMP snooping to send us multicast
25464 	 * packets for a given group on the interface we have joined.
25465 	 * If we can't find an ire, igmp_sendpkt has already initialized
25466 	 * ipsec_out_attach_if so that this will not be load spread in
25467 	 * ip_newroute_ipif.
25468 	 */
25469 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25470 	    MATCH_IRE_ILL, ipst);
25471 	if (!ire) {
25472 		/*
25473 		 * Mark this packet to make it be delivered to
25474 		 * ip_wput_ire after the new ire has been
25475 		 * created.
25476 		 */
25477 		mp->b_prev = NULL;
25478 		mp->b_next = NULL;
25479 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25480 		    zoneid, &zero_info);
25481 		return;
25482 	}
25483 
25484 	/*
25485 	 * Honor the RTF_SETSRC flag; this is the only case
25486 	 * where we force this addr whatever the current src addr is,
25487 	 * because this address is set by igmp_sendpkt(), and
25488 	 * cannot be specified by any user.
25489 	 */
25490 	if (ire->ire_flags & RTF_SETSRC) {
25491 		ipha->ipha_src = ire->ire_src_addr;
25492 	}
25493 
25494 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25495 }
25496 
25497 /*
25498  * NOTE : This function does not ire_refrele the ire argument passed in.
25499  *
25500  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25501  * failure. The nce_fp_mp can vanish any time in the case of
25502  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25503  * the ire_lock to access the nce_fp_mp in this case.
25504  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25505  * prepending a fastpath message IPQoS processing must precede it, we also set
25506  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25507  * (IPQoS might have set the b_band for CoS marking).
25508  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25509  * must follow it so that IPQoS can mark the dl_priority field for CoS
25510  * marking, if needed.
25511  */
25512 static mblk_t *
25513 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc,
25514     uint32_t ill_index, ipha_t **iphap)
25515 {
25516 	uint_t	hlen;
25517 	ipha_t *ipha;
25518 	mblk_t *mp1;
25519 	boolean_t qos_done = B_FALSE;
25520 	uchar_t	*ll_hdr;
25521 	ip_stack_t	*ipst = ire->ire_ipst;
25522 
25523 #define	rptr	((uchar_t *)ipha)
25524 
25525 	ipha = (ipha_t *)mp->b_rptr;
25526 	hlen = 0;
25527 	LOCK_IRE_FP_MP(ire);
25528 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25529 		ASSERT(DB_TYPE(mp1) == M_DATA);
25530 		/* Initiate IPPF processing */
25531 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25532 			UNLOCK_IRE_FP_MP(ire);
25533 			ip_process(proc, &mp, ill_index);
25534 			if (mp == NULL)
25535 				return (NULL);
25536 
25537 			ipha = (ipha_t *)mp->b_rptr;
25538 			LOCK_IRE_FP_MP(ire);
25539 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25540 				qos_done = B_TRUE;
25541 				goto no_fp_mp;
25542 			}
25543 			ASSERT(DB_TYPE(mp1) == M_DATA);
25544 		}
25545 		hlen = MBLKL(mp1);
25546 		/*
25547 		 * Check if we have enough room to prepend fastpath
25548 		 * header
25549 		 */
25550 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25551 			ll_hdr = rptr - hlen;
25552 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25553 			/*
25554 			 * Set the b_rptr to the start of the link layer
25555 			 * header
25556 			 */
25557 			mp->b_rptr = ll_hdr;
25558 			mp1 = mp;
25559 		} else {
25560 			mp1 = copyb(mp1);
25561 			if (mp1 == NULL)
25562 				goto unlock_err;
25563 			mp1->b_band = mp->b_band;
25564 			mp1->b_cont = mp;
25565 			/*
25566 			 * certain system generated traffic may not
25567 			 * have cred/label in ip header block. This
25568 			 * is true even for a labeled system. But for
25569 			 * labeled traffic, inherit the label in the
25570 			 * new header.
25571 			 */
25572 			if (DB_CRED(mp) != NULL)
25573 				mblk_setcred(mp1, DB_CRED(mp));
25574 			/*
25575 			 * XXX disable ICK_VALID and compute checksum
25576 			 * here; can happen if nce_fp_mp changes and
25577 			 * it can't be copied now due to insufficient
25578 			 * space. (unlikely, fp mp can change, but it
25579 			 * does not increase in length)
25580 			 */
25581 		}
25582 		UNLOCK_IRE_FP_MP(ire);
25583 	} else {
25584 no_fp_mp:
25585 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25586 		if (mp1 == NULL) {
25587 unlock_err:
25588 			UNLOCK_IRE_FP_MP(ire);
25589 			freemsg(mp);
25590 			return (NULL);
25591 		}
25592 		UNLOCK_IRE_FP_MP(ire);
25593 		mp1->b_cont = mp;
25594 		/*
25595 		 * certain system generated traffic may not
25596 		 * have cred/label in ip header block. This
25597 		 * is true even for a labeled system. But for
25598 		 * labeled traffic, inherit the label in the
25599 		 * new header.
25600 		 */
25601 		if (DB_CRED(mp) != NULL)
25602 			mblk_setcred(mp1, DB_CRED(mp));
25603 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25604 			ip_process(proc, &mp1, ill_index);
25605 			if (mp1 == NULL)
25606 				return (NULL);
25607 
25608 			if (mp1->b_cont == NULL)
25609 				ipha = NULL;
25610 			else
25611 				ipha = (ipha_t *)mp1->b_cont->b_rptr;
25612 		}
25613 	}
25614 
25615 	*iphap = ipha;
25616 	return (mp1);
25617 #undef rptr
25618 }
25619 
25620 /*
25621  * Finish the outbound IPsec processing for an IPv6 packet. This function
25622  * is called from ipsec_out_process() if the IPsec packet was processed
25623  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25624  * asynchronously.
25625  */
25626 void
25627 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25628     ire_t *ire_arg)
25629 {
25630 	in6_addr_t *v6dstp;
25631 	ire_t *ire;
25632 	mblk_t *mp;
25633 	ip6_t *ip6h1;
25634 	uint_t	ill_index;
25635 	ipsec_out_t *io;
25636 	boolean_t attach_if, hwaccel;
25637 	uint32_t flags = IP6_NO_IPPOLICY;
25638 	int match_flags;
25639 	zoneid_t zoneid;
25640 	boolean_t ill_need_rele = B_FALSE;
25641 	boolean_t ire_need_rele = B_FALSE;
25642 	ip_stack_t	*ipst;
25643 
25644 	mp = ipsec_mp->b_cont;
25645 	ip6h1 = (ip6_t *)mp->b_rptr;
25646 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25647 	ASSERT(io->ipsec_out_ns != NULL);
25648 	ipst = io->ipsec_out_ns->netstack_ip;
25649 	ill_index = io->ipsec_out_ill_index;
25650 	if (io->ipsec_out_reachable) {
25651 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25652 	}
25653 	attach_if = io->ipsec_out_attach_if;
25654 	hwaccel = io->ipsec_out_accelerated;
25655 	zoneid = io->ipsec_out_zoneid;
25656 	ASSERT(zoneid != ALL_ZONES);
25657 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25658 	/* Multicast addresses should have non-zero ill_index. */
25659 	v6dstp = &ip6h->ip6_dst;
25660 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25661 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25662 	ASSERT(!attach_if || ill_index != 0);
25663 	if (ill_index != 0) {
25664 		if (ill == NULL) {
25665 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25666 			    B_TRUE, ipst);
25667 
25668 			/* Failure case frees things for us. */
25669 			if (ill == NULL)
25670 				return;
25671 
25672 			ill_need_rele = B_TRUE;
25673 		}
25674 		/*
25675 		 * If this packet needs to go out on a particular interface
25676 		 * honor it.
25677 		 */
25678 		if (attach_if) {
25679 			match_flags = MATCH_IRE_ILL;
25680 
25681 			/*
25682 			 * Check if we need an ire that will not be
25683 			 * looked up by anybody else i.e. HIDDEN.
25684 			 */
25685 			if (ill_is_probeonly(ill)) {
25686 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25687 			}
25688 		}
25689 	}
25690 	ASSERT(mp != NULL);
25691 
25692 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25693 		boolean_t unspec_src;
25694 		ipif_t	*ipif;
25695 
25696 		/*
25697 		 * Use the ill_index to get the right ill.
25698 		 */
25699 		unspec_src = io->ipsec_out_unspec_src;
25700 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25701 		if (ipif == NULL) {
25702 			if (ill_need_rele)
25703 				ill_refrele(ill);
25704 			freemsg(ipsec_mp);
25705 			return;
25706 		}
25707 
25708 		if (ire_arg != NULL) {
25709 			ire = ire_arg;
25710 		} else {
25711 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25712 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25713 			ire_need_rele = B_TRUE;
25714 		}
25715 		if (ire != NULL) {
25716 			ipif_refrele(ipif);
25717 			/*
25718 			 * XXX Do the multicast forwarding now, as the IPsec
25719 			 * processing has been done.
25720 			 */
25721 			goto send;
25722 		}
25723 
25724 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25725 		mp->b_prev = NULL;
25726 		mp->b_next = NULL;
25727 
25728 		/*
25729 		 * If the IPsec packet was processed asynchronously,
25730 		 * drop it now.
25731 		 */
25732 		if (q == NULL) {
25733 			if (ill_need_rele)
25734 				ill_refrele(ill);
25735 			freemsg(ipsec_mp);
25736 			return;
25737 		}
25738 
25739 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25740 		    unspec_src, zoneid);
25741 		ipif_refrele(ipif);
25742 	} else {
25743 		if (attach_if) {
25744 			ipif_t	*ipif;
25745 
25746 			ipif = ipif_get_next_ipif(NULL, ill);
25747 			if (ipif == NULL) {
25748 				if (ill_need_rele)
25749 					ill_refrele(ill);
25750 				freemsg(ipsec_mp);
25751 				return;
25752 			}
25753 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25754 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25755 			ire_need_rele = B_TRUE;
25756 			ipif_refrele(ipif);
25757 		} else {
25758 			if (ire_arg != NULL) {
25759 				ire = ire_arg;
25760 			} else {
25761 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25762 				    ipst);
25763 				ire_need_rele = B_TRUE;
25764 			}
25765 		}
25766 		if (ire != NULL)
25767 			goto send;
25768 		/*
25769 		 * ire disappeared underneath.
25770 		 *
25771 		 * What we need to do here is the ip_newroute
25772 		 * logic to get the ire without doing the IPsec
25773 		 * processing. Follow the same old path. But this
25774 		 * time, ip_wput or ire_add_then_send will call us
25775 		 * directly as all the IPsec operations are done.
25776 		 */
25777 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25778 		mp->b_prev = NULL;
25779 		mp->b_next = NULL;
25780 
25781 		/*
25782 		 * If the IPsec packet was processed asynchronously,
25783 		 * drop it now.
25784 		 */
25785 		if (q == NULL) {
25786 			if (ill_need_rele)
25787 				ill_refrele(ill);
25788 			freemsg(ipsec_mp);
25789 			return;
25790 		}
25791 
25792 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25793 		    zoneid, ipst);
25794 	}
25795 	if (ill != NULL && ill_need_rele)
25796 		ill_refrele(ill);
25797 	return;
25798 send:
25799 	if (ill != NULL && ill_need_rele)
25800 		ill_refrele(ill);
25801 
25802 	/* Local delivery */
25803 	if (ire->ire_stq == NULL) {
25804 		ill_t	*out_ill;
25805 		ASSERT(q != NULL);
25806 
25807 		/* PFHooks: LOOPBACK_OUT */
25808 		out_ill = ire_to_ill(ire);
25809 
25810 		/*
25811 		 * DTrace this as ip:::send.  A blocked packet will fire the
25812 		 * send probe, but not the receive probe.
25813 		 */
25814 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
25815 		    void_ip_t *, ip6h, __dtrace_ipsr_ill_t *, out_ill,
25816 		    ipha_t *, NULL, ip6_t *, ip6h, int, 1);
25817 
25818 		DTRACE_PROBE4(ip6__loopback__out__start,
25819 		    ill_t *, NULL, ill_t *, out_ill,
25820 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25821 
25822 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25823 		    ipst->ips_ipv6firewall_loopback_out,
25824 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25825 
25826 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25827 
25828 		if (ipsec_mp != NULL)
25829 			ip_wput_local_v6(RD(q), out_ill,
25830 			    ip6h, ipsec_mp, ire, 0);
25831 		if (ire_need_rele)
25832 			ire_refrele(ire);
25833 		return;
25834 	}
25835 	/*
25836 	 * Everything is done. Send it out on the wire.
25837 	 * We force the insertion of a fragment header using the
25838 	 * IPH_FRAG_HDR flag in two cases:
25839 	 * - after reception of an ICMPv6 "packet too big" message
25840 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25841 	 * - for multirouted IPv6 packets, so that the receiver can
25842 	 *   discard duplicates according to their fragment identifier
25843 	 */
25844 	/* XXX fix flow control problems. */
25845 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25846 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25847 		if (hwaccel) {
25848 			/*
25849 			 * hardware acceleration does not handle these
25850 			 * "slow path" cases.
25851 			 */
25852 			/* IPsec KSTATS: should bump bean counter here. */
25853 			if (ire_need_rele)
25854 				ire_refrele(ire);
25855 			freemsg(ipsec_mp);
25856 			return;
25857 		}
25858 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25859 		    (mp->b_cont ? msgdsize(mp) :
25860 		    mp->b_wptr - (uchar_t *)ip6h)) {
25861 			/* IPsec KSTATS: should bump bean counter here. */
25862 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25863 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25864 			    msgdsize(mp)));
25865 			if (ire_need_rele)
25866 				ire_refrele(ire);
25867 			freemsg(ipsec_mp);
25868 			return;
25869 		}
25870 		ASSERT(mp->b_prev == NULL);
25871 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25872 		    ntohs(ip6h->ip6_plen) +
25873 		    IPV6_HDR_LEN, ire->ire_max_frag));
25874 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25875 		    ire->ire_max_frag);
25876 	} else {
25877 		UPDATE_OB_PKT_COUNT(ire);
25878 		ire->ire_last_used_time = lbolt;
25879 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25880 	}
25881 	if (ire_need_rele)
25882 		ire_refrele(ire);
25883 	freeb(ipsec_mp);
25884 }
25885 
25886 void
25887 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25888 {
25889 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25890 	da_ipsec_t *hada;	/* data attributes */
25891 	ill_t *ill = (ill_t *)q->q_ptr;
25892 
25893 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25894 
25895 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25896 		/* IPsec KSTATS: Bump lose counter here! */
25897 		freemsg(mp);
25898 		return;
25899 	}
25900 
25901 	/*
25902 	 * It's an IPsec packet that must be
25903 	 * accelerated by the Provider, and the
25904 	 * outbound ill is IPsec acceleration capable.
25905 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25906 	 * to the ill.
25907 	 * IPsec KSTATS: should bump packet counter here.
25908 	 */
25909 
25910 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25911 	if (hada_mp == NULL) {
25912 		/* IPsec KSTATS: should bump packet counter here. */
25913 		freemsg(mp);
25914 		return;
25915 	}
25916 
25917 	hada_mp->b_datap->db_type = M_CTL;
25918 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25919 	hada_mp->b_cont = mp;
25920 
25921 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25922 	bzero(hada, sizeof (da_ipsec_t));
25923 	hada->da_type = IPHADA_M_CTL;
25924 
25925 	putnext(q, hada_mp);
25926 }
25927 
25928 /*
25929  * Finish the outbound IPsec processing. This function is called from
25930  * ipsec_out_process() if the IPsec packet was processed
25931  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25932  * asynchronously.
25933  */
25934 void
25935 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25936     ire_t *ire_arg)
25937 {
25938 	uint32_t v_hlen_tos_len;
25939 	ipaddr_t	dst;
25940 	ipif_t	*ipif = NULL;
25941 	ire_t *ire;
25942 	ire_t *ire1 = NULL;
25943 	mblk_t *next_mp = NULL;
25944 	uint32_t max_frag;
25945 	boolean_t multirt_send = B_FALSE;
25946 	mblk_t *mp;
25947 	ipha_t *ipha1;
25948 	uint_t	ill_index;
25949 	ipsec_out_t *io;
25950 	boolean_t attach_if;
25951 	int match_flags;
25952 	irb_t *irb = NULL;
25953 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25954 	zoneid_t zoneid;
25955 	ipxmit_state_t	pktxmit_state;
25956 	ip_stack_t	*ipst;
25957 
25958 #ifdef	_BIG_ENDIAN
25959 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25960 #else
25961 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25962 #endif
25963 
25964 	mp = ipsec_mp->b_cont;
25965 	ipha1 = (ipha_t *)mp->b_rptr;
25966 	ASSERT(mp != NULL);
25967 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25968 	dst = ipha->ipha_dst;
25969 
25970 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25971 	ill_index = io->ipsec_out_ill_index;
25972 	attach_if = io->ipsec_out_attach_if;
25973 	zoneid = io->ipsec_out_zoneid;
25974 	ASSERT(zoneid != ALL_ZONES);
25975 	ipst = io->ipsec_out_ns->netstack_ip;
25976 	ASSERT(io->ipsec_out_ns != NULL);
25977 
25978 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25979 	if (ill_index != 0) {
25980 		if (ill == NULL) {
25981 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25982 			    ill_index, B_FALSE, ipst);
25983 
25984 			/* Failure case frees things for us. */
25985 			if (ill == NULL)
25986 				return;
25987 
25988 			ill_need_rele = B_TRUE;
25989 		}
25990 		/*
25991 		 * If this packet needs to go out on a particular interface
25992 		 * honor it.
25993 		 */
25994 		if (attach_if) {
25995 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25996 
25997 			/*
25998 			 * Check if we need an ire that will not be
25999 			 * looked up by anybody else i.e. HIDDEN.
26000 			 */
26001 			if (ill_is_probeonly(ill)) {
26002 				match_flags |= MATCH_IRE_MARK_HIDDEN;
26003 			}
26004 		}
26005 	}
26006 
26007 	if (CLASSD(dst)) {
26008 		boolean_t conn_dontroute;
26009 		/*
26010 		 * Use the ill_index to get the right ipif.
26011 		 */
26012 		conn_dontroute = io->ipsec_out_dontroute;
26013 		if (ill_index == 0)
26014 			ipif = ipif_lookup_group(dst, zoneid, ipst);
26015 		else
26016 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
26017 		if (ipif == NULL) {
26018 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
26019 			    " multicast\n"));
26020 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
26021 			freemsg(ipsec_mp);
26022 			goto done;
26023 		}
26024 		/*
26025 		 * ipha_src has already been intialized with the
26026 		 * value of the ipif in ip_wput. All we need now is
26027 		 * an ire to send this downstream.
26028 		 */
26029 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
26030 		    MBLK_GETLABEL(mp), match_flags, ipst);
26031 		if (ire != NULL) {
26032 			ill_t *ill1;
26033 			/*
26034 			 * Do the multicast forwarding now, as the IPsec
26035 			 * processing has been done.
26036 			 */
26037 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26038 			    (ill1 = ire_to_ill(ire))) {
26039 				if (ip_mforward(ill1, ipha, mp)) {
26040 					freemsg(ipsec_mp);
26041 					ip1dbg(("ip_wput_ipsec_out: mforward "
26042 					    "failed\n"));
26043 					ire_refrele(ire);
26044 					goto done;
26045 				}
26046 			}
26047 			goto send;
26048 		}
26049 
26050 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26051 		mp->b_prev = NULL;
26052 		mp->b_next = NULL;
26053 
26054 		/*
26055 		 * If the IPsec packet was processed asynchronously,
26056 		 * drop it now.
26057 		 */
26058 		if (q == NULL) {
26059 			freemsg(ipsec_mp);
26060 			goto done;
26061 		}
26062 
26063 		/*
26064 		 * We may be using a wrong ipif to create the ire.
26065 		 * But it is okay as the source address is assigned
26066 		 * for the packet already. Next outbound packet would
26067 		 * create the IRE with the right IPIF in ip_wput.
26068 		 *
26069 		 * Also handle RTF_MULTIRT routes.
26070 		 */
26071 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26072 		    zoneid, &zero_info);
26073 	} else {
26074 		if (attach_if) {
26075 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26076 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26077 		} else {
26078 			if (ire_arg != NULL) {
26079 				ire = ire_arg;
26080 				ire_need_rele = B_FALSE;
26081 			} else {
26082 				ire = ire_cache_lookup(dst, zoneid,
26083 				    MBLK_GETLABEL(mp), ipst);
26084 			}
26085 		}
26086 		if (ire != NULL) {
26087 			goto send;
26088 		}
26089 
26090 		/*
26091 		 * ire disappeared underneath.
26092 		 *
26093 		 * What we need to do here is the ip_newroute
26094 		 * logic to get the ire without doing the IPsec
26095 		 * processing. Follow the same old path. But this
26096 		 * time, ip_wput or ire_add_then_put will call us
26097 		 * directly as all the IPsec operations are done.
26098 		 */
26099 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26100 		mp->b_prev = NULL;
26101 		mp->b_next = NULL;
26102 
26103 		/*
26104 		 * If the IPsec packet was processed asynchronously,
26105 		 * drop it now.
26106 		 */
26107 		if (q == NULL) {
26108 			freemsg(ipsec_mp);
26109 			goto done;
26110 		}
26111 
26112 		/*
26113 		 * Since we're going through ip_newroute() again, we
26114 		 * need to make sure we don't:
26115 		 *
26116 		 *	1.) Trigger the ASSERT() with the ipha_ident
26117 		 *	    overloading.
26118 		 *	2.) Redo transport-layer checksumming, since we've
26119 		 *	    already done all that to get this far.
26120 		 *
26121 		 * The easiest way not do either of the above is to set
26122 		 * the ipha_ident field to IP_HDR_INCLUDED.
26123 		 */
26124 		ipha->ipha_ident = IP_HDR_INCLUDED;
26125 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26126 		    zoneid, ipst);
26127 	}
26128 	goto done;
26129 send:
26130 	if (ire->ire_stq == NULL) {
26131 		ill_t	*out_ill;
26132 		/*
26133 		 * Loopbacks go through ip_wput_local except for one case.
26134 		 * We come here if we generate a icmp_frag_needed message
26135 		 * after IPsec processing is over. When this function calls
26136 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26137 		 * icmp_frag_needed. The message generated comes back here
26138 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26139 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26140 		 * source address as it is usually set in ip_wput_ire. As
26141 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26142 		 * and we end up here. We can't enter ip_wput_ire once the
26143 		 * IPsec processing is over and hence we need to do it here.
26144 		 */
26145 		ASSERT(q != NULL);
26146 		UPDATE_OB_PKT_COUNT(ire);
26147 		ire->ire_last_used_time = lbolt;
26148 		if (ipha->ipha_src == 0)
26149 			ipha->ipha_src = ire->ire_src_addr;
26150 
26151 		/* PFHooks: LOOPBACK_OUT */
26152 		out_ill = ire_to_ill(ire);
26153 
26154 		/*
26155 		 * DTrace this as ip:::send.  A blocked packet will fire the
26156 		 * send probe, but not the receive probe.
26157 		 */
26158 		DTRACE_IP7(send, mblk_t *, ipsec_mp, conn_t *, NULL,
26159 		    void_ip_t *, ipha, __dtrace_ipsr_ill_t *, out_ill,
26160 		    ipha_t *, ipha, ip6_t *, NULL, int, 1);
26161 
26162 		DTRACE_PROBE4(ip4__loopback__out__start,
26163 		    ill_t *, NULL, ill_t *, out_ill,
26164 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26165 
26166 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26167 		    ipst->ips_ipv4firewall_loopback_out,
26168 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26169 
26170 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26171 
26172 		if (ipsec_mp != NULL)
26173 			ip_wput_local(RD(q), out_ill,
26174 			    ipha, ipsec_mp, ire, 0, zoneid);
26175 		if (ire_need_rele)
26176 			ire_refrele(ire);
26177 		goto done;
26178 	}
26179 
26180 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26181 		/*
26182 		 * We are through with IPsec processing.
26183 		 * Fragment this and send it on the wire.
26184 		 */
26185 		if (io->ipsec_out_accelerated) {
26186 			/*
26187 			 * The packet has been accelerated but must
26188 			 * be fragmented. This should not happen
26189 			 * since AH and ESP must not accelerate
26190 			 * packets that need fragmentation, however
26191 			 * the configuration could have changed
26192 			 * since the AH or ESP processing.
26193 			 * Drop packet.
26194 			 * IPsec KSTATS: bump bean counter here.
26195 			 */
26196 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26197 			    "fragmented accelerated packet!\n"));
26198 			freemsg(ipsec_mp);
26199 		} else {
26200 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26201 		}
26202 		if (ire_need_rele)
26203 			ire_refrele(ire);
26204 		goto done;
26205 	}
26206 
26207 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26208 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26209 	    (void *)ire->ire_ipif, (void *)ipif));
26210 
26211 	/*
26212 	 * Multiroute the secured packet, unless IPsec really
26213 	 * requires the packet to go out only through a particular
26214 	 * interface.
26215 	 */
26216 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26217 		ire_t *first_ire;
26218 		irb = ire->ire_bucket;
26219 		ASSERT(irb != NULL);
26220 		/*
26221 		 * This ire has been looked up as the one that
26222 		 * goes through the given ipif;
26223 		 * make sure we do not omit any other multiroute ire
26224 		 * that may be present in the bucket before this one.
26225 		 */
26226 		IRB_REFHOLD(irb);
26227 		for (first_ire = irb->irb_ire;
26228 		    first_ire != NULL;
26229 		    first_ire = first_ire->ire_next) {
26230 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26231 			    (first_ire->ire_addr == ire->ire_addr) &&
26232 			    !(first_ire->ire_marks &
26233 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26234 				break;
26235 			}
26236 		}
26237 
26238 		if ((first_ire != NULL) && (first_ire != ire)) {
26239 			/*
26240 			 * Don't change the ire if the packet must
26241 			 * be fragmented if sent via this new one.
26242 			 */
26243 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26244 				IRE_REFHOLD(first_ire);
26245 				if (ire_need_rele)
26246 					ire_refrele(ire);
26247 				else
26248 					ire_need_rele = B_TRUE;
26249 				ire = first_ire;
26250 			}
26251 		}
26252 		IRB_REFRELE(irb);
26253 
26254 		multirt_send = B_TRUE;
26255 		max_frag = ire->ire_max_frag;
26256 	} else {
26257 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26258 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26259 			    "flag, attach_if %d\n", attach_if));
26260 		}
26261 	}
26262 
26263 	/*
26264 	 * In most cases, the emission loop below is entered only once.
26265 	 * Only in the case where the ire holds the RTF_MULTIRT
26266 	 * flag, we loop to process all RTF_MULTIRT ires in the
26267 	 * bucket, and send the packet through all crossed
26268 	 * RTF_MULTIRT routes.
26269 	 */
26270 	do {
26271 		if (multirt_send) {
26272 			/*
26273 			 * ire1 holds here the next ire to process in the
26274 			 * bucket. If multirouting is expected,
26275 			 * any non-RTF_MULTIRT ire that has the
26276 			 * right destination address is ignored.
26277 			 */
26278 			ASSERT(irb != NULL);
26279 			IRB_REFHOLD(irb);
26280 			for (ire1 = ire->ire_next;
26281 			    ire1 != NULL;
26282 			    ire1 = ire1->ire_next) {
26283 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26284 					continue;
26285 				if (ire1->ire_addr != ire->ire_addr)
26286 					continue;
26287 				if (ire1->ire_marks &
26288 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26289 					continue;
26290 				/* No loopback here */
26291 				if (ire1->ire_stq == NULL)
26292 					continue;
26293 				/*
26294 				 * Ensure we do not exceed the MTU
26295 				 * of the next route.
26296 				 */
26297 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26298 					ip_multirt_bad_mtu(ire1, max_frag);
26299 					continue;
26300 				}
26301 
26302 				IRE_REFHOLD(ire1);
26303 				break;
26304 			}
26305 			IRB_REFRELE(irb);
26306 			if (ire1 != NULL) {
26307 				/*
26308 				 * We are in a multiple send case, need to
26309 				 * make a copy of the packet.
26310 				 */
26311 				next_mp = copymsg(ipsec_mp);
26312 				if (next_mp == NULL) {
26313 					ire_refrele(ire1);
26314 					ire1 = NULL;
26315 				}
26316 			}
26317 		}
26318 		/*
26319 		 * Everything is done. Send it out on the wire
26320 		 *
26321 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26322 		 * either send it on the wire or, in the case of
26323 		 * HW acceleration, call ipsec_hw_putnext.
26324 		 */
26325 		if (ire->ire_nce &&
26326 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26327 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26328 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26329 			/*
26330 			 * If ire's link-layer is unresolved (this
26331 			 * would only happen if the incomplete ire
26332 			 * was added to cachetable via forwarding path)
26333 			 * don't bother going to ip_xmit_v4. Just drop the
26334 			 * packet.
26335 			 * There is a slight risk here, in that, if we
26336 			 * have the forwarding path create an incomplete
26337 			 * IRE, then until the IRE is completed, any
26338 			 * transmitted IPsec packets will be dropped
26339 			 * instead of being queued waiting for resolution.
26340 			 *
26341 			 * But the likelihood of a forwarding packet and a wput
26342 			 * packet sending to the same dst at the same time
26343 			 * and there not yet be an ARP entry for it is small.
26344 			 * Furthermore, if this actually happens, it might
26345 			 * be likely that wput would generate multiple
26346 			 * packets (and forwarding would also have a train
26347 			 * of packets) for that destination. If this is
26348 			 * the case, some of them would have been dropped
26349 			 * anyway, since ARP only queues a few packets while
26350 			 * waiting for resolution
26351 			 *
26352 			 * NOTE: We should really call ip_xmit_v4,
26353 			 * and let it queue the packet and send the
26354 			 * ARP query and have ARP come back thus:
26355 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26356 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26357 			 * hw accel work. But it's too complex to get
26358 			 * the IPsec hw  acceleration approach to fit
26359 			 * well with ip_xmit_v4 doing ARP without
26360 			 * doing IPsec simplification. For now, we just
26361 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26362 			 * that we can continue with the send on the next
26363 			 * attempt.
26364 			 *
26365 			 * XXX THis should be revisited, when
26366 			 * the IPsec/IP interaction is cleaned up
26367 			 */
26368 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26369 			    " - dropping packet\n"));
26370 			freemsg(ipsec_mp);
26371 			/*
26372 			 * Call ip_xmit_v4() to trigger ARP query
26373 			 * in case the nce_state is ND_INITIAL
26374 			 */
26375 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26376 			goto drop_pkt;
26377 		}
26378 
26379 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26380 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26381 		    mblk_t *, ipsec_mp);
26382 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26383 		    ipst->ips_ipv4firewall_physical_out, NULL,
26384 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26385 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26386 		if (ipsec_mp == NULL)
26387 			goto drop_pkt;
26388 
26389 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26390 		pktxmit_state = ip_xmit_v4(mp, ire,
26391 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26392 
26393 		if ((pktxmit_state ==  SEND_FAILED) ||
26394 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26395 
26396 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26397 drop_pkt:
26398 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26399 			    ipIfStatsOutDiscards);
26400 			if (ire_need_rele)
26401 				ire_refrele(ire);
26402 			if (ire1 != NULL) {
26403 				ire_refrele(ire1);
26404 				freemsg(next_mp);
26405 			}
26406 			goto done;
26407 		}
26408 
26409 		freeb(ipsec_mp);
26410 		if (ire_need_rele)
26411 			ire_refrele(ire);
26412 
26413 		if (ire1 != NULL) {
26414 			ire = ire1;
26415 			ire_need_rele = B_TRUE;
26416 			ASSERT(next_mp);
26417 			ipsec_mp = next_mp;
26418 			mp = ipsec_mp->b_cont;
26419 			ire1 = NULL;
26420 			next_mp = NULL;
26421 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26422 		} else {
26423 			multirt_send = B_FALSE;
26424 		}
26425 	} while (multirt_send);
26426 done:
26427 	if (ill != NULL && ill_need_rele)
26428 		ill_refrele(ill);
26429 	if (ipif != NULL)
26430 		ipif_refrele(ipif);
26431 }
26432 
26433 /*
26434  * Get the ill corresponding to the specified ire, and compare its
26435  * capabilities with the protocol and algorithms specified by the
26436  * the SA obtained from ipsec_out. If they match, annotate the
26437  * ipsec_out structure to indicate that the packet needs acceleration.
26438  *
26439  *
26440  * A packet is eligible for outbound hardware acceleration if the
26441  * following conditions are satisfied:
26442  *
26443  * 1. the packet will not be fragmented
26444  * 2. the provider supports the algorithm
26445  * 3. there is no pending control message being exchanged
26446  * 4. snoop is not attached
26447  * 5. the destination address is not a broadcast or multicast address.
26448  *
26449  * Rationale:
26450  *	- Hardware drivers do not support fragmentation with
26451  *	  the current interface.
26452  *	- snoop, multicast, and broadcast may result in exposure of
26453  *	  a cleartext datagram.
26454  * We check all five of these conditions here.
26455  *
26456  * XXX would like to nuke "ire_t *" parameter here; problem is that
26457  * IRE is only way to figure out if a v4 address is a broadcast and
26458  * thus ineligible for acceleration...
26459  */
26460 static void
26461 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26462 {
26463 	ipsec_out_t *io;
26464 	mblk_t *data_mp;
26465 	uint_t plen, overhead;
26466 	ip_stack_t	*ipst;
26467 
26468 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26469 		return;
26470 
26471 	if (ill == NULL)
26472 		return;
26473 	ipst = ill->ill_ipst;
26474 	/*
26475 	 * Destination address is a broadcast or multicast.  Punt.
26476 	 */
26477 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26478 	    IRE_LOCAL)))
26479 		return;
26480 
26481 	data_mp = ipsec_mp->b_cont;
26482 
26483 	if (ill->ill_isv6) {
26484 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26485 
26486 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26487 			return;
26488 
26489 		plen = ip6h->ip6_plen;
26490 	} else {
26491 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26492 
26493 		if (CLASSD(ipha->ipha_dst))
26494 			return;
26495 
26496 		plen = ipha->ipha_length;
26497 	}
26498 	/*
26499 	 * Is there a pending DLPI control message being exchanged
26500 	 * between IP/IPsec and the DLS Provider? If there is, it
26501 	 * could be a SADB update, and the state of the DLS Provider
26502 	 * SADB might not be in sync with the SADB maintained by
26503 	 * IPsec. To avoid dropping packets or using the wrong keying
26504 	 * material, we do not accelerate this packet.
26505 	 */
26506 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26507 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26508 		    "ill_dlpi_pending! don't accelerate packet\n"));
26509 		return;
26510 	}
26511 
26512 	/*
26513 	 * Is the Provider in promiscous mode? If it does, we don't
26514 	 * accelerate the packet since it will bounce back up to the
26515 	 * listeners in the clear.
26516 	 */
26517 	if (ill->ill_promisc_on_phys) {
26518 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26519 		    "ill in promiscous mode, don't accelerate packet\n"));
26520 		return;
26521 	}
26522 
26523 	/*
26524 	 * Will the packet require fragmentation?
26525 	 */
26526 
26527 	/*
26528 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26529 	 * as is used elsewhere.
26530 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26531 	 *	+ 2-byte trailer
26532 	 */
26533 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26534 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26535 
26536 	if ((plen + overhead) > ill->ill_max_mtu)
26537 		return;
26538 
26539 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26540 
26541 	/*
26542 	 * Can the ill accelerate this IPsec protocol and algorithm
26543 	 * specified by the SA?
26544 	 */
26545 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26546 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26547 		return;
26548 	}
26549 
26550 	/*
26551 	 * Tell AH or ESP that the outbound ill is capable of
26552 	 * accelerating this packet.
26553 	 */
26554 	io->ipsec_out_is_capab_ill = B_TRUE;
26555 }
26556 
26557 /*
26558  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26559  *
26560  * If this function returns B_TRUE, the requested SA's have been filled
26561  * into the ipsec_out_*_sa pointers.
26562  *
26563  * If the function returns B_FALSE, the packet has been "consumed", most
26564  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26565  *
26566  * The SA references created by the protocol-specific "select"
26567  * function will be released when the ipsec_mp is freed, thanks to the
26568  * ipsec_out_free destructor -- see spd.c.
26569  */
26570 static boolean_t
26571 ipsec_out_select_sa(mblk_t *ipsec_mp)
26572 {
26573 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26574 	ipsec_out_t *io;
26575 	ipsec_policy_t *pp;
26576 	ipsec_action_t *ap;
26577 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26578 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26579 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26580 
26581 	if (!io->ipsec_out_secure) {
26582 		/*
26583 		 * We came here by mistake.
26584 		 * Don't bother with ipsec processing
26585 		 * We should "discourage" this path in the future.
26586 		 */
26587 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26588 		return (B_FALSE);
26589 	}
26590 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26591 	ASSERT((io->ipsec_out_policy != NULL) ||
26592 	    (io->ipsec_out_act != NULL));
26593 
26594 	ASSERT(io->ipsec_out_failed == B_FALSE);
26595 
26596 	/*
26597 	 * IPsec processing has started.
26598 	 */
26599 	io->ipsec_out_proc_begin = B_TRUE;
26600 	ap = io->ipsec_out_act;
26601 	if (ap == NULL) {
26602 		pp = io->ipsec_out_policy;
26603 		ASSERT(pp != NULL);
26604 		ap = pp->ipsp_act;
26605 		ASSERT(ap != NULL);
26606 	}
26607 
26608 	/*
26609 	 * We have an action.  now, let's select SA's.
26610 	 * (In the future, we can cache this in the conn_t..)
26611 	 */
26612 	if (ap->ipa_want_esp) {
26613 		if (io->ipsec_out_esp_sa == NULL) {
26614 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26615 			    IPPROTO_ESP);
26616 		}
26617 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26618 	}
26619 
26620 	if (ap->ipa_want_ah) {
26621 		if (io->ipsec_out_ah_sa == NULL) {
26622 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26623 			    IPPROTO_AH);
26624 		}
26625 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26626 		/*
26627 		 * The ESP and AH processing order needs to be preserved
26628 		 * when both protocols are required (ESP should be applied
26629 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26630 		 * when both ESP and AH are required, and an AH ACQUIRE
26631 		 * is needed.
26632 		 */
26633 		if (ap->ipa_want_esp && need_ah_acquire)
26634 			need_esp_acquire = B_TRUE;
26635 	}
26636 
26637 	/*
26638 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26639 	 * Release SAs that got referenced, but will not be used until we
26640 	 * acquire _all_ of the SAs we need.
26641 	 */
26642 	if (need_ah_acquire || need_esp_acquire) {
26643 		if (io->ipsec_out_ah_sa != NULL) {
26644 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26645 			io->ipsec_out_ah_sa = NULL;
26646 		}
26647 		if (io->ipsec_out_esp_sa != NULL) {
26648 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26649 			io->ipsec_out_esp_sa = NULL;
26650 		}
26651 
26652 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26653 		return (B_FALSE);
26654 	}
26655 
26656 	return (B_TRUE);
26657 }
26658 
26659 /*
26660  * Process an IPSEC_OUT message and see what you can
26661  * do with it.
26662  * IPQoS Notes:
26663  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26664  * IPsec.
26665  * XXX would like to nuke ire_t.
26666  * XXX ill_index better be "real"
26667  */
26668 void
26669 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26670 {
26671 	ipsec_out_t *io;
26672 	ipsec_policy_t *pp;
26673 	ipsec_action_t *ap;
26674 	ipha_t *ipha;
26675 	ip6_t *ip6h;
26676 	mblk_t *mp;
26677 	ill_t *ill;
26678 	zoneid_t zoneid;
26679 	ipsec_status_t ipsec_rc;
26680 	boolean_t ill_need_rele = B_FALSE;
26681 	ip_stack_t	*ipst;
26682 	ipsec_stack_t	*ipss;
26683 
26684 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26685 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26686 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26687 	ipst = io->ipsec_out_ns->netstack_ip;
26688 	mp = ipsec_mp->b_cont;
26689 
26690 	/*
26691 	 * Initiate IPPF processing. We do it here to account for packets
26692 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26693 	 * We can check for ipsec_out_proc_begin even for such packets, as
26694 	 * they will always be false (asserted below).
26695 	 */
26696 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26697 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26698 		    io->ipsec_out_ill_index : ill_index);
26699 		if (mp == NULL) {
26700 			ip2dbg(("ipsec_out_process: packet dropped "\
26701 			    "during IPPF processing\n"));
26702 			freeb(ipsec_mp);
26703 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26704 			return;
26705 		}
26706 	}
26707 
26708 	if (!io->ipsec_out_secure) {
26709 		/*
26710 		 * We came here by mistake.
26711 		 * Don't bother with ipsec processing
26712 		 * Should "discourage" this path in the future.
26713 		 */
26714 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26715 		goto done;
26716 	}
26717 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26718 	ASSERT((io->ipsec_out_policy != NULL) ||
26719 	    (io->ipsec_out_act != NULL));
26720 	ASSERT(io->ipsec_out_failed == B_FALSE);
26721 
26722 	ipss = ipst->ips_netstack->netstack_ipsec;
26723 	if (!ipsec_loaded(ipss)) {
26724 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26725 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26726 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26727 		} else {
26728 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26729 		}
26730 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26731 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26732 		    &ipss->ipsec_dropper);
26733 		return;
26734 	}
26735 
26736 	/*
26737 	 * IPsec processing has started.
26738 	 */
26739 	io->ipsec_out_proc_begin = B_TRUE;
26740 	ap = io->ipsec_out_act;
26741 	if (ap == NULL) {
26742 		pp = io->ipsec_out_policy;
26743 		ASSERT(pp != NULL);
26744 		ap = pp->ipsp_act;
26745 		ASSERT(ap != NULL);
26746 	}
26747 
26748 	/*
26749 	 * Save the outbound ill index. When the packet comes back
26750 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26751 	 * before sending it the accelerated packet.
26752 	 */
26753 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26754 		int ifindex;
26755 		ill = ire_to_ill(ire);
26756 		ifindex = ill->ill_phyint->phyint_ifindex;
26757 		io->ipsec_out_capab_ill_index = ifindex;
26758 	}
26759 
26760 	/*
26761 	 * The order of processing is first insert a IP header if needed.
26762 	 * Then insert the ESP header and then the AH header.
26763 	 */
26764 	if ((io->ipsec_out_se_done == B_FALSE) &&
26765 	    (ap->ipa_want_se)) {
26766 		/*
26767 		 * First get the outer IP header before sending
26768 		 * it to ESP.
26769 		 */
26770 		ipha_t *oipha, *iipha;
26771 		mblk_t *outer_mp, *inner_mp;
26772 
26773 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26774 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26775 			    "ipsec_out_process: "
26776 			    "Self-Encapsulation failed: Out of memory\n");
26777 			freemsg(ipsec_mp);
26778 			if (ill != NULL) {
26779 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26780 			} else {
26781 				BUMP_MIB(&ipst->ips_ip_mib,
26782 				    ipIfStatsOutDiscards);
26783 			}
26784 			return;
26785 		}
26786 		inner_mp = ipsec_mp->b_cont;
26787 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26788 		oipha = (ipha_t *)outer_mp->b_rptr;
26789 		iipha = (ipha_t *)inner_mp->b_rptr;
26790 		*oipha = *iipha;
26791 		outer_mp->b_wptr += sizeof (ipha_t);
26792 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26793 		    sizeof (ipha_t));
26794 		oipha->ipha_protocol = IPPROTO_ENCAP;
26795 		oipha->ipha_version_and_hdr_length =
26796 		    IP_SIMPLE_HDR_VERSION;
26797 		oipha->ipha_hdr_checksum = 0;
26798 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26799 		outer_mp->b_cont = inner_mp;
26800 		ipsec_mp->b_cont = outer_mp;
26801 
26802 		io->ipsec_out_se_done = B_TRUE;
26803 		io->ipsec_out_tunnel = B_TRUE;
26804 	}
26805 
26806 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26807 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26808 	    !ipsec_out_select_sa(ipsec_mp))
26809 		return;
26810 
26811 	/*
26812 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26813 	 * to do the heavy lifting.
26814 	 */
26815 	zoneid = io->ipsec_out_zoneid;
26816 	ASSERT(zoneid != ALL_ZONES);
26817 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26818 		ASSERT(io->ipsec_out_esp_sa != NULL);
26819 		io->ipsec_out_esp_done = B_TRUE;
26820 		/*
26821 		 * Note that since hw accel can only apply one transform,
26822 		 * not two, we skip hw accel for ESP if we also have AH
26823 		 * This is an design limitation of the interface
26824 		 * which should be revisited.
26825 		 */
26826 		ASSERT(ire != NULL);
26827 		if (io->ipsec_out_ah_sa == NULL) {
26828 			ill = (ill_t *)ire->ire_stq->q_ptr;
26829 			ipsec_out_is_accelerated(ipsec_mp,
26830 			    io->ipsec_out_esp_sa, ill, ire);
26831 		}
26832 
26833 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26834 		switch (ipsec_rc) {
26835 		case IPSEC_STATUS_SUCCESS:
26836 			break;
26837 		case IPSEC_STATUS_FAILED:
26838 			if (ill != NULL) {
26839 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26840 			} else {
26841 				BUMP_MIB(&ipst->ips_ip_mib,
26842 				    ipIfStatsOutDiscards);
26843 			}
26844 			/* FALLTHRU */
26845 		case IPSEC_STATUS_PENDING:
26846 			return;
26847 		}
26848 	}
26849 
26850 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26851 		ASSERT(io->ipsec_out_ah_sa != NULL);
26852 		io->ipsec_out_ah_done = B_TRUE;
26853 		if (ire == NULL) {
26854 			int idx = io->ipsec_out_capab_ill_index;
26855 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26856 			    NULL, NULL, NULL, NULL, ipst);
26857 			ill_need_rele = B_TRUE;
26858 		} else {
26859 			ill = (ill_t *)ire->ire_stq->q_ptr;
26860 		}
26861 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26862 		    ire);
26863 
26864 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26865 		switch (ipsec_rc) {
26866 		case IPSEC_STATUS_SUCCESS:
26867 			break;
26868 		case IPSEC_STATUS_FAILED:
26869 			if (ill != NULL) {
26870 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26871 			} else {
26872 				BUMP_MIB(&ipst->ips_ip_mib,
26873 				    ipIfStatsOutDiscards);
26874 			}
26875 			/* FALLTHRU */
26876 		case IPSEC_STATUS_PENDING:
26877 			if (ill != NULL && ill_need_rele)
26878 				ill_refrele(ill);
26879 			return;
26880 		}
26881 	}
26882 	/*
26883 	 * We are done with IPsec processing. Send it over
26884 	 * the wire.
26885 	 */
26886 done:
26887 	mp = ipsec_mp->b_cont;
26888 	ipha = (ipha_t *)mp->b_rptr;
26889 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26890 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26891 	} else {
26892 		ip6h = (ip6_t *)ipha;
26893 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26894 	}
26895 	if (ill != NULL && ill_need_rele)
26896 		ill_refrele(ill);
26897 }
26898 
26899 /* ARGSUSED */
26900 void
26901 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26902 {
26903 	opt_restart_t	*or;
26904 	int	err;
26905 	conn_t	*connp;
26906 
26907 	ASSERT(CONN_Q(q));
26908 	connp = Q_TO_CONN(q);
26909 
26910 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26911 	or = (opt_restart_t *)first_mp->b_rptr;
26912 	/*
26913 	 * We don't need to pass any credentials here since this is just
26914 	 * a restart. The credentials are passed in when svr4_optcom_req
26915 	 * is called the first time (from ip_wput_nondata).
26916 	 */
26917 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26918 		err = svr4_optcom_req(q, first_mp, NULL,
26919 		    &ip_opt_obj, B_FALSE);
26920 	} else {
26921 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26922 		err = tpi_optcom_req(q, first_mp, NULL,
26923 		    &ip_opt_obj, B_FALSE);
26924 	}
26925 	if (err != EINPROGRESS) {
26926 		/* operation is done */
26927 		CONN_OPER_PENDING_DONE(connp);
26928 	}
26929 }
26930 
26931 /*
26932  * ioctls that go through a down/up sequence may need to wait for the down
26933  * to complete. This involves waiting for the ire and ipif refcnts to go down
26934  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26935  */
26936 /* ARGSUSED */
26937 void
26938 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26939 {
26940 	struct iocblk *iocp;
26941 	mblk_t *mp1;
26942 	ip_ioctl_cmd_t *ipip;
26943 	int err;
26944 	sin_t	*sin;
26945 	struct lifreq *lifr;
26946 	struct ifreq *ifr;
26947 
26948 	iocp = (struct iocblk *)mp->b_rptr;
26949 	ASSERT(ipsq != NULL);
26950 	/* Existence of mp1 verified in ip_wput_nondata */
26951 	mp1 = mp->b_cont->b_cont;
26952 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26953 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26954 		/*
26955 		 * Special case where ipsq_current_ipif is not set:
26956 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26957 		 * ill could also have become part of a ipmp group in the
26958 		 * process, we are here as were not able to complete the
26959 		 * operation in ipif_set_values because we could not become
26960 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26961 		 * will not be set so we need to set it.
26962 		 */
26963 		ill_t *ill = q->q_ptr;
26964 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26965 	}
26966 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26967 
26968 	if (ipip->ipi_cmd_type == IF_CMD) {
26969 		/* This a old style SIOC[GS]IF* command */
26970 		ifr = (struct ifreq *)mp1->b_rptr;
26971 		sin = (sin_t *)&ifr->ifr_addr;
26972 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26973 		/* This a new style SIOC[GS]LIF* command */
26974 		lifr = (struct lifreq *)mp1->b_rptr;
26975 		sin = (sin_t *)&lifr->lifr_addr;
26976 	} else {
26977 		sin = NULL;
26978 	}
26979 
26980 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26981 	    ipip, mp1->b_rptr);
26982 
26983 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26984 }
26985 
26986 /*
26987  * ioctl processing
26988  *
26989  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26990  * the ioctl command in the ioctl tables, determines the copyin data size
26991  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26992  *
26993  * ioctl processing then continues when the M_IOCDATA makes its way down to
26994  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26995  * associated 'conn' is refheld till the end of the ioctl and the general
26996  * ioctl processing function ip_process_ioctl() is called to extract the
26997  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26998  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26999  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
27000  * is used to extract the ioctl's arguments.
27001  *
27002  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
27003  * so goes thru the serialization primitive ipsq_try_enter. Then the
27004  * appropriate function to handle the ioctl is called based on the entry in
27005  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
27006  * which also refreleases the 'conn' that was refheld at the start of the
27007  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
27008  *
27009  * Many exclusive ioctls go thru an internal down up sequence as part of
27010  * the operation. For example an attempt to change the IP address of an
27011  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
27012  * does all the cleanup such as deleting all ires that use this address.
27013  * Then we need to wait till all references to the interface go away.
27014  */
27015 void
27016 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
27017 {
27018 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
27019 	ip_ioctl_cmd_t *ipip = arg;
27020 	ip_extract_func_t *extract_funcp;
27021 	cmd_info_t ci;
27022 	int err;
27023 	boolean_t entered_ipsq = B_FALSE;
27024 
27025 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
27026 
27027 	if (ipip == NULL)
27028 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27029 
27030 	/*
27031 	 * SIOCLIFADDIF needs to go thru a special path since the
27032 	 * ill may not exist yet. This happens in the case of lo0
27033 	 * which is created using this ioctl.
27034 	 */
27035 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
27036 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
27037 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27038 		return;
27039 	}
27040 
27041 	ci.ci_ipif = NULL;
27042 	if (ipip->ipi_cmd_type == MISC_CMD) {
27043 		/*
27044 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27045 		 */
27046 		if (ipip->ipi_cmd == IF_UNITSEL) {
27047 			/* ioctl comes down the ill */
27048 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27049 			ipif_refhold(ci.ci_ipif);
27050 		}
27051 		err = 0;
27052 		ci.ci_sin = NULL;
27053 		ci.ci_sin6 = NULL;
27054 		ci.ci_lifr = NULL;
27055 	} else {
27056 		switch (ipip->ipi_cmd_type) {
27057 		case IF_CMD:
27058 		case LIF_CMD:
27059 			extract_funcp = ip_extract_lifreq;
27060 			break;
27061 
27062 		case ARP_CMD:
27063 		case XARP_CMD:
27064 			extract_funcp = ip_extract_arpreq;
27065 			break;
27066 
27067 		case TUN_CMD:
27068 			extract_funcp = ip_extract_tunreq;
27069 			break;
27070 
27071 		case MSFILT_CMD:
27072 			extract_funcp = ip_extract_msfilter;
27073 			break;
27074 
27075 		default:
27076 			ASSERT(0);
27077 		}
27078 
27079 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27080 		if (err != 0) {
27081 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27082 			return;
27083 		}
27084 
27085 		/*
27086 		 * All of the extraction functions return a refheld ipif.
27087 		 */
27088 		ASSERT(ci.ci_ipif != NULL);
27089 	}
27090 
27091 	/*
27092 	 * If ipsq is non-null, we are already being called exclusively
27093 	 */
27094 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27095 	if (!(ipip->ipi_flags & IPI_WR)) {
27096 		/*
27097 		 * A return value of EINPROGRESS means the ioctl is
27098 		 * either queued and waiting for some reason or has
27099 		 * already completed.
27100 		 */
27101 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27102 		    ci.ci_lifr);
27103 		if (ci.ci_ipif != NULL)
27104 			ipif_refrele(ci.ci_ipif);
27105 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27106 		return;
27107 	}
27108 
27109 	ASSERT(ci.ci_ipif != NULL);
27110 
27111 	if (ipsq == NULL) {
27112 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27113 		    ip_process_ioctl, NEW_OP, B_TRUE);
27114 		entered_ipsq = B_TRUE;
27115 	}
27116 	/*
27117 	 * Release the ipif so that ipif_down and friends that wait for
27118 	 * references to go away are not misled about the current ipif_refcnt
27119 	 * values. We are writer so we can access the ipif even after releasing
27120 	 * the ipif.
27121 	 */
27122 	ipif_refrele(ci.ci_ipif);
27123 	if (ipsq == NULL)
27124 		return;
27125 
27126 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27127 
27128 	/*
27129 	 * For most set ioctls that come here, this serves as a single point
27130 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27131 	 * be any new references to the ipif. This helps functions that go
27132 	 * through this path and end up trying to wait for the refcnts
27133 	 * associated with the ipif to go down to zero. Some exceptions are
27134 	 * Failover, Failback, and Groupname commands that operate on more than
27135 	 * just the ci.ci_ipif. These commands internally determine the
27136 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27137 	 * flags on that set. Another exception is the Removeif command that
27138 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27139 	 * ipif to operate on.
27140 	 */
27141 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27142 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27143 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27144 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27145 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27146 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27147 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27148 
27149 	/*
27150 	 * A return value of EINPROGRESS means the ioctl is
27151 	 * either queued and waiting for some reason or has
27152 	 * already completed.
27153 	 */
27154 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27155 
27156 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27157 
27158 	if (entered_ipsq)
27159 		ipsq_exit(ipsq);
27160 }
27161 
27162 /*
27163  * Complete the ioctl. Typically ioctls use the mi package and need to
27164  * do mi_copyout/mi_copy_done.
27165  */
27166 void
27167 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27168 {
27169 	conn_t	*connp = NULL;
27170 
27171 	if (err == EINPROGRESS)
27172 		return;
27173 
27174 	if (CONN_Q(q)) {
27175 		connp = Q_TO_CONN(q);
27176 		ASSERT(connp->conn_ref >= 2);
27177 	}
27178 
27179 	switch (mode) {
27180 	case COPYOUT:
27181 		if (err == 0)
27182 			mi_copyout(q, mp);
27183 		else
27184 			mi_copy_done(q, mp, err);
27185 		break;
27186 
27187 	case NO_COPYOUT:
27188 		mi_copy_done(q, mp, err);
27189 		break;
27190 
27191 	default:
27192 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27193 		break;
27194 	}
27195 
27196 	/*
27197 	 * The refhold placed at the start of the ioctl is released here.
27198 	 */
27199 	if (connp != NULL)
27200 		CONN_OPER_PENDING_DONE(connp);
27201 
27202 	if (ipsq != NULL)
27203 		ipsq_current_finish(ipsq);
27204 }
27205 
27206 /*
27207  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27208  */
27209 /* ARGSUSED */
27210 void
27211 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27212 {
27213 	conn_t *connp = arg;
27214 	tcp_t	*tcp;
27215 
27216 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27217 	tcp = connp->conn_tcp;
27218 
27219 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27220 		freemsg(mp);
27221 	else
27222 		tcp_rput_other(tcp, mp);
27223 	CONN_OPER_PENDING_DONE(connp);
27224 }
27225 
27226 /* Called from ip_wput for all non data messages */
27227 /* ARGSUSED */
27228 void
27229 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27230 {
27231 	mblk_t		*mp1;
27232 	ire_t		*ire, *fake_ire;
27233 	ill_t		*ill;
27234 	struct iocblk	*iocp;
27235 	ip_ioctl_cmd_t	*ipip;
27236 	cred_t		*cr;
27237 	conn_t		*connp;
27238 	int		err;
27239 	nce_t		*nce;
27240 	ipif_t		*ipif;
27241 	ip_stack_t	*ipst;
27242 	char		*proto_str;
27243 
27244 	if (CONN_Q(q)) {
27245 		connp = Q_TO_CONN(q);
27246 		ipst = connp->conn_netstack->netstack_ip;
27247 	} else {
27248 		connp = NULL;
27249 		ipst = ILLQ_TO_IPST(q);
27250 	}
27251 
27252 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27253 
27254 	switch (DB_TYPE(mp)) {
27255 	case M_IOCTL:
27256 		/*
27257 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27258 		 * will arrange to copy in associated control structures.
27259 		 */
27260 		ip_sioctl_copyin_setup(q, mp);
27261 		return;
27262 	case M_IOCDATA:
27263 		/*
27264 		 * Ensure that this is associated with one of our trans-
27265 		 * parent ioctls.  If it's not ours, discard it if we're
27266 		 * running as a driver, or pass it on if we're a module.
27267 		 */
27268 		iocp = (struct iocblk *)mp->b_rptr;
27269 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27270 		if (ipip == NULL) {
27271 			if (q->q_next == NULL) {
27272 				goto nak;
27273 			} else {
27274 				putnext(q, mp);
27275 			}
27276 			return;
27277 		}
27278 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27279 			/*
27280 			 * the ioctl is one we recognise, but is not
27281 			 * consumed by IP as a module, pass M_IOCDATA
27282 			 * for processing downstream, but only for
27283 			 * common Streams ioctls.
27284 			 */
27285 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27286 				putnext(q, mp);
27287 				return;
27288 			} else {
27289 				goto nak;
27290 			}
27291 		}
27292 
27293 		/* IOCTL continuation following copyin or copyout. */
27294 		if (mi_copy_state(q, mp, NULL) == -1) {
27295 			/*
27296 			 * The copy operation failed.  mi_copy_state already
27297 			 * cleaned up, so we're out of here.
27298 			 */
27299 			return;
27300 		}
27301 		/*
27302 		 * If we just completed a copy in, we become writer and
27303 		 * continue processing in ip_sioctl_copyin_done.  If it
27304 		 * was a copy out, we call mi_copyout again.  If there is
27305 		 * nothing more to copy out, it will complete the IOCTL.
27306 		 */
27307 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27308 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27309 				mi_copy_done(q, mp, EPROTO);
27310 				return;
27311 			}
27312 			/*
27313 			 * Check for cases that need more copying.  A return
27314 			 * value of 0 means a second copyin has been started,
27315 			 * so we return; a return value of 1 means no more
27316 			 * copying is needed, so we continue.
27317 			 */
27318 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27319 			    MI_COPY_COUNT(mp) == 1) {
27320 				if (ip_copyin_msfilter(q, mp) == 0)
27321 					return;
27322 			}
27323 			/*
27324 			 * Refhold the conn, till the ioctl completes. This is
27325 			 * needed in case the ioctl ends up in the pending mp
27326 			 * list. Every mp in the ill_pending_mp list and
27327 			 * the ipsq_pending_mp must have a refhold on the conn
27328 			 * to resume processing. The refhold is released when
27329 			 * the ioctl completes. (normally or abnormally)
27330 			 * In all cases ip_ioctl_finish is called to finish
27331 			 * the ioctl.
27332 			 */
27333 			if (connp != NULL) {
27334 				/* This is not a reentry */
27335 				ASSERT(ipsq == NULL);
27336 				CONN_INC_REF(connp);
27337 			} else {
27338 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27339 					mi_copy_done(q, mp, EINVAL);
27340 					return;
27341 				}
27342 			}
27343 
27344 			ip_process_ioctl(ipsq, q, mp, ipip);
27345 
27346 		} else {
27347 			mi_copyout(q, mp);
27348 		}
27349 		return;
27350 nak:
27351 		iocp->ioc_error = EINVAL;
27352 		mp->b_datap->db_type = M_IOCNAK;
27353 		iocp->ioc_count = 0;
27354 		qreply(q, mp);
27355 		return;
27356 
27357 	case M_IOCNAK:
27358 		/*
27359 		 * The only way we could get here is if a resolver didn't like
27360 		 * an IOCTL we sent it.	 This shouldn't happen.
27361 		 */
27362 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27363 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27364 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27365 		freemsg(mp);
27366 		return;
27367 	case M_IOCACK:
27368 		/* /dev/ip shouldn't see this */
27369 		if (CONN_Q(q))
27370 			goto nak;
27371 
27372 		/* Finish socket ioctls passed through to ARP. */
27373 		ip_sioctl_iocack(q, mp);
27374 		return;
27375 	case M_FLUSH:
27376 		if (*mp->b_rptr & FLUSHW)
27377 			flushq(q, FLUSHALL);
27378 		if (q->q_next) {
27379 			putnext(q, mp);
27380 			return;
27381 		}
27382 		if (*mp->b_rptr & FLUSHR) {
27383 			*mp->b_rptr &= ~FLUSHW;
27384 			qreply(q, mp);
27385 			return;
27386 		}
27387 		freemsg(mp);
27388 		return;
27389 	case IRE_DB_REQ_TYPE:
27390 		if (connp == NULL) {
27391 			proto_str = "IRE_DB_REQ_TYPE";
27392 			goto protonak;
27393 		}
27394 		/* An Upper Level Protocol wants a copy of an IRE. */
27395 		ip_ire_req(q, mp);
27396 		return;
27397 	case M_CTL:
27398 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27399 			break;
27400 
27401 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27402 		    TUN_HELLO) {
27403 			ASSERT(connp != NULL);
27404 			connp->conn_flags |= IPCL_IPTUN;
27405 			freeb(mp);
27406 			return;
27407 		}
27408 
27409 		/* M_CTL messages are used by ARP to tell us things. */
27410 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27411 			break;
27412 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27413 		case AR_ENTRY_SQUERY:
27414 			ip_wput_ctl(q, mp);
27415 			return;
27416 		case AR_CLIENT_NOTIFY:
27417 			ip_arp_news(q, mp);
27418 			return;
27419 		case AR_DLPIOP_DONE:
27420 			ASSERT(q->q_next != NULL);
27421 			ill = (ill_t *)q->q_ptr;
27422 			/* qwriter_ip releases the refhold */
27423 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27424 			ill_refhold(ill);
27425 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27426 			return;
27427 		case AR_ARP_CLOSING:
27428 			/*
27429 			 * ARP (above us) is closing. If no ARP bringup is
27430 			 * currently pending, ack the message so that ARP
27431 			 * can complete its close. Also mark ill_arp_closing
27432 			 * so that new ARP bringups will fail. If any
27433 			 * ARP bringup is currently in progress, we will
27434 			 * ack this when the current ARP bringup completes.
27435 			 */
27436 			ASSERT(q->q_next != NULL);
27437 			ill = (ill_t *)q->q_ptr;
27438 			mutex_enter(&ill->ill_lock);
27439 			ill->ill_arp_closing = 1;
27440 			if (!ill->ill_arp_bringup_pending) {
27441 				mutex_exit(&ill->ill_lock);
27442 				qreply(q, mp);
27443 			} else {
27444 				mutex_exit(&ill->ill_lock);
27445 				freemsg(mp);
27446 			}
27447 			return;
27448 		case AR_ARP_EXTEND:
27449 			/*
27450 			 * The ARP module above us is capable of duplicate
27451 			 * address detection.  Old ATM drivers will not send
27452 			 * this message.
27453 			 */
27454 			ASSERT(q->q_next != NULL);
27455 			ill = (ill_t *)q->q_ptr;
27456 			ill->ill_arp_extend = B_TRUE;
27457 			freemsg(mp);
27458 			return;
27459 		default:
27460 			break;
27461 		}
27462 		break;
27463 	case M_PROTO:
27464 	case M_PCPROTO:
27465 		/*
27466 		 * The only PROTO messages we expect are ULP binds and
27467 		 * copies of option negotiation acknowledgements.
27468 		 */
27469 		switch (((union T_primitives *)mp->b_rptr)->type) {
27470 		case O_T_BIND_REQ:
27471 		case T_BIND_REQ: {
27472 			/* Request can get queued in bind */
27473 			if (connp == NULL) {
27474 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27475 				goto protonak;
27476 			}
27477 			/*
27478 			 * The transports except SCTP call ip_bind_{v4,v6}()
27479 			 * directly instead of a a putnext. SCTP doesn't
27480 			 * generate any T_BIND_REQ since it has its own
27481 			 * fanout data structures. However, ESP and AH
27482 			 * come in for regular binds; all other cases are
27483 			 * bind retries.
27484 			 */
27485 			ASSERT(!IPCL_IS_SCTP(connp));
27486 
27487 			/* Don't increment refcnt if this is a re-entry */
27488 			if (ipsq == NULL)
27489 				CONN_INC_REF(connp);
27490 
27491 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27492 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27493 			if (mp == NULL)
27494 				return;
27495 			if (IPCL_IS_TCP(connp)) {
27496 				/*
27497 				 * In the case of TCP endpoint we
27498 				 * come here only for bind retries
27499 				 */
27500 				ASSERT(ipsq != NULL);
27501 				CONN_INC_REF(connp);
27502 				squeue_fill(connp->conn_sqp, mp,
27503 				    ip_resume_tcp_bind, connp,
27504 				    SQTAG_BIND_RETRY);
27505 			} else if (IPCL_IS_UDP(connp)) {
27506 				/*
27507 				 * In the case of UDP endpoint we
27508 				 * come here only for bind retries
27509 				 */
27510 				ASSERT(ipsq != NULL);
27511 				udp_resume_bind(connp, mp);
27512 			} else if (IPCL_IS_RAWIP(connp)) {
27513 				/*
27514 				 * In the case of RAWIP endpoint we
27515 				 * come here only for bind retries
27516 				 */
27517 				ASSERT(ipsq != NULL);
27518 				rawip_resume_bind(connp, mp);
27519 			} else {
27520 				/* The case of AH and ESP */
27521 				qreply(q, mp);
27522 				CONN_OPER_PENDING_DONE(connp);
27523 			}
27524 			return;
27525 		}
27526 		case T_SVR4_OPTMGMT_REQ:
27527 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27528 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27529 
27530 			if (connp == NULL) {
27531 				proto_str = "T_SVR4_OPTMGMT_REQ";
27532 				goto protonak;
27533 			}
27534 
27535 			if (!snmpcom_req(q, mp, ip_snmp_set,
27536 			    ip_snmp_get, cr)) {
27537 				/*
27538 				 * Call svr4_optcom_req so that it can
27539 				 * generate the ack. We don't come here
27540 				 * if this operation is being restarted.
27541 				 * ip_restart_optmgmt will drop the conn ref.
27542 				 * In the case of ipsec option after the ipsec
27543 				 * load is complete conn_restart_ipsec_waiter
27544 				 * drops the conn ref.
27545 				 */
27546 				ASSERT(ipsq == NULL);
27547 				CONN_INC_REF(connp);
27548 				if (ip_check_for_ipsec_opt(q, mp))
27549 					return;
27550 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27551 				    B_FALSE);
27552 				if (err != EINPROGRESS) {
27553 					/* Operation is done */
27554 					CONN_OPER_PENDING_DONE(connp);
27555 				}
27556 			}
27557 			return;
27558 		case T_OPTMGMT_REQ:
27559 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27560 			/*
27561 			 * Note: No snmpcom_req support through new
27562 			 * T_OPTMGMT_REQ.
27563 			 * Call tpi_optcom_req so that it can
27564 			 * generate the ack.
27565 			 */
27566 			if (connp == NULL) {
27567 				proto_str = "T_OPTMGMT_REQ";
27568 				goto protonak;
27569 			}
27570 
27571 			ASSERT(ipsq == NULL);
27572 			/*
27573 			 * We don't come here for restart. ip_restart_optmgmt
27574 			 * will drop the conn ref. In the case of ipsec option
27575 			 * after the ipsec load is complete
27576 			 * conn_restart_ipsec_waiter drops the conn ref.
27577 			 */
27578 			CONN_INC_REF(connp);
27579 			if (ip_check_for_ipsec_opt(q, mp))
27580 				return;
27581 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27582 			if (err != EINPROGRESS) {
27583 				/* Operation is done */
27584 				CONN_OPER_PENDING_DONE(connp);
27585 			}
27586 			return;
27587 		case T_UNBIND_REQ:
27588 			if (connp == NULL) {
27589 				proto_str = "T_UNBIND_REQ";
27590 				goto protonak;
27591 			}
27592 			mp = ip_unbind(q, mp);
27593 			qreply(q, mp);
27594 			return;
27595 		default:
27596 			/*
27597 			 * Have to drop any DLPI messages coming down from
27598 			 * arp (such as an info_req which would cause ip
27599 			 * to receive an extra info_ack if it was passed
27600 			 * through.
27601 			 */
27602 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27603 			    (int)*(uint_t *)mp->b_rptr));
27604 			freemsg(mp);
27605 			return;
27606 		}
27607 		/* NOTREACHED */
27608 	case IRE_DB_TYPE: {
27609 		nce_t		*nce;
27610 		ill_t		*ill;
27611 		in6_addr_t	gw_addr_v6;
27612 
27613 
27614 		/*
27615 		 * This is a response back from a resolver.  It
27616 		 * consists of a message chain containing:
27617 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27618 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27619 		 * The LL_HDR_MBLK is the DLPI header to use to get
27620 		 * the attached packet, and subsequent ones for the
27621 		 * same destination, transmitted.
27622 		 */
27623 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27624 			break;
27625 		/*
27626 		 * First, check to make sure the resolution succeeded.
27627 		 * If it failed, the second mblk will be empty.
27628 		 * If it is, free the chain, dropping the packet.
27629 		 * (We must ire_delete the ire; that frees the ire mblk)
27630 		 * We're doing this now to support PVCs for ATM; it's
27631 		 * a partial xresolv implementation. When we fully implement
27632 		 * xresolv interfaces, instead of freeing everything here
27633 		 * we'll initiate neighbor discovery.
27634 		 *
27635 		 * For v4 (ARP and other external resolvers) the resolver
27636 		 * frees the message, so no check is needed. This check
27637 		 * is required, though, for a full xresolve implementation.
27638 		 * Including this code here now both shows how external
27639 		 * resolvers can NACK a resolution request using an
27640 		 * existing design that has no specific provisions for NACKs,
27641 		 * and also takes into account that the current non-ARP
27642 		 * external resolver has been coded to use this method of
27643 		 * NACKing for all IPv6 (xresolv) cases,
27644 		 * whether our xresolv implementation is complete or not.
27645 		 *
27646 		 */
27647 		ire = (ire_t *)mp->b_rptr;
27648 		ill = ire_to_ill(ire);
27649 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27650 		if (mp1->b_rptr == mp1->b_wptr) {
27651 			if (ire->ire_ipversion == IPV6_VERSION) {
27652 				/*
27653 				 * XRESOLV interface.
27654 				 */
27655 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27656 				mutex_enter(&ire->ire_lock);
27657 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27658 				mutex_exit(&ire->ire_lock);
27659 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27660 					nce = ndp_lookup_v6(ill,
27661 					    &ire->ire_addr_v6, B_FALSE);
27662 				} else {
27663 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27664 					    B_FALSE);
27665 				}
27666 				if (nce != NULL) {
27667 					nce_resolv_failed(nce);
27668 					ndp_delete(nce);
27669 					NCE_REFRELE(nce);
27670 				}
27671 			}
27672 			mp->b_cont = NULL;
27673 			freemsg(mp1);		/* frees the pkt as well */
27674 			ASSERT(ire->ire_nce == NULL);
27675 			ire_delete((ire_t *)mp->b_rptr);
27676 			return;
27677 		}
27678 
27679 		/*
27680 		 * Split them into IRE_MBLK and pkt and feed it into
27681 		 * ire_add_then_send. Then in ire_add_then_send
27682 		 * the IRE will be added, and then the packet will be
27683 		 * run back through ip_wput. This time it will make
27684 		 * it to the wire.
27685 		 */
27686 		mp->b_cont = NULL;
27687 		mp = mp1->b_cont;		/* now, mp points to pkt */
27688 		mp1->b_cont = NULL;
27689 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27690 		if (ire->ire_ipversion == IPV6_VERSION) {
27691 			/*
27692 			 * XRESOLV interface. Find the nce and put a copy
27693 			 * of the dl_unitdata_req in nce_res_mp
27694 			 */
27695 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27696 			mutex_enter(&ire->ire_lock);
27697 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27698 			mutex_exit(&ire->ire_lock);
27699 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27700 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27701 				    B_FALSE);
27702 			} else {
27703 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27704 			}
27705 			if (nce != NULL) {
27706 				/*
27707 				 * We have to protect nce_res_mp here
27708 				 * from being accessed by other threads
27709 				 * while we change the mblk pointer.
27710 				 * Other functions will also lock the nce when
27711 				 * accessing nce_res_mp.
27712 				 *
27713 				 * The reason we change the mblk pointer
27714 				 * here rather than copying the resolved address
27715 				 * into the template is that, unlike with
27716 				 * ethernet, we have no guarantee that the
27717 				 * resolved address length will be
27718 				 * smaller than or equal to the lla length
27719 				 * with which the template was allocated,
27720 				 * (for ethernet, they're equal)
27721 				 * so we have to use the actual resolved
27722 				 * address mblk - which holds the real
27723 				 * dl_unitdata_req with the resolved address.
27724 				 *
27725 				 * Doing this is the same behavior as was
27726 				 * previously used in the v4 ARP case.
27727 				 */
27728 				mutex_enter(&nce->nce_lock);
27729 				if (nce->nce_res_mp != NULL)
27730 					freemsg(nce->nce_res_mp);
27731 				nce->nce_res_mp = mp1;
27732 				mutex_exit(&nce->nce_lock);
27733 				/*
27734 				 * We do a fastpath probe here because
27735 				 * we have resolved the address without
27736 				 * using Neighbor Discovery.
27737 				 * In the non-XRESOLV v6 case, the fastpath
27738 				 * probe is done right after neighbor
27739 				 * discovery completes.
27740 				 */
27741 				if (nce->nce_res_mp != NULL) {
27742 					int res;
27743 					nce_fastpath_list_add(nce);
27744 					res = ill_fastpath_probe(ill,
27745 					    nce->nce_res_mp);
27746 					if (res != 0 && res != EAGAIN)
27747 						nce_fastpath_list_delete(nce);
27748 				}
27749 
27750 				ire_add_then_send(q, ire, mp);
27751 				/*
27752 				 * Now we have to clean out any packets
27753 				 * that may have been queued on the nce
27754 				 * while it was waiting for address resolution
27755 				 * to complete.
27756 				 */
27757 				mutex_enter(&nce->nce_lock);
27758 				mp1 = nce->nce_qd_mp;
27759 				nce->nce_qd_mp = NULL;
27760 				mutex_exit(&nce->nce_lock);
27761 				while (mp1 != NULL) {
27762 					mblk_t *nxt_mp;
27763 					queue_t *fwdq = NULL;
27764 					ill_t   *inbound_ill;
27765 					uint_t ifindex;
27766 
27767 					nxt_mp = mp1->b_next;
27768 					mp1->b_next = NULL;
27769 					/*
27770 					 * Retrieve ifindex stored in
27771 					 * ip_rput_data_v6()
27772 					 */
27773 					ifindex =
27774 					    (uint_t)(uintptr_t)mp1->b_prev;
27775 					inbound_ill =
27776 					    ill_lookup_on_ifindex(ifindex,
27777 					    B_TRUE, NULL, NULL, NULL,
27778 					    NULL, ipst);
27779 					mp1->b_prev = NULL;
27780 					if (inbound_ill != NULL)
27781 						fwdq = inbound_ill->ill_rq;
27782 
27783 					if (fwdq != NULL) {
27784 						put(fwdq, mp1);
27785 						ill_refrele(inbound_ill);
27786 					} else
27787 						put(WR(ill->ill_rq), mp1);
27788 					mp1 = nxt_mp;
27789 				}
27790 				NCE_REFRELE(nce);
27791 			} else {	/* nce is NULL; clean up */
27792 				ire_delete(ire);
27793 				freemsg(mp);
27794 				freemsg(mp1);
27795 				return;
27796 			}
27797 		} else {
27798 			nce_t *arpce;
27799 			/*
27800 			 * Link layer resolution succeeded. Recompute the
27801 			 * ire_nce.
27802 			 */
27803 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27804 			if ((arpce = ndp_lookup_v4(ill,
27805 			    (ire->ire_gateway_addr != INADDR_ANY ?
27806 			    &ire->ire_gateway_addr : &ire->ire_addr),
27807 			    B_FALSE)) == NULL) {
27808 				freeb(ire->ire_mp);
27809 				freeb(mp1);
27810 				freemsg(mp);
27811 				return;
27812 			}
27813 			mutex_enter(&arpce->nce_lock);
27814 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27815 			if (arpce->nce_state == ND_REACHABLE) {
27816 				/*
27817 				 * Someone resolved this before us;
27818 				 * cleanup the res_mp. Since ire has
27819 				 * not been added yet, the call to ire_add_v4
27820 				 * from ire_add_then_send (when a dup is
27821 				 * detected) will clean up the ire.
27822 				 */
27823 				freeb(mp1);
27824 			} else {
27825 				ASSERT(arpce->nce_res_mp == NULL);
27826 				arpce->nce_res_mp = mp1;
27827 				arpce->nce_state = ND_REACHABLE;
27828 			}
27829 			mutex_exit(&arpce->nce_lock);
27830 			if (ire->ire_marks & IRE_MARK_NOADD) {
27831 				/*
27832 				 * this ire will not be added to the ire
27833 				 * cache table, so we can set the ire_nce
27834 				 * here, as there are no atomicity constraints.
27835 				 */
27836 				ire->ire_nce = arpce;
27837 				/*
27838 				 * We are associating this nce with the ire
27839 				 * so change the nce ref taken in
27840 				 * ndp_lookup_v4() from
27841 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27842 				 */
27843 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27844 			} else {
27845 				NCE_REFRELE(arpce);
27846 			}
27847 			ire_add_then_send(q, ire, mp);
27848 		}
27849 		return;	/* All is well, the packet has been sent. */
27850 	}
27851 	case IRE_ARPRESOLVE_TYPE: {
27852 
27853 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27854 			break;
27855 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27856 		mp->b_cont = NULL;
27857 		/*
27858 		 * First, check to make sure the resolution succeeded.
27859 		 * If it failed, the second mblk will be empty.
27860 		 */
27861 		if (mp1->b_rptr == mp1->b_wptr) {
27862 			/* cleanup  the incomplete ire, free queued packets */
27863 			freemsg(mp); /* fake ire */
27864 			freeb(mp1);  /* dl_unitdata response */
27865 			return;
27866 		}
27867 
27868 		/*
27869 		 * update any incomplete nce_t found. we lookup the ctable
27870 		 * and find the nce from the ire->ire_nce because we need
27871 		 * to pass the ire to ip_xmit_v4 later, and can find both
27872 		 * ire and nce in one lookup from the ctable.
27873 		 */
27874 		fake_ire = (ire_t *)mp->b_rptr;
27875 		/*
27876 		 * By the time we come back here from ARP
27877 		 * the logical outgoing interface  of the incomplete ire
27878 		 * we added in ire_forward could have disappeared,
27879 		 * causing the incomplete ire to also have
27880 		 * dissapeared. So we need to retreive the
27881 		 * proper ipif for the ire  before looking
27882 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27883 		 */
27884 		ill = q->q_ptr;
27885 
27886 		/* Get the outgoing ipif */
27887 		mutex_enter(&ill->ill_lock);
27888 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27889 			mutex_exit(&ill->ill_lock);
27890 			freemsg(mp); /* fake ire */
27891 			freeb(mp1);  /* dl_unitdata response */
27892 			return;
27893 		}
27894 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27895 
27896 		if (ipif == NULL) {
27897 			mutex_exit(&ill->ill_lock);
27898 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27899 			freemsg(mp);
27900 			freeb(mp1);
27901 			return;
27902 		}
27903 		ipif_refhold_locked(ipif);
27904 		mutex_exit(&ill->ill_lock);
27905 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27906 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27907 		    ipif, fake_ire->ire_zoneid, NULL,
27908 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY|
27909 		    MATCH_IRE_TYPE), ipst);
27910 		ipif_refrele(ipif);
27911 		if (ire == NULL) {
27912 			/*
27913 			 * no ire was found; check if there is an nce
27914 			 * for this lookup; if it has no ire's pointing at it
27915 			 * cleanup.
27916 			 */
27917 			if ((nce = ndp_lookup_v4(ill,
27918 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27919 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27920 			    B_FALSE)) != NULL) {
27921 				/*
27922 				 * cleanup:
27923 				 * We check for refcnt 2 (one for the nce
27924 				 * hash list + 1 for the ref taken by
27925 				 * ndp_lookup_v4) to check that there are
27926 				 * no ire's pointing at the nce.
27927 				 */
27928 				if (nce->nce_refcnt == 2)
27929 					ndp_delete(nce);
27930 				NCE_REFRELE(nce);
27931 			}
27932 			freeb(mp1);  /* dl_unitdata response */
27933 			freemsg(mp); /* fake ire */
27934 			return;
27935 		}
27936 		nce = ire->ire_nce;
27937 		DTRACE_PROBE2(ire__arpresolve__type,
27938 		    ire_t *, ire, nce_t *, nce);
27939 		ASSERT(nce->nce_state != ND_INITIAL);
27940 		mutex_enter(&nce->nce_lock);
27941 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27942 		if (nce->nce_state == ND_REACHABLE) {
27943 			/*
27944 			 * Someone resolved this before us;
27945 			 * our response is not needed any more.
27946 			 */
27947 			mutex_exit(&nce->nce_lock);
27948 			freeb(mp1);  /* dl_unitdata response */
27949 		} else {
27950 			ASSERT(nce->nce_res_mp == NULL);
27951 			nce->nce_res_mp = mp1;
27952 			nce->nce_state = ND_REACHABLE;
27953 			mutex_exit(&nce->nce_lock);
27954 			nce_fastpath(nce);
27955 		}
27956 		/*
27957 		 * The cached nce_t has been updated to be reachable;
27958 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27959 		 */
27960 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27961 		freemsg(mp);
27962 		/*
27963 		 * send out queued packets.
27964 		 */
27965 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27966 
27967 		IRE_REFRELE(ire);
27968 		return;
27969 	}
27970 	default:
27971 		break;
27972 	}
27973 	if (q->q_next) {
27974 		putnext(q, mp);
27975 	} else
27976 		freemsg(mp);
27977 	return;
27978 
27979 protonak:
27980 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27981 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27982 		qreply(q, mp);
27983 }
27984 
27985 /*
27986  * Process IP options in an outbound packet.  Modify the destination if there
27987  * is a source route option.
27988  * Returns non-zero if something fails in which case an ICMP error has been
27989  * sent and mp freed.
27990  */
27991 static int
27992 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27993     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27994 {
27995 	ipoptp_t	opts;
27996 	uchar_t		*opt;
27997 	uint8_t		optval;
27998 	uint8_t		optlen;
27999 	ipaddr_t	dst;
28000 	intptr_t	code = 0;
28001 	mblk_t		*mp;
28002 	ire_t		*ire = NULL;
28003 
28004 	ip2dbg(("ip_wput_options\n"));
28005 	mp = ipsec_mp;
28006 	if (mctl_present) {
28007 		mp = ipsec_mp->b_cont;
28008 	}
28009 
28010 	dst = ipha->ipha_dst;
28011 	for (optval = ipoptp_first(&opts, ipha);
28012 	    optval != IPOPT_EOL;
28013 	    optval = ipoptp_next(&opts)) {
28014 		opt = opts.ipoptp_cur;
28015 		optlen = opts.ipoptp_len;
28016 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
28017 		    optval, optlen));
28018 		switch (optval) {
28019 			uint32_t off;
28020 		case IPOPT_SSRR:
28021 		case IPOPT_LSRR:
28022 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28023 				ip1dbg((
28024 				    "ip_wput_options: bad option offset\n"));
28025 				code = (char *)&opt[IPOPT_OLEN] -
28026 				    (char *)ipha;
28027 				goto param_prob;
28028 			}
28029 			off = opt[IPOPT_OFFSET];
28030 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
28031 			    ntohl(dst)));
28032 			/*
28033 			 * For strict: verify that dst is directly
28034 			 * reachable.
28035 			 */
28036 			if (optval == IPOPT_SSRR) {
28037 				ire = ire_ftable_lookup(dst, 0, 0,
28038 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
28039 				    MBLK_GETLABEL(mp),
28040 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28041 				if (ire == NULL) {
28042 					ip1dbg(("ip_wput_options: SSRR not"
28043 					    " directly reachable: 0x%x\n",
28044 					    ntohl(dst)));
28045 					goto bad_src_route;
28046 				}
28047 				ire_refrele(ire);
28048 			}
28049 			break;
28050 		case IPOPT_RR:
28051 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28052 				ip1dbg((
28053 				    "ip_wput_options: bad option offset\n"));
28054 				code = (char *)&opt[IPOPT_OLEN] -
28055 				    (char *)ipha;
28056 				goto param_prob;
28057 			}
28058 			break;
28059 		case IPOPT_TS:
28060 			/*
28061 			 * Verify that length >=5 and that there is either
28062 			 * room for another timestamp or that the overflow
28063 			 * counter is not maxed out.
28064 			 */
28065 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28066 			if (optlen < IPOPT_MINLEN_IT) {
28067 				goto param_prob;
28068 			}
28069 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28070 				ip1dbg((
28071 				    "ip_wput_options: bad option offset\n"));
28072 				code = (char *)&opt[IPOPT_OFFSET] -
28073 				    (char *)ipha;
28074 				goto param_prob;
28075 			}
28076 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28077 			case IPOPT_TS_TSONLY:
28078 				off = IPOPT_TS_TIMELEN;
28079 				break;
28080 			case IPOPT_TS_TSANDADDR:
28081 			case IPOPT_TS_PRESPEC:
28082 			case IPOPT_TS_PRESPEC_RFC791:
28083 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28084 				break;
28085 			default:
28086 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28087 				    (char *)ipha;
28088 				goto param_prob;
28089 			}
28090 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28091 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28092 				/*
28093 				 * No room and the overflow counter is 15
28094 				 * already.
28095 				 */
28096 				goto param_prob;
28097 			}
28098 			break;
28099 		}
28100 	}
28101 
28102 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28103 		return (0);
28104 
28105 	ip1dbg(("ip_wput_options: error processing IP options."));
28106 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28107 
28108 param_prob:
28109 	/*
28110 	 * Since ip_wput() isn't close to finished, we fill
28111 	 * in enough of the header for credible error reporting.
28112 	 */
28113 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28114 		/* Failed */
28115 		freemsg(ipsec_mp);
28116 		return (-1);
28117 	}
28118 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28119 	return (-1);
28120 
28121 bad_src_route:
28122 	/*
28123 	 * Since ip_wput() isn't close to finished, we fill
28124 	 * in enough of the header for credible error reporting.
28125 	 */
28126 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28127 		/* Failed */
28128 		freemsg(ipsec_mp);
28129 		return (-1);
28130 	}
28131 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28132 	return (-1);
28133 }
28134 
28135 /*
28136  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28137  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28138  * thru /etc/system.
28139  */
28140 #define	CONN_MAXDRAINCNT	64
28141 
28142 static void
28143 conn_drain_init(ip_stack_t *ipst)
28144 {
28145 	int i;
28146 
28147 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28148 
28149 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28150 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28151 		/*
28152 		 * Default value of the number of drainers is the
28153 		 * number of cpus, subject to maximum of 8 drainers.
28154 		 */
28155 		if (boot_max_ncpus != -1)
28156 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28157 		else
28158 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28159 	}
28160 
28161 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28162 	    sizeof (idl_t), KM_SLEEP);
28163 
28164 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28165 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28166 		    MUTEX_DEFAULT, NULL);
28167 	}
28168 }
28169 
28170 static void
28171 conn_drain_fini(ip_stack_t *ipst)
28172 {
28173 	int i;
28174 
28175 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28176 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28177 	kmem_free(ipst->ips_conn_drain_list,
28178 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28179 	ipst->ips_conn_drain_list = NULL;
28180 }
28181 
28182 /*
28183  * Note: For an overview of how flowcontrol is handled in IP please see the
28184  * IP Flowcontrol notes at the top of this file.
28185  *
28186  * Flow control has blocked us from proceeding. Insert the given conn in one
28187  * of the conn drain lists. These conn wq's will be qenabled later on when
28188  * STREAMS flow control does a backenable. conn_walk_drain will enable
28189  * the first conn in each of these drain lists. Each of these qenabled conns
28190  * in turn enables the next in the list, after it runs, or when it closes,
28191  * thus sustaining the drain process.
28192  *
28193  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28194  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28195  * running at any time, on a given conn, since there can be only 1 service proc
28196  * running on a queue at any time.
28197  */
28198 void
28199 conn_drain_insert(conn_t *connp)
28200 {
28201 	idl_t	*idl;
28202 	uint_t	index;
28203 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28204 
28205 	mutex_enter(&connp->conn_lock);
28206 	if (connp->conn_state_flags & CONN_CLOSING) {
28207 		/*
28208 		 * The conn is closing as a result of which CONN_CLOSING
28209 		 * is set. Return.
28210 		 */
28211 		mutex_exit(&connp->conn_lock);
28212 		return;
28213 	} else if (connp->conn_idl == NULL) {
28214 		/*
28215 		 * Assign the next drain list round robin. We dont' use
28216 		 * a lock, and thus it may not be strictly round robin.
28217 		 * Atomicity of load/stores is enough to make sure that
28218 		 * conn_drain_list_index is always within bounds.
28219 		 */
28220 		index = ipst->ips_conn_drain_list_index;
28221 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28222 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28223 		index++;
28224 		if (index == ipst->ips_conn_drain_list_cnt)
28225 			index = 0;
28226 		ipst->ips_conn_drain_list_index = index;
28227 	}
28228 	mutex_exit(&connp->conn_lock);
28229 
28230 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28231 	if ((connp->conn_drain_prev != NULL) ||
28232 	    (connp->conn_state_flags & CONN_CLOSING)) {
28233 		/*
28234 		 * The conn is already in the drain list, OR
28235 		 * the conn is closing. We need to check again for
28236 		 * the closing case again since close can happen
28237 		 * after we drop the conn_lock, and before we
28238 		 * acquire the CONN_DRAIN_LIST_LOCK.
28239 		 */
28240 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28241 		return;
28242 	} else {
28243 		idl = connp->conn_idl;
28244 	}
28245 
28246 	/*
28247 	 * The conn is not in the drain list. Insert it at the
28248 	 * tail of the drain list. The drain list is circular
28249 	 * and doubly linked. idl_conn points to the 1st element
28250 	 * in the list.
28251 	 */
28252 	if (idl->idl_conn == NULL) {
28253 		idl->idl_conn = connp;
28254 		connp->conn_drain_next = connp;
28255 		connp->conn_drain_prev = connp;
28256 	} else {
28257 		conn_t *head = idl->idl_conn;
28258 
28259 		connp->conn_drain_next = head;
28260 		connp->conn_drain_prev = head->conn_drain_prev;
28261 		head->conn_drain_prev->conn_drain_next = connp;
28262 		head->conn_drain_prev = connp;
28263 	}
28264 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28265 }
28266 
28267 /*
28268  * This conn is closing, and we are called from ip_close. OR
28269  * This conn has been serviced by ip_wsrv, and we need to do the tail
28270  * processing.
28271  * If this conn is part of the drain list, we may need to sustain the drain
28272  * process by qenabling the next conn in the drain list. We may also need to
28273  * remove this conn from the list, if it is done.
28274  */
28275 static void
28276 conn_drain_tail(conn_t *connp, boolean_t closing)
28277 {
28278 	idl_t *idl;
28279 
28280 	/*
28281 	 * connp->conn_idl is stable at this point, and no lock is needed
28282 	 * to check it. If we are called from ip_close, close has already
28283 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28284 	 * called us only because conn_idl is non-null. If we are called thru
28285 	 * service, conn_idl could be null, but it cannot change because
28286 	 * service is single-threaded per queue, and there cannot be another
28287 	 * instance of service trying to call conn_drain_insert on this conn
28288 	 * now.
28289 	 */
28290 	ASSERT(!closing || (connp->conn_idl != NULL));
28291 
28292 	/*
28293 	 * If connp->conn_idl is null, the conn has not been inserted into any
28294 	 * drain list even once since creation of the conn. Just return.
28295 	 */
28296 	if (connp->conn_idl == NULL)
28297 		return;
28298 
28299 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28300 
28301 	if (connp->conn_drain_prev == NULL) {
28302 		/* This conn is currently not in the drain list.  */
28303 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28304 		return;
28305 	}
28306 	idl = connp->conn_idl;
28307 	if (idl->idl_conn_draining == connp) {
28308 		/*
28309 		 * This conn is the current drainer. If this is the last conn
28310 		 * in the drain list, we need to do more checks, in the 'if'
28311 		 * below. Otherwwise we need to just qenable the next conn,
28312 		 * to sustain the draining, and is handled in the 'else'
28313 		 * below.
28314 		 */
28315 		if (connp->conn_drain_next == idl->idl_conn) {
28316 			/*
28317 			 * This conn is the last in this list. This round
28318 			 * of draining is complete. If idl_repeat is set,
28319 			 * it means another flow enabling has happened from
28320 			 * the driver/streams and we need to another round
28321 			 * of draining.
28322 			 * If there are more than 2 conns in the drain list,
28323 			 * do a left rotate by 1, so that all conns except the
28324 			 * conn at the head move towards the head by 1, and the
28325 			 * the conn at the head goes to the tail. This attempts
28326 			 * a more even share for all queues that are being
28327 			 * drained.
28328 			 */
28329 			if ((connp->conn_drain_next != connp) &&
28330 			    (idl->idl_conn->conn_drain_next != connp)) {
28331 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28332 			}
28333 			if (idl->idl_repeat) {
28334 				qenable(idl->idl_conn->conn_wq);
28335 				idl->idl_conn_draining = idl->idl_conn;
28336 				idl->idl_repeat = 0;
28337 			} else {
28338 				idl->idl_conn_draining = NULL;
28339 			}
28340 		} else {
28341 			/*
28342 			 * If the next queue that we are now qenable'ing,
28343 			 * is closing, it will remove itself from this list
28344 			 * and qenable the subsequent queue in ip_close().
28345 			 * Serialization is acheived thru idl_lock.
28346 			 */
28347 			qenable(connp->conn_drain_next->conn_wq);
28348 			idl->idl_conn_draining = connp->conn_drain_next;
28349 		}
28350 	}
28351 	if (!connp->conn_did_putbq || closing) {
28352 		/*
28353 		 * Remove ourself from the drain list, if we did not do
28354 		 * a putbq, or if the conn is closing.
28355 		 * Note: It is possible that q->q_first is non-null. It means
28356 		 * that these messages landed after we did a enableok() in
28357 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28358 		 * service them.
28359 		 */
28360 		if (connp->conn_drain_next == connp) {
28361 			/* Singleton in the list */
28362 			ASSERT(connp->conn_drain_prev == connp);
28363 			idl->idl_conn = NULL;
28364 			idl->idl_conn_draining = NULL;
28365 		} else {
28366 			connp->conn_drain_prev->conn_drain_next =
28367 			    connp->conn_drain_next;
28368 			connp->conn_drain_next->conn_drain_prev =
28369 			    connp->conn_drain_prev;
28370 			if (idl->idl_conn == connp)
28371 				idl->idl_conn = connp->conn_drain_next;
28372 			ASSERT(idl->idl_conn_draining != connp);
28373 
28374 		}
28375 		connp->conn_drain_next = NULL;
28376 		connp->conn_drain_prev = NULL;
28377 	}
28378 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28379 }
28380 
28381 /*
28382  * Write service routine. Shared perimeter entry point.
28383  * ip_wsrv can be called in any of the following ways.
28384  * 1. The device queue's messages has fallen below the low water mark
28385  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28386  *    the drain lists and backenable the first conn in each list.
28387  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28388  *    qenabled non-tcp upper layers. We start dequeing messages and call
28389  *    ip_wput for each message.
28390  */
28391 
28392 void
28393 ip_wsrv(queue_t *q)
28394 {
28395 	conn_t	*connp;
28396 	ill_t	*ill;
28397 	mblk_t	*mp;
28398 
28399 	if (q->q_next) {
28400 		ill = (ill_t *)q->q_ptr;
28401 		if (ill->ill_state_flags == 0) {
28402 			/*
28403 			 * The device flow control has opened up.
28404 			 * Walk through conn drain lists and qenable the
28405 			 * first conn in each list. This makes sense only
28406 			 * if the stream is fully plumbed and setup.
28407 			 * Hence the if check above.
28408 			 */
28409 			ip1dbg(("ip_wsrv: walking\n"));
28410 			conn_walk_drain(ill->ill_ipst);
28411 		}
28412 		return;
28413 	}
28414 
28415 	connp = Q_TO_CONN(q);
28416 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28417 
28418 	/*
28419 	 * 1. Set conn_draining flag to signal that service is active.
28420 	 *
28421 	 * 2. ip_output determines whether it has been called from service,
28422 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28423 	 *    has been called from service.
28424 	 *
28425 	 * 3. Message ordering is preserved by the following logic.
28426 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28427 	 *    the message at the tail, if conn_draining is set (i.e. service
28428 	 *    is running) or if q->q_first is non-null.
28429 	 *
28430 	 *    ii. If ip_output is called from service, and if ip_output cannot
28431 	 *    putnext due to flow control, it does a putbq.
28432 	 *
28433 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28434 	 *    (causing an infinite loop).
28435 	 */
28436 	ASSERT(!connp->conn_did_putbq);
28437 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28438 		connp->conn_draining = 1;
28439 		noenable(q);
28440 		while ((mp = getq(q)) != NULL) {
28441 			ASSERT(CONN_Q(q));
28442 
28443 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28444 			if (connp->conn_did_putbq) {
28445 				/* ip_wput did a putbq */
28446 				break;
28447 			}
28448 		}
28449 		/*
28450 		 * At this point, a thread coming down from top, calling
28451 		 * ip_wput, may end up queueing the message. We have not yet
28452 		 * enabled the queue, so ip_wsrv won't be called again.
28453 		 * To avoid this race, check q->q_first again (in the loop)
28454 		 * If the other thread queued the message before we call
28455 		 * enableok(), we will catch it in the q->q_first check.
28456 		 * If the other thread queues the message after we call
28457 		 * enableok(), ip_wsrv will be called again by STREAMS.
28458 		 */
28459 		connp->conn_draining = 0;
28460 		enableok(q);
28461 	}
28462 
28463 	/* Enable the next conn for draining */
28464 	conn_drain_tail(connp, B_FALSE);
28465 
28466 	connp->conn_did_putbq = 0;
28467 }
28468 
28469 /*
28470  * Walk the list of all conn's calling the function provided with the
28471  * specified argument for each.	 Note that this only walks conn's that
28472  * have been bound.
28473  * Applies to both IPv4 and IPv6.
28474  */
28475 static void
28476 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28477 {
28478 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28479 	    ipst->ips_ipcl_udp_fanout_size,
28480 	    func, arg, zoneid);
28481 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28482 	    ipst->ips_ipcl_conn_fanout_size,
28483 	    func, arg, zoneid);
28484 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28485 	    ipst->ips_ipcl_bind_fanout_size,
28486 	    func, arg, zoneid);
28487 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28488 	    IPPROTO_MAX, func, arg, zoneid);
28489 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28490 	    IPPROTO_MAX, func, arg, zoneid);
28491 }
28492 
28493 /*
28494  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28495  * of conns that need to be drained, check if drain is already in progress.
28496  * If so set the idl_repeat bit, indicating that the last conn in the list
28497  * needs to reinitiate the drain once again, for the list. If drain is not
28498  * in progress for the list, initiate the draining, by qenabling the 1st
28499  * conn in the list. The drain is self-sustaining, each qenabled conn will
28500  * in turn qenable the next conn, when it is done/blocked/closing.
28501  */
28502 static void
28503 conn_walk_drain(ip_stack_t *ipst)
28504 {
28505 	int i;
28506 	idl_t *idl;
28507 
28508 	IP_STAT(ipst, ip_conn_walk_drain);
28509 
28510 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28511 		idl = &ipst->ips_conn_drain_list[i];
28512 		mutex_enter(&idl->idl_lock);
28513 		if (idl->idl_conn == NULL) {
28514 			mutex_exit(&idl->idl_lock);
28515 			continue;
28516 		}
28517 		/*
28518 		 * If this list is not being drained currently by
28519 		 * an ip_wsrv thread, start the process.
28520 		 */
28521 		if (idl->idl_conn_draining == NULL) {
28522 			ASSERT(idl->idl_repeat == 0);
28523 			qenable(idl->idl_conn->conn_wq);
28524 			idl->idl_conn_draining = idl->idl_conn;
28525 		} else {
28526 			idl->idl_repeat = 1;
28527 		}
28528 		mutex_exit(&idl->idl_lock);
28529 	}
28530 }
28531 
28532 /*
28533  * Walk an conn hash table of `count' buckets, calling func for each entry.
28534  */
28535 static void
28536 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28537     zoneid_t zoneid)
28538 {
28539 	conn_t	*connp;
28540 
28541 	while (count-- > 0) {
28542 		mutex_enter(&connfp->connf_lock);
28543 		for (connp = connfp->connf_head; connp != NULL;
28544 		    connp = connp->conn_next) {
28545 			if (zoneid == GLOBAL_ZONEID ||
28546 			    zoneid == connp->conn_zoneid) {
28547 				CONN_INC_REF(connp);
28548 				mutex_exit(&connfp->connf_lock);
28549 				(*func)(connp, arg);
28550 				mutex_enter(&connfp->connf_lock);
28551 				CONN_DEC_REF(connp);
28552 			}
28553 		}
28554 		mutex_exit(&connfp->connf_lock);
28555 		connfp++;
28556 	}
28557 }
28558 
28559 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28560 static void
28561 conn_report1(conn_t *connp, void *mp)
28562 {
28563 	char	buf1[INET6_ADDRSTRLEN];
28564 	char	buf2[INET6_ADDRSTRLEN];
28565 	uint_t	print_len, buf_len;
28566 
28567 	ASSERT(connp != NULL);
28568 
28569 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28570 	if (buf_len <= 0)
28571 		return;
28572 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28573 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28574 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28575 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28576 	    "%5d %s/%05d %s/%05d\n",
28577 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28578 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28579 	    buf1, connp->conn_lport,
28580 	    buf2, connp->conn_fport);
28581 	if (print_len < buf_len) {
28582 		((mblk_t *)mp)->b_wptr += print_len;
28583 	} else {
28584 		((mblk_t *)mp)->b_wptr += buf_len;
28585 	}
28586 }
28587 
28588 /*
28589  * Named Dispatch routine to produce a formatted report on all conns
28590  * that are listed in one of the fanout tables.
28591  * This report is accessed by using the ndd utility to "get" ND variable
28592  * "ip_conn_status".
28593  */
28594 /* ARGSUSED */
28595 static int
28596 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28597 {
28598 	conn_t *connp = Q_TO_CONN(q);
28599 
28600 	(void) mi_mpprintf(mp,
28601 	    "CONN      " MI_COL_HDRPAD_STR
28602 	    "rfq      " MI_COL_HDRPAD_STR
28603 	    "stq      " MI_COL_HDRPAD_STR
28604 	    " zone local                 remote");
28605 
28606 	/*
28607 	 * Because of the ndd constraint, at most we can have 64K buffer
28608 	 * to put in all conn info.  So to be more efficient, just
28609 	 * allocate a 64K buffer here, assuming we need that large buffer.
28610 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28611 	 */
28612 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28613 		/* The following may work even if we cannot get a large buf. */
28614 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28615 		return (0);
28616 	}
28617 
28618 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28619 	    connp->conn_netstack->netstack_ip);
28620 	return (0);
28621 }
28622 
28623 /*
28624  * Determine if the ill and multicast aspects of that packets
28625  * "matches" the conn.
28626  */
28627 boolean_t
28628 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28629     zoneid_t zoneid)
28630 {
28631 	ill_t *in_ill;
28632 	boolean_t found;
28633 	ipif_t *ipif;
28634 	ire_t *ire;
28635 	ipaddr_t dst, src;
28636 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28637 
28638 	dst = ipha->ipha_dst;
28639 	src = ipha->ipha_src;
28640 
28641 	/*
28642 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28643 	 * unicast, broadcast and multicast reception to
28644 	 * conn_incoming_ill. conn_wantpacket itself is called
28645 	 * only for BROADCAST and multicast.
28646 	 *
28647 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28648 	 *    is part of a group. Hence, we should be receiving
28649 	 *    just one copy of broadcast for the whole group.
28650 	 *    Thus, if it is part of the group the packet could
28651 	 *    come on any ill of the group and hence we need a
28652 	 *    match on the group. Otherwise, match on ill should
28653 	 *    be sufficient.
28654 	 *
28655 	 * 2) ip_rput does not suppress duplicate multicast packets.
28656 	 *    If there are two interfaces in a ill group and we have
28657 	 *    2 applications (conns) joined a multicast group G on
28658 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28659 	 *    will give us two packets because we join G on both the
28660 	 *    interfaces rather than nominating just one interface
28661 	 *    for receiving multicast like broadcast above. So,
28662 	 *    we have to call ilg_lookup_ill to filter out duplicate
28663 	 *    copies, if ill is part of a group.
28664 	 */
28665 	in_ill = connp->conn_incoming_ill;
28666 	if (in_ill != NULL) {
28667 		if (in_ill->ill_group == NULL) {
28668 			if (in_ill != ill)
28669 				return (B_FALSE);
28670 		} else if (in_ill->ill_group != ill->ill_group) {
28671 			return (B_FALSE);
28672 		}
28673 	}
28674 
28675 	if (!CLASSD(dst)) {
28676 		if (IPCL_ZONE_MATCH(connp, zoneid))
28677 			return (B_TRUE);
28678 		/*
28679 		 * The conn is in a different zone; we need to check that this
28680 		 * broadcast address is configured in the application's zone and
28681 		 * on one ill in the group.
28682 		 */
28683 		ipif = ipif_get_next_ipif(NULL, ill);
28684 		if (ipif == NULL)
28685 			return (B_FALSE);
28686 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28687 		    connp->conn_zoneid, NULL,
28688 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28689 		ipif_refrele(ipif);
28690 		if (ire != NULL) {
28691 			ire_refrele(ire);
28692 			return (B_TRUE);
28693 		} else {
28694 			return (B_FALSE);
28695 		}
28696 	}
28697 
28698 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28699 	    connp->conn_zoneid == zoneid) {
28700 		/*
28701 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28702 		 * disabled, therefore we don't dispatch the multicast packet to
28703 		 * the sending zone.
28704 		 */
28705 		return (B_FALSE);
28706 	}
28707 
28708 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28709 		/*
28710 		 * Multicast packet on the loopback interface: we only match
28711 		 * conns who joined the group in the specified zone.
28712 		 */
28713 		return (B_FALSE);
28714 	}
28715 
28716 	if (connp->conn_multi_router) {
28717 		/* multicast packet and multicast router socket: send up */
28718 		return (B_TRUE);
28719 	}
28720 
28721 	mutex_enter(&connp->conn_lock);
28722 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28723 	mutex_exit(&connp->conn_lock);
28724 	return (found);
28725 }
28726 
28727 /*
28728  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28729  */
28730 /* ARGSUSED */
28731 static void
28732 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28733 {
28734 	ill_t *ill = (ill_t *)q->q_ptr;
28735 	mblk_t	*mp1, *mp2;
28736 	ipif_t  *ipif;
28737 	int err = 0;
28738 	conn_t *connp = NULL;
28739 	ipsq_t	*ipsq;
28740 	arc_t	*arc;
28741 
28742 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28743 
28744 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28745 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28746 
28747 	ASSERT(IAM_WRITER_ILL(ill));
28748 	mp2 = mp->b_cont;
28749 	mp->b_cont = NULL;
28750 
28751 	/*
28752 	 * We have now received the arp bringup completion message
28753 	 * from ARP. Mark the arp bringup as done. Also if the arp
28754 	 * stream has already started closing, send up the AR_ARP_CLOSING
28755 	 * ack now since ARP is waiting in close for this ack.
28756 	 */
28757 	mutex_enter(&ill->ill_lock);
28758 	ill->ill_arp_bringup_pending = 0;
28759 	if (ill->ill_arp_closing) {
28760 		mutex_exit(&ill->ill_lock);
28761 		/* Let's reuse the mp for sending the ack */
28762 		arc = (arc_t *)mp->b_rptr;
28763 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28764 		arc->arc_cmd = AR_ARP_CLOSING;
28765 		qreply(q, mp);
28766 	} else {
28767 		mutex_exit(&ill->ill_lock);
28768 		freeb(mp);
28769 	}
28770 
28771 	ipsq = ill->ill_phyint->phyint_ipsq;
28772 	ipif = ipsq->ipsq_pending_ipif;
28773 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28774 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28775 	if (mp1 == NULL) {
28776 		/* bringup was aborted by the user */
28777 		freemsg(mp2);
28778 		return;
28779 	}
28780 
28781 	/*
28782 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28783 	 * must have an associated conn_t.  Otherwise, we're bringing this
28784 	 * interface back up as part of handling an asynchronous event (e.g.,
28785 	 * physical address change).
28786 	 */
28787 	if (ipsq->ipsq_current_ioctl != 0) {
28788 		ASSERT(connp != NULL);
28789 		q = CONNP_TO_WQ(connp);
28790 	} else {
28791 		ASSERT(connp == NULL);
28792 		q = ill->ill_rq;
28793 	}
28794 
28795 	/*
28796 	 * If the DL_BIND_REQ fails, it is noted
28797 	 * in arc_name_offset.
28798 	 */
28799 	err = *((int *)mp2->b_rptr);
28800 	if (err == 0) {
28801 		if (ipif->ipif_isv6) {
28802 			if ((err = ipif_up_done_v6(ipif)) != 0)
28803 				ip0dbg(("ip_arp_done: init failed\n"));
28804 		} else {
28805 			if ((err = ipif_up_done(ipif)) != 0)
28806 				ip0dbg(("ip_arp_done: init failed\n"));
28807 		}
28808 	} else {
28809 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28810 	}
28811 
28812 	freemsg(mp2);
28813 
28814 	if ((err == 0) && (ill->ill_up_ipifs)) {
28815 		err = ill_up_ipifs(ill, q, mp1);
28816 		if (err == EINPROGRESS)
28817 			return;
28818 	}
28819 
28820 	if (ill->ill_up_ipifs)
28821 		ill_group_cleanup(ill);
28822 
28823 	/*
28824 	 * The operation must complete without EINPROGRESS since
28825 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28826 	 * Otherwise, the operation will be stuck forever in the ipsq.
28827 	 */
28828 	ASSERT(err != EINPROGRESS);
28829 	if (ipsq->ipsq_current_ioctl != 0)
28830 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28831 	else
28832 		ipsq_current_finish(ipsq);
28833 }
28834 
28835 /* Allocate the private structure */
28836 static int
28837 ip_priv_alloc(void **bufp)
28838 {
28839 	void	*buf;
28840 
28841 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28842 		return (ENOMEM);
28843 
28844 	*bufp = buf;
28845 	return (0);
28846 }
28847 
28848 /* Function to delete the private structure */
28849 void
28850 ip_priv_free(void *buf)
28851 {
28852 	ASSERT(buf != NULL);
28853 	kmem_free(buf, sizeof (ip_priv_t));
28854 }
28855 
28856 /*
28857  * The entry point for IPPF processing.
28858  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28859  * routine just returns.
28860  *
28861  * When called, ip_process generates an ipp_packet_t structure
28862  * which holds the state information for this packet and invokes the
28863  * the classifier (via ipp_packet_process). The classification, depending on
28864  * configured filters, results in a list of actions for this packet. Invoking
28865  * an action may cause the packet to be dropped, in which case the resulting
28866  * mblk (*mpp) is NULL. proc indicates the callout position for
28867  * this packet and ill_index is the interface this packet on or will leave
28868  * on (inbound and outbound resp.).
28869  */
28870 void
28871 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28872 {
28873 	mblk_t		*mp;
28874 	ip_priv_t	*priv;
28875 	ipp_action_id_t	aid;
28876 	int		rc = 0;
28877 	ipp_packet_t	*pp;
28878 #define	IP_CLASS	"ip"
28879 
28880 	/* If the classifier is not loaded, return  */
28881 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28882 		return;
28883 	}
28884 
28885 	mp = *mpp;
28886 	ASSERT(mp != NULL);
28887 
28888 	/* Allocate the packet structure */
28889 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28890 	if (rc != 0) {
28891 		*mpp = NULL;
28892 		freemsg(mp);
28893 		return;
28894 	}
28895 
28896 	/* Allocate the private structure */
28897 	rc = ip_priv_alloc((void **)&priv);
28898 	if (rc != 0) {
28899 		*mpp = NULL;
28900 		freemsg(mp);
28901 		ipp_packet_free(pp);
28902 		return;
28903 	}
28904 	priv->proc = proc;
28905 	priv->ill_index = ill_index;
28906 	ipp_packet_set_private(pp, priv, ip_priv_free);
28907 	ipp_packet_set_data(pp, mp);
28908 
28909 	/* Invoke the classifier */
28910 	rc = ipp_packet_process(&pp);
28911 	if (pp != NULL) {
28912 		mp = ipp_packet_get_data(pp);
28913 		ipp_packet_free(pp);
28914 		if (rc != 0) {
28915 			freemsg(mp);
28916 			*mpp = NULL;
28917 		}
28918 	} else {
28919 		*mpp = NULL;
28920 	}
28921 #undef	IP_CLASS
28922 }
28923 
28924 /*
28925  * Propagate a multicast group membership operation (add/drop) on
28926  * all the interfaces crossed by the related multirt routes.
28927  * The call is considered successful if the operation succeeds
28928  * on at least one interface.
28929  */
28930 static int
28931 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28932     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28933     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28934     mblk_t *first_mp)
28935 {
28936 	ire_t		*ire_gw;
28937 	irb_t		*irb;
28938 	int		error = 0;
28939 	opt_restart_t	*or;
28940 	ip_stack_t	*ipst = ire->ire_ipst;
28941 
28942 	irb = ire->ire_bucket;
28943 	ASSERT(irb != NULL);
28944 
28945 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28946 
28947 	or = (opt_restart_t *)first_mp->b_rptr;
28948 	IRB_REFHOLD(irb);
28949 	for (; ire != NULL; ire = ire->ire_next) {
28950 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28951 			continue;
28952 		if (ire->ire_addr != group)
28953 			continue;
28954 
28955 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28956 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28957 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28958 		/* No resolver exists for the gateway; skip this ire. */
28959 		if (ire_gw == NULL)
28960 			continue;
28961 
28962 		/*
28963 		 * This function can return EINPROGRESS. If so the operation
28964 		 * will be restarted from ip_restart_optmgmt which will
28965 		 * call ip_opt_set and option processing will restart for
28966 		 * this option. So we may end up calling 'fn' more than once.
28967 		 * This requires that 'fn' is idempotent except for the
28968 		 * return value. The operation is considered a success if
28969 		 * it succeeds at least once on any one interface.
28970 		 */
28971 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28972 		    NULL, fmode, src, first_mp);
28973 		if (error == 0)
28974 			or->or_private = CGTP_MCAST_SUCCESS;
28975 
28976 		if (ip_debug > 0) {
28977 			ulong_t	off;
28978 			char	*ksym;
28979 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28980 			ip2dbg(("ip_multirt_apply_membership: "
28981 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28982 			    "error %d [success %u]\n",
28983 			    ksym ? ksym : "?",
28984 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28985 			    error, or->or_private));
28986 		}
28987 
28988 		ire_refrele(ire_gw);
28989 		if (error == EINPROGRESS) {
28990 			IRB_REFRELE(irb);
28991 			return (error);
28992 		}
28993 	}
28994 	IRB_REFRELE(irb);
28995 	/*
28996 	 * Consider the call as successful if we succeeded on at least
28997 	 * one interface. Otherwise, return the last encountered error.
28998 	 */
28999 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
29000 }
29001 
29002 
29003 /*
29004  * Issue a warning regarding a route crossing an interface with an
29005  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
29006  * amount of time is logged.
29007  */
29008 static void
29009 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
29010 {
29011 	hrtime_t	current = gethrtime();
29012 	char		buf[INET_ADDRSTRLEN];
29013 	ip_stack_t	*ipst = ire->ire_ipst;
29014 
29015 	/* Convert interval in ms to hrtime in ns */
29016 	if (ipst->ips_multirt_bad_mtu_last_time +
29017 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
29018 	    current) {
29019 		cmn_err(CE_WARN, "ip: ignoring multiroute "
29020 		    "to %s, incorrect MTU %u (expected %u)\n",
29021 		    ip_dot_addr(ire->ire_addr, buf),
29022 		    ire->ire_max_frag, max_frag);
29023 
29024 		ipst->ips_multirt_bad_mtu_last_time = current;
29025 	}
29026 }
29027 
29028 
29029 /*
29030  * Get the CGTP (multirouting) filtering status.
29031  * If 0, the CGTP hooks are transparent.
29032  */
29033 /* ARGSUSED */
29034 static int
29035 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
29036 {
29037 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29038 
29039 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
29040 	return (0);
29041 }
29042 
29043 
29044 /*
29045  * Set the CGTP (multirouting) filtering status.
29046  * If the status is changed from active to transparent
29047  * or from transparent to active, forward the new status
29048  * to the filtering module (if loaded).
29049  */
29050 /* ARGSUSED */
29051 static int
29052 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29053     cred_t *ioc_cr)
29054 {
29055 	long		new_value;
29056 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29057 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29058 
29059 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29060 		return (EPERM);
29061 
29062 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29063 	    new_value < 0 || new_value > 1) {
29064 		return (EINVAL);
29065 	}
29066 
29067 	if ((!*ip_cgtp_filter_value) && new_value) {
29068 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29069 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29070 		    " (module not loaded)" : "");
29071 	}
29072 	if (*ip_cgtp_filter_value && (!new_value)) {
29073 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29074 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29075 		    " (module not loaded)" : "");
29076 	}
29077 
29078 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29079 		int	res;
29080 		netstackid_t stackid;
29081 
29082 		stackid = ipst->ips_netstack->netstack_stackid;
29083 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29084 		    new_value);
29085 		if (res)
29086 			return (res);
29087 	}
29088 
29089 	*ip_cgtp_filter_value = (boolean_t)new_value;
29090 
29091 	return (0);
29092 }
29093 
29094 
29095 /*
29096  * Return the expected CGTP hooks version number.
29097  */
29098 int
29099 ip_cgtp_filter_supported(void)
29100 {
29101 	return (ip_cgtp_filter_rev);
29102 }
29103 
29104 
29105 /*
29106  * CGTP hooks can be registered by invoking this function.
29107  * Checks that the version number matches.
29108  */
29109 int
29110 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29111 {
29112 	netstack_t *ns;
29113 	ip_stack_t *ipst;
29114 
29115 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29116 		return (ENOTSUP);
29117 
29118 	ns = netstack_find_by_stackid(stackid);
29119 	if (ns == NULL)
29120 		return (EINVAL);
29121 	ipst = ns->netstack_ip;
29122 	ASSERT(ipst != NULL);
29123 
29124 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29125 		netstack_rele(ns);
29126 		return (EALREADY);
29127 	}
29128 
29129 	ipst->ips_ip_cgtp_filter_ops = ops;
29130 	netstack_rele(ns);
29131 	return (0);
29132 }
29133 
29134 /*
29135  * CGTP hooks can be unregistered by invoking this function.
29136  * Returns ENXIO if there was no registration.
29137  * Returns EBUSY if the ndd variable has not been turned off.
29138  */
29139 int
29140 ip_cgtp_filter_unregister(netstackid_t stackid)
29141 {
29142 	netstack_t *ns;
29143 	ip_stack_t *ipst;
29144 
29145 	ns = netstack_find_by_stackid(stackid);
29146 	if (ns == NULL)
29147 		return (EINVAL);
29148 	ipst = ns->netstack_ip;
29149 	ASSERT(ipst != NULL);
29150 
29151 	if (ipst->ips_ip_cgtp_filter) {
29152 		netstack_rele(ns);
29153 		return (EBUSY);
29154 	}
29155 
29156 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29157 		netstack_rele(ns);
29158 		return (ENXIO);
29159 	}
29160 	ipst->ips_ip_cgtp_filter_ops = NULL;
29161 	netstack_rele(ns);
29162 	return (0);
29163 }
29164 
29165 /*
29166  * Check whether there is a CGTP filter registration.
29167  * Returns non-zero if there is a registration, otherwise returns zero.
29168  * Note: returns zero if bad stackid.
29169  */
29170 int
29171 ip_cgtp_filter_is_registered(netstackid_t stackid)
29172 {
29173 	netstack_t *ns;
29174 	ip_stack_t *ipst;
29175 	int ret;
29176 
29177 	ns = netstack_find_by_stackid(stackid);
29178 	if (ns == NULL)
29179 		return (0);
29180 	ipst = ns->netstack_ip;
29181 	ASSERT(ipst != NULL);
29182 
29183 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29184 		ret = 1;
29185 	else
29186 		ret = 0;
29187 
29188 	netstack_rele(ns);
29189 	return (ret);
29190 }
29191 
29192 static squeue_func_t
29193 ip_squeue_switch(int val)
29194 {
29195 	squeue_func_t rval = squeue_fill;
29196 
29197 	switch (val) {
29198 	case IP_SQUEUE_ENTER_NODRAIN:
29199 		rval = squeue_enter_nodrain;
29200 		break;
29201 	case IP_SQUEUE_ENTER:
29202 		rval = squeue_enter;
29203 		break;
29204 	default:
29205 		break;
29206 	}
29207 	return (rval);
29208 }
29209 
29210 /* ARGSUSED */
29211 static int
29212 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29213     caddr_t addr, cred_t *cr)
29214 {
29215 	int *v = (int *)addr;
29216 	long new_value;
29217 
29218 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29219 		return (EPERM);
29220 
29221 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29222 		return (EINVAL);
29223 
29224 	ip_input_proc = ip_squeue_switch(new_value);
29225 	*v = new_value;
29226 	return (0);
29227 }
29228 
29229 /*
29230  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29231  * ip_debug.
29232  */
29233 /* ARGSUSED */
29234 static int
29235 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29236     caddr_t addr, cred_t *cr)
29237 {
29238 	int *v = (int *)addr;
29239 	long new_value;
29240 
29241 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29242 		return (EPERM);
29243 
29244 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29245 		return (EINVAL);
29246 
29247 	*v = new_value;
29248 	return (0);
29249 }
29250 
29251 /*
29252  * Handle changes to ipmp_hook_emulation ndd variable.
29253  * Need to update phyint_hook_ifindex.
29254  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29255  */
29256 static void
29257 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29258 {
29259 	phyint_t *phyi;
29260 	phyint_t *phyi_tmp;
29261 	char *groupname;
29262 	int namelen;
29263 	ill_t	*ill;
29264 	boolean_t new_group;
29265 
29266 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29267 	/*
29268 	 * Group indicies are stored in the phyint - a common structure
29269 	 * to both IPv4 and IPv6.
29270 	 */
29271 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29272 	for (; phyi != NULL;
29273 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29274 	    phyi, AVL_AFTER)) {
29275 		/* Ignore the ones that do not have a group */
29276 		if (phyi->phyint_groupname_len == 0)
29277 			continue;
29278 
29279 		/*
29280 		 * Look for other phyint in group.
29281 		 * Clear name/namelen so the lookup doesn't find ourselves.
29282 		 */
29283 		namelen = phyi->phyint_groupname_len;
29284 		groupname = phyi->phyint_groupname;
29285 		phyi->phyint_groupname_len = 0;
29286 		phyi->phyint_groupname = NULL;
29287 
29288 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29289 		/* Restore */
29290 		phyi->phyint_groupname_len = namelen;
29291 		phyi->phyint_groupname = groupname;
29292 
29293 		new_group = B_FALSE;
29294 		if (ipst->ips_ipmp_hook_emulation) {
29295 			/*
29296 			 * If the group already exists and has already
29297 			 * been assigned a group ifindex, we use the existing
29298 			 * group_ifindex, otherwise we pick a new group_ifindex
29299 			 * here.
29300 			 */
29301 			if (phyi_tmp != NULL &&
29302 			    phyi_tmp->phyint_group_ifindex != 0) {
29303 				phyi->phyint_group_ifindex =
29304 				    phyi_tmp->phyint_group_ifindex;
29305 			} else {
29306 				/* XXX We need a recovery strategy here. */
29307 				if (!ip_assign_ifindex(
29308 				    &phyi->phyint_group_ifindex, ipst))
29309 					cmn_err(CE_PANIC,
29310 					    "ip_assign_ifindex() failed");
29311 				new_group = B_TRUE;
29312 			}
29313 		} else {
29314 			phyi->phyint_group_ifindex = 0;
29315 		}
29316 		if (ipst->ips_ipmp_hook_emulation)
29317 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29318 		else
29319 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29320 
29321 		/*
29322 		 * For IP Filter to find out the relationship between
29323 		 * names and interface indicies, we need to generate
29324 		 * a NE_PLUMB event when a new group can appear.
29325 		 * We always generate events when a new interface appears
29326 		 * (even when ipmp_hook_emulation is set) so there
29327 		 * is no need to generate NE_PLUMB events when
29328 		 * ipmp_hook_emulation is turned off.
29329 		 * And since it isn't critical for IP Filter to get
29330 		 * the NE_UNPLUMB events we skip those here.
29331 		 */
29332 		if (new_group) {
29333 			/*
29334 			 * First phyint in group - generate group PLUMB event.
29335 			 * Since we are not running inside the ipsq we do
29336 			 * the dispatch immediately.
29337 			 */
29338 			if (phyi->phyint_illv4 != NULL)
29339 				ill = phyi->phyint_illv4;
29340 			else
29341 				ill = phyi->phyint_illv6;
29342 
29343 			if (ill != NULL) {
29344 				mutex_enter(&ill->ill_lock);
29345 				ill_nic_info_plumb(ill, B_TRUE);
29346 				ill_nic_info_dispatch(ill);
29347 				mutex_exit(&ill->ill_lock);
29348 			}
29349 		}
29350 	}
29351 	rw_exit(&ipst->ips_ill_g_lock);
29352 }
29353 
29354 /* ARGSUSED */
29355 static int
29356 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29357     caddr_t addr, cred_t *cr)
29358 {
29359 	int *v = (int *)addr;
29360 	long new_value;
29361 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29362 
29363 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29364 		return (EINVAL);
29365 
29366 	if (*v != new_value) {
29367 		*v = new_value;
29368 		ipmp_hook_emulation_changed(ipst);
29369 	}
29370 	return (0);
29371 }
29372 
29373 static void *
29374 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29375 {
29376 	kstat_t *ksp;
29377 
29378 	ip_stat_t template = {
29379 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29380 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29381 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29382 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29383 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29384 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29385 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29386 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29387 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29388 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29389 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29390 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29391 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29392 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29393 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29394 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29395 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29396 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29397 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29398 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29399 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29400 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29401 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29402 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29403 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29404 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29405 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29406 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29407 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29408 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29409 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29410 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29411 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29412 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29413 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29414 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29415 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29416 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29417 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29418 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29419 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29420 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29421 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29422 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29423 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29424 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29425 	};
29426 
29427 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29428 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29429 	    KSTAT_FLAG_VIRTUAL, stackid);
29430 
29431 	if (ksp == NULL)
29432 		return (NULL);
29433 
29434 	bcopy(&template, ip_statisticsp, sizeof (template));
29435 	ksp->ks_data = (void *)ip_statisticsp;
29436 	ksp->ks_private = (void *)(uintptr_t)stackid;
29437 
29438 	kstat_install(ksp);
29439 	return (ksp);
29440 }
29441 
29442 static void
29443 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29444 {
29445 	if (ksp != NULL) {
29446 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29447 		kstat_delete_netstack(ksp, stackid);
29448 	}
29449 }
29450 
29451 static void *
29452 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29453 {
29454 	kstat_t	*ksp;
29455 
29456 	ip_named_kstat_t template = {
29457 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29458 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29459 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29460 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29461 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29462 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29463 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29464 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29465 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29466 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29467 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29468 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29469 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29470 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29471 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29472 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29473 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29474 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29475 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29476 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29477 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29478 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29479 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29480 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29481 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29482 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29483 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29484 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29485 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29486 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29487 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29488 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29489 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29490 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29491 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29492 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29493 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29494 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29495 	};
29496 
29497 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29498 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29499 	if (ksp == NULL || ksp->ks_data == NULL)
29500 		return (NULL);
29501 
29502 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29503 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29504 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29505 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29506 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29507 
29508 	template.netToMediaEntrySize.value.i32 =
29509 	    sizeof (mib2_ipNetToMediaEntry_t);
29510 
29511 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29512 
29513 	bcopy(&template, ksp->ks_data, sizeof (template));
29514 	ksp->ks_update = ip_kstat_update;
29515 	ksp->ks_private = (void *)(uintptr_t)stackid;
29516 
29517 	kstat_install(ksp);
29518 	return (ksp);
29519 }
29520 
29521 static void
29522 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29523 {
29524 	if (ksp != NULL) {
29525 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29526 		kstat_delete_netstack(ksp, stackid);
29527 	}
29528 }
29529 
29530 static int
29531 ip_kstat_update(kstat_t *kp, int rw)
29532 {
29533 	ip_named_kstat_t *ipkp;
29534 	mib2_ipIfStatsEntry_t ipmib;
29535 	ill_walk_context_t ctx;
29536 	ill_t *ill;
29537 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29538 	netstack_t	*ns;
29539 	ip_stack_t	*ipst;
29540 
29541 	if (kp == NULL || kp->ks_data == NULL)
29542 		return (EIO);
29543 
29544 	if (rw == KSTAT_WRITE)
29545 		return (EACCES);
29546 
29547 	ns = netstack_find_by_stackid(stackid);
29548 	if (ns == NULL)
29549 		return (-1);
29550 	ipst = ns->netstack_ip;
29551 	if (ipst == NULL) {
29552 		netstack_rele(ns);
29553 		return (-1);
29554 	}
29555 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29556 
29557 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29558 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29559 	ill = ILL_START_WALK_V4(&ctx, ipst);
29560 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29561 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29562 	rw_exit(&ipst->ips_ill_g_lock);
29563 
29564 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29565 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29566 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29567 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29568 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29569 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29570 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29571 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29572 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29573 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29574 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29575 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29576 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29577 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29578 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29579 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29580 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29581 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29582 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29583 
29584 	ipkp->routingDiscards.value.ui32 =	0;
29585 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29586 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29587 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29588 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29589 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29590 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29591 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29592 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29593 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29594 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29595 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29596 
29597 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29598 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29599 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29600 
29601 	netstack_rele(ns);
29602 
29603 	return (0);
29604 }
29605 
29606 static void *
29607 icmp_kstat_init(netstackid_t stackid)
29608 {
29609 	kstat_t	*ksp;
29610 
29611 	icmp_named_kstat_t template = {
29612 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29613 		{ "inErrors",		KSTAT_DATA_UINT32 },
29614 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29615 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29616 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29617 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29618 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29619 		{ "inEchos",		KSTAT_DATA_UINT32 },
29620 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29621 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29622 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29623 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29624 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29625 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29626 		{ "outErrors",		KSTAT_DATA_UINT32 },
29627 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29628 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29629 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29630 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29631 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29632 		{ "outEchos",		KSTAT_DATA_UINT32 },
29633 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29634 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29635 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29636 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29637 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29638 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29639 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29640 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29641 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29642 		{ "outDrops",		KSTAT_DATA_UINT32 },
29643 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29644 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29645 	};
29646 
29647 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29648 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29649 	if (ksp == NULL || ksp->ks_data == NULL)
29650 		return (NULL);
29651 
29652 	bcopy(&template, ksp->ks_data, sizeof (template));
29653 
29654 	ksp->ks_update = icmp_kstat_update;
29655 	ksp->ks_private = (void *)(uintptr_t)stackid;
29656 
29657 	kstat_install(ksp);
29658 	return (ksp);
29659 }
29660 
29661 static void
29662 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29663 {
29664 	if (ksp != NULL) {
29665 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29666 		kstat_delete_netstack(ksp, stackid);
29667 	}
29668 }
29669 
29670 static int
29671 icmp_kstat_update(kstat_t *kp, int rw)
29672 {
29673 	icmp_named_kstat_t *icmpkp;
29674 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29675 	netstack_t	*ns;
29676 	ip_stack_t	*ipst;
29677 
29678 	if ((kp == NULL) || (kp->ks_data == NULL))
29679 		return (EIO);
29680 
29681 	if (rw == KSTAT_WRITE)
29682 		return (EACCES);
29683 
29684 	ns = netstack_find_by_stackid(stackid);
29685 	if (ns == NULL)
29686 		return (-1);
29687 	ipst = ns->netstack_ip;
29688 	if (ipst == NULL) {
29689 		netstack_rele(ns);
29690 		return (-1);
29691 	}
29692 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29693 
29694 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29695 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29696 	icmpkp->inDestUnreachs.value.ui32 =
29697 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29698 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29699 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29700 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29701 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29702 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29703 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29704 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29705 	icmpkp->inTimestampReps.value.ui32 =
29706 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29707 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29708 	icmpkp->inAddrMaskReps.value.ui32 =
29709 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29710 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29711 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29712 	icmpkp->outDestUnreachs.value.ui32 =
29713 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29714 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29715 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29716 	icmpkp->outSrcQuenchs.value.ui32 =
29717 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29718 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29719 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29720 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29721 	icmpkp->outTimestamps.value.ui32 =
29722 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29723 	icmpkp->outTimestampReps.value.ui32 =
29724 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29725 	icmpkp->outAddrMasks.value.ui32 =
29726 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29727 	icmpkp->outAddrMaskReps.value.ui32 =
29728 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29729 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29730 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29731 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29732 	icmpkp->outFragNeeded.value.ui32 =
29733 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29734 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29735 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29736 	icmpkp->inBadRedirects.value.ui32 =
29737 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29738 
29739 	netstack_rele(ns);
29740 	return (0);
29741 }
29742 
29743 /*
29744  * This is the fanout function for raw socket opened for SCTP.  Note
29745  * that it is called after SCTP checks that there is no socket which
29746  * wants a packet.  Then before SCTP handles this out of the blue packet,
29747  * this function is called to see if there is any raw socket for SCTP.
29748  * If there is and it is bound to the correct address, the packet will
29749  * be sent to that socket.  Note that only one raw socket can be bound to
29750  * a port.  This is assured in ipcl_sctp_hash_insert();
29751  */
29752 void
29753 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29754     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29755     zoneid_t zoneid)
29756 {
29757 	conn_t		*connp;
29758 	queue_t		*rq;
29759 	mblk_t		*first_mp;
29760 	boolean_t	secure;
29761 	ip6_t		*ip6h;
29762 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29763 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29764 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29765 	boolean_t	sctp_csum_err = B_FALSE;
29766 
29767 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29768 		sctp_csum_err = B_TRUE;
29769 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29770 	}
29771 
29772 	first_mp = mp;
29773 	if (mctl_present) {
29774 		mp = first_mp->b_cont;
29775 		secure = ipsec_in_is_secure(first_mp);
29776 		ASSERT(mp != NULL);
29777 	} else {
29778 		secure = B_FALSE;
29779 	}
29780 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29781 
29782 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29783 	if (connp == NULL) {
29784 		/*
29785 		 * Although raw sctp is not summed, OOB chunks must be.
29786 		 * Drop the packet here if the sctp checksum failed.
29787 		 */
29788 		if (sctp_csum_err) {
29789 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29790 			freemsg(first_mp);
29791 			return;
29792 		}
29793 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29794 		return;
29795 	}
29796 	rq = connp->conn_rq;
29797 	if (!canputnext(rq)) {
29798 		CONN_DEC_REF(connp);
29799 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29800 		freemsg(first_mp);
29801 		return;
29802 	}
29803 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29804 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29805 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29806 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29807 		if (first_mp == NULL) {
29808 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29809 			CONN_DEC_REF(connp);
29810 			return;
29811 		}
29812 	}
29813 	/*
29814 	 * We probably should not send M_CTL message up to
29815 	 * raw socket.
29816 	 */
29817 	if (mctl_present)
29818 		freeb(first_mp);
29819 
29820 	/* Initiate IPPF processing here if needed. */
29821 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29822 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29823 		ip_process(IPP_LOCAL_IN, &mp,
29824 		    recv_ill->ill_phyint->phyint_ifindex);
29825 		if (mp == NULL) {
29826 			CONN_DEC_REF(connp);
29827 			return;
29828 		}
29829 	}
29830 
29831 	if (connp->conn_recvif || connp->conn_recvslla ||
29832 	    ((connp->conn_ip_recvpktinfo ||
29833 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29834 	    (flags & IP_FF_IPINFO))) {
29835 		int in_flags = 0;
29836 
29837 		/*
29838 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29839 		 * IPF_RECVIF.
29840 		 */
29841 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29842 			in_flags = IPF_RECVIF;
29843 		}
29844 		if (connp->conn_recvslla) {
29845 			in_flags |= IPF_RECVSLLA;
29846 		}
29847 		if (isv4) {
29848 			mp = ip_add_info(mp, recv_ill, in_flags,
29849 			    IPCL_ZONEID(connp), ipst);
29850 		} else {
29851 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29852 			if (mp == NULL) {
29853 				BUMP_MIB(recv_ill->ill_ip_mib,
29854 				    ipIfStatsInDiscards);
29855 				CONN_DEC_REF(connp);
29856 				return;
29857 			}
29858 		}
29859 	}
29860 
29861 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29862 	/*
29863 	 * We are sending the IPSEC_IN message also up. Refer
29864 	 * to comments above this function.
29865 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29866 	 */
29867 	(connp->conn_recv)(connp, mp, NULL);
29868 	CONN_DEC_REF(connp);
29869 }
29870 
29871 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29872 {									\
29873 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29874 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29875 }
29876 /*
29877  * This function should be called only if all packet processing
29878  * including fragmentation is complete. Callers of this function
29879  * must set mp->b_prev to one of these values:
29880  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29881  * prior to handing over the mp as first argument to this function.
29882  *
29883  * If the ire passed by caller is incomplete, this function
29884  * queues the packet and if necessary, sends ARP request and bails.
29885  * If the ire passed is fully resolved, we simply prepend
29886  * the link-layer header to the packet, do ipsec hw acceleration
29887  * work if necessary, and send the packet out on the wire.
29888  *
29889  * NOTE: IPsec will only call this function with fully resolved
29890  * ires if hw acceleration is involved.
29891  * TODO list :
29892  * 	a Handle M_MULTIDATA so that
29893  *	  tcp_multisend->tcp_multisend_data can
29894  *	  call ip_xmit_v4 directly
29895  *	b Handle post-ARP work for fragments so that
29896  *	  ip_wput_frag can call this function.
29897  */
29898 ipxmit_state_t
29899 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29900 {
29901 	nce_t		*arpce;
29902 	ipha_t		*ipha;
29903 	queue_t		*q;
29904 	int		ill_index;
29905 	mblk_t		*nxt_mp, *first_mp;
29906 	boolean_t	xmit_drop = B_FALSE;
29907 	ip_proc_t	proc;
29908 	ill_t		*out_ill;
29909 	int		pkt_len;
29910 
29911 	arpce = ire->ire_nce;
29912 	ASSERT(arpce != NULL);
29913 
29914 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29915 
29916 	mutex_enter(&arpce->nce_lock);
29917 	switch (arpce->nce_state) {
29918 	case ND_REACHABLE:
29919 		/* If there are other queued packets, queue this packet */
29920 		if (arpce->nce_qd_mp != NULL) {
29921 			if (mp != NULL)
29922 				nce_queue_mp_common(arpce, mp, B_FALSE);
29923 			mp = arpce->nce_qd_mp;
29924 		}
29925 		arpce->nce_qd_mp = NULL;
29926 		mutex_exit(&arpce->nce_lock);
29927 
29928 		/*
29929 		 * Flush the queue.  In the common case, where the
29930 		 * ARP is already resolved,  it will go through the
29931 		 * while loop only once.
29932 		 */
29933 		while (mp != NULL) {
29934 
29935 			nxt_mp = mp->b_next;
29936 			mp->b_next = NULL;
29937 			ASSERT(mp->b_datap->db_type != M_CTL);
29938 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29939 			/*
29940 			 * This info is needed for IPQOS to do COS marking
29941 			 * in ip_wput_attach_llhdr->ip_process.
29942 			 */
29943 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29944 			mp->b_prev = NULL;
29945 
29946 			/* set up ill index for outbound qos processing */
29947 			out_ill = ire_to_ill(ire);
29948 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29949 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29950 			    ill_index, &ipha);
29951 			if (first_mp == NULL) {
29952 				xmit_drop = B_TRUE;
29953 				BUMP_MIB(out_ill->ill_ip_mib,
29954 				    ipIfStatsOutDiscards);
29955 				goto next_mp;
29956 			}
29957 
29958 			/* non-ipsec hw accel case */
29959 			if (io == NULL || !io->ipsec_out_accelerated) {
29960 				/* send it */
29961 				q = ire->ire_stq;
29962 				if (proc == IPP_FWD_OUT) {
29963 					UPDATE_IB_PKT_COUNT(ire);
29964 				} else {
29965 					UPDATE_OB_PKT_COUNT(ire);
29966 				}
29967 				ire->ire_last_used_time = lbolt;
29968 
29969 				if (flow_ctl_enabled || canputnext(q)) {
29970 					if (proc == IPP_FWD_OUT) {
29971 
29972 					BUMP_MIB(out_ill->ill_ip_mib,
29973 					    ipIfStatsHCOutForwDatagrams);
29974 
29975 					}
29976 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29977 					    pkt_len);
29978 
29979 					DTRACE_IP7(send, mblk_t *, first_mp,
29980 					    conn_t *, NULL, void_ip_t *, ipha,
29981 					    __dtrace_ipsr_ill_t *, out_ill,
29982 					    ipha_t *, ipha, ip6_t *, NULL, int,
29983 					    0);
29984 
29985 					putnext(q, first_mp);
29986 				} else {
29987 					BUMP_MIB(out_ill->ill_ip_mib,
29988 					    ipIfStatsOutDiscards);
29989 					xmit_drop = B_TRUE;
29990 					freemsg(first_mp);
29991 				}
29992 			} else {
29993 				/*
29994 				 * Safety Pup says: make sure this
29995 				 *  is going to the right interface!
29996 				 */
29997 				ill_t *ill1 =
29998 				    (ill_t *)ire->ire_stq->q_ptr;
29999 				int ifindex =
30000 				    ill1->ill_phyint->phyint_ifindex;
30001 				if (ifindex !=
30002 				    io->ipsec_out_capab_ill_index) {
30003 					xmit_drop = B_TRUE;
30004 					freemsg(mp);
30005 				} else {
30006 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
30007 					    pkt_len);
30008 
30009 					DTRACE_IP7(send, mblk_t *, first_mp,
30010 					    conn_t *, NULL, void_ip_t *, ipha,
30011 					    __dtrace_ipsr_ill_t *, ill1,
30012 					    ipha_t *, ipha, ip6_t *, NULL,
30013 					    int, 0);
30014 
30015 					ipsec_hw_putnext(ire->ire_stq, mp);
30016 				}
30017 			}
30018 next_mp:
30019 			mp = nxt_mp;
30020 		} /* while (mp != NULL) */
30021 		if (xmit_drop)
30022 			return (SEND_FAILED);
30023 		else
30024 			return (SEND_PASSED);
30025 
30026 	case ND_INITIAL:
30027 	case ND_INCOMPLETE:
30028 
30029 		/*
30030 		 * While we do send off packets to dests that
30031 		 * use fully-resolved CGTP routes, we do not
30032 		 * handle unresolved CGTP routes.
30033 		 */
30034 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
30035 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
30036 
30037 		if (mp != NULL) {
30038 			/* queue the packet */
30039 			nce_queue_mp_common(arpce, mp, B_FALSE);
30040 		}
30041 
30042 		if (arpce->nce_state == ND_INCOMPLETE) {
30043 			mutex_exit(&arpce->nce_lock);
30044 			DTRACE_PROBE3(ip__xmit__incomplete,
30045 			    (ire_t *), ire, (mblk_t *), mp,
30046 			    (ipsec_out_t *), io);
30047 			return (LOOKUP_IN_PROGRESS);
30048 		}
30049 
30050 		arpce->nce_state = ND_INCOMPLETE;
30051 		mutex_exit(&arpce->nce_lock);
30052 		/*
30053 		 * Note that ire_add() (called from ire_forward())
30054 		 * holds a ref on the ire until ARP is completed.
30055 		 */
30056 
30057 		ire_arpresolve(ire, ire_to_ill(ire));
30058 		return (LOOKUP_IN_PROGRESS);
30059 	default:
30060 		ASSERT(0);
30061 		mutex_exit(&arpce->nce_lock);
30062 		return (LLHDR_RESLV_FAILED);
30063 	}
30064 }
30065 
30066 #undef	UPDATE_IP_MIB_OB_COUNTERS
30067 
30068 /*
30069  * Return B_TRUE if the buffers differ in length or content.
30070  * This is used for comparing extension header buffers.
30071  * Note that an extension header would be declared different
30072  * even if all that changed was the next header value in that header i.e.
30073  * what really changed is the next extension header.
30074  */
30075 boolean_t
30076 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30077     uint_t blen)
30078 {
30079 	if (!b_valid)
30080 		blen = 0;
30081 
30082 	if (alen != blen)
30083 		return (B_TRUE);
30084 	if (alen == 0)
30085 		return (B_FALSE);	/* Both zero length */
30086 	return (bcmp(abuf, bbuf, alen));
30087 }
30088 
30089 /*
30090  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30091  * Return B_FALSE if memory allocation fails - don't change any state!
30092  */
30093 boolean_t
30094 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30095     const void *src, uint_t srclen)
30096 {
30097 	void *dst;
30098 
30099 	if (!src_valid)
30100 		srclen = 0;
30101 
30102 	ASSERT(*dstlenp == 0);
30103 	if (src != NULL && srclen != 0) {
30104 		dst = mi_alloc(srclen, BPRI_MED);
30105 		if (dst == NULL)
30106 			return (B_FALSE);
30107 	} else {
30108 		dst = NULL;
30109 	}
30110 	if (*dstp != NULL)
30111 		mi_free(*dstp);
30112 	*dstp = dst;
30113 	*dstlenp = dst == NULL ? 0 : srclen;
30114 	return (B_TRUE);
30115 }
30116 
30117 /*
30118  * Replace what is in *dst, *dstlen with the source.
30119  * Assumes ip_allocbuf has already been called.
30120  */
30121 void
30122 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30123     const void *src, uint_t srclen)
30124 {
30125 	if (!src_valid)
30126 		srclen = 0;
30127 
30128 	ASSERT(*dstlenp == srclen);
30129 	if (src != NULL && srclen != 0)
30130 		bcopy(src, *dstp, srclen);
30131 }
30132 
30133 /*
30134  * Free the storage pointed to by the members of an ip6_pkt_t.
30135  */
30136 void
30137 ip6_pkt_free(ip6_pkt_t *ipp)
30138 {
30139 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30140 
30141 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30142 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30143 		ipp->ipp_hopopts = NULL;
30144 		ipp->ipp_hopoptslen = 0;
30145 	}
30146 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30147 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30148 		ipp->ipp_rtdstopts = NULL;
30149 		ipp->ipp_rtdstoptslen = 0;
30150 	}
30151 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30152 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30153 		ipp->ipp_dstopts = NULL;
30154 		ipp->ipp_dstoptslen = 0;
30155 	}
30156 	if (ipp->ipp_fields & IPPF_RTHDR) {
30157 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30158 		ipp->ipp_rthdr = NULL;
30159 		ipp->ipp_rthdrlen = 0;
30160 	}
30161 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30162 	    IPPF_RTHDR);
30163 }
30164