xref: /titanic_51/usr/src/uts/common/inet/ip/ip.c (revision 1b47e080b07ee427f2239a6564769802c9e5ac99)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <sys/mac.h>
60 #include <net/if.h>
61 #include <net/if_arp.h>
62 #include <net/route.h>
63 #include <sys/sockio.h>
64 #include <netinet/in.h>
65 #include <net/if_dl.h>
66 
67 #include <inet/common.h>
68 #include <inet/mi.h>
69 #include <inet/mib2.h>
70 #include <inet/nd.h>
71 #include <inet/arp.h>
72 #include <inet/snmpcom.h>
73 #include <inet/optcom.h>
74 #include <inet/kstatcom.h>
75 
76 #include <netinet/igmp_var.h>
77 #include <netinet/ip6.h>
78 #include <netinet/icmp6.h>
79 #include <netinet/sctp.h>
80 
81 #include <inet/ip.h>
82 #include <inet/ip_impl.h>
83 #include <inet/ip6.h>
84 #include <inet/ip6_asp.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <inet/ip_multi.h>
88 #include <inet/ip_if.h>
89 #include <inet/ip_ire.h>
90 #include <inet/ip_ftable.h>
91 #include <inet/ip_rts.h>
92 #include <inet/ip_ndp.h>
93 #include <inet/ip_listutils.h>
94 #include <netinet/igmp.h>
95 #include <netinet/ip_mroute.h>
96 #include <inet/ipp_common.h>
97 
98 #include <net/pfkeyv2.h>
99 #include <inet/ipsec_info.h>
100 #include <inet/sadb.h>
101 #include <inet/ipsec_impl.h>
102 #include <sys/iphada.h>
103 #include <inet/tun.h>
104 #include <inet/ipdrop.h>
105 #include <inet/ip_netinfo.h>
106 
107 #include <sys/ethernet.h>
108 #include <net/if_types.h>
109 #include <sys/cpuvar.h>
110 
111 #include <ipp/ipp.h>
112 #include <ipp/ipp_impl.h>
113 #include <ipp/ipgpc/ipgpc.h>
114 
115 #include <sys/multidata.h>
116 #include <sys/pattr.h>
117 
118 #include <inet/ipclassifier.h>
119 #include <inet/sctp_ip.h>
120 #include <inet/sctp/sctp_impl.h>
121 #include <inet/udp_impl.h>
122 #include <inet/rawip_impl.h>
123 #include <inet/rts_impl.h>
124 #include <sys/sunddi.h>
125 
126 #include <sys/tsol/label.h>
127 #include <sys/tsol/tnet.h>
128 
129 #include <rpc/pmap_prot.h>
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
134  * IP_SQUEUE_ENTER: squeue_enter
135  * IP_SQUEUE_FILL: squeue_fill
136  */
137 int ip_squeue_enter = 2;	/* Setable in /etc/system */
138 
139 squeue_func_t ip_input_proc;
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 /*
143  * Setable in /etc/system
144  */
145 int ip_poll_normal_ms = 100;
146 int ip_poll_normal_ticks = 0;
147 int ip_modclose_ackwait_ms = 3000;
148 
149 /*
150  * It would be nice to have these present only in DEBUG systems, but the
151  * current design of the global symbol checking logic requires them to be
152  * unconditionally present.
153  */
154 uint_t ip_thread_data;			/* TSD key for debug support */
155 krwlock_t ip_thread_rwlock;
156 list_t	ip_thread_list;
157 
158 /*
159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
160  */
161 
162 struct listptr_s {
163 	mblk_t	*lp_head;	/* pointer to the head of the list */
164 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
165 };
166 
167 typedef struct listptr_s listptr_t;
168 
169 /*
170  * This is used by ip_snmp_get_mib2_ip_route_media and
171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
172  */
173 typedef struct iproutedata_s {
174 	uint_t		ird_idx;
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
199     uint8_t *laddrp, uint8_t *faddrp) = NULL;
200 
201 /*
202  * Synchronization notes:
203  *
204  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
205  * MT level protection given by STREAMS. IP uses a combination of its own
206  * internal serialization mechanism and standard Solaris locking techniques.
207  * The internal serialization is per phyint (no IPMP) or per IPMP group.
208  * This is used to serialize plumbing operations, IPMP operations, certain
209  * multicast operations, most set ioctls, igmp/mld timers etc.
210  *
211  * Plumbing is a long sequence of operations involving message
212  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
213  * involved in plumbing operations. A natural model is to serialize these
214  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
215  * parallel without any interference. But various set ioctls on hme0 are best
216  * serialized. However if the system uses IPMP, the operations are easier if
217  * they are serialized on a per IPMP group basis since IPMP operations
218  * happen across ill's of a group. Thus the lowest common denominator is to
219  * serialize most set ioctls, multicast join/leave operations, IPMP operations
220  * igmp/mld timer operations, and processing of DLPI control messages received
221  * from drivers on a per IPMP group basis. If the system does not employ
222  * IPMP the serialization is on a per phyint basis. This serialization is
223  * provided by the ipsq_t and primitives operating on this. Details can
224  * be found in ip_if.c above the core primitives operating on ipsq_t.
225  *
226  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
227  * Simiarly lookup of an ire by a thread also returns a refheld ire.
228  * In addition ipif's and ill's referenced by the ire are also indirectly
229  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
230  * the ipif's address or netmask change as long as an ipif is refheld
231  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
232  * address of an ipif has to go through the ipsq_t. This ensures that only
233  * 1 such exclusive operation proceeds at any time on the ipif. It then
234  * deletes all ires associated with this ipif, and waits for all refcnts
235  * associated with this ipif to come down to zero. The address is changed
236  * only after the ipif has been quiesced. Then the ipif is brought up again.
237  * More details are described above the comment in ip_sioctl_flags.
238  *
239  * Packet processing is based mostly on IREs and are fully multi-threaded
240  * using standard Solaris MT techniques.
241  *
242  * There are explicit locks in IP to handle:
243  * - The ip_g_head list maintained by mi_open_link() and friends.
244  *
245  * - The reassembly data structures (one lock per hash bucket)
246  *
247  * - conn_lock is meant to protect conn_t fields. The fields actually
248  *   protected by conn_lock are documented in the conn_t definition.
249  *
250  * - ire_lock to protect some of the fields of the ire, IRE tables
251  *   (one lock per hash bucket). Refer to ip_ire.c for details.
252  *
253  * - ndp_g_lock and nce_lock for protecting NCEs.
254  *
255  * - ill_lock protects fields of the ill and ipif. Details in ip.h
256  *
257  * - ill_g_lock: This is a global reader/writer lock. Protects the following
258  *	* The AVL tree based global multi list of all ills.
259  *	* The linked list of all ipifs of an ill
260  *	* The <ill-ipsq> mapping
261  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
262  *	* The illgroup list threaded by ill_group_next.
263  *	* <ill-phyint> association
264  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
265  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
266  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
267  *   will all have to hold the ill_g_lock as writer for the actual duration
268  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
269  *   may be found in the IPMP section.
270  *
271  * - ill_lock:  This is a per ill mutex.
272  *   It protects some members of the ill and is documented below.
273  *   It also protects the <ill-ipsq> mapping
274  *   It also protects the illgroup list threaded by ill_group_next.
275  *   It also protects the <ill-phyint> assoc.
276  *   It also protects the list of ipifs hanging off the ill.
277  *
278  * - ipsq_lock: This is a per ipsq_t mutex lock.
279  *   This protects all the other members of the ipsq struct except
280  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
281  *
282  * - illgrp_lock: This is a per ill_group mutex lock.
283  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
284  *   which dictates which is the next ill in an ill_group that is to be chosen
285  *   for sending outgoing packets, through creation of an IRE_CACHE that
286  *   references this ill.
287  *
288  * - phyint_lock: This is a per phyint mutex lock. Protects just the
289  *   phyint_flags
290  *
291  * - ip_g_nd_lock: This is a global reader/writer lock.
292  *   Any call to nd_load to load a new parameter to the ND table must hold the
293  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
294  *   as reader.
295  *
296  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
297  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
298  *   uniqueness check also done atomically.
299  *
300  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
301  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
302  *   as a writer when adding or deleting elements from these lists, and
303  *   as a reader when walking these lists to send a SADB update to the
304  *   IPsec capable ills.
305  *
306  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
307  *   group list linked by ill_usesrc_grp_next. It also protects the
308  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
309  *   group is being added or deleted.  This lock is taken as a reader when
310  *   walking the list/group(eg: to get the number of members in a usesrc group).
311  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
312  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
313  *   example, it is not necessary to take this lock in the initial portion
314  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
315  *   ip_sioctl_flags since the these operations are executed exclusively and
316  *   that ensures that the "usesrc group state" cannot change. The "usesrc
317  *   group state" change can happen only in the latter part of
318  *   ip_sioctl_slifusesrc and in ill_delete.
319  *
320  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
321  *
322  * To change the <ill-phyint> association, the ill_g_lock must be held
323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
324  * must be held.
325  *
326  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
327  * and the ill_lock of the ill in question must be held.
328  *
329  * To change the <ill-illgroup> association the ill_g_lock must be held as
330  * writer and the ill_lock of the ill in question must be held.
331  *
332  * To add or delete an ipif from the list of ipifs hanging off the ill,
333  * ill_g_lock (writer) and ill_lock must be held and the thread must be
334  * a writer on the associated ipsq,.
335  *
336  * To add or delete an ill to the system, the ill_g_lock must be held as
337  * writer and the thread must be a writer on the associated ipsq.
338  *
339  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
340  * must be a writer on the associated ipsq.
341  *
342  * Lock hierarchy
343  *
344  * Some lock hierarchy scenarios are listed below.
345  *
346  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
347  * ill_g_lock -> illgrp_lock -> ill_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  *
354  * When more than 1 ill lock is needed to be held, all ill lock addresses
355  * are sorted on address and locked starting from highest addressed lock
356  * downward.
357  *
358  * IPsec scenarios
359  *
360  * ipsa_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
362  * ipsec_capab_ills_lock -> ipsa_lock
363  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
364  *
365  * Trusted Solaris scenarios
366  *
367  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
368  * igsa_lock -> gcdb_lock
369  * gcgrp_rwlock -> ire_lock
370  * gcgrp_rwlock -> gcdb_lock
371  *
372  *
373  * Routing/forwarding table locking notes:
374  *
375  * Lock acquisition order: Radix tree lock, irb_lock.
376  * Requirements:
377  * i.  Walker must not hold any locks during the walker callback.
378  * ii  Walker must not see a truncated tree during the walk because of any node
379  *     deletion.
380  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
381  *     in many places in the code to walk the irb list. Thus even if all the
382  *     ires in a bucket have been deleted, we still can't free the radix node
383  *     until the ires have actually been inactive'd (freed).
384  *
385  * Tree traversal - Need to hold the global tree lock in read mode.
386  * Before dropping the global tree lock, need to either increment the ire_refcnt
387  * to ensure that the radix node can't be deleted.
388  *
389  * Tree add - Need to hold the global tree lock in write mode to add a
390  * radix node. To prevent the node from being deleted, increment the
391  * irb_refcnt, after the node is added to the tree. The ire itself is
392  * added later while holding the irb_lock, but not the tree lock.
393  *
394  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
395  * All associated ires must be inactive (i.e. freed), and irb_refcnt
396  * must be zero.
397  *
398  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
399  * global tree lock (read mode) for traversal.
400  *
401  * IPsec notes :
402  *
403  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
404  * in front of the actual packet. For outbound datagrams, the M_CTL
405  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
406  * information used by the IPsec code for applying the right level of
407  * protection. The information initialized by IP in the ipsec_out_t
408  * is determined by the per-socket policy or global policy in the system.
409  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
410  * ipsec_info.h) which starts out with nothing in it. It gets filled
411  * with the right information if it goes through the AH/ESP code, which
412  * happens if the incoming packet is secure. The information initialized
413  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
414  * the policy requirements needed by per-socket policy or global policy
415  * is met or not.
416  *
417  * If there is both per-socket policy (set using setsockopt) and there
418  * is also global policy match for the 5 tuples of the socket,
419  * ipsec_override_policy() makes the decision of which one to use.
420  *
421  * For fully connected sockets i.e dst, src [addr, port] is known,
422  * conn_policy_cached is set indicating that policy has been cached.
423  * conn_in_enforce_policy may or may not be set depending on whether
424  * there is a global policy match or per-socket policy match.
425  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
426  * Once the right policy is set on the conn_t, policy cannot change for
427  * this socket. This makes life simpler for TCP (UDP ?) where
428  * re-transmissions go out with the same policy. For symmetry, policy
429  * is cached for fully connected UDP sockets also. Thus if policy is cached,
430  * it also implies that policy is latched i.e policy cannot change
431  * on these sockets. As we have the right policy on the conn, we don't
432  * have to lookup global policy for every outbound and inbound datagram
433  * and thus serving as an optimization. Note that a global policy change
434  * does not affect fully connected sockets if they have policy. If fully
435  * connected sockets did not have any policy associated with it, global
436  * policy change may affect them.
437  *
438  * IP Flow control notes:
439  *
440  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
441  * cannot be sent down to the driver by IP, because of a canput failure, IP
442  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
443  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
444  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
445  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
446  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
447  * the queued messages, and removes the conn from the drain list, if all
448  * messages were drained. It also qenables the next conn in the drain list to
449  * continue the drain process.
450  *
451  * In reality the drain list is not a single list, but a configurable number
452  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
453  * list. If the ip_wsrv of the next qenabled conn does not run, because the
454  * stream closes, ip_close takes responsibility to qenable the next conn in
455  * the drain list. The directly called ip_wput path always does a putq, if
456  * it cannot putnext. Thus synchronization problems are handled between
457  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
458  * functions that manipulate this drain list. Furthermore conn_drain_insert
459  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
460  * running on a queue at any time. conn_drain_tail can be simultaneously called
461  * from both ip_wsrv and ip_close.
462  *
463  * IPQOS notes:
464  *
465  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
466  * and IPQoS modules. IPPF includes hooks in IP at different control points
467  * (callout positions) which direct packets to IPQoS modules for policy
468  * processing. Policies, if present, are global.
469  *
470  * The callout positions are located in the following paths:
471  *		o local_in (packets destined for this host)
472  *		o local_out (packets orginating from this host )
473  *		o fwd_in  (packets forwarded by this m/c - inbound)
474  *		o fwd_out (packets forwarded by this m/c - outbound)
475  * Hooks at these callout points can be enabled/disabled using the ndd variable
476  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
477  * By default all the callout positions are enabled.
478  *
479  * Outbound (local_out)
480  * Hooks are placed in ip_wput_ire and ipsec_out_process.
481  *
482  * Inbound (local_in)
483  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
484  * TCP and UDP fanout routines.
485  *
486  * Forwarding (in and out)
487  * Hooks are placed in ip_rput_forward.
488  *
489  * IP Policy Framework processing (IPPF processing)
490  * Policy processing for a packet is initiated by ip_process, which ascertains
491  * that the classifier (ipgpc) is loaded and configured, failing which the
492  * packet resumes normal processing in IP. If the clasifier is present, the
493  * packet is acted upon by one or more IPQoS modules (action instances), per
494  * filters configured in ipgpc and resumes normal IP processing thereafter.
495  * An action instance can drop a packet in course of its processing.
496  *
497  * A boolean variable, ip_policy, is used in all the fanout routines that can
498  * invoke ip_process for a packet. This variable indicates if the packet should
499  * to be sent for policy processing. The variable is set to B_TRUE by default,
500  * i.e. when the routines are invoked in the normal ip procesing path for a
501  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
502  * ip_policy is set to B_FALSE for all the routines called in these two
503  * functions because, in the former case,  we don't process loopback traffic
504  * currently while in the latter, the packets have already been processed in
505  * icmp_inbound.
506  *
507  * Zones notes:
508  *
509  * The partitioning rules for networking are as follows:
510  * 1) Packets coming from a zone must have a source address belonging to that
511  * zone.
512  * 2) Packets coming from a zone can only be sent on a physical interface on
513  * which the zone has an IP address.
514  * 3) Between two zones on the same machine, packet delivery is only allowed if
515  * there's a matching route for the destination and zone in the forwarding
516  * table.
517  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
518  * different zones can bind to the same port with the wildcard address
519  * (INADDR_ANY).
520  *
521  * The granularity of interface partitioning is at the logical interface level.
522  * Therefore, every zone has its own IP addresses, and incoming packets can be
523  * attributed to a zone unambiguously. A logical interface is placed into a zone
524  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
525  * structure. Rule (1) is implemented by modifying the source address selection
526  * algorithm so that the list of eligible addresses is filtered based on the
527  * sending process zone.
528  *
529  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
530  * across all zones, depending on their type. Here is the break-up:
531  *
532  * IRE type				Shared/exclusive
533  * --------				----------------
534  * IRE_BROADCAST			Exclusive
535  * IRE_DEFAULT (default routes)		Shared (*)
536  * IRE_LOCAL				Exclusive (x)
537  * IRE_LOOPBACK				Exclusive
538  * IRE_PREFIX (net routes)		Shared (*)
539  * IRE_CACHE				Exclusive
540  * IRE_IF_NORESOLVER (interface routes)	Exclusive
541  * IRE_IF_RESOLVER (interface routes)	Exclusive
542  * IRE_HOST (host routes)		Shared (*)
543  *
544  * (*) A zone can only use a default or off-subnet route if the gateway is
545  * directly reachable from the zone, that is, if the gateway's address matches
546  * one of the zone's logical interfaces.
547  *
548  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
549  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
550  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
551  * address of the zone itself (the destination). Since IRE_LOCAL is used
552  * for communication between zones, ip_wput_ire has special logic to set
553  * the right source address when sending using an IRE_LOCAL.
554  *
555  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
556  * ire_cache_lookup restricts loopback using an IRE_LOCAL
557  * between zone to the case when L2 would have conceptually looped the packet
558  * back, i.e. the loopback which is required since neither Ethernet drivers
559  * nor Ethernet hardware loops them back. This is the case when the normal
560  * routes (ignoring IREs with different zoneids) would send out the packet on
561  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
562  * associated.
563  *
564  * Multiple zones can share a common broadcast address; typically all zones
565  * share the 255.255.255.255 address. Incoming as well as locally originated
566  * broadcast packets must be dispatched to all the zones on the broadcast
567  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
568  * since some zones may not be on the 10.16.72/24 network. To handle this, each
569  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
570  * sent to every zone that has an IRE_BROADCAST entry for the destination
571  * address on the input ill, see conn_wantpacket().
572  *
573  * Applications in different zones can join the same multicast group address.
574  * For IPv4, group memberships are per-logical interface, so they're already
575  * inherently part of a zone. For IPv6, group memberships are per-physical
576  * interface, so we distinguish IPv6 group memberships based on group address,
577  * interface and zoneid. In both cases, received multicast packets are sent to
578  * every zone for which a group membership entry exists. On IPv6 we need to
579  * check that the target zone still has an address on the receiving physical
580  * interface; it could have been removed since the application issued the
581  * IPV6_JOIN_GROUP.
582  */
583 
584 /*
585  * Squeue Fanout flags:
586  *	0: No fanout.
587  *	1: Fanout across all squeues
588  */
589 boolean_t	ip_squeue_fanout = 0;
590 
591 /*
592  * Maximum dups allowed per packet.
593  */
594 uint_t ip_max_frag_dups = 10;
595 
596 #define	IS_SIMPLE_IPH(ipha)						\
597 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
598 
599 /* RFC1122 Conformance */
600 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
601 
602 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
603 
604 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
605 
606 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
607 		    cred_t *credp, boolean_t isv6);
608 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
609 
610 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
611 		    ip_stack_t *);
612 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
613 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
614 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
615 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
616 		    mblk_t *, int, ip_stack_t *);
617 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
618 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
619 		    ill_t *, zoneid_t);
620 static void	icmp_options_update(ipha_t *);
621 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
622 		    ip_stack_t *);
623 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
624 		    zoneid_t zoneid, ip_stack_t *);
625 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
626 static void	icmp_redirect(ill_t *, mblk_t *);
627 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
628 		    ip_stack_t *);
629 
630 static void	ip_arp_news(queue_t *, mblk_t *);
631 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
632 		    ip_stack_t *);
633 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
634 char		*ip_dot_addr(ipaddr_t, char *);
635 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
636 int		ip_close(queue_t *, int);
637 static char	*ip_dot_saddr(uchar_t *, char *);
638 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
639 		    boolean_t, boolean_t, ill_t *, zoneid_t);
640 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, zoneid_t);
642 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
643 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
644 static void	ip_lrput(queue_t *, mblk_t *);
645 ipaddr_t	ip_net_mask(ipaddr_t);
646 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
647 		    ip_stack_t *);
648 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
649 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
650 char		*ip_nv_lookup(nv_t *, int);
651 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
652 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
654 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
655     ipndp_t *, size_t);
656 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
657 void	ip_rput(queue_t *, mblk_t *);
658 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
659 		    void *dummy_arg);
660 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
661 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
662     ip_stack_t *);
663 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
664 			    ire_t *, ip_stack_t *);
665 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
666 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
667 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
668     ip_stack_t *);
669 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
670 		    uint16_t *);
671 int		ip_snmp_get(queue_t *, mblk_t *, int);
672 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
673 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
674 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
675 		    ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
682 		    ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
684 		    ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
702 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
703 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
704 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
705 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
706 static boolean_t	ip_source_route_included(ipha_t *);
707 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
708 
709 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
710 		    zoneid_t, ip_stack_t *);
711 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
712 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
713 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
714 		    zoneid_t, ip_stack_t *);
715 
716 static void	conn_drain_init(ip_stack_t *);
717 static void	conn_drain_fini(ip_stack_t *);
718 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
719 
720 static void	conn_walk_drain(ip_stack_t *);
721 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
722     zoneid_t);
723 
724 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
725 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
726 static void	ip_stack_fini(netstackid_t stackid, void *arg);
727 
728 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
729     zoneid_t);
730 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
731     void *dummy_arg);
732 
733 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
734 
735 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
736     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
737     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
738 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
739 
740 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
741 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
742     caddr_t, cred_t *);
743 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
748     caddr_t cp, cred_t *cr);
749 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
750     cred_t *);
751 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
752     cred_t *);
753 static squeue_func_t ip_squeue_switch(int);
754 
755 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
756 static void	ip_kstat_fini(netstackid_t, kstat_t *);
757 static int	ip_kstat_update(kstat_t *kp, int rw);
758 static void	*icmp_kstat_init(netstackid_t);
759 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
760 static int	icmp_kstat_update(kstat_t *kp, int rw);
761 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
762 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
763 
764 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
765 
766 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
767     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
768 
769 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
770     ipha_t *, ill_t *, boolean_t);
771 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
772 
773 /* How long, in seconds, we allow frags to hang around. */
774 #define	IP_FRAG_TIMEOUT	60
775 
776 /*
777  * Threshold which determines whether MDT should be used when
778  * generating IP fragments; payload size must be greater than
779  * this threshold for MDT to take place.
780  */
781 #define	IP_WPUT_FRAG_MDT_MIN	32768
782 
783 /* Setable in /etc/system only */
784 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
785 
786 static long ip_rput_pullups;
787 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
788 
789 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
790 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
791 
792 int	ip_debug;
793 
794 #ifdef DEBUG
795 uint32_t ipsechw_debug = 0;
796 #endif
797 
798 /*
799  * Multirouting/CGTP stuff
800  */
801 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
802 
803 /*
804  * XXX following really should only be in a header. Would need more
805  * header and .c clean up first.
806  */
807 extern optdb_obj_t	ip_opt_obj;
808 
809 ulong_t ip_squeue_enter_unbound = 0;
810 
811 /*
812  * Named Dispatch Parameter Table.
813  * All of these are alterable, within the min/max values given, at run time.
814  */
815 static ipparam_t	lcl_param_arr[] = {
816 	/* min	max	value	name */
817 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
818 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
819 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
820 	{  0,	1,	0,	"ip_respond_to_timestamp"},
821 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
822 	{  0,	1,	1,	"ip_send_redirects"},
823 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
824 	{  0,	10,	0,	"ip_mrtdebug"},
825 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
826 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
827 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
828 	{  1,	255,	255,	"ip_def_ttl" },
829 	{  0,	1,	0,	"ip_forward_src_routed"},
830 	{  0,	256,	32,	"ip_wroff_extra" },
831 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
832 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
833 	{  0,	1,	1,	"ip_path_mtu_discovery" },
834 	{  0,	240,	30,	"ip_ignore_delete_time" },
835 	{  0,	1,	0,	"ip_ignore_redirect" },
836 	{  0,	1,	1,	"ip_output_queue" },
837 	{  1,	254,	1,	"ip_broadcast_ttl" },
838 	{  0,	99999,	100,	"ip_icmp_err_interval" },
839 	{  1,	99999,	10,	"ip_icmp_err_burst" },
840 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
841 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
842 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
843 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
844 	{  0,	1,	1,	"icmp_accept_clear_messages" },
845 	{  0,	1,	1,	"igmp_accept_clear_messages" },
846 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
847 				"ip_ndp_delay_first_probe_time"},
848 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
849 				"ip_ndp_max_unicast_solicit"},
850 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
851 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
852 	{  0,	1,	0,	"ip6_forward_src_routed"},
853 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
854 	{  0,	1,	1,	"ip6_send_redirects"},
855 	{  0,	1,	0,	"ip6_ignore_redirect" },
856 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
857 
858 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
859 
860 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
861 
862 	{  0,	1,	1,	"pim_accept_clear_messages" },
863 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
864 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
865 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
866 	{  0,	15,	0,	"ip_policy_mask" },
867 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
868 	{  0,	255,	1,	"ip_multirt_ttl" },
869 	{  0,	1,	1,	"ip_multidata_outbound" },
870 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
871 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
872 	{  0,	1000,	1,	"ip_max_temp_defend" },
873 	{  0,	1000,	3,	"ip_max_defend" },
874 	{  0,	999999,	30,	"ip_defend_interval" },
875 	{  0,	3600000, 300000, "ip_dup_recovery" },
876 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
877 	{  0,	1,	1,	"ip_lso_outbound" },
878 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
879 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
880 #ifdef DEBUG
881 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
882 #else
883 	{  0,	0,	0,	"" },
884 #endif
885 };
886 
887 /*
888  * Extended NDP table
889  * The addresses for the first two are filled in to be ips_ip_g_forward
890  * and ips_ipv6_forward at init time.
891  */
892 static ipndp_t	lcl_ndp_arr[] = {
893 	/* getf			setf		data			name */
894 #define	IPNDP_IP_FORWARDING_OFFSET	0
895 	{  ip_param_generic_get,	ip_forward_set,	NULL,
896 	    "ip_forwarding" },
897 #define	IPNDP_IP6_FORWARDING_OFFSET	1
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip6_forwarding" },
900 	{  ip_ill_report,	NULL,		NULL,
901 	    "ip_ill_status" },
902 	{  ip_ipif_report,	NULL,		NULL,
903 	    "ip_ipif_status" },
904 	{  ip_ire_report,	NULL,		NULL,
905 	    "ipv4_ire_status" },
906 	{  ip_ire_report_v6,	NULL,		NULL,
907 	    "ipv6_ire_status" },
908 	{  ip_conn_report,	NULL,		NULL,
909 	    "ip_conn_status" },
910 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
911 	    "ip_rput_pullups" },
912 	{  ndp_report,		NULL,		NULL,
913 	    "ip_ndp_cache_report" },
914 	{  ip_srcid_report,	NULL,		NULL,
915 	    "ip_srcid_status" },
916 	{ ip_param_generic_get, ip_squeue_profile_set,
917 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
918 	{ ip_param_generic_get, ip_squeue_bind_set,
919 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
920 	{ ip_param_generic_get, ip_input_proc_set,
921 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
922 	{ ip_param_generic_get, ip_int_set,
923 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
924 #define	IPNDP_CGTP_FILTER_OFFSET	14
925 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
926 	    "ip_cgtp_filter" },
927 	{ ip_param_generic_get, ip_int_set,
928 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
929 #define	IPNDP_IPMP_HOOK_OFFSET	16
930 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
931 	    "ipmp_hook_emulation" },
932 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
933 	    "ip_debug" },
934 };
935 
936 /*
937  * Table of IP ioctls encoding the various properties of the ioctl and
938  * indexed based on the last byte of the ioctl command. Occasionally there
939  * is a clash, and there is more than 1 ioctl with the same last byte.
940  * In such a case 1 ioctl is encoded in the ndx table and the remaining
941  * ioctls are encoded in the misc table. An entry in the ndx table is
942  * retrieved by indexing on the last byte of the ioctl command and comparing
943  * the ioctl command with the value in the ndx table. In the event of a
944  * mismatch the misc table is then searched sequentially for the desired
945  * ioctl command.
946  *
947  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
948  */
949 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
950 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
955 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
956 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
957 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
958 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
959 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
960 
961 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
962 			MISC_CMD, ip_siocaddrt, NULL },
963 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
964 			MISC_CMD, ip_siocdelrt, NULL },
965 
966 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
967 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
968 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
969 			IF_CMD, ip_sioctl_get_addr, NULL },
970 
971 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
972 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
973 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
974 			IPI_GET_CMD | IPI_REPL,
975 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
976 
977 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
978 			IPI_PRIV | IPI_WR | IPI_REPL,
979 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
980 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
981 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
982 			IF_CMD, ip_sioctl_get_flags, NULL },
983 
984 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
985 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
986 
987 	/* copyin size cannot be coded for SIOCGIFCONF */
988 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
989 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
990 
991 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
992 			IF_CMD, ip_sioctl_mtu, NULL },
993 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
994 			IF_CMD, ip_sioctl_get_mtu, NULL },
995 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
996 			IPI_GET_CMD | IPI_REPL,
997 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
998 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
999 			IF_CMD, ip_sioctl_brdaddr, NULL },
1000 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
1001 			IPI_GET_CMD | IPI_REPL,
1002 			IF_CMD, ip_sioctl_get_netmask, NULL },
1003 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
1004 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1005 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1006 			IPI_GET_CMD | IPI_REPL,
1007 			IF_CMD, ip_sioctl_get_metric, NULL },
1008 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1009 			IF_CMD, ip_sioctl_metric, NULL },
1010 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1011 
1012 	/* See 166-168 below for extended SIOC*XARP ioctls */
1013 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1014 			ARP_CMD, ip_sioctl_arp, NULL },
1015 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1016 			ARP_CMD, ip_sioctl_arp, NULL },
1017 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1018 			ARP_CMD, ip_sioctl_arp, NULL },
1019 
1020 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1036 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1037 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1038 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1039 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 
1042 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1043 			MISC_CMD, if_unitsel, if_unitsel_restart },
1044 
1045 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1058 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1059 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1060 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1061 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1062 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 
1064 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1065 			IPI_PRIV | IPI_WR | IPI_MODOK,
1066 			IF_CMD, ip_sioctl_sifname, NULL },
1067 
1068 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1076 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1077 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1078 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1079 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1080 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1081 
1082 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1083 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1084 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1085 			IF_CMD, ip_sioctl_get_muxid, NULL },
1086 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1087 			IPI_PRIV | IPI_WR | IPI_REPL,
1088 			IF_CMD, ip_sioctl_muxid, NULL },
1089 
1090 	/* Both if and lif variants share same func */
1091 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1092 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1093 	/* Both if and lif variants share same func */
1094 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1095 			IPI_PRIV | IPI_WR | IPI_REPL,
1096 			IF_CMD, ip_sioctl_slifindex, NULL },
1097 
1098 	/* copyin size cannot be coded for SIOCGIFCONF */
1099 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1100 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1101 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1113 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1114 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1115 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1116 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1117 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1118 
1119 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1120 			IPI_PRIV | IPI_WR | IPI_REPL,
1121 			LIF_CMD, ip_sioctl_removeif,
1122 			ip_sioctl_removeif_restart },
1123 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1124 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1125 			LIF_CMD, ip_sioctl_addif, NULL },
1126 #define	SIOCLIFADDR_NDX 112
1127 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1128 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1129 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1130 			IPI_GET_CMD | IPI_REPL,
1131 			LIF_CMD, ip_sioctl_get_addr, NULL },
1132 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1133 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1134 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1137 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1138 			IPI_PRIV | IPI_WR | IPI_REPL,
1139 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1140 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1141 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1142 			LIF_CMD, ip_sioctl_get_flags, NULL },
1143 
1144 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1145 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1146 
1147 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1148 			ip_sioctl_get_lifconf, NULL },
1149 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1150 			LIF_CMD, ip_sioctl_mtu, NULL },
1151 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1152 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1153 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1154 			IPI_GET_CMD | IPI_REPL,
1155 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1156 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1157 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1158 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1159 			IPI_GET_CMD | IPI_REPL,
1160 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1161 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1162 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1163 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1164 			IPI_GET_CMD | IPI_REPL,
1165 			LIF_CMD, ip_sioctl_get_metric, NULL },
1166 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1167 			LIF_CMD, ip_sioctl_metric, NULL },
1168 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1169 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1170 			LIF_CMD, ip_sioctl_slifname,
1171 			ip_sioctl_slifname_restart },
1172 
1173 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1174 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1175 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1176 			IPI_GET_CMD | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1178 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1179 			IPI_PRIV | IPI_WR | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_muxid, NULL },
1181 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1182 			IPI_GET_CMD | IPI_REPL,
1183 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1184 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1185 			IPI_PRIV | IPI_WR | IPI_REPL,
1186 			LIF_CMD, ip_sioctl_slifindex, 0 },
1187 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1188 			LIF_CMD, ip_sioctl_token, NULL },
1189 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1190 			IPI_GET_CMD | IPI_REPL,
1191 			LIF_CMD, ip_sioctl_get_token, NULL },
1192 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1193 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1194 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1197 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1198 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1199 
1200 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1201 			IPI_GET_CMD | IPI_REPL,
1202 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1203 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1204 			LIF_CMD, ip_siocdelndp_v6, NULL },
1205 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1206 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1207 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1208 			LIF_CMD, ip_siocsetndp_v6, NULL },
1209 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1210 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1211 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1212 			MISC_CMD, ip_sioctl_tonlink, NULL },
1213 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1214 			MISC_CMD, ip_sioctl_tmysite, NULL },
1215 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1216 			TUN_CMD, ip_sioctl_tunparam, NULL },
1217 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1218 			IPI_PRIV | IPI_WR,
1219 			TUN_CMD, ip_sioctl_tunparam, NULL },
1220 
1221 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1222 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1223 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1224 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1225 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1226 
1227 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR | IPI_REPL,
1229 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1230 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1231 			IPI_PRIV | IPI_WR | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1233 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1234 			IPI_PRIV | IPI_WR,
1235 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1236 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1237 			IPI_GET_CMD | IPI_REPL,
1238 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1239 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1240 			IPI_GET_CMD | IPI_REPL,
1241 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1242 
1243 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1244 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1245 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1246 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1247 
1248 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1249 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1250 
1251 	/* These are handled in ip_sioctl_copyin_setup itself */
1252 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1253 			MISC_CMD, NULL, NULL },
1254 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1255 			MISC_CMD, NULL, NULL },
1256 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1257 
1258 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1259 			ip_sioctl_get_lifconf, NULL },
1260 
1261 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1262 			XARP_CMD, ip_sioctl_arp, NULL },
1263 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1264 			XARP_CMD, ip_sioctl_arp, NULL },
1265 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1266 			XARP_CMD, ip_sioctl_arp, NULL },
1267 
1268 	/* SIOCPOPSOCKFS is not handled by IP */
1269 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1270 
1271 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1272 			IPI_GET_CMD | IPI_REPL,
1273 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1274 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1275 			IPI_PRIV | IPI_WR | IPI_REPL,
1276 			LIF_CMD, ip_sioctl_slifzone,
1277 			ip_sioctl_slifzone_restart },
1278 	/* 172-174 are SCTP ioctls and not handled by IP */
1279 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1280 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1281 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1282 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1283 			IPI_GET_CMD, LIF_CMD,
1284 			ip_sioctl_get_lifusesrc, 0 },
1285 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1286 			IPI_PRIV | IPI_WR,
1287 			LIF_CMD, ip_sioctl_slifusesrc,
1288 			NULL },
1289 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1290 			ip_sioctl_get_lifsrcof, NULL },
1291 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1294 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1295 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1296 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1297 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1298 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1299 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1300 			ip_sioctl_set_ipmpfailback, NULL },
1301 	/* SIOCSENABLESDP is handled by SDP */
1302 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1303 };
1304 
1305 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1306 
1307 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1308 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1309 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1310 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1311 		TUN_CMD, ip_sioctl_tunparam, NULL },
1312 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1313 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1314 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1315 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1316 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1317 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1318 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1319 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1320 		MISC_CMD, mrt_ioctl},
1321 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1322 		MISC_CMD, mrt_ioctl},
1323 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1324 		MISC_CMD, mrt_ioctl}
1325 };
1326 
1327 int ip_misc_ioctl_count =
1328     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1329 
1330 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1331 					/* Settable in /etc/system */
1332 /* Defined in ip_ire.c */
1333 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1334 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1335 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1336 
1337 static nv_t	ire_nv_arr[] = {
1338 	{ IRE_BROADCAST, "BROADCAST" },
1339 	{ IRE_LOCAL, "LOCAL" },
1340 	{ IRE_LOOPBACK, "LOOPBACK" },
1341 	{ IRE_CACHE, "CACHE" },
1342 	{ IRE_DEFAULT, "DEFAULT" },
1343 	{ IRE_PREFIX, "PREFIX" },
1344 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1345 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1346 	{ IRE_HOST, "HOST" },
1347 	{ 0 }
1348 };
1349 
1350 nv_t	*ire_nv_tbl = ire_nv_arr;
1351 
1352 /* Defined in ip_netinfo.c */
1353 extern ddi_taskq_t	*eventq_queue_nic;
1354 
1355 /* Simple ICMP IP Header Template */
1356 static ipha_t icmp_ipha = {
1357 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1358 };
1359 
1360 struct module_info ip_mod_info = {
1361 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1362 };
1363 
1364 /*
1365  * Duplicate static symbols within a module confuses mdb; so we avoid the
1366  * problem by making the symbols here distinct from those in udp.c.
1367  */
1368 
1369 /*
1370  * Entry points for IP as a device and as a module.
1371  * FIXME: down the road we might want a separate module and driver qinit.
1372  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1373  */
1374 static struct qinit iprinitv4 = {
1375 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1376 	&ip_mod_info
1377 };
1378 
1379 struct qinit iprinitv6 = {
1380 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1381 	&ip_mod_info
1382 };
1383 
1384 static struct qinit ipwinitv4 = {
1385 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1386 	&ip_mod_info
1387 };
1388 
1389 struct qinit ipwinitv6 = {
1390 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1391 	&ip_mod_info
1392 };
1393 
1394 static struct qinit iplrinit = {
1395 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1396 	&ip_mod_info
1397 };
1398 
1399 static struct qinit iplwinit = {
1400 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1401 	&ip_mod_info
1402 };
1403 
1404 /* For AF_INET aka /dev/ip */
1405 struct streamtab ipinfov4 = {
1406 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1407 };
1408 
1409 /* For AF_INET6 aka /dev/ip6 */
1410 struct streamtab ipinfov6 = {
1411 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1412 };
1413 
1414 #ifdef	DEBUG
1415 static boolean_t skip_sctp_cksum = B_FALSE;
1416 #endif
1417 
1418 /*
1419  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1420  * ip_rput_v6(), ip_output(), etc.  If the message
1421  * block already has a M_CTL at the front of it, then simply set the zoneid
1422  * appropriately.
1423  */
1424 mblk_t *
1425 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1426 {
1427 	mblk_t		*first_mp;
1428 	ipsec_out_t	*io;
1429 
1430 	ASSERT(zoneid != ALL_ZONES);
1431 	if (mp->b_datap->db_type == M_CTL) {
1432 		io = (ipsec_out_t *)mp->b_rptr;
1433 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1434 		io->ipsec_out_zoneid = zoneid;
1435 		return (mp);
1436 	}
1437 
1438 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1439 	if (first_mp == NULL)
1440 		return (NULL);
1441 	io = (ipsec_out_t *)first_mp->b_rptr;
1442 	/* This is not a secure packet */
1443 	io->ipsec_out_secure = B_FALSE;
1444 	io->ipsec_out_zoneid = zoneid;
1445 	first_mp->b_cont = mp;
1446 	return (first_mp);
1447 }
1448 
1449 /*
1450  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1451  */
1452 mblk_t *
1453 ip_copymsg(mblk_t *mp)
1454 {
1455 	mblk_t *nmp;
1456 	ipsec_info_t *in;
1457 
1458 	if (mp->b_datap->db_type != M_CTL)
1459 		return (copymsg(mp));
1460 
1461 	in = (ipsec_info_t *)mp->b_rptr;
1462 
1463 	/*
1464 	 * Note that M_CTL is also used for delivering ICMP error messages
1465 	 * upstream to transport layers.
1466 	 */
1467 	if (in->ipsec_info_type != IPSEC_OUT &&
1468 	    in->ipsec_info_type != IPSEC_IN)
1469 		return (copymsg(mp));
1470 
1471 	nmp = copymsg(mp->b_cont);
1472 
1473 	if (in->ipsec_info_type == IPSEC_OUT) {
1474 		return (ipsec_out_tag(mp, nmp,
1475 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1476 	} else {
1477 		return (ipsec_in_tag(mp, nmp,
1478 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1479 	}
1480 }
1481 
1482 /* Generate an ICMP fragmentation needed message. */
1483 static void
1484 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1485     ip_stack_t *ipst)
1486 {
1487 	icmph_t	icmph;
1488 	mblk_t *first_mp;
1489 	boolean_t mctl_present;
1490 
1491 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1492 
1493 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1494 		if (mctl_present)
1495 			freeb(first_mp);
1496 		return;
1497 	}
1498 
1499 	bzero(&icmph, sizeof (icmph_t));
1500 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1501 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1502 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1503 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1504 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1505 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1506 	    ipst);
1507 }
1508 
1509 /*
1510  * icmp_inbound deals with ICMP messages in the following ways.
1511  *
1512  * 1) It needs to send a reply back and possibly delivering it
1513  *    to the "interested" upper clients.
1514  * 2) It needs to send it to the upper clients only.
1515  * 3) It needs to change some values in IP only.
1516  * 4) It needs to change some values in IP and upper layers e.g TCP.
1517  *
1518  * We need to accomodate icmp messages coming in clear until we get
1519  * everything secure from the wire. If icmp_accept_clear_messages
1520  * is zero we check with the global policy and act accordingly. If
1521  * it is non-zero, we accept the message without any checks. But
1522  * *this does not mean* that this will be delivered to the upper
1523  * clients. By accepting we might send replies back, change our MTU
1524  * value etc. but delivery to the ULP/clients depends on their policy
1525  * dispositions.
1526  *
1527  * We handle the above 4 cases in the context of IPsec in the
1528  * following way :
1529  *
1530  * 1) Send the reply back in the same way as the request came in.
1531  *    If it came in encrypted, it goes out encrypted. If it came in
1532  *    clear, it goes out in clear. Thus, this will prevent chosen
1533  *    plain text attack.
1534  * 2) The client may or may not expect things to come in secure.
1535  *    If it comes in secure, the policy constraints are checked
1536  *    before delivering it to the upper layers. If it comes in
1537  *    clear, ipsec_inbound_accept_clear will decide whether to
1538  *    accept this in clear or not. In both the cases, if the returned
1539  *    message (IP header + 8 bytes) that caused the icmp message has
1540  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1541  *    sending up. If there are only 8 bytes of returned message, then
1542  *    upper client will not be notified.
1543  * 3) Check with global policy to see whether it matches the constaints.
1544  *    But this will be done only if icmp_accept_messages_in_clear is
1545  *    zero.
1546  * 4) If we need to change both in IP and ULP, then the decision taken
1547  *    while affecting the values in IP and while delivering up to TCP
1548  *    should be the same.
1549  *
1550  * 	There are two cases.
1551  *
1552  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1553  *	   failed), we will not deliver it to the ULP, even though they
1554  *	   are *willing* to accept in *clear*. This is fine as our global
1555  *	   disposition to icmp messages asks us reject the datagram.
1556  *
1557  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1558  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1559  *	   to deliver it to ULP (policy failed), it can lead to
1560  *	   consistency problems. The cases known at this time are
1561  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1562  *	   values :
1563  *
1564  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1565  *	     and Upper layer rejects. Then the communication will
1566  *	     come to a stop. This is solved by making similar decisions
1567  *	     at both levels. Currently, when we are unable to deliver
1568  *	     to the Upper Layer (due to policy failures) while IP has
1569  *	     adjusted ire_max_frag, the next outbound datagram would
1570  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1571  *	     will be with the right level of protection. Thus the right
1572  *	     value will be communicated even if we are not able to
1573  *	     communicate when we get from the wire initially. But this
1574  *	     assumes there would be at least one outbound datagram after
1575  *	     IP has adjusted its ire_max_frag value. To make things
1576  *	     simpler, we accept in clear after the validation of
1577  *	     AH/ESP headers.
1578  *
1579  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1580  *	     upper layer depending on the level of protection the upper
1581  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1582  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1583  *	     should be accepted in clear when the Upper layer expects secure.
1584  *	     Thus the communication may get aborted by some bad ICMP
1585  *	     packets.
1586  *
1587  * IPQoS Notes:
1588  * The only instance when a packet is sent for processing is when there
1589  * isn't an ICMP client and if we are interested in it.
1590  * If there is a client, IPPF processing will take place in the
1591  * ip_fanout_proto routine.
1592  *
1593  * Zones notes:
1594  * The packet is only processed in the context of the specified zone: typically
1595  * only this zone will reply to an echo request, and only interested clients in
1596  * this zone will receive a copy of the packet. This means that the caller must
1597  * call icmp_inbound() for each relevant zone.
1598  */
1599 static void
1600 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1601     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1602     ill_t *recv_ill, zoneid_t zoneid)
1603 {
1604 	icmph_t	*icmph;
1605 	ipha_t	*ipha;
1606 	int	iph_hdr_length;
1607 	int	hdr_length;
1608 	boolean_t	interested;
1609 	uint32_t	ts;
1610 	uchar_t	*wptr;
1611 	ipif_t	*ipif;
1612 	mblk_t *first_mp;
1613 	ipsec_in_t *ii;
1614 	ire_t *src_ire;
1615 	boolean_t onlink;
1616 	timestruc_t now;
1617 	uint32_t ill_index;
1618 	ip_stack_t *ipst;
1619 
1620 	ASSERT(ill != NULL);
1621 	ipst = ill->ill_ipst;
1622 
1623 	first_mp = mp;
1624 	if (mctl_present) {
1625 		mp = first_mp->b_cont;
1626 		ASSERT(mp != NULL);
1627 	}
1628 
1629 	ipha = (ipha_t *)mp->b_rptr;
1630 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1631 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1632 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1633 		if (first_mp == NULL)
1634 			return;
1635 	}
1636 
1637 	/*
1638 	 * On a labeled system, we have to check whether the zone itself is
1639 	 * permitted to receive raw traffic.
1640 	 */
1641 	if (is_system_labeled()) {
1642 		if (zoneid == ALL_ZONES)
1643 			zoneid = tsol_packet_to_zoneid(mp);
1644 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1645 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1646 			    zoneid));
1647 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1648 			freemsg(first_mp);
1649 			return;
1650 		}
1651 	}
1652 
1653 	/*
1654 	 * We have accepted the ICMP message. It means that we will
1655 	 * respond to the packet if needed. It may not be delivered
1656 	 * to the upper client depending on the policy constraints
1657 	 * and the disposition in ipsec_inbound_accept_clear.
1658 	 */
1659 
1660 	ASSERT(ill != NULL);
1661 
1662 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1663 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1664 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1665 		/* Last chance to get real. */
1666 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1667 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1668 			freemsg(first_mp);
1669 			return;
1670 		}
1671 		/* Refresh iph following the pullup. */
1672 		ipha = (ipha_t *)mp->b_rptr;
1673 	}
1674 	/* ICMP header checksum, including checksum field, should be zero. */
1675 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1676 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1677 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1678 		freemsg(first_mp);
1679 		return;
1680 	}
1681 	/* The IP header will always be a multiple of four bytes */
1682 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1683 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1684 	    icmph->icmph_code));
1685 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1686 	/* We will set "interested" to "true" if we want a copy */
1687 	interested = B_FALSE;
1688 	switch (icmph->icmph_type) {
1689 	case ICMP_ECHO_REPLY:
1690 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1691 		break;
1692 	case ICMP_DEST_UNREACHABLE:
1693 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1694 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1695 		interested = B_TRUE;	/* Pass up to transport */
1696 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1697 		break;
1698 	case ICMP_SOURCE_QUENCH:
1699 		interested = B_TRUE;	/* Pass up to transport */
1700 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1701 		break;
1702 	case ICMP_REDIRECT:
1703 		if (!ipst->ips_ip_ignore_redirect)
1704 			interested = B_TRUE;
1705 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1706 		break;
1707 	case ICMP_ECHO_REQUEST:
1708 		/*
1709 		 * Whether to respond to echo requests that come in as IP
1710 		 * broadcasts or as IP multicast is subject to debate
1711 		 * (what isn't?).  We aim to please, you pick it.
1712 		 * Default is do it.
1713 		 */
1714 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1715 			/* unicast: always respond */
1716 			interested = B_TRUE;
1717 		} else if (CLASSD(ipha->ipha_dst)) {
1718 			/* multicast: respond based on tunable */
1719 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1720 		} else if (broadcast) {
1721 			/* broadcast: respond based on tunable */
1722 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1723 		}
1724 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1725 		break;
1726 	case ICMP_ROUTER_ADVERTISEMENT:
1727 	case ICMP_ROUTER_SOLICITATION:
1728 		break;
1729 	case ICMP_TIME_EXCEEDED:
1730 		interested = B_TRUE;	/* Pass up to transport */
1731 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1732 		break;
1733 	case ICMP_PARAM_PROBLEM:
1734 		interested = B_TRUE;	/* Pass up to transport */
1735 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1736 		break;
1737 	case ICMP_TIME_STAMP_REQUEST:
1738 		/* Response to Time Stamp Requests is local policy. */
1739 		if (ipst->ips_ip_g_resp_to_timestamp &&
1740 		    /* So is whether to respond if it was an IP broadcast. */
1741 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1742 			int tstamp_len = 3 * sizeof (uint32_t);
1743 
1744 			if (wptr +  tstamp_len > mp->b_wptr) {
1745 				if (!pullupmsg(mp, wptr + tstamp_len -
1746 				    mp->b_rptr)) {
1747 					BUMP_MIB(ill->ill_ip_mib,
1748 					    ipIfStatsInDiscards);
1749 					freemsg(first_mp);
1750 					return;
1751 				}
1752 				/* Refresh ipha following the pullup. */
1753 				ipha = (ipha_t *)mp->b_rptr;
1754 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1755 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1756 			}
1757 			interested = B_TRUE;
1758 		}
1759 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1760 		break;
1761 	case ICMP_TIME_STAMP_REPLY:
1762 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1763 		break;
1764 	case ICMP_INFO_REQUEST:
1765 		/* Per RFC 1122 3.2.2.7, ignore this. */
1766 	case ICMP_INFO_REPLY:
1767 		break;
1768 	case ICMP_ADDRESS_MASK_REQUEST:
1769 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1770 		    !broadcast) &&
1771 		    /* TODO m_pullup of complete header? */
1772 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1773 			interested = B_TRUE;
1774 		}
1775 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1776 		break;
1777 	case ICMP_ADDRESS_MASK_REPLY:
1778 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1779 		break;
1780 	default:
1781 		interested = B_TRUE;	/* Pass up to transport */
1782 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1783 		break;
1784 	}
1785 	/* See if there is an ICMP client. */
1786 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1787 		/* If there is an ICMP client and we want one too, copy it. */
1788 		mblk_t *first_mp1;
1789 
1790 		if (!interested) {
1791 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1792 			    ip_policy, recv_ill, zoneid);
1793 			return;
1794 		}
1795 		first_mp1 = ip_copymsg(first_mp);
1796 		if (first_mp1 != NULL) {
1797 			ip_fanout_proto(q, first_mp1, ill, ipha,
1798 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1799 		}
1800 	} else if (!interested) {
1801 		freemsg(first_mp);
1802 		return;
1803 	} else {
1804 		/*
1805 		 * Initiate policy processing for this packet if ip_policy
1806 		 * is true.
1807 		 */
1808 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1809 			ill_index = ill->ill_phyint->phyint_ifindex;
1810 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1811 			if (mp == NULL) {
1812 				if (mctl_present) {
1813 					freeb(first_mp);
1814 				}
1815 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1816 				return;
1817 			}
1818 		}
1819 	}
1820 	/* We want to do something with it. */
1821 	/* Check db_ref to make sure we can modify the packet. */
1822 	if (mp->b_datap->db_ref > 1) {
1823 		mblk_t	*first_mp1;
1824 
1825 		first_mp1 = ip_copymsg(first_mp);
1826 		freemsg(first_mp);
1827 		if (!first_mp1) {
1828 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1829 			return;
1830 		}
1831 		first_mp = first_mp1;
1832 		if (mctl_present) {
1833 			mp = first_mp->b_cont;
1834 			ASSERT(mp != NULL);
1835 		} else {
1836 			mp = first_mp;
1837 		}
1838 		ipha = (ipha_t *)mp->b_rptr;
1839 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1840 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1841 	}
1842 	switch (icmph->icmph_type) {
1843 	case ICMP_ADDRESS_MASK_REQUEST:
1844 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1845 		if (ipif == NULL) {
1846 			freemsg(first_mp);
1847 			return;
1848 		}
1849 		/*
1850 		 * outging interface must be IPv4
1851 		 */
1852 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1853 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1854 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1855 		ipif_refrele(ipif);
1856 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1857 		break;
1858 	case ICMP_ECHO_REQUEST:
1859 		icmph->icmph_type = ICMP_ECHO_REPLY;
1860 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1861 		break;
1862 	case ICMP_TIME_STAMP_REQUEST: {
1863 		uint32_t *tsp;
1864 
1865 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1866 		tsp = (uint32_t *)wptr;
1867 		tsp++;		/* Skip past 'originate time' */
1868 		/* Compute # of milliseconds since midnight */
1869 		gethrestime(&now);
1870 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1871 		    now.tv_nsec / (NANOSEC / MILLISEC);
1872 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1873 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1874 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1875 		break;
1876 	}
1877 	default:
1878 		ipha = (ipha_t *)&icmph[1];
1879 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1880 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1881 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1882 				freemsg(first_mp);
1883 				return;
1884 			}
1885 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1886 			ipha = (ipha_t *)&icmph[1];
1887 		}
1888 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1889 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1890 			freemsg(first_mp);
1891 			return;
1892 		}
1893 		hdr_length = IPH_HDR_LENGTH(ipha);
1894 		if (hdr_length < sizeof (ipha_t)) {
1895 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1896 			freemsg(first_mp);
1897 			return;
1898 		}
1899 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1900 			if (!pullupmsg(mp,
1901 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1902 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1903 				freemsg(first_mp);
1904 				return;
1905 			}
1906 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1907 			ipha = (ipha_t *)&icmph[1];
1908 		}
1909 		switch (icmph->icmph_type) {
1910 		case ICMP_REDIRECT:
1911 			/*
1912 			 * As there is no upper client to deliver, we don't
1913 			 * need the first_mp any more.
1914 			 */
1915 			if (mctl_present) {
1916 				freeb(first_mp);
1917 			}
1918 			icmp_redirect(ill, mp);
1919 			return;
1920 		case ICMP_DEST_UNREACHABLE:
1921 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1922 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1923 				    zoneid, mp, iph_hdr_length, ipst)) {
1924 					freemsg(first_mp);
1925 					return;
1926 				}
1927 				/*
1928 				 * icmp_inbound_too_big() may alter mp.
1929 				 * Resynch ipha and icmph accordingly.
1930 				 */
1931 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1932 				ipha = (ipha_t *)&icmph[1];
1933 			}
1934 			/* FALLTHRU */
1935 		default :
1936 			/*
1937 			 * IPQoS notes: Since we have already done IPQoS
1938 			 * processing we don't want to do it again in
1939 			 * the fanout routines called by
1940 			 * icmp_inbound_error_fanout, hence the last
1941 			 * argument, ip_policy, is B_FALSE.
1942 			 */
1943 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1944 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1945 			    B_FALSE, recv_ill, zoneid);
1946 		}
1947 		return;
1948 	}
1949 	/* Send out an ICMP packet */
1950 	icmph->icmph_checksum = 0;
1951 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1952 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1953 		ipif_t	*ipif_chosen;
1954 		/*
1955 		 * Make it look like it was directed to us, so we don't look
1956 		 * like a fool with a broadcast or multicast source address.
1957 		 */
1958 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1959 		/*
1960 		 * Make sure that we haven't grabbed an interface that's DOWN.
1961 		 */
1962 		if (ipif != NULL) {
1963 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1964 			    ipha->ipha_src, zoneid);
1965 			if (ipif_chosen != NULL) {
1966 				ipif_refrele(ipif);
1967 				ipif = ipif_chosen;
1968 			}
1969 		}
1970 		if (ipif == NULL) {
1971 			ip0dbg(("icmp_inbound: "
1972 			    "No source for broadcast/multicast:\n"
1973 			    "\tsrc 0x%x dst 0x%x ill %p "
1974 			    "ipif_lcl_addr 0x%x\n",
1975 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1976 			    (void *)ill,
1977 			    ill->ill_ipif->ipif_lcl_addr));
1978 			freemsg(first_mp);
1979 			return;
1980 		}
1981 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1982 		ipha->ipha_dst = ipif->ipif_src_addr;
1983 		ipif_refrele(ipif);
1984 	}
1985 	/* Reset time to live. */
1986 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1987 	{
1988 		/* Swap source and destination addresses */
1989 		ipaddr_t tmp;
1990 
1991 		tmp = ipha->ipha_src;
1992 		ipha->ipha_src = ipha->ipha_dst;
1993 		ipha->ipha_dst = tmp;
1994 	}
1995 	ipha->ipha_ident = 0;
1996 	if (!IS_SIMPLE_IPH(ipha))
1997 		icmp_options_update(ipha);
1998 
1999 	/*
2000 	 * ICMP echo replies should go out on the same interface
2001 	 * the request came on as probes used by in.mpathd for detecting
2002 	 * NIC failures are ECHO packets. We turn-off load spreading
2003 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
2004 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
2005 	 * function. This is in turn handled by ip_wput and ip_newroute
2006 	 * to make sure that the packet goes out on the interface it came
2007 	 * in on. If we don't turnoff load spreading, the packets might get
2008 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2009 	 * to go out and in.mpathd would wrongly detect a failure or
2010 	 * mis-detect a NIC failure for link failure. As load spreading
2011 	 * can happen only if ill_group is not NULL, we do only for
2012 	 * that case and this does not affect the normal case.
2013 	 *
2014 	 * We turn off load spreading only on echo packets that came from
2015 	 * on-link hosts. If the interface route has been deleted, this will
2016 	 * not be enforced as we can't do much. For off-link hosts, as the
2017 	 * default routes in IPv4 does not typically have an ire_ipif
2018 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2019 	 * Moreover, expecting a default route through this interface may
2020 	 * not be correct. We use ipha_dst because of the swap above.
2021 	 */
2022 	onlink = B_FALSE;
2023 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2024 		/*
2025 		 * First, we need to make sure that it is not one of our
2026 		 * local addresses. If we set onlink when it is one of
2027 		 * our local addresses, we will end up creating IRE_CACHES
2028 		 * for one of our local addresses. Then, we will never
2029 		 * accept packets for them afterwards.
2030 		 */
2031 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2032 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2033 		if (src_ire == NULL) {
2034 			ipif = ipif_get_next_ipif(NULL, ill);
2035 			if (ipif == NULL) {
2036 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2037 				freemsg(mp);
2038 				return;
2039 			}
2040 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2041 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2042 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2043 			ipif_refrele(ipif);
2044 			if (src_ire != NULL) {
2045 				onlink = B_TRUE;
2046 				ire_refrele(src_ire);
2047 			}
2048 		} else {
2049 			ire_refrele(src_ire);
2050 		}
2051 	}
2052 	if (!mctl_present) {
2053 		/*
2054 		 * This packet should go out the same way as it
2055 		 * came in i.e in clear. To make sure that global
2056 		 * policy will not be applied to this in ip_wput_ire,
2057 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2058 		 */
2059 		ASSERT(first_mp == mp);
2060 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2061 		if (first_mp == NULL) {
2062 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2063 			freemsg(mp);
2064 			return;
2065 		}
2066 		ii = (ipsec_in_t *)first_mp->b_rptr;
2067 
2068 		/* This is not a secure packet */
2069 		ii->ipsec_in_secure = B_FALSE;
2070 		if (onlink) {
2071 			ii->ipsec_in_attach_if = B_TRUE;
2072 			ii->ipsec_in_ill_index =
2073 			    ill->ill_phyint->phyint_ifindex;
2074 			ii->ipsec_in_rill_index =
2075 			    recv_ill->ill_phyint->phyint_ifindex;
2076 		}
2077 		first_mp->b_cont = mp;
2078 	} else if (onlink) {
2079 		ii = (ipsec_in_t *)first_mp->b_rptr;
2080 		ii->ipsec_in_attach_if = B_TRUE;
2081 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2082 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2083 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2084 	} else {
2085 		ii = (ipsec_in_t *)first_mp->b_rptr;
2086 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2087 	}
2088 	ii->ipsec_in_zoneid = zoneid;
2089 	ASSERT(zoneid != ALL_ZONES);
2090 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2091 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2092 		return;
2093 	}
2094 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2095 	put(WR(q), first_mp);
2096 }
2097 
2098 static ipaddr_t
2099 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2100 {
2101 	conn_t *connp;
2102 	connf_t *connfp;
2103 	ipaddr_t nexthop_addr = INADDR_ANY;
2104 	int hdr_length = IPH_HDR_LENGTH(ipha);
2105 	uint16_t *up;
2106 	uint32_t ports;
2107 	ip_stack_t *ipst = ill->ill_ipst;
2108 
2109 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2110 	switch (ipha->ipha_protocol) {
2111 		case IPPROTO_TCP:
2112 		{
2113 			tcph_t *tcph;
2114 
2115 			/* do a reverse lookup */
2116 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2117 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2118 			    TCPS_LISTEN, ipst);
2119 			break;
2120 		}
2121 		case IPPROTO_UDP:
2122 		{
2123 			uint32_t dstport, srcport;
2124 
2125 			((uint16_t *)&ports)[0] = up[1];
2126 			((uint16_t *)&ports)[1] = up[0];
2127 
2128 			/* Extract ports in net byte order */
2129 			dstport = htons(ntohl(ports) & 0xFFFF);
2130 			srcport = htons(ntohl(ports) >> 16);
2131 
2132 			connfp = &ipst->ips_ipcl_udp_fanout[
2133 			    IPCL_UDP_HASH(dstport, ipst)];
2134 			mutex_enter(&connfp->connf_lock);
2135 			connp = connfp->connf_head;
2136 
2137 			/* do a reverse lookup */
2138 			while ((connp != NULL) &&
2139 			    (!IPCL_UDP_MATCH(connp, dstport,
2140 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2141 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2142 				connp = connp->conn_next;
2143 			}
2144 			if (connp != NULL)
2145 				CONN_INC_REF(connp);
2146 			mutex_exit(&connfp->connf_lock);
2147 			break;
2148 		}
2149 		case IPPROTO_SCTP:
2150 		{
2151 			in6_addr_t map_src, map_dst;
2152 
2153 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2154 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2155 			((uint16_t *)&ports)[0] = up[1];
2156 			((uint16_t *)&ports)[1] = up[0];
2157 
2158 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2159 			    zoneid, ipst->ips_netstack->netstack_sctp);
2160 			if (connp == NULL) {
2161 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2162 				    zoneid, ports, ipha, ipst);
2163 			} else {
2164 				CONN_INC_REF(connp);
2165 				SCTP_REFRELE(CONN2SCTP(connp));
2166 			}
2167 			break;
2168 		}
2169 		default:
2170 		{
2171 			ipha_t ripha;
2172 
2173 			ripha.ipha_src = ipha->ipha_dst;
2174 			ripha.ipha_dst = ipha->ipha_src;
2175 			ripha.ipha_protocol = ipha->ipha_protocol;
2176 
2177 			connfp = &ipst->ips_ipcl_proto_fanout[
2178 			    ipha->ipha_protocol];
2179 			mutex_enter(&connfp->connf_lock);
2180 			connp = connfp->connf_head;
2181 			for (connp = connfp->connf_head; connp != NULL;
2182 			    connp = connp->conn_next) {
2183 				if (IPCL_PROTO_MATCH(connp,
2184 				    ipha->ipha_protocol, &ripha, ill,
2185 				    0, zoneid)) {
2186 					CONN_INC_REF(connp);
2187 					break;
2188 				}
2189 			}
2190 			mutex_exit(&connfp->connf_lock);
2191 		}
2192 	}
2193 	if (connp != NULL) {
2194 		if (connp->conn_nexthop_set)
2195 			nexthop_addr = connp->conn_nexthop_v4;
2196 		CONN_DEC_REF(connp);
2197 	}
2198 	return (nexthop_addr);
2199 }
2200 
2201 /* Table from RFC 1191 */
2202 static int icmp_frag_size_table[] =
2203 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2204 
2205 /*
2206  * Process received ICMP Packet too big.
2207  * After updating any IRE it does the fanout to any matching transport streams.
2208  * Assumes the message has been pulled up till the IP header that caused
2209  * the error.
2210  *
2211  * Returns B_FALSE on failure and B_TRUE on success.
2212  */
2213 static boolean_t
2214 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2215     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2216     ip_stack_t *ipst)
2217 {
2218 	ire_t	*ire, *first_ire;
2219 	int	mtu;
2220 	int	hdr_length;
2221 	ipaddr_t nexthop_addr;
2222 
2223 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2224 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2225 	ASSERT(ill != NULL);
2226 
2227 	hdr_length = IPH_HDR_LENGTH(ipha);
2228 
2229 	/* Drop if the original packet contained a source route */
2230 	if (ip_source_route_included(ipha)) {
2231 		return (B_FALSE);
2232 	}
2233 	/*
2234 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2235 	 * header.
2236 	 */
2237 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2238 	    mp->b_wptr) {
2239 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2240 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2241 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2242 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2243 			return (B_FALSE);
2244 		}
2245 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2246 		ipha = (ipha_t *)&icmph[1];
2247 	}
2248 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2249 	if (nexthop_addr != INADDR_ANY) {
2250 		/* nexthop set */
2251 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2252 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2253 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2254 	} else {
2255 		/* nexthop not set */
2256 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2257 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2258 	}
2259 
2260 	if (!first_ire) {
2261 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2262 		    ntohl(ipha->ipha_dst)));
2263 		return (B_FALSE);
2264 	}
2265 	/* Check for MTU discovery advice as described in RFC 1191 */
2266 	mtu = ntohs(icmph->icmph_du_mtu);
2267 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2268 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2269 	    ire = ire->ire_next) {
2270 		/*
2271 		 * Look for the connection to which this ICMP message is
2272 		 * directed. If it has the IP_NEXTHOP option set, then the
2273 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2274 		 * option. Else the search is limited to regular IREs.
2275 		 */
2276 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2277 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2278 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2279 		    (nexthop_addr != INADDR_ANY)))
2280 			continue;
2281 
2282 		mutex_enter(&ire->ire_lock);
2283 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2284 			/* Reduce the IRE max frag value as advised. */
2285 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2286 			    mtu, ire->ire_max_frag));
2287 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2288 		} else {
2289 			uint32_t length;
2290 			int	i;
2291 
2292 			/*
2293 			 * Use the table from RFC 1191 to figure out
2294 			 * the next "plateau" based on the length in
2295 			 * the original IP packet.
2296 			 */
2297 			length = ntohs(ipha->ipha_length);
2298 			if (ire->ire_max_frag <= length &&
2299 			    ire->ire_max_frag >= length - hdr_length) {
2300 				/*
2301 				 * Handle broken BSD 4.2 systems that
2302 				 * return the wrong iph_length in ICMP
2303 				 * errors.
2304 				 */
2305 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2306 				    length, ire->ire_max_frag));
2307 				length -= hdr_length;
2308 			}
2309 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2310 				if (length > icmp_frag_size_table[i])
2311 					break;
2312 			}
2313 			if (i == A_CNT(icmp_frag_size_table)) {
2314 				/* Smaller than 68! */
2315 				ip1dbg(("Too big for packet size %d\n",
2316 				    length));
2317 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2318 				ire->ire_frag_flag = 0;
2319 			} else {
2320 				mtu = icmp_frag_size_table[i];
2321 				ip1dbg(("Calculated mtu %d, packet size %d, "
2322 				    "before %d", mtu, length,
2323 				    ire->ire_max_frag));
2324 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2325 				ip1dbg((", after %d\n", ire->ire_max_frag));
2326 			}
2327 			/* Record the new max frag size for the ULP. */
2328 			icmph->icmph_du_zero = 0;
2329 			icmph->icmph_du_mtu =
2330 			    htons((uint16_t)ire->ire_max_frag);
2331 		}
2332 		mutex_exit(&ire->ire_lock);
2333 	}
2334 	rw_exit(&first_ire->ire_bucket->irb_lock);
2335 	ire_refrele(first_ire);
2336 	return (B_TRUE);
2337 }
2338 
2339 /*
2340  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2341  * calls this function.
2342  */
2343 static mblk_t *
2344 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2345 {
2346 	ipha_t *ipha;
2347 	icmph_t *icmph;
2348 	ipha_t *in_ipha;
2349 	int length;
2350 
2351 	ASSERT(mp->b_datap->db_type == M_DATA);
2352 
2353 	/*
2354 	 * For Self-encapsulated packets, we added an extra IP header
2355 	 * without the options. Inner IP header is the one from which
2356 	 * the outer IP header was formed. Thus, we need to remove the
2357 	 * outer IP header. To do this, we pullup the whole message
2358 	 * and overlay whatever follows the outer IP header over the
2359 	 * outer IP header.
2360 	 */
2361 
2362 	if (!pullupmsg(mp, -1))
2363 		return (NULL);
2364 
2365 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2366 	ipha = (ipha_t *)&icmph[1];
2367 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2368 
2369 	/*
2370 	 * The length that we want to overlay is following the inner
2371 	 * IP header. Subtracting the IP header + icmp header + outer
2372 	 * IP header's length should give us the length that we want to
2373 	 * overlay.
2374 	 */
2375 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2376 	    hdr_length;
2377 	/*
2378 	 * Overlay whatever follows the inner header over the
2379 	 * outer header.
2380 	 */
2381 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2382 
2383 	/* Set the wptr to account for the outer header */
2384 	mp->b_wptr -= hdr_length;
2385 	return (mp);
2386 }
2387 
2388 /*
2389  * Try to pass the ICMP message upstream in case the ULP cares.
2390  *
2391  * If the packet that caused the ICMP error is secure, we send
2392  * it to AH/ESP to make sure that the attached packet has a
2393  * valid association. ipha in the code below points to the
2394  * IP header of the packet that caused the error.
2395  *
2396  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2397  * in the context of IPsec. Normally we tell the upper layer
2398  * whenever we send the ire (including ip_bind), the IPsec header
2399  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2400  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2401  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2402  * same thing. As TCP has the IPsec options size that needs to be
2403  * adjusted, we just pass the MTU unchanged.
2404  *
2405  * IFN could have been generated locally or by some router.
2406  *
2407  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2408  *	    This happens because IP adjusted its value of MTU on an
2409  *	    earlier IFN message and could not tell the upper layer,
2410  *	    the new adjusted value of MTU e.g. Packet was encrypted
2411  *	    or there was not enough information to fanout to upper
2412  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2413  *	    generates the IFN, where IPsec processing has *not* been
2414  *	    done.
2415  *
2416  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2417  *	    could have generated this. This happens because ire_max_frag
2418  *	    value in IP was set to a new value, while the IPsec processing
2419  *	    was being done and after we made the fragmentation check in
2420  *	    ip_wput_ire. Thus on return from IPsec processing,
2421  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2422  *	    and generates the IFN. As IPsec processing is over, we fanout
2423  *	    to AH/ESP to remove the header.
2424  *
2425  *	    In both these cases, ipsec_in_loopback will be set indicating
2426  *	    that IFN was generated locally.
2427  *
2428  * ROUTER : IFN could be secure or non-secure.
2429  *
2430  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2431  *	      packet in error has AH/ESP headers to validate the AH/ESP
2432  *	      headers. AH/ESP will verify whether there is a valid SA or
2433  *	      not and send it back. We will fanout again if we have more
2434  *	      data in the packet.
2435  *
2436  *	      If the packet in error does not have AH/ESP, we handle it
2437  *	      like any other case.
2438  *
2439  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2440  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2441  *	      for validation. AH/ESP will verify whether there is a
2442  *	      valid SA or not and send it back. We will fanout again if
2443  *	      we have more data in the packet.
2444  *
2445  *	      If the packet in error does not have AH/ESP, we handle it
2446  *	      like any other case.
2447  */
2448 static void
2449 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2450     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2451     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2452     zoneid_t zoneid)
2453 {
2454 	uint16_t *up;	/* Pointer to ports in ULP header */
2455 	uint32_t ports;	/* reversed ports for fanout */
2456 	ipha_t ripha;	/* With reversed addresses */
2457 	mblk_t *first_mp;
2458 	ipsec_in_t *ii;
2459 	tcph_t	*tcph;
2460 	conn_t	*connp;
2461 	ip_stack_t *ipst;
2462 
2463 	ASSERT(ill != NULL);
2464 
2465 	ASSERT(recv_ill != NULL);
2466 	ipst = recv_ill->ill_ipst;
2467 
2468 	first_mp = mp;
2469 	if (mctl_present) {
2470 		mp = first_mp->b_cont;
2471 		ASSERT(mp != NULL);
2472 
2473 		ii = (ipsec_in_t *)first_mp->b_rptr;
2474 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2475 	} else {
2476 		ii = NULL;
2477 	}
2478 
2479 	switch (ipha->ipha_protocol) {
2480 	case IPPROTO_UDP:
2481 		/*
2482 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2483 		 * transport header.
2484 		 */
2485 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2486 		    mp->b_wptr) {
2487 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2488 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2489 				goto discard_pkt;
2490 			}
2491 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2492 			ipha = (ipha_t *)&icmph[1];
2493 		}
2494 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2495 
2496 		/*
2497 		 * Attempt to find a client stream based on port.
2498 		 * Note that we do a reverse lookup since the header is
2499 		 * in the form we sent it out.
2500 		 * The ripha header is only used for the IP_UDP_MATCH and we
2501 		 * only set the src and dst addresses and protocol.
2502 		 */
2503 		ripha.ipha_src = ipha->ipha_dst;
2504 		ripha.ipha_dst = ipha->ipha_src;
2505 		ripha.ipha_protocol = ipha->ipha_protocol;
2506 		((uint16_t *)&ports)[0] = up[1];
2507 		((uint16_t *)&ports)[1] = up[0];
2508 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2509 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2510 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2511 		    icmph->icmph_type, icmph->icmph_code));
2512 
2513 		/* Have to change db_type after any pullupmsg */
2514 		DB_TYPE(mp) = M_CTL;
2515 
2516 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2517 		    mctl_present, ip_policy, recv_ill, zoneid);
2518 		return;
2519 
2520 	case IPPROTO_TCP:
2521 		/*
2522 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2523 		 * transport header.
2524 		 */
2525 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2526 		    mp->b_wptr) {
2527 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2528 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2529 				goto discard_pkt;
2530 			}
2531 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2532 			ipha = (ipha_t *)&icmph[1];
2533 		}
2534 		/*
2535 		 * Find a TCP client stream for this packet.
2536 		 * Note that we do a reverse lookup since the header is
2537 		 * in the form we sent it out.
2538 		 */
2539 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2540 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2541 		    ipst);
2542 		if (connp == NULL)
2543 			goto discard_pkt;
2544 
2545 		/* Have to change db_type after any pullupmsg */
2546 		DB_TYPE(mp) = M_CTL;
2547 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2548 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2549 		return;
2550 
2551 	case IPPROTO_SCTP:
2552 		/*
2553 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2554 		 * transport header.
2555 		 */
2556 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2557 		    mp->b_wptr) {
2558 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2559 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2560 				goto discard_pkt;
2561 			}
2562 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2563 			ipha = (ipha_t *)&icmph[1];
2564 		}
2565 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2566 		/*
2567 		 * Find a SCTP client stream for this packet.
2568 		 * Note that we do a reverse lookup since the header is
2569 		 * in the form we sent it out.
2570 		 * The ripha header is only used for the matching and we
2571 		 * only set the src and dst addresses, protocol, and version.
2572 		 */
2573 		ripha.ipha_src = ipha->ipha_dst;
2574 		ripha.ipha_dst = ipha->ipha_src;
2575 		ripha.ipha_protocol = ipha->ipha_protocol;
2576 		ripha.ipha_version_and_hdr_length =
2577 		    ipha->ipha_version_and_hdr_length;
2578 		((uint16_t *)&ports)[0] = up[1];
2579 		((uint16_t *)&ports)[1] = up[0];
2580 
2581 		/* Have to change db_type after any pullupmsg */
2582 		DB_TYPE(mp) = M_CTL;
2583 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2584 		    mctl_present, ip_policy, zoneid);
2585 		return;
2586 
2587 	case IPPROTO_ESP:
2588 	case IPPROTO_AH: {
2589 		int ipsec_rc;
2590 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2591 
2592 		/*
2593 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2594 		 * We will re-use the IPSEC_IN if it is already present as
2595 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2596 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2597 		 * one and attach it in the front.
2598 		 */
2599 		if (ii != NULL) {
2600 			/*
2601 			 * ip_fanout_proto_again converts the ICMP errors
2602 			 * that come back from AH/ESP to M_DATA so that
2603 			 * if it is non-AH/ESP and we do a pullupmsg in
2604 			 * this function, it would work. Convert it back
2605 			 * to M_CTL before we send up as this is a ICMP
2606 			 * error. This could have been generated locally or
2607 			 * by some router. Validate the inner IPsec
2608 			 * headers.
2609 			 *
2610 			 * NOTE : ill_index is used by ip_fanout_proto_again
2611 			 * to locate the ill.
2612 			 */
2613 			ASSERT(ill != NULL);
2614 			ii->ipsec_in_ill_index =
2615 			    ill->ill_phyint->phyint_ifindex;
2616 			ii->ipsec_in_rill_index =
2617 			    recv_ill->ill_phyint->phyint_ifindex;
2618 			DB_TYPE(first_mp->b_cont) = M_CTL;
2619 		} else {
2620 			/*
2621 			 * IPSEC_IN is not present. We attach a ipsec_in
2622 			 * message and send up to IPsec for validating
2623 			 * and removing the IPsec headers. Clear
2624 			 * ipsec_in_secure so that when we return
2625 			 * from IPsec, we don't mistakenly think that this
2626 			 * is a secure packet came from the network.
2627 			 *
2628 			 * NOTE : ill_index is used by ip_fanout_proto_again
2629 			 * to locate the ill.
2630 			 */
2631 			ASSERT(first_mp == mp);
2632 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2633 			if (first_mp == NULL) {
2634 				freemsg(mp);
2635 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2636 				return;
2637 			}
2638 			ii = (ipsec_in_t *)first_mp->b_rptr;
2639 
2640 			/* This is not a secure packet */
2641 			ii->ipsec_in_secure = B_FALSE;
2642 			first_mp->b_cont = mp;
2643 			DB_TYPE(mp) = M_CTL;
2644 			ASSERT(ill != NULL);
2645 			ii->ipsec_in_ill_index =
2646 			    ill->ill_phyint->phyint_ifindex;
2647 			ii->ipsec_in_rill_index =
2648 			    recv_ill->ill_phyint->phyint_ifindex;
2649 		}
2650 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2651 
2652 		if (!ipsec_loaded(ipss)) {
2653 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2654 			return;
2655 		}
2656 
2657 		if (ipha->ipha_protocol == IPPROTO_ESP)
2658 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2659 		else
2660 			ipsec_rc = ipsecah_icmp_error(first_mp);
2661 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2662 			return;
2663 
2664 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2665 		return;
2666 	}
2667 	default:
2668 		/*
2669 		 * The ripha header is only used for the lookup and we
2670 		 * only set the src and dst addresses and protocol.
2671 		 */
2672 		ripha.ipha_src = ipha->ipha_dst;
2673 		ripha.ipha_dst = ipha->ipha_src;
2674 		ripha.ipha_protocol = ipha->ipha_protocol;
2675 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2676 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2677 		    ntohl(ipha->ipha_dst),
2678 		    icmph->icmph_type, icmph->icmph_code));
2679 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2680 			ipha_t *in_ipha;
2681 
2682 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2683 			    mp->b_wptr) {
2684 				if (!pullupmsg(mp, (uchar_t *)ipha +
2685 				    hdr_length + sizeof (ipha_t) -
2686 				    mp->b_rptr)) {
2687 					goto discard_pkt;
2688 				}
2689 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2690 				ipha = (ipha_t *)&icmph[1];
2691 			}
2692 			/*
2693 			 * Caller has verified that length has to be
2694 			 * at least the size of IP header.
2695 			 */
2696 			ASSERT(hdr_length >= sizeof (ipha_t));
2697 			/*
2698 			 * Check the sanity of the inner IP header like
2699 			 * we did for the outer header.
2700 			 */
2701 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2702 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2703 				goto discard_pkt;
2704 			}
2705 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2706 				goto discard_pkt;
2707 			}
2708 			/* Check for Self-encapsulated tunnels */
2709 			if (in_ipha->ipha_src == ipha->ipha_src &&
2710 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2711 
2712 				mp = icmp_inbound_self_encap_error(mp,
2713 				    iph_hdr_length, hdr_length);
2714 				if (mp == NULL)
2715 					goto discard_pkt;
2716 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2717 				ipha = (ipha_t *)&icmph[1];
2718 				hdr_length = IPH_HDR_LENGTH(ipha);
2719 				/*
2720 				 * The packet in error is self-encapsualted.
2721 				 * And we are finding it further encapsulated
2722 				 * which we could not have possibly generated.
2723 				 */
2724 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2725 					goto discard_pkt;
2726 				}
2727 				icmp_inbound_error_fanout(q, ill, first_mp,
2728 				    icmph, ipha, iph_hdr_length, hdr_length,
2729 				    mctl_present, ip_policy, recv_ill, zoneid);
2730 				return;
2731 			}
2732 		}
2733 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2734 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2735 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2736 		    ii != NULL &&
2737 		    ii->ipsec_in_loopback &&
2738 		    ii->ipsec_in_secure) {
2739 			/*
2740 			 * For IP tunnels that get a looped-back
2741 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2742 			 * reported new MTU to take into account the IPsec
2743 			 * headers protecting this configured tunnel.
2744 			 *
2745 			 * This allows the tunnel module (tun.c) to blindly
2746 			 * accept the MTU reported in an ICMP "too big"
2747 			 * message.
2748 			 *
2749 			 * Non-looped back ICMP messages will just be
2750 			 * handled by the security protocols (if needed),
2751 			 * and the first subsequent packet will hit this
2752 			 * path.
2753 			 */
2754 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2755 			    ipsec_in_extra_length(first_mp));
2756 		}
2757 		/* Have to change db_type after any pullupmsg */
2758 		DB_TYPE(mp) = M_CTL;
2759 
2760 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2761 		    ip_policy, recv_ill, zoneid);
2762 		return;
2763 	}
2764 	/* NOTREACHED */
2765 discard_pkt:
2766 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2767 drop_pkt:;
2768 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2769 	freemsg(first_mp);
2770 }
2771 
2772 /*
2773  * Common IP options parser.
2774  *
2775  * Setup routine: fill in *optp with options-parsing state, then
2776  * tail-call ipoptp_next to return the first option.
2777  */
2778 uint8_t
2779 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2780 {
2781 	uint32_t totallen; /* total length of all options */
2782 
2783 	totallen = ipha->ipha_version_and_hdr_length -
2784 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2785 	totallen <<= 2;
2786 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2787 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2788 	optp->ipoptp_flags = 0;
2789 	return (ipoptp_next(optp));
2790 }
2791 
2792 /*
2793  * Common IP options parser: extract next option.
2794  */
2795 uint8_t
2796 ipoptp_next(ipoptp_t *optp)
2797 {
2798 	uint8_t *end = optp->ipoptp_end;
2799 	uint8_t *cur = optp->ipoptp_next;
2800 	uint8_t opt, len, pointer;
2801 
2802 	/*
2803 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2804 	 * has been corrupted.
2805 	 */
2806 	ASSERT(cur <= end);
2807 
2808 	if (cur == end)
2809 		return (IPOPT_EOL);
2810 
2811 	opt = cur[IPOPT_OPTVAL];
2812 
2813 	/*
2814 	 * Skip any NOP options.
2815 	 */
2816 	while (opt == IPOPT_NOP) {
2817 		cur++;
2818 		if (cur == end)
2819 			return (IPOPT_EOL);
2820 		opt = cur[IPOPT_OPTVAL];
2821 	}
2822 
2823 	if (opt == IPOPT_EOL)
2824 		return (IPOPT_EOL);
2825 
2826 	/*
2827 	 * Option requiring a length.
2828 	 */
2829 	if ((cur + 1) >= end) {
2830 		optp->ipoptp_flags |= IPOPTP_ERROR;
2831 		return (IPOPT_EOL);
2832 	}
2833 	len = cur[IPOPT_OLEN];
2834 	if (len < 2) {
2835 		optp->ipoptp_flags |= IPOPTP_ERROR;
2836 		return (IPOPT_EOL);
2837 	}
2838 	optp->ipoptp_cur = cur;
2839 	optp->ipoptp_len = len;
2840 	optp->ipoptp_next = cur + len;
2841 	if (cur + len > end) {
2842 		optp->ipoptp_flags |= IPOPTP_ERROR;
2843 		return (IPOPT_EOL);
2844 	}
2845 
2846 	/*
2847 	 * For the options which require a pointer field, make sure
2848 	 * its there, and make sure it points to either something
2849 	 * inside this option, or the end of the option.
2850 	 */
2851 	switch (opt) {
2852 	case IPOPT_RR:
2853 	case IPOPT_TS:
2854 	case IPOPT_LSRR:
2855 	case IPOPT_SSRR:
2856 		if (len <= IPOPT_OFFSET) {
2857 			optp->ipoptp_flags |= IPOPTP_ERROR;
2858 			return (opt);
2859 		}
2860 		pointer = cur[IPOPT_OFFSET];
2861 		if (pointer - 1 > len) {
2862 			optp->ipoptp_flags |= IPOPTP_ERROR;
2863 			return (opt);
2864 		}
2865 		break;
2866 	}
2867 
2868 	/*
2869 	 * Sanity check the pointer field based on the type of the
2870 	 * option.
2871 	 */
2872 	switch (opt) {
2873 	case IPOPT_RR:
2874 	case IPOPT_SSRR:
2875 	case IPOPT_LSRR:
2876 		if (pointer < IPOPT_MINOFF_SR)
2877 			optp->ipoptp_flags |= IPOPTP_ERROR;
2878 		break;
2879 	case IPOPT_TS:
2880 		if (pointer < IPOPT_MINOFF_IT)
2881 			optp->ipoptp_flags |= IPOPTP_ERROR;
2882 		/*
2883 		 * Note that the Internet Timestamp option also
2884 		 * contains two four bit fields (the Overflow field,
2885 		 * and the Flag field), which follow the pointer
2886 		 * field.  We don't need to check that these fields
2887 		 * fall within the length of the option because this
2888 		 * was implicitely done above.  We've checked that the
2889 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2890 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2891 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2892 		 */
2893 		ASSERT(len > IPOPT_POS_OV_FLG);
2894 		break;
2895 	}
2896 
2897 	return (opt);
2898 }
2899 
2900 /*
2901  * Use the outgoing IP header to create an IP_OPTIONS option the way
2902  * it was passed down from the application.
2903  */
2904 int
2905 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2906 {
2907 	ipoptp_t	opts;
2908 	const uchar_t	*opt;
2909 	uint8_t		optval;
2910 	uint8_t		optlen;
2911 	uint32_t	len = 0;
2912 	uchar_t	*buf1 = buf;
2913 
2914 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2915 	len += IP_ADDR_LEN;
2916 	bzero(buf1, IP_ADDR_LEN);
2917 
2918 	/*
2919 	 * OK to cast away const here, as we don't store through the returned
2920 	 * opts.ipoptp_cur pointer.
2921 	 */
2922 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2923 	    optval != IPOPT_EOL;
2924 	    optval = ipoptp_next(&opts)) {
2925 		int	off;
2926 
2927 		opt = opts.ipoptp_cur;
2928 		optlen = opts.ipoptp_len;
2929 		switch (optval) {
2930 		case IPOPT_SSRR:
2931 		case IPOPT_LSRR:
2932 
2933 			/*
2934 			 * Insert ipha_dst as the first entry in the source
2935 			 * route and move down the entries on step.
2936 			 * The last entry gets placed at buf1.
2937 			 */
2938 			buf[IPOPT_OPTVAL] = optval;
2939 			buf[IPOPT_OLEN] = optlen;
2940 			buf[IPOPT_OFFSET] = optlen;
2941 
2942 			off = optlen - IP_ADDR_LEN;
2943 			if (off < 0) {
2944 				/* No entries in source route */
2945 				break;
2946 			}
2947 			/* Last entry in source route */
2948 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2949 			off -= IP_ADDR_LEN;
2950 
2951 			while (off > 0) {
2952 				bcopy(opt + off,
2953 				    buf + off + IP_ADDR_LEN,
2954 				    IP_ADDR_LEN);
2955 				off -= IP_ADDR_LEN;
2956 			}
2957 			/* ipha_dst into first slot */
2958 			bcopy(&ipha->ipha_dst,
2959 			    buf + off + IP_ADDR_LEN,
2960 			    IP_ADDR_LEN);
2961 			buf += optlen;
2962 			len += optlen;
2963 			break;
2964 
2965 		case IPOPT_COMSEC:
2966 		case IPOPT_SECURITY:
2967 			/* if passing up a label is not ok, then remove */
2968 			if (is_system_labeled())
2969 				break;
2970 			/* FALLTHROUGH */
2971 		default:
2972 			bcopy(opt, buf, optlen);
2973 			buf += optlen;
2974 			len += optlen;
2975 			break;
2976 		}
2977 	}
2978 done:
2979 	/* Pad the resulting options */
2980 	while (len & 0x3) {
2981 		*buf++ = IPOPT_EOL;
2982 		len++;
2983 	}
2984 	return (len);
2985 }
2986 
2987 /*
2988  * Update any record route or timestamp options to include this host.
2989  * Reverse any source route option.
2990  * This routine assumes that the options are well formed i.e. that they
2991  * have already been checked.
2992  */
2993 static void
2994 icmp_options_update(ipha_t *ipha)
2995 {
2996 	ipoptp_t	opts;
2997 	uchar_t		*opt;
2998 	uint8_t		optval;
2999 	ipaddr_t	src;		/* Our local address */
3000 	ipaddr_t	dst;
3001 
3002 	ip2dbg(("icmp_options_update\n"));
3003 	src = ipha->ipha_src;
3004 	dst = ipha->ipha_dst;
3005 
3006 	for (optval = ipoptp_first(&opts, ipha);
3007 	    optval != IPOPT_EOL;
3008 	    optval = ipoptp_next(&opts)) {
3009 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3010 		opt = opts.ipoptp_cur;
3011 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3012 		    optval, opts.ipoptp_len));
3013 		switch (optval) {
3014 			int off1, off2;
3015 		case IPOPT_SSRR:
3016 		case IPOPT_LSRR:
3017 			/*
3018 			 * Reverse the source route.  The first entry
3019 			 * should be the next to last one in the current
3020 			 * source route (the last entry is our address).
3021 			 * The last entry should be the final destination.
3022 			 */
3023 			off1 = IPOPT_MINOFF_SR - 1;
3024 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3025 			if (off2 < 0) {
3026 				/* No entries in source route */
3027 				ip1dbg((
3028 				    "icmp_options_update: bad src route\n"));
3029 				break;
3030 			}
3031 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3032 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3033 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3034 			off2 -= IP_ADDR_LEN;
3035 
3036 			while (off1 < off2) {
3037 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3038 				bcopy((char *)opt + off2, (char *)opt + off1,
3039 				    IP_ADDR_LEN);
3040 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3041 				off1 += IP_ADDR_LEN;
3042 				off2 -= IP_ADDR_LEN;
3043 			}
3044 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3045 			break;
3046 		}
3047 	}
3048 }
3049 
3050 /*
3051  * Process received ICMP Redirect messages.
3052  */
3053 static void
3054 icmp_redirect(ill_t *ill, mblk_t *mp)
3055 {
3056 	ipha_t	*ipha;
3057 	int	iph_hdr_length;
3058 	icmph_t	*icmph;
3059 	ipha_t	*ipha_err;
3060 	ire_t	*ire;
3061 	ire_t	*prev_ire;
3062 	ire_t	*save_ire;
3063 	ipaddr_t  src, dst, gateway;
3064 	iulp_t	ulp_info = { 0 };
3065 	int	error;
3066 	ip_stack_t *ipst;
3067 
3068 	ASSERT(ill != NULL);
3069 	ipst = ill->ill_ipst;
3070 
3071 	ipha = (ipha_t *)mp->b_rptr;
3072 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3073 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3074 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3075 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3076 		freemsg(mp);
3077 		return;
3078 	}
3079 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3080 	ipha_err = (ipha_t *)&icmph[1];
3081 	src = ipha->ipha_src;
3082 	dst = ipha_err->ipha_dst;
3083 	gateway = icmph->icmph_rd_gateway;
3084 	/* Make sure the new gateway is reachable somehow. */
3085 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3086 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3087 	/*
3088 	 * Make sure we had a route for the dest in question and that
3089 	 * that route was pointing to the old gateway (the source of the
3090 	 * redirect packet.)
3091 	 */
3092 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3093 	    NULL, MATCH_IRE_GW, ipst);
3094 	/*
3095 	 * Check that
3096 	 *	the redirect was not from ourselves
3097 	 *	the new gateway and the old gateway are directly reachable
3098 	 */
3099 	if (!prev_ire ||
3100 	    !ire ||
3101 	    ire->ire_type == IRE_LOCAL) {
3102 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3103 		freemsg(mp);
3104 		if (ire != NULL)
3105 			ire_refrele(ire);
3106 		if (prev_ire != NULL)
3107 			ire_refrele(prev_ire);
3108 		return;
3109 	}
3110 
3111 	/*
3112 	 * Should we use the old ULP info to create the new gateway?  From
3113 	 * a user's perspective, we should inherit the info so that it
3114 	 * is a "smooth" transition.  If we do not do that, then new
3115 	 * connections going thru the new gateway will have no route metrics,
3116 	 * which is counter-intuitive to user.  From a network point of
3117 	 * view, this may or may not make sense even though the new gateway
3118 	 * is still directly connected to us so the route metrics should not
3119 	 * change much.
3120 	 *
3121 	 * But if the old ire_uinfo is not initialized, we do another
3122 	 * recursive lookup on the dest using the new gateway.  There may
3123 	 * be a route to that.  If so, use it to initialize the redirect
3124 	 * route.
3125 	 */
3126 	if (prev_ire->ire_uinfo.iulp_set) {
3127 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3128 	} else {
3129 		ire_t *tmp_ire;
3130 		ire_t *sire;
3131 
3132 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3133 		    ALL_ZONES, 0, NULL,
3134 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3135 		    ipst);
3136 		if (sire != NULL) {
3137 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3138 			/*
3139 			 * If sire != NULL, ire_ftable_lookup() should not
3140 			 * return a NULL value.
3141 			 */
3142 			ASSERT(tmp_ire != NULL);
3143 			ire_refrele(tmp_ire);
3144 			ire_refrele(sire);
3145 		} else if (tmp_ire != NULL) {
3146 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3147 			    sizeof (iulp_t));
3148 			ire_refrele(tmp_ire);
3149 		}
3150 	}
3151 	if (prev_ire->ire_type == IRE_CACHE)
3152 		ire_delete(prev_ire);
3153 	ire_refrele(prev_ire);
3154 	/*
3155 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3156 	 * require TOS routing
3157 	 */
3158 	switch (icmph->icmph_code) {
3159 	case 0:
3160 	case 1:
3161 		/* TODO: TOS specificity for cases 2 and 3 */
3162 	case 2:
3163 	case 3:
3164 		break;
3165 	default:
3166 		freemsg(mp);
3167 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3168 		ire_refrele(ire);
3169 		return;
3170 	}
3171 	/*
3172 	 * Create a Route Association.  This will allow us to remember that
3173 	 * someone we believe told us to use the particular gateway.
3174 	 */
3175 	save_ire = ire;
3176 	ire = ire_create(
3177 	    (uchar_t *)&dst,			/* dest addr */
3178 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3179 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3180 	    (uchar_t *)&gateway,		/* gateway addr */
3181 	    &save_ire->ire_max_frag,		/* max frag */
3182 	    NULL,				/* no src nce */
3183 	    NULL,				/* no rfq */
3184 	    NULL,				/* no stq */
3185 	    IRE_HOST,
3186 	    NULL,				/* ipif */
3187 	    0,					/* cmask */
3188 	    0,					/* phandle */
3189 	    0,					/* ihandle */
3190 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3191 	    &ulp_info,
3192 	    NULL,				/* tsol_gc_t */
3193 	    NULL,				/* gcgrp */
3194 	    ipst);
3195 
3196 	if (ire == NULL) {
3197 		freemsg(mp);
3198 		ire_refrele(save_ire);
3199 		return;
3200 	}
3201 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3202 	ire_refrele(save_ire);
3203 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3204 
3205 	if (error == 0) {
3206 		ire_refrele(ire);		/* Held in ire_add_v4 */
3207 		/* tell routing sockets that we received a redirect */
3208 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3209 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3210 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3211 	}
3212 
3213 	/*
3214 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3215 	 * This together with the added IRE has the effect of
3216 	 * modifying an existing redirect.
3217 	 */
3218 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3219 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3220 	if (prev_ire != NULL) {
3221 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3222 			ire_delete(prev_ire);
3223 		ire_refrele(prev_ire);
3224 	}
3225 
3226 	freemsg(mp);
3227 }
3228 
3229 /*
3230  * Generate an ICMP parameter problem message.
3231  */
3232 static void
3233 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3234 	ip_stack_t *ipst)
3235 {
3236 	icmph_t	icmph;
3237 	boolean_t mctl_present;
3238 	mblk_t *first_mp;
3239 
3240 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3241 
3242 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3243 		if (mctl_present)
3244 			freeb(first_mp);
3245 		return;
3246 	}
3247 
3248 	bzero(&icmph, sizeof (icmph_t));
3249 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3250 	icmph.icmph_pp_ptr = ptr;
3251 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3252 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3253 	    ipst);
3254 }
3255 
3256 /*
3257  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3258  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3259  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3260  * an icmp error packet can be sent.
3261  * Assigns an appropriate source address to the packet. If ipha_dst is
3262  * one of our addresses use it for source. Otherwise pick a source based
3263  * on a route lookup back to ipha_src.
3264  * Note that ipha_src must be set here since the
3265  * packet is likely to arrive on an ill queue in ip_wput() which will
3266  * not set a source address.
3267  */
3268 static void
3269 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3270     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3271 {
3272 	ipaddr_t dst;
3273 	icmph_t	*icmph;
3274 	ipha_t	*ipha;
3275 	uint_t	len_needed;
3276 	size_t	msg_len;
3277 	mblk_t	*mp1;
3278 	ipaddr_t src;
3279 	ire_t	*ire;
3280 	mblk_t *ipsec_mp;
3281 	ipsec_out_t	*io = NULL;
3282 
3283 	if (mctl_present) {
3284 		/*
3285 		 * If it is :
3286 		 *
3287 		 * 1) a IPSEC_OUT, then this is caused by outbound
3288 		 *    datagram originating on this host. IPsec processing
3289 		 *    may or may not have been done. Refer to comments above
3290 		 *    icmp_inbound_error_fanout for details.
3291 		 *
3292 		 * 2) a IPSEC_IN if we are generating a icmp_message
3293 		 *    for an incoming datagram destined for us i.e called
3294 		 *    from ip_fanout_send_icmp.
3295 		 */
3296 		ipsec_info_t *in;
3297 		ipsec_mp = mp;
3298 		mp = ipsec_mp->b_cont;
3299 
3300 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3301 		ipha = (ipha_t *)mp->b_rptr;
3302 
3303 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3304 		    in->ipsec_info_type == IPSEC_IN);
3305 
3306 		if (in->ipsec_info_type == IPSEC_IN) {
3307 			/*
3308 			 * Convert the IPSEC_IN to IPSEC_OUT.
3309 			 */
3310 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3311 				BUMP_MIB(&ipst->ips_ip_mib,
3312 				    ipIfStatsOutDiscards);
3313 				return;
3314 			}
3315 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3316 		} else {
3317 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3318 			io = (ipsec_out_t *)in;
3319 			/*
3320 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3321 			 * ire lookup.
3322 			 */
3323 			io->ipsec_out_proc_begin = B_FALSE;
3324 		}
3325 		ASSERT(zoneid == io->ipsec_out_zoneid);
3326 		ASSERT(zoneid != ALL_ZONES);
3327 	} else {
3328 		/*
3329 		 * This is in clear. The icmp message we are building
3330 		 * here should go out in clear.
3331 		 *
3332 		 * Pardon the convolution of it all, but it's easier to
3333 		 * allocate a "use cleartext" IPSEC_IN message and convert
3334 		 * it than it is to allocate a new one.
3335 		 */
3336 		ipsec_in_t *ii;
3337 		ASSERT(DB_TYPE(mp) == M_DATA);
3338 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3339 		if (ipsec_mp == NULL) {
3340 			freemsg(mp);
3341 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3342 			return;
3343 		}
3344 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3345 
3346 		/* This is not a secure packet */
3347 		ii->ipsec_in_secure = B_FALSE;
3348 		/*
3349 		 * For trusted extensions using a shared IP address we can
3350 		 * send using any zoneid.
3351 		 */
3352 		if (zoneid == ALL_ZONES)
3353 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3354 		else
3355 			ii->ipsec_in_zoneid = zoneid;
3356 		ipsec_mp->b_cont = mp;
3357 		ipha = (ipha_t *)mp->b_rptr;
3358 		/*
3359 		 * Convert the IPSEC_IN to IPSEC_OUT.
3360 		 */
3361 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3362 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3363 			return;
3364 		}
3365 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3366 	}
3367 
3368 	/* Remember our eventual destination */
3369 	dst = ipha->ipha_src;
3370 
3371 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3372 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3373 	if (ire != NULL &&
3374 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3375 		src = ipha->ipha_dst;
3376 	} else {
3377 		if (ire != NULL)
3378 			ire_refrele(ire);
3379 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3380 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3381 		    ipst);
3382 		if (ire == NULL) {
3383 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3384 			freemsg(ipsec_mp);
3385 			return;
3386 		}
3387 		src = ire->ire_src_addr;
3388 	}
3389 
3390 	if (ire != NULL)
3391 		ire_refrele(ire);
3392 
3393 	/*
3394 	 * Check if we can send back more then 8 bytes in addition to
3395 	 * the IP header.  We try to send 64 bytes of data and the internal
3396 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3397 	 */
3398 	len_needed = IPH_HDR_LENGTH(ipha);
3399 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3400 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3401 
3402 		if (!pullupmsg(mp, -1)) {
3403 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3404 			freemsg(ipsec_mp);
3405 			return;
3406 		}
3407 		ipha = (ipha_t *)mp->b_rptr;
3408 
3409 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3410 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3411 			    len_needed));
3412 		} else {
3413 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3414 
3415 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3416 			len_needed += ip_hdr_length_v6(mp, ip6h);
3417 		}
3418 	}
3419 	len_needed += ipst->ips_ip_icmp_return;
3420 	msg_len = msgdsize(mp);
3421 	if (msg_len > len_needed) {
3422 		(void) adjmsg(mp, len_needed - msg_len);
3423 		msg_len = len_needed;
3424 	}
3425 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3426 	if (mp1 == NULL) {
3427 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3428 		freemsg(ipsec_mp);
3429 		return;
3430 	}
3431 	mp1->b_cont = mp;
3432 	mp = mp1;
3433 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3434 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3435 	    io->ipsec_out_type == IPSEC_OUT);
3436 	ipsec_mp->b_cont = mp;
3437 
3438 	/*
3439 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3440 	 * node generates be accepted in peace by all on-host destinations.
3441 	 * If we do NOT assume that all on-host destinations trust
3442 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3443 	 * (Look for ipsec_out_icmp_loopback).
3444 	 */
3445 	io->ipsec_out_icmp_loopback = B_TRUE;
3446 
3447 	ipha = (ipha_t *)mp->b_rptr;
3448 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3449 	*ipha = icmp_ipha;
3450 	ipha->ipha_src = src;
3451 	ipha->ipha_dst = dst;
3452 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3453 	msg_len += sizeof (icmp_ipha) + len;
3454 	if (msg_len > IP_MAXPACKET) {
3455 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3456 		msg_len = IP_MAXPACKET;
3457 	}
3458 	ipha->ipha_length = htons((uint16_t)msg_len);
3459 	icmph = (icmph_t *)&ipha[1];
3460 	bcopy(stuff, icmph, len);
3461 	icmph->icmph_checksum = 0;
3462 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3463 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3464 	put(q, ipsec_mp);
3465 }
3466 
3467 /*
3468  * Determine if an ICMP error packet can be sent given the rate limit.
3469  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3470  * in milliseconds) and a burst size. Burst size number of packets can
3471  * be sent arbitrarely closely spaced.
3472  * The state is tracked using two variables to implement an approximate
3473  * token bucket filter:
3474  *	icmp_pkt_err_last - lbolt value when the last burst started
3475  *	icmp_pkt_err_sent - number of packets sent in current burst
3476  */
3477 boolean_t
3478 icmp_err_rate_limit(ip_stack_t *ipst)
3479 {
3480 	clock_t now = TICK_TO_MSEC(lbolt);
3481 	uint_t refilled; /* Number of packets refilled in tbf since last */
3482 	/* Guard against changes by loading into local variable */
3483 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3484 
3485 	if (err_interval == 0)
3486 		return (B_FALSE);
3487 
3488 	if (ipst->ips_icmp_pkt_err_last > now) {
3489 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3490 		ipst->ips_icmp_pkt_err_last = 0;
3491 		ipst->ips_icmp_pkt_err_sent = 0;
3492 	}
3493 	/*
3494 	 * If we are in a burst update the token bucket filter.
3495 	 * Update the "last" time to be close to "now" but make sure
3496 	 * we don't loose precision.
3497 	 */
3498 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3499 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3500 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3501 			ipst->ips_icmp_pkt_err_sent = 0;
3502 		} else {
3503 			ipst->ips_icmp_pkt_err_sent -= refilled;
3504 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3505 		}
3506 	}
3507 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3508 		/* Start of new burst */
3509 		ipst->ips_icmp_pkt_err_last = now;
3510 	}
3511 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3512 		ipst->ips_icmp_pkt_err_sent++;
3513 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3514 		    ipst->ips_icmp_pkt_err_sent));
3515 		return (B_FALSE);
3516 	}
3517 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3518 	return (B_TRUE);
3519 }
3520 
3521 /*
3522  * Check if it is ok to send an IPv4 ICMP error packet in
3523  * response to the IPv4 packet in mp.
3524  * Free the message and return null if no
3525  * ICMP error packet should be sent.
3526  */
3527 static mblk_t *
3528 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3529 {
3530 	icmph_t	*icmph;
3531 	ipha_t	*ipha;
3532 	uint_t	len_needed;
3533 	ire_t	*src_ire;
3534 	ire_t	*dst_ire;
3535 
3536 	if (!mp)
3537 		return (NULL);
3538 	ipha = (ipha_t *)mp->b_rptr;
3539 	if (ip_csum_hdr(ipha)) {
3540 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3541 		freemsg(mp);
3542 		return (NULL);
3543 	}
3544 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3545 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3546 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3547 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3548 	if (src_ire != NULL || dst_ire != NULL ||
3549 	    CLASSD(ipha->ipha_dst) ||
3550 	    CLASSD(ipha->ipha_src) ||
3551 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3552 		/* Note: only errors to the fragment with offset 0 */
3553 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3554 		freemsg(mp);
3555 		if (src_ire != NULL)
3556 			ire_refrele(src_ire);
3557 		if (dst_ire != NULL)
3558 			ire_refrele(dst_ire);
3559 		return (NULL);
3560 	}
3561 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3562 		/*
3563 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3564 		 * errors in response to any ICMP errors.
3565 		 */
3566 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3567 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3568 			if (!pullupmsg(mp, len_needed)) {
3569 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3570 				freemsg(mp);
3571 				return (NULL);
3572 			}
3573 			ipha = (ipha_t *)mp->b_rptr;
3574 		}
3575 		icmph = (icmph_t *)
3576 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3577 		switch (icmph->icmph_type) {
3578 		case ICMP_DEST_UNREACHABLE:
3579 		case ICMP_SOURCE_QUENCH:
3580 		case ICMP_TIME_EXCEEDED:
3581 		case ICMP_PARAM_PROBLEM:
3582 		case ICMP_REDIRECT:
3583 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3584 			freemsg(mp);
3585 			return (NULL);
3586 		default:
3587 			break;
3588 		}
3589 	}
3590 	/*
3591 	 * If this is a labeled system, then check to see if we're allowed to
3592 	 * send a response to this particular sender.  If not, then just drop.
3593 	 */
3594 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3595 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3596 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3597 		freemsg(mp);
3598 		return (NULL);
3599 	}
3600 	if (icmp_err_rate_limit(ipst)) {
3601 		/*
3602 		 * Only send ICMP error packets every so often.
3603 		 * This should be done on a per port/source basis,
3604 		 * but for now this will suffice.
3605 		 */
3606 		freemsg(mp);
3607 		return (NULL);
3608 	}
3609 	return (mp);
3610 }
3611 
3612 /*
3613  * Generate an ICMP redirect message.
3614  */
3615 static void
3616 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3617 {
3618 	icmph_t	icmph;
3619 
3620 	/*
3621 	 * We are called from ip_rput where we could
3622 	 * not have attached an IPSEC_IN.
3623 	 */
3624 	ASSERT(mp->b_datap->db_type == M_DATA);
3625 
3626 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3627 		return;
3628 	}
3629 
3630 	bzero(&icmph, sizeof (icmph_t));
3631 	icmph.icmph_type = ICMP_REDIRECT;
3632 	icmph.icmph_code = 1;
3633 	icmph.icmph_rd_gateway = gateway;
3634 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3635 	/* Redirects sent by router, and router is global zone */
3636 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3637 }
3638 
3639 /*
3640  * Generate an ICMP time exceeded message.
3641  */
3642 void
3643 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3644     ip_stack_t *ipst)
3645 {
3646 	icmph_t	icmph;
3647 	boolean_t mctl_present;
3648 	mblk_t *first_mp;
3649 
3650 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3651 
3652 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3653 		if (mctl_present)
3654 			freeb(first_mp);
3655 		return;
3656 	}
3657 
3658 	bzero(&icmph, sizeof (icmph_t));
3659 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3660 	icmph.icmph_code = code;
3661 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3662 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3663 	    ipst);
3664 }
3665 
3666 /*
3667  * Generate an ICMP unreachable message.
3668  */
3669 void
3670 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3671     ip_stack_t *ipst)
3672 {
3673 	icmph_t	icmph;
3674 	mblk_t *first_mp;
3675 	boolean_t mctl_present;
3676 
3677 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3678 
3679 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3680 		if (mctl_present)
3681 			freeb(first_mp);
3682 		return;
3683 	}
3684 
3685 	bzero(&icmph, sizeof (icmph_t));
3686 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3687 	icmph.icmph_code = code;
3688 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3689 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3690 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3691 	    zoneid, ipst);
3692 }
3693 
3694 /*
3695  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3696  * duplicate.  As long as someone else holds the address, the interface will
3697  * stay down.  When that conflict goes away, the interface is brought back up.
3698  * This is done so that accidental shutdowns of addresses aren't made
3699  * permanent.  Your server will recover from a failure.
3700  *
3701  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3702  * user space process (dhcpagent).
3703  *
3704  * Recovery completes if ARP reports that the address is now ours (via
3705  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3706  *
3707  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3708  */
3709 static void
3710 ipif_dup_recovery(void *arg)
3711 {
3712 	ipif_t *ipif = arg;
3713 	ill_t *ill = ipif->ipif_ill;
3714 	mblk_t *arp_add_mp;
3715 	mblk_t *arp_del_mp;
3716 	area_t *area;
3717 	ip_stack_t *ipst = ill->ill_ipst;
3718 
3719 	ipif->ipif_recovery_id = 0;
3720 
3721 	/*
3722 	 * No lock needed for moving or condemned check, as this is just an
3723 	 * optimization.
3724 	 */
3725 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3726 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3727 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3728 		/* No reason to try to bring this address back. */
3729 		return;
3730 	}
3731 
3732 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3733 		goto alloc_fail;
3734 
3735 	if (ipif->ipif_arp_del_mp == NULL) {
3736 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3737 			goto alloc_fail;
3738 		ipif->ipif_arp_del_mp = arp_del_mp;
3739 	}
3740 
3741 	/* Setting the 'unverified' flag restarts DAD */
3742 	area = (area_t *)arp_add_mp->b_rptr;
3743 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3744 	    ACE_F_UNVERIFIED;
3745 	putnext(ill->ill_rq, arp_add_mp);
3746 	return;
3747 
3748 alloc_fail:
3749 	/*
3750 	 * On allocation failure, just restart the timer.  Note that the ipif
3751 	 * is down here, so no other thread could be trying to start a recovery
3752 	 * timer.  The ill_lock protects the condemned flag and the recovery
3753 	 * timer ID.
3754 	 */
3755 	freemsg(arp_add_mp);
3756 	mutex_enter(&ill->ill_lock);
3757 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3758 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3759 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3760 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3761 	}
3762 	mutex_exit(&ill->ill_lock);
3763 }
3764 
3765 /*
3766  * This is for exclusive changes due to ARP.  Either tear down an interface due
3767  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3768  */
3769 /* ARGSUSED */
3770 static void
3771 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3772 {
3773 	ill_t	*ill = rq->q_ptr;
3774 	arh_t *arh;
3775 	ipaddr_t src;
3776 	ipif_t	*ipif;
3777 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3778 	char hbuf[MAC_STR_LEN];
3779 	char sbuf[INET_ADDRSTRLEN];
3780 	const char *failtype;
3781 	boolean_t bring_up;
3782 	ip_stack_t *ipst = ill->ill_ipst;
3783 
3784 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3785 	case AR_CN_READY:
3786 		failtype = NULL;
3787 		bring_up = B_TRUE;
3788 		break;
3789 	case AR_CN_FAILED:
3790 		failtype = "in use";
3791 		bring_up = B_FALSE;
3792 		break;
3793 	default:
3794 		failtype = "claimed";
3795 		bring_up = B_FALSE;
3796 		break;
3797 	}
3798 
3799 	arh = (arh_t *)mp->b_cont->b_rptr;
3800 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3801 
3802 	/* Handle failures due to probes */
3803 	if (src == 0) {
3804 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3805 		    IP_ADDR_LEN);
3806 	}
3807 
3808 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3809 	    sizeof (hbuf));
3810 	(void) ip_dot_addr(src, sbuf);
3811 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3812 
3813 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3814 		    ipif->ipif_lcl_addr != src) {
3815 			continue;
3816 		}
3817 
3818 		/*
3819 		 * If we failed on a recovery probe, then restart the timer to
3820 		 * try again later.
3821 		 */
3822 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3823 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3824 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3825 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3826 		    ipst->ips_ip_dup_recovery > 0 &&
3827 		    ipif->ipif_recovery_id == 0) {
3828 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3829 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3830 			continue;
3831 		}
3832 
3833 		/*
3834 		 * If what we're trying to do has already been done, then do
3835 		 * nothing.
3836 		 */
3837 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3838 			continue;
3839 
3840 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3841 
3842 		if (failtype == NULL) {
3843 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3844 			    ibuf);
3845 		} else {
3846 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3847 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3848 		}
3849 
3850 		if (bring_up) {
3851 			ASSERT(ill->ill_dl_up);
3852 			/*
3853 			 * Free up the ARP delete message so we can allocate
3854 			 * a fresh one through the normal path.
3855 			 */
3856 			freemsg(ipif->ipif_arp_del_mp);
3857 			ipif->ipif_arp_del_mp = NULL;
3858 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3859 			    EINPROGRESS) {
3860 				ipif->ipif_addr_ready = 1;
3861 				(void) ipif_up_done(ipif);
3862 			}
3863 			continue;
3864 		}
3865 
3866 		mutex_enter(&ill->ill_lock);
3867 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3868 		ipif->ipif_flags |= IPIF_DUPLICATE;
3869 		ill->ill_ipif_dup_count++;
3870 		mutex_exit(&ill->ill_lock);
3871 		/*
3872 		 * Already exclusive on the ill; no need to handle deferred
3873 		 * processing here.
3874 		 */
3875 		(void) ipif_down(ipif, NULL, NULL);
3876 		ipif_down_tail(ipif);
3877 		mutex_enter(&ill->ill_lock);
3878 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3879 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3880 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3881 		    ipst->ips_ip_dup_recovery > 0) {
3882 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3883 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3884 		}
3885 		mutex_exit(&ill->ill_lock);
3886 	}
3887 	freemsg(mp);
3888 }
3889 
3890 /* ARGSUSED */
3891 static void
3892 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3893 {
3894 	ill_t	*ill = rq->q_ptr;
3895 	arh_t *arh;
3896 	ipaddr_t src;
3897 	ipif_t	*ipif;
3898 
3899 	arh = (arh_t *)mp->b_cont->b_rptr;
3900 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3901 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3902 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3903 			(void) ipif_resolver_up(ipif, Res_act_defend);
3904 	}
3905 	freemsg(mp);
3906 }
3907 
3908 /*
3909  * News from ARP.  ARP sends notification of interesting events down
3910  * to its clients using M_CTL messages with the interesting ARP packet
3911  * attached via b_cont.
3912  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3913  * queue as opposed to ARP sending the message to all the clients, i.e. all
3914  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3915  * table if a cache IRE is found to delete all the entries for the address in
3916  * the packet.
3917  */
3918 static void
3919 ip_arp_news(queue_t *q, mblk_t *mp)
3920 {
3921 	arcn_t		*arcn;
3922 	arh_t		*arh;
3923 	ire_t		*ire = NULL;
3924 	char		hbuf[MAC_STR_LEN];
3925 	char		sbuf[INET_ADDRSTRLEN];
3926 	ipaddr_t	src;
3927 	in6_addr_t	v6src;
3928 	boolean_t	isv6 = B_FALSE;
3929 	ipif_t		*ipif;
3930 	ill_t		*ill;
3931 	ip_stack_t	*ipst;
3932 
3933 	if (CONN_Q(q)) {
3934 		conn_t *connp = Q_TO_CONN(q);
3935 
3936 		ipst = connp->conn_netstack->netstack_ip;
3937 	} else {
3938 		ill_t *ill = (ill_t *)q->q_ptr;
3939 
3940 		ipst = ill->ill_ipst;
3941 	}
3942 
3943 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3944 		if (q->q_next) {
3945 			putnext(q, mp);
3946 		} else
3947 			freemsg(mp);
3948 		return;
3949 	}
3950 	arh = (arh_t *)mp->b_cont->b_rptr;
3951 	/* Is it one we are interested in? */
3952 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3953 		isv6 = B_TRUE;
3954 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3955 		    IPV6_ADDR_LEN);
3956 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3957 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3958 		    IP_ADDR_LEN);
3959 	} else {
3960 		freemsg(mp);
3961 		return;
3962 	}
3963 
3964 	ill = q->q_ptr;
3965 
3966 	arcn = (arcn_t *)mp->b_rptr;
3967 	switch (arcn->arcn_code) {
3968 	case AR_CN_BOGON:
3969 		/*
3970 		 * Someone is sending ARP packets with a source protocol
3971 		 * address that we have published and for which we believe our
3972 		 * entry is authoritative and (when ill_arp_extend is set)
3973 		 * verified to be unique on the network.
3974 		 *
3975 		 * The ARP module internally handles the cases where the sender
3976 		 * is just probing (for DAD) and where the hardware address of
3977 		 * a non-authoritative entry has changed.  Thus, these are the
3978 		 * real conflicts, and we have to do resolution.
3979 		 *
3980 		 * We back away quickly from the address if it's from DHCP or
3981 		 * otherwise temporary and hasn't been used recently (or at
3982 		 * all).  We'd like to include "deprecated" addresses here as
3983 		 * well (as there's no real reason to defend something we're
3984 		 * discarding), but IPMP "reuses" this flag to mean something
3985 		 * other than the standard meaning.
3986 		 *
3987 		 * If the ARP module above is not extended (meaning that it
3988 		 * doesn't know how to defend the address), then we just log
3989 		 * the problem as we always did and continue on.  It's not
3990 		 * right, but there's little else we can do, and those old ATM
3991 		 * users are going away anyway.
3992 		 */
3993 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3994 		    hbuf, sizeof (hbuf));
3995 		(void) ip_dot_addr(src, sbuf);
3996 		if (isv6) {
3997 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3998 			    ipst);
3999 		} else {
4000 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
4001 		}
4002 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
4003 			uint32_t now;
4004 			uint32_t maxage;
4005 			clock_t lused;
4006 			uint_t maxdefense;
4007 			uint_t defs;
4008 
4009 			/*
4010 			 * First, figure out if this address hasn't been used
4011 			 * in a while.  If it hasn't, then it's a better
4012 			 * candidate for abandoning.
4013 			 */
4014 			ipif = ire->ire_ipif;
4015 			ASSERT(ipif != NULL);
4016 			now = gethrestime_sec();
4017 			maxage = now - ire->ire_create_time;
4018 			if (maxage > ipst->ips_ip_max_temp_idle)
4019 				maxage = ipst->ips_ip_max_temp_idle;
4020 			lused = drv_hztousec(ddi_get_lbolt() -
4021 			    ire->ire_last_used_time) / MICROSEC + 1;
4022 			if (lused >= maxage && (ipif->ipif_flags &
4023 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4024 				maxdefense = ipst->ips_ip_max_temp_defend;
4025 			else
4026 				maxdefense = ipst->ips_ip_max_defend;
4027 
4028 			/*
4029 			 * Now figure out how many times we've defended
4030 			 * ourselves.  Ignore defenses that happened long in
4031 			 * the past.
4032 			 */
4033 			mutex_enter(&ire->ire_lock);
4034 			if ((defs = ire->ire_defense_count) > 0 &&
4035 			    now - ire->ire_defense_time >
4036 			    ipst->ips_ip_defend_interval) {
4037 				ire->ire_defense_count = defs = 0;
4038 			}
4039 			ire->ire_defense_count++;
4040 			ire->ire_defense_time = now;
4041 			mutex_exit(&ire->ire_lock);
4042 			ill_refhold(ill);
4043 			ire_refrele(ire);
4044 
4045 			/*
4046 			 * If we've defended ourselves too many times already,
4047 			 * then give up and tear down the interface(s) using
4048 			 * this address.  Otherwise, defend by sending out a
4049 			 * gratuitous ARP.
4050 			 */
4051 			if (defs >= maxdefense && ill->ill_arp_extend) {
4052 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4053 				    B_FALSE);
4054 			} else {
4055 				cmn_err(CE_WARN,
4056 				    "node %s is using our IP address %s on %s",
4057 				    hbuf, sbuf, ill->ill_name);
4058 				/*
4059 				 * If this is an old (ATM) ARP module, then
4060 				 * don't try to defend the address.  Remain
4061 				 * compatible with the old behavior.  Defend
4062 				 * only with new ARP.
4063 				 */
4064 				if (ill->ill_arp_extend) {
4065 					qwriter_ip(ill, q, mp, ip_arp_defend,
4066 					    NEW_OP, B_FALSE);
4067 				} else {
4068 					ill_refrele(ill);
4069 				}
4070 			}
4071 			return;
4072 		}
4073 		cmn_err(CE_WARN,
4074 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4075 		    hbuf, sbuf, ill->ill_name);
4076 		if (ire != NULL)
4077 			ire_refrele(ire);
4078 		break;
4079 	case AR_CN_ANNOUNCE:
4080 		if (isv6) {
4081 			/*
4082 			 * For XRESOLV interfaces.
4083 			 * Delete the IRE cache entry and NCE for this
4084 			 * v6 address
4085 			 */
4086 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4087 			/*
4088 			 * If v6src is a non-zero, it's a router address
4089 			 * as below. Do the same sort of thing to clean
4090 			 * out off-net IRE_CACHE entries that go through
4091 			 * the router.
4092 			 */
4093 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4094 				ire_walk_v6(ire_delete_cache_gw_v6,
4095 				    (char *)&v6src, ALL_ZONES, ipst);
4096 			}
4097 		} else {
4098 			nce_hw_map_t hwm;
4099 
4100 			/*
4101 			 * ARP gives us a copy of any packet where it thinks
4102 			 * the address has changed, so that we can update our
4103 			 * caches.  We're responsible for caching known answers
4104 			 * in the current design.  We check whether the
4105 			 * hardware address really has changed in all of our
4106 			 * entries that have cached this mapping, and if so, we
4107 			 * blow them away.  This way we will immediately pick
4108 			 * up the rare case of a host changing hardware
4109 			 * address.
4110 			 */
4111 			if (src == 0)
4112 				break;
4113 			hwm.hwm_addr = src;
4114 			hwm.hwm_hwlen = arh->arh_hlen;
4115 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4116 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4117 			ndp_walk_common(ipst->ips_ndp4, NULL,
4118 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4119 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4120 		}
4121 		break;
4122 	case AR_CN_READY:
4123 		/* No external v6 resolver has a contract to use this */
4124 		if (isv6)
4125 			break;
4126 		/* If the link is down, we'll retry this later */
4127 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4128 			break;
4129 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4130 		    NULL, NULL, ipst);
4131 		if (ipif != NULL) {
4132 			/*
4133 			 * If this is a duplicate recovery, then we now need to
4134 			 * go exclusive to bring this thing back up.
4135 			 */
4136 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4137 			    IPIF_DUPLICATE) {
4138 				ipif_refrele(ipif);
4139 				ill_refhold(ill);
4140 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4141 				    B_FALSE);
4142 				return;
4143 			}
4144 			/*
4145 			 * If this is the first notice that this address is
4146 			 * ready, then let the user know now.
4147 			 */
4148 			if ((ipif->ipif_flags & IPIF_UP) &&
4149 			    !ipif->ipif_addr_ready) {
4150 				ipif_mask_reply(ipif);
4151 				ip_rts_ifmsg(ipif);
4152 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4153 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4154 			}
4155 			ipif->ipif_addr_ready = 1;
4156 			ipif_refrele(ipif);
4157 		}
4158 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4159 		if (ire != NULL) {
4160 			ire->ire_defense_count = 0;
4161 			ire_refrele(ire);
4162 		}
4163 		break;
4164 	case AR_CN_FAILED:
4165 		/* No external v6 resolver has a contract to use this */
4166 		if (isv6)
4167 			break;
4168 		ill_refhold(ill);
4169 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4170 		return;
4171 	}
4172 	freemsg(mp);
4173 }
4174 
4175 /*
4176  * Create a mblk suitable for carrying the interface index and/or source link
4177  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4178  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4179  * application.
4180  */
4181 mblk_t *
4182 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4183     ip_stack_t *ipst)
4184 {
4185 	mblk_t		*mp;
4186 	ip_pktinfo_t	*pinfo;
4187 	ipha_t *ipha;
4188 	struct ether_header *pether;
4189 
4190 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4191 	if (mp == NULL) {
4192 		ip1dbg(("ip_add_info: allocation failure.\n"));
4193 		return (data_mp);
4194 	}
4195 
4196 	ipha	= (ipha_t *)data_mp->b_rptr;
4197 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4198 	bzero(pinfo, sizeof (ip_pktinfo_t));
4199 	pinfo->ip_pkt_flags = (uchar_t)flags;
4200 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4201 
4202 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4203 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4204 	if (flags & IPF_RECVADDR) {
4205 		ipif_t	*ipif;
4206 		ire_t	*ire;
4207 
4208 		/*
4209 		 * Only valid for V4
4210 		 */
4211 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4212 		    (IPV4_VERSION << 4));
4213 
4214 		ipif = ipif_get_next_ipif(NULL, ill);
4215 		if (ipif != NULL) {
4216 			/*
4217 			 * Since a decision has already been made to deliver the
4218 			 * packet, there is no need to test for SECATTR and
4219 			 * ZONEONLY.
4220 			 * When a multicast packet is transmitted
4221 			 * a cache entry is created for the multicast address.
4222 			 * When delivering a copy of the packet or when new
4223 			 * packets are received we do not want to match on the
4224 			 * cached entry so explicitly match on
4225 			 * IRE_LOCAL and IRE_LOOPBACK
4226 			 */
4227 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4228 			    IRE_LOCAL | IRE_LOOPBACK,
4229 			    ipif, zoneid, NULL,
4230 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4231 			if (ire == NULL) {
4232 				/*
4233 				 * packet must have come on a different
4234 				 * interface.
4235 				 * Since a decision has already been made to
4236 				 * deliver the packet, there is no need to test
4237 				 * for SECATTR and ZONEONLY.
4238 				 * Only match on local and broadcast ire's.
4239 				 * See detailed comment above.
4240 				 */
4241 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4242 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4243 				    NULL, MATCH_IRE_TYPE, ipst);
4244 			}
4245 
4246 			if (ire == NULL) {
4247 				/*
4248 				 * This is either a multicast packet or
4249 				 * the address has been removed since
4250 				 * the packet was received.
4251 				 * Return INADDR_ANY so that normal source
4252 				 * selection occurs for the response.
4253 				 */
4254 
4255 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4256 			} else {
4257 				pinfo->ip_pkt_match_addr.s_addr =
4258 				    ire->ire_src_addr;
4259 				ire_refrele(ire);
4260 			}
4261 			ipif_refrele(ipif);
4262 		} else {
4263 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4264 		}
4265 	}
4266 
4267 	pether = (struct ether_header *)((char *)ipha
4268 	    - sizeof (struct ether_header));
4269 	/*
4270 	 * Make sure the interface is an ethernet type, since this option
4271 	 * is currently supported only on this type of interface. Also make
4272 	 * sure we are pointing correctly above db_base.
4273 	 */
4274 
4275 	if ((flags & IPF_RECVSLLA) &&
4276 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4277 	    (ill->ill_type == IFT_ETHER) &&
4278 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4279 
4280 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4281 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4282 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4283 	} else {
4284 		/*
4285 		 * Clear the bit. Indicate to upper layer that IP is not
4286 		 * sending this ancillary info.
4287 		 */
4288 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4289 	}
4290 
4291 	mp->b_datap->db_type = M_CTL;
4292 	mp->b_wptr += sizeof (ip_pktinfo_t);
4293 	mp->b_cont = data_mp;
4294 
4295 	return (mp);
4296 }
4297 
4298 /*
4299  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4300  * part of the bind request.
4301  */
4302 
4303 boolean_t
4304 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4305 {
4306 	ipsec_in_t *ii;
4307 
4308 	ASSERT(policy_mp != NULL);
4309 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4310 
4311 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4312 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4313 
4314 	connp->conn_policy = ii->ipsec_in_policy;
4315 	ii->ipsec_in_policy = NULL;
4316 
4317 	if (ii->ipsec_in_action != NULL) {
4318 		if (connp->conn_latch == NULL) {
4319 			connp->conn_latch = iplatch_create();
4320 			if (connp->conn_latch == NULL)
4321 				return (B_FALSE);
4322 		}
4323 		ipsec_latch_inbound(connp->conn_latch, ii);
4324 	}
4325 	return (B_TRUE);
4326 }
4327 
4328 /*
4329  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4330  * and to arrange for power-fanout assist.  The ULP is identified by
4331  * adding a single byte at the end of the original bind message.
4332  * A ULP other than UDP or TCP that wishes to be recognized passes
4333  * down a bind with a zero length address.
4334  *
4335  * The binding works as follows:
4336  * - A zero byte address means just bind to the protocol.
4337  * - A four byte address is treated as a request to validate
4338  *   that the address is a valid local address, appropriate for
4339  *   an application to bind to. This does not affect any fanout
4340  *   information in IP.
4341  * - A sizeof sin_t byte address is used to bind to only the local address
4342  *   and port.
4343  * - A sizeof ipa_conn_t byte address contains complete fanout information
4344  *   consisting of local and remote addresses and ports.  In
4345  *   this case, the addresses are both validated as appropriate
4346  *   for this operation, and, if so, the information is retained
4347  *   for use in the inbound fanout.
4348  *
4349  * The ULP (except in the zero-length bind) can append an
4350  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4351  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4352  * a copy of the source or destination IRE (source for local bind;
4353  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4354  * policy information contained should be copied on to the conn.
4355  *
4356  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4357  */
4358 mblk_t *
4359 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4360 {
4361 	ssize_t		len;
4362 	struct T_bind_req	*tbr;
4363 	sin_t		*sin;
4364 	ipa_conn_t	*ac;
4365 	uchar_t		*ucp;
4366 	mblk_t		*mp1;
4367 	boolean_t	ire_requested;
4368 	boolean_t	ipsec_policy_set = B_FALSE;
4369 	int		error = 0;
4370 	int		protocol;
4371 	ipa_conn_x_t	*acx;
4372 
4373 	ASSERT(!connp->conn_af_isv6);
4374 	connp->conn_pkt_isv6 = B_FALSE;
4375 
4376 	len = MBLKL(mp);
4377 	if (len < (sizeof (*tbr) + 1)) {
4378 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4379 		    "ip_bind: bogus msg, len %ld", len);
4380 		/* XXX: Need to return something better */
4381 		goto bad_addr;
4382 	}
4383 	/* Back up and extract the protocol identifier. */
4384 	mp->b_wptr--;
4385 	protocol = *mp->b_wptr & 0xFF;
4386 	tbr = (struct T_bind_req *)mp->b_rptr;
4387 	/* Reset the message type in preparation for shipping it back. */
4388 	DB_TYPE(mp) = M_PCPROTO;
4389 
4390 	connp->conn_ulp = (uint8_t)protocol;
4391 
4392 	/*
4393 	 * Check for a zero length address.  This is from a protocol that
4394 	 * wants to register to receive all packets of its type.
4395 	 */
4396 	if (tbr->ADDR_length == 0) {
4397 		/*
4398 		 * These protocols are now intercepted in ip_bind_v6().
4399 		 * Reject protocol-level binds here for now.
4400 		 *
4401 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4402 		 * so that the protocol type cannot be SCTP.
4403 		 */
4404 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4405 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4406 			goto bad_addr;
4407 		}
4408 
4409 		/*
4410 		 *
4411 		 * The udp module never sends down a zero-length address,
4412 		 * and allowing this on a labeled system will break MLP
4413 		 * functionality.
4414 		 */
4415 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4416 			goto bad_addr;
4417 
4418 		if (connp->conn_mac_exempt)
4419 			goto bad_addr;
4420 
4421 		/* No hash here really.  The table is big enough. */
4422 		connp->conn_srcv6 = ipv6_all_zeros;
4423 
4424 		ipcl_proto_insert(connp, protocol);
4425 
4426 		tbr->PRIM_type = T_BIND_ACK;
4427 		return (mp);
4428 	}
4429 
4430 	/* Extract the address pointer from the message. */
4431 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4432 	    tbr->ADDR_length);
4433 	if (ucp == NULL) {
4434 		ip1dbg(("ip_bind: no address\n"));
4435 		goto bad_addr;
4436 	}
4437 	if (!OK_32PTR(ucp)) {
4438 		ip1dbg(("ip_bind: unaligned address\n"));
4439 		goto bad_addr;
4440 	}
4441 	/*
4442 	 * Check for trailing mps.
4443 	 */
4444 
4445 	mp1 = mp->b_cont;
4446 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4447 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4448 
4449 	switch (tbr->ADDR_length) {
4450 	default:
4451 		ip1dbg(("ip_bind: bad address length %d\n",
4452 		    (int)tbr->ADDR_length));
4453 		goto bad_addr;
4454 
4455 	case IP_ADDR_LEN:
4456 		/* Verification of local address only */
4457 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4458 		    ire_requested, ipsec_policy_set, B_FALSE);
4459 		break;
4460 
4461 	case sizeof (sin_t):
4462 		sin = (sin_t *)ucp;
4463 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4464 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4465 		break;
4466 
4467 	case sizeof (ipa_conn_t):
4468 		ac = (ipa_conn_t *)ucp;
4469 		/* For raw socket, the local port is not set. */
4470 		if (ac->ac_lport == 0)
4471 			ac->ac_lport = connp->conn_lport;
4472 		/* Always verify destination reachability. */
4473 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4474 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4475 		    ipsec_policy_set, B_TRUE, B_TRUE);
4476 		break;
4477 
4478 	case sizeof (ipa_conn_x_t):
4479 		acx = (ipa_conn_x_t *)ucp;
4480 		/*
4481 		 * Whether or not to verify destination reachability depends
4482 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4483 		 */
4484 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4485 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4486 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4487 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4488 		break;
4489 	}
4490 	if (error == EINPROGRESS)
4491 		return (NULL);
4492 	else if (error != 0)
4493 		goto bad_addr;
4494 	/*
4495 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4496 	 * We can't do this in ip_bind_insert_ire because the policy
4497 	 * may not have been inherited at that point in time and hence
4498 	 * conn_out_enforce_policy may not be set.
4499 	 */
4500 	mp1 = mp->b_cont;
4501 	if (ire_requested && connp->conn_out_enforce_policy &&
4502 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4503 		ire_t *ire = (ire_t *)mp1->b_rptr;
4504 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4505 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4506 	}
4507 
4508 	/* Send it home. */
4509 	mp->b_datap->db_type = M_PCPROTO;
4510 	tbr->PRIM_type = T_BIND_ACK;
4511 	return (mp);
4512 
4513 bad_addr:
4514 	/*
4515 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4516 	 * a unix errno.
4517 	 */
4518 	if (error > 0)
4519 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4520 	else
4521 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4522 	return (mp);
4523 }
4524 
4525 /*
4526  * Here address is verified to be a valid local address.
4527  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4528  * address is also considered a valid local address.
4529  * In the case of a broadcast/multicast address, however, the
4530  * upper protocol is expected to reset the src address
4531  * to 0 if it sees a IRE_BROADCAST type returned so that
4532  * no packets are emitted with broadcast/multicast address as
4533  * source address (that violates hosts requirements RFC1122)
4534  * The addresses valid for bind are:
4535  *	(1) - INADDR_ANY (0)
4536  *	(2) - IP address of an UP interface
4537  *	(3) - IP address of a DOWN interface
4538  *	(4) - valid local IP broadcast addresses. In this case
4539  *	the conn will only receive packets destined to
4540  *	the specified broadcast address.
4541  *	(5) - a multicast address. In this case
4542  *	the conn will only receive packets destined to
4543  *	the specified multicast address. Note: the
4544  *	application still has to issue an
4545  *	IP_ADD_MEMBERSHIP socket option.
4546  *
4547  * On error, return -1 for TBADADDR otherwise pass the
4548  * errno with TSYSERR reply.
4549  *
4550  * In all the above cases, the bound address must be valid in the current zone.
4551  * When the address is loopback, multicast or broadcast, there might be many
4552  * matching IREs so bind has to look up based on the zone.
4553  *
4554  * Note: lport is in network byte order.
4555  */
4556 int
4557 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4558     boolean_t ire_requested, boolean_t ipsec_policy_set,
4559     boolean_t fanout_insert)
4560 {
4561 	int		error = 0;
4562 	ire_t		*src_ire;
4563 	mblk_t		*policy_mp;
4564 	ipif_t		*ipif;
4565 	zoneid_t	zoneid;
4566 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4567 
4568 	if (ipsec_policy_set) {
4569 		policy_mp = mp->b_cont;
4570 	}
4571 
4572 	/*
4573 	 * If it was previously connected, conn_fully_bound would have
4574 	 * been set.
4575 	 */
4576 	connp->conn_fully_bound = B_FALSE;
4577 
4578 	src_ire = NULL;
4579 	ipif = NULL;
4580 
4581 	zoneid = IPCL_ZONEID(connp);
4582 
4583 	if (src_addr) {
4584 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4585 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4586 		/*
4587 		 * If an address other than 0.0.0.0 is requested,
4588 		 * we verify that it is a valid address for bind
4589 		 * Note: Following code is in if-else-if form for
4590 		 * readability compared to a condition check.
4591 		 */
4592 		/* LINTED - statement has no consequent */
4593 		if (IRE_IS_LOCAL(src_ire)) {
4594 			/*
4595 			 * (2) Bind to address of local UP interface
4596 			 */
4597 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4598 			/*
4599 			 * (4) Bind to broadcast address
4600 			 * Note: permitted only from transports that
4601 			 * request IRE
4602 			 */
4603 			if (!ire_requested)
4604 				error = EADDRNOTAVAIL;
4605 		} else {
4606 			/*
4607 			 * (3) Bind to address of local DOWN interface
4608 			 * (ipif_lookup_addr() looks up all interfaces
4609 			 * but we do not get here for UP interfaces
4610 			 * - case (2) above)
4611 			 * We put the protocol byte back into the mblk
4612 			 * since we may come back via ip_wput_nondata()
4613 			 * later with this mblk if ipif_lookup_addr chooses
4614 			 * to defer processing.
4615 			 */
4616 			*mp->b_wptr++ = (char)connp->conn_ulp;
4617 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4618 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4619 			    &error, ipst)) != NULL) {
4620 				ipif_refrele(ipif);
4621 			} else if (error == EINPROGRESS) {
4622 				if (src_ire != NULL)
4623 					ire_refrele(src_ire);
4624 				return (EINPROGRESS);
4625 			} else if (CLASSD(src_addr)) {
4626 				error = 0;
4627 				if (src_ire != NULL)
4628 					ire_refrele(src_ire);
4629 				/*
4630 				 * (5) bind to multicast address.
4631 				 * Fake out the IRE returned to upper
4632 				 * layer to be a broadcast IRE.
4633 				 */
4634 				src_ire = ire_ctable_lookup(
4635 				    INADDR_BROADCAST, INADDR_ANY,
4636 				    IRE_BROADCAST, NULL, zoneid, NULL,
4637 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4638 				    ipst);
4639 				if (src_ire == NULL || !ire_requested)
4640 					error = EADDRNOTAVAIL;
4641 			} else {
4642 				/*
4643 				 * Not a valid address for bind
4644 				 */
4645 				error = EADDRNOTAVAIL;
4646 			}
4647 			/*
4648 			 * Just to keep it consistent with the processing in
4649 			 * ip_bind_v4()
4650 			 */
4651 			mp->b_wptr--;
4652 		}
4653 		if (error) {
4654 			/* Red Alert!  Attempting to be a bogon! */
4655 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4656 			    ntohl(src_addr)));
4657 			goto bad_addr;
4658 		}
4659 	}
4660 
4661 	/*
4662 	 * Allow setting new policies. For example, disconnects come
4663 	 * down as ipa_t bind. As we would have set conn_policy_cached
4664 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4665 	 * can change after the disconnect.
4666 	 */
4667 	connp->conn_policy_cached = B_FALSE;
4668 
4669 	/*
4670 	 * If not fanout_insert this was just an address verification
4671 	 */
4672 	if (fanout_insert) {
4673 		/*
4674 		 * The addresses have been verified. Time to insert in
4675 		 * the correct fanout list.
4676 		 */
4677 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4678 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4679 		connp->conn_lport = lport;
4680 		connp->conn_fport = 0;
4681 		/*
4682 		 * Do we need to add a check to reject Multicast packets
4683 		 */
4684 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4685 	}
4686 
4687 	if (error == 0) {
4688 		if (ire_requested) {
4689 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4690 				error = -1;
4691 				/* Falls through to bad_addr */
4692 			}
4693 		} else if (ipsec_policy_set) {
4694 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4695 				error = -1;
4696 				/* Falls through to bad_addr */
4697 			}
4698 		}
4699 	}
4700 bad_addr:
4701 	if (error != 0) {
4702 		if (connp->conn_anon_port) {
4703 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4704 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4705 			    B_FALSE);
4706 		}
4707 		connp->conn_mlp_type = mlptSingle;
4708 	}
4709 	if (src_ire != NULL)
4710 		IRE_REFRELE(src_ire);
4711 	if (ipsec_policy_set) {
4712 		ASSERT(policy_mp == mp->b_cont);
4713 		ASSERT(policy_mp != NULL);
4714 		freeb(policy_mp);
4715 		/*
4716 		 * As of now assume that nothing else accompanies
4717 		 * IPSEC_POLICY_SET.
4718 		 */
4719 		mp->b_cont = NULL;
4720 	}
4721 	return (error);
4722 }
4723 
4724 /*
4725  * Verify that both the source and destination addresses
4726  * are valid.  If verify_dst is false, then the destination address may be
4727  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4728  * destination reachability, while tunnels do not.
4729  * Note that we allow connect to broadcast and multicast
4730  * addresses when ire_requested is set. Thus the ULP
4731  * has to check for IRE_BROADCAST and multicast.
4732  *
4733  * Returns zero if ok.
4734  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4735  * (for use with TSYSERR reply).
4736  *
4737  * Note: lport and fport are in network byte order.
4738  */
4739 int
4740 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4741     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4742     boolean_t ire_requested, boolean_t ipsec_policy_set,
4743     boolean_t fanout_insert, boolean_t verify_dst)
4744 {
4745 	ire_t		*src_ire;
4746 	ire_t		*dst_ire;
4747 	int		error = 0;
4748 	int 		protocol;
4749 	mblk_t		*policy_mp;
4750 	ire_t		*sire = NULL;
4751 	ire_t		*md_dst_ire = NULL;
4752 	ire_t		*lso_dst_ire = NULL;
4753 	ill_t		*ill = NULL;
4754 	zoneid_t	zoneid;
4755 	ipaddr_t	src_addr = *src_addrp;
4756 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4757 
4758 	src_ire = dst_ire = NULL;
4759 	protocol = *mp->b_wptr & 0xFF;
4760 
4761 	/*
4762 	 * If we never got a disconnect before, clear it now.
4763 	 */
4764 	connp->conn_fully_bound = B_FALSE;
4765 
4766 	if (ipsec_policy_set) {
4767 		policy_mp = mp->b_cont;
4768 	}
4769 
4770 	zoneid = IPCL_ZONEID(connp);
4771 
4772 	if (CLASSD(dst_addr)) {
4773 		/* Pick up an IRE_BROADCAST */
4774 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4775 		    NULL, zoneid, MBLK_GETLABEL(mp),
4776 		    (MATCH_IRE_RECURSIVE |
4777 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4778 		    MATCH_IRE_SECATTR), ipst);
4779 	} else {
4780 		/*
4781 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4782 		 * and onlink ipif is not found set ENETUNREACH error.
4783 		 */
4784 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4785 			ipif_t *ipif;
4786 
4787 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4788 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4789 			if (ipif == NULL) {
4790 				error = ENETUNREACH;
4791 				goto bad_addr;
4792 			}
4793 			ipif_refrele(ipif);
4794 		}
4795 
4796 		if (connp->conn_nexthop_set) {
4797 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4798 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4799 			    MATCH_IRE_SECATTR, ipst);
4800 		} else {
4801 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4802 			    &sire, zoneid, MBLK_GETLABEL(mp),
4803 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4804 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4805 			    MATCH_IRE_SECATTR), ipst);
4806 		}
4807 	}
4808 	/*
4809 	 * dst_ire can't be a broadcast when not ire_requested.
4810 	 * We also prevent ire's with src address INADDR_ANY to
4811 	 * be used, which are created temporarily for
4812 	 * sending out packets from endpoints that have
4813 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4814 	 * reachable.  If verify_dst is false, the destination needn't be
4815 	 * reachable.
4816 	 *
4817 	 * If we match on a reject or black hole, then we've got a
4818 	 * local failure.  May as well fail out the connect() attempt,
4819 	 * since it's never going to succeed.
4820 	 */
4821 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4822 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4823 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4824 		/*
4825 		 * If we're verifying destination reachability, we always want
4826 		 * to complain here.
4827 		 *
4828 		 * If we're not verifying destination reachability but the
4829 		 * destination has a route, we still want to fail on the
4830 		 * temporary address and broadcast address tests.
4831 		 */
4832 		if (verify_dst || (dst_ire != NULL)) {
4833 			if (ip_debug > 2) {
4834 				pr_addr_dbg("ip_bind_connected: bad connected "
4835 				    "dst %s\n", AF_INET, &dst_addr);
4836 			}
4837 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4838 				error = ENETUNREACH;
4839 			else
4840 				error = EHOSTUNREACH;
4841 			goto bad_addr;
4842 		}
4843 	}
4844 
4845 	/*
4846 	 * We now know that routing will allow us to reach the destination.
4847 	 * Check whether Trusted Solaris policy allows communication with this
4848 	 * host, and pretend that the destination is unreachable if not.
4849 	 *
4850 	 * This is never a problem for TCP, since that transport is known to
4851 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4852 	 * handling.  If the remote is unreachable, it will be detected at that
4853 	 * point, so there's no reason to check it here.
4854 	 *
4855 	 * Note that for sendto (and other datagram-oriented friends), this
4856 	 * check is done as part of the data path label computation instead.
4857 	 * The check here is just to make non-TCP connect() report the right
4858 	 * error.
4859 	 */
4860 	if (dst_ire != NULL && is_system_labeled() &&
4861 	    !IPCL_IS_TCP(connp) &&
4862 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4863 	    connp->conn_mac_exempt, ipst) != 0) {
4864 		error = EHOSTUNREACH;
4865 		if (ip_debug > 2) {
4866 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4867 			    AF_INET, &dst_addr);
4868 		}
4869 		goto bad_addr;
4870 	}
4871 
4872 	/*
4873 	 * If the app does a connect(), it means that it will most likely
4874 	 * send more than 1 packet to the destination.  It makes sense
4875 	 * to clear the temporary flag.
4876 	 */
4877 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4878 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4879 		irb_t *irb = dst_ire->ire_bucket;
4880 
4881 		rw_enter(&irb->irb_lock, RW_WRITER);
4882 		/*
4883 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4884 		 * the lock to guarantee irb_tmp_ire_cnt.
4885 		 */
4886 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4887 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4888 			irb->irb_tmp_ire_cnt--;
4889 		}
4890 		rw_exit(&irb->irb_lock);
4891 	}
4892 
4893 	/*
4894 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4895 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4896 	 * eligibility tests for passive connects are handled separately
4897 	 * through tcp_adapt_ire().  We do this before the source address
4898 	 * selection, because dst_ire may change after a call to
4899 	 * ipif_select_source().  This is a best-effort check, as the
4900 	 * packet for this connection may not actually go through
4901 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4902 	 * calling ip_newroute().  This is why we further check on the
4903 	 * IRE during LSO/Multidata packet transmission in
4904 	 * tcp_lsosend()/tcp_multisend().
4905 	 */
4906 	if (!ipsec_policy_set && dst_ire != NULL &&
4907 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4908 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4909 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4910 			lso_dst_ire = dst_ire;
4911 			IRE_REFHOLD(lso_dst_ire);
4912 		} else if (ipst->ips_ip_multidata_outbound &&
4913 		    ILL_MDT_CAPABLE(ill)) {
4914 			md_dst_ire = dst_ire;
4915 			IRE_REFHOLD(md_dst_ire);
4916 		}
4917 	}
4918 
4919 	if (dst_ire != NULL &&
4920 	    dst_ire->ire_type == IRE_LOCAL &&
4921 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4922 		/*
4923 		 * If the IRE belongs to a different zone, look for a matching
4924 		 * route in the forwarding table and use the source address from
4925 		 * that route.
4926 		 */
4927 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4928 		    zoneid, 0, NULL,
4929 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4930 		    MATCH_IRE_RJ_BHOLE, ipst);
4931 		if (src_ire == NULL) {
4932 			error = EHOSTUNREACH;
4933 			goto bad_addr;
4934 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4935 			if (!(src_ire->ire_type & IRE_HOST))
4936 				error = ENETUNREACH;
4937 			else
4938 				error = EHOSTUNREACH;
4939 			goto bad_addr;
4940 		}
4941 		if (src_addr == INADDR_ANY)
4942 			src_addr = src_ire->ire_src_addr;
4943 		ire_refrele(src_ire);
4944 		src_ire = NULL;
4945 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4946 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4947 			src_addr = sire->ire_src_addr;
4948 			ire_refrele(dst_ire);
4949 			dst_ire = sire;
4950 			sire = NULL;
4951 		} else {
4952 			/*
4953 			 * Pick a source address so that a proper inbound
4954 			 * load spreading would happen.
4955 			 */
4956 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4957 			ipif_t *src_ipif = NULL;
4958 			ire_t *ipif_ire;
4959 
4960 			/*
4961 			 * Supply a local source address such that inbound
4962 			 * load spreading happens.
4963 			 *
4964 			 * Determine the best source address on this ill for
4965 			 * the destination.
4966 			 *
4967 			 * 1) For broadcast, we should return a broadcast ire
4968 			 *    found above so that upper layers know that the
4969 			 *    destination address is a broadcast address.
4970 			 *
4971 			 * 2) If this is part of a group, select a better
4972 			 *    source address so that better inbound load
4973 			 *    balancing happens. Do the same if the ipif
4974 			 *    is DEPRECATED.
4975 			 *
4976 			 * 3) If the outgoing interface is part of a usesrc
4977 			 *    group, then try selecting a source address from
4978 			 *    the usesrc ILL.
4979 			 */
4980 			if ((dst_ire->ire_zoneid != zoneid &&
4981 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4982 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4983 			    ((dst_ill->ill_group != NULL) ||
4984 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4985 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4986 				/*
4987 				 * If the destination is reachable via a
4988 				 * given gateway, the selected source address
4989 				 * should be in the same subnet as the gateway.
4990 				 * Otherwise, the destination is not reachable.
4991 				 *
4992 				 * If there are no interfaces on the same subnet
4993 				 * as the destination, ipif_select_source gives
4994 				 * first non-deprecated interface which might be
4995 				 * on a different subnet than the gateway.
4996 				 * This is not desirable. Hence pass the dst_ire
4997 				 * source address to ipif_select_source.
4998 				 * It is sure that the destination is reachable
4999 				 * with the dst_ire source address subnet.
5000 				 * So passing dst_ire source address to
5001 				 * ipif_select_source will make sure that the
5002 				 * selected source will be on the same subnet
5003 				 * as dst_ire source address.
5004 				 */
5005 				ipaddr_t saddr =
5006 				    dst_ire->ire_ipif->ipif_src_addr;
5007 				src_ipif = ipif_select_source(dst_ill,
5008 				    saddr, zoneid);
5009 				if (src_ipif != NULL) {
5010 					if (IS_VNI(src_ipif->ipif_ill)) {
5011 						/*
5012 						 * For VNI there is no
5013 						 * interface route
5014 						 */
5015 						src_addr =
5016 						    src_ipif->ipif_src_addr;
5017 					} else {
5018 						ipif_ire =
5019 						    ipif_to_ire(src_ipif);
5020 						if (ipif_ire != NULL) {
5021 							IRE_REFRELE(dst_ire);
5022 							dst_ire = ipif_ire;
5023 						}
5024 						src_addr =
5025 						    dst_ire->ire_src_addr;
5026 					}
5027 					ipif_refrele(src_ipif);
5028 				} else {
5029 					src_addr = dst_ire->ire_src_addr;
5030 				}
5031 			} else {
5032 				src_addr = dst_ire->ire_src_addr;
5033 			}
5034 		}
5035 	}
5036 
5037 	/*
5038 	 * We do ire_route_lookup() here (and not
5039 	 * interface lookup as we assert that
5040 	 * src_addr should only come from an
5041 	 * UP interface for hard binding.
5042 	 */
5043 	ASSERT(src_ire == NULL);
5044 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5045 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5046 	/* src_ire must be a local|loopback */
5047 	if (!IRE_IS_LOCAL(src_ire)) {
5048 		if (ip_debug > 2) {
5049 			pr_addr_dbg("ip_bind_connected: bad connected "
5050 			    "src %s\n", AF_INET, &src_addr);
5051 		}
5052 		error = EADDRNOTAVAIL;
5053 		goto bad_addr;
5054 	}
5055 
5056 	/*
5057 	 * If the source address is a loopback address, the
5058 	 * destination had best be local or multicast.
5059 	 * The transports that can't handle multicast will reject
5060 	 * those addresses.
5061 	 */
5062 	if (src_ire->ire_type == IRE_LOOPBACK &&
5063 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5064 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5065 		error = -1;
5066 		goto bad_addr;
5067 	}
5068 
5069 	/*
5070 	 * Allow setting new policies. For example, disconnects come
5071 	 * down as ipa_t bind. As we would have set conn_policy_cached
5072 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5073 	 * can change after the disconnect.
5074 	 */
5075 	connp->conn_policy_cached = B_FALSE;
5076 
5077 	/*
5078 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5079 	 * can handle their passed-in conn's.
5080 	 */
5081 
5082 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5083 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5084 	connp->conn_lport = lport;
5085 	connp->conn_fport = fport;
5086 	*src_addrp = src_addr;
5087 
5088 	ASSERT(!(ipsec_policy_set && ire_requested));
5089 	if (ire_requested) {
5090 		iulp_t *ulp_info = NULL;
5091 
5092 		/*
5093 		 * Note that sire will not be NULL if this is an off-link
5094 		 * connection and there is not cache for that dest yet.
5095 		 *
5096 		 * XXX Because of an existing bug, if there are multiple
5097 		 * default routes, the IRE returned now may not be the actual
5098 		 * default route used (default routes are chosen in a
5099 		 * round robin fashion).  So if the metrics for different
5100 		 * default routes are different, we may return the wrong
5101 		 * metrics.  This will not be a problem if the existing
5102 		 * bug is fixed.
5103 		 */
5104 		if (sire != NULL) {
5105 			ulp_info = &(sire->ire_uinfo);
5106 		}
5107 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5108 			error = -1;
5109 			goto bad_addr;
5110 		}
5111 	} else if (ipsec_policy_set) {
5112 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5113 			error = -1;
5114 			goto bad_addr;
5115 		}
5116 	}
5117 
5118 	/*
5119 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5120 	 * we'll cache that.  If we don't, we'll inherit global policy.
5121 	 *
5122 	 * We can't insert until the conn reflects the policy. Note that
5123 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5124 	 * connections where we don't have a policy. This is to prevent
5125 	 * global policy lookups in the inbound path.
5126 	 *
5127 	 * If we insert before we set conn_policy_cached,
5128 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5129 	 * because global policy cound be non-empty. We normally call
5130 	 * ipsec_check_policy() for conn_policy_cached connections only if
5131 	 * ipc_in_enforce_policy is set. But in this case,
5132 	 * conn_policy_cached can get set anytime since we made the
5133 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5134 	 * called, which will make the above assumption false.  Thus, we
5135 	 * need to insert after we set conn_policy_cached.
5136 	 */
5137 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5138 		goto bad_addr;
5139 
5140 	if (fanout_insert) {
5141 		/*
5142 		 * The addresses have been verified. Time to insert in
5143 		 * the correct fanout list.
5144 		 */
5145 		error = ipcl_conn_insert(connp, protocol, src_addr,
5146 		    dst_addr, connp->conn_ports);
5147 	}
5148 
5149 	if (error == 0) {
5150 		connp->conn_fully_bound = B_TRUE;
5151 		/*
5152 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5153 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5154 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5155 		 * ip_xxinfo_return(), which performs further checks
5156 		 * against them and upon success, returns the LSO/MDT info
5157 		 * mblk which we will attach to the bind acknowledgment.
5158 		 */
5159 		if (lso_dst_ire != NULL) {
5160 			mblk_t *lsoinfo_mp;
5161 
5162 			ASSERT(ill->ill_lso_capab != NULL);
5163 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5164 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5165 				linkb(mp, lsoinfo_mp);
5166 		} else if (md_dst_ire != NULL) {
5167 			mblk_t *mdinfo_mp;
5168 
5169 			ASSERT(ill->ill_mdt_capab != NULL);
5170 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5171 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5172 				linkb(mp, mdinfo_mp);
5173 		}
5174 	}
5175 bad_addr:
5176 	if (ipsec_policy_set) {
5177 		ASSERT(policy_mp == mp->b_cont);
5178 		ASSERT(policy_mp != NULL);
5179 		freeb(policy_mp);
5180 		/*
5181 		 * As of now assume that nothing else accompanies
5182 		 * IPSEC_POLICY_SET.
5183 		 */
5184 		mp->b_cont = NULL;
5185 	}
5186 	if (src_ire != NULL)
5187 		IRE_REFRELE(src_ire);
5188 	if (dst_ire != NULL)
5189 		IRE_REFRELE(dst_ire);
5190 	if (sire != NULL)
5191 		IRE_REFRELE(sire);
5192 	if (md_dst_ire != NULL)
5193 		IRE_REFRELE(md_dst_ire);
5194 	if (lso_dst_ire != NULL)
5195 		IRE_REFRELE(lso_dst_ire);
5196 	return (error);
5197 }
5198 
5199 /*
5200  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5201  * Prefers dst_ire over src_ire.
5202  */
5203 static boolean_t
5204 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5205 {
5206 	mblk_t	*mp1;
5207 	ire_t *ret_ire = NULL;
5208 
5209 	mp1 = mp->b_cont;
5210 	ASSERT(mp1 != NULL);
5211 
5212 	if (ire != NULL) {
5213 		/*
5214 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5215 		 * appended mblk. Its <upper protocol>'s
5216 		 * job to make sure there is room.
5217 		 */
5218 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5219 			return (0);
5220 
5221 		mp1->b_datap->db_type = IRE_DB_TYPE;
5222 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5223 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5224 		ret_ire = (ire_t *)mp1->b_rptr;
5225 		/*
5226 		 * Pass the latest setting of the ip_path_mtu_discovery and
5227 		 * copy the ulp info if any.
5228 		 */
5229 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5230 		    IPH_DF : 0;
5231 		if (ulp_info != NULL) {
5232 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5233 			    sizeof (iulp_t));
5234 		}
5235 		ret_ire->ire_mp = mp1;
5236 	} else {
5237 		/*
5238 		 * No IRE was found. Remove IRE mblk.
5239 		 */
5240 		mp->b_cont = mp1->b_cont;
5241 		freeb(mp1);
5242 	}
5243 
5244 	return (1);
5245 }
5246 
5247 /*
5248  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5249  * the final piece where we don't.  Return a pointer to the first mblk in the
5250  * result, and update the pointer to the next mblk to chew on.  If anything
5251  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5252  * NULL pointer.
5253  */
5254 mblk_t *
5255 ip_carve_mp(mblk_t **mpp, ssize_t len)
5256 {
5257 	mblk_t	*mp0;
5258 	mblk_t	*mp1;
5259 	mblk_t	*mp2;
5260 
5261 	if (!len || !mpp || !(mp0 = *mpp))
5262 		return (NULL);
5263 	/* If we aren't going to consume the first mblk, we need a dup. */
5264 	if (mp0->b_wptr - mp0->b_rptr > len) {
5265 		mp1 = dupb(mp0);
5266 		if (mp1) {
5267 			/* Partition the data between the two mblks. */
5268 			mp1->b_wptr = mp1->b_rptr + len;
5269 			mp0->b_rptr = mp1->b_wptr;
5270 			/*
5271 			 * after adjustments if mblk not consumed is now
5272 			 * unaligned, try to align it. If this fails free
5273 			 * all messages and let upper layer recover.
5274 			 */
5275 			if (!OK_32PTR(mp0->b_rptr)) {
5276 				if (!pullupmsg(mp0, -1)) {
5277 					freemsg(mp0);
5278 					freemsg(mp1);
5279 					*mpp = NULL;
5280 					return (NULL);
5281 				}
5282 			}
5283 		}
5284 		return (mp1);
5285 	}
5286 	/* Eat through as many mblks as we need to get len bytes. */
5287 	len -= mp0->b_wptr - mp0->b_rptr;
5288 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5289 		if (mp2->b_wptr - mp2->b_rptr > len) {
5290 			/*
5291 			 * We won't consume the entire last mblk.  Like
5292 			 * above, dup and partition it.
5293 			 */
5294 			mp1->b_cont = dupb(mp2);
5295 			mp1 = mp1->b_cont;
5296 			if (!mp1) {
5297 				/*
5298 				 * Trouble.  Rather than go to a lot of
5299 				 * trouble to clean up, we free the messages.
5300 				 * This won't be any worse than losing it on
5301 				 * the wire.
5302 				 */
5303 				freemsg(mp0);
5304 				freemsg(mp2);
5305 				*mpp = NULL;
5306 				return (NULL);
5307 			}
5308 			mp1->b_wptr = mp1->b_rptr + len;
5309 			mp2->b_rptr = mp1->b_wptr;
5310 			/*
5311 			 * after adjustments if mblk not consumed is now
5312 			 * unaligned, try to align it. If this fails free
5313 			 * all messages and let upper layer recover.
5314 			 */
5315 			if (!OK_32PTR(mp2->b_rptr)) {
5316 				if (!pullupmsg(mp2, -1)) {
5317 					freemsg(mp0);
5318 					freemsg(mp2);
5319 					*mpp = NULL;
5320 					return (NULL);
5321 				}
5322 			}
5323 			*mpp = mp2;
5324 			return (mp0);
5325 		}
5326 		/* Decrement len by the amount we just got. */
5327 		len -= mp2->b_wptr - mp2->b_rptr;
5328 	}
5329 	/*
5330 	 * len should be reduced to zero now.  If not our caller has
5331 	 * screwed up.
5332 	 */
5333 	if (len) {
5334 		/* Shouldn't happen! */
5335 		freemsg(mp0);
5336 		*mpp = NULL;
5337 		return (NULL);
5338 	}
5339 	/*
5340 	 * We consumed up to exactly the end of an mblk.  Detach the part
5341 	 * we are returning from the rest of the chain.
5342 	 */
5343 	mp1->b_cont = NULL;
5344 	*mpp = mp2;
5345 	return (mp0);
5346 }
5347 
5348 /* The ill stream is being unplumbed. Called from ip_close */
5349 int
5350 ip_modclose(ill_t *ill)
5351 {
5352 	boolean_t success;
5353 	ipsq_t	*ipsq;
5354 	ipif_t	*ipif;
5355 	queue_t	*q = ill->ill_rq;
5356 	ip_stack_t	*ipst = ill->ill_ipst;
5357 	clock_t timeout;
5358 
5359 	/*
5360 	 * Wait for the ACKs of all deferred control messages to be processed.
5361 	 * In particular, we wait for a potential capability reset initiated
5362 	 * in ip_sioctl_plink() to complete before proceeding.
5363 	 *
5364 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5365 	 * in case the driver never replies.
5366 	 */
5367 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5368 	mutex_enter(&ill->ill_lock);
5369 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5370 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5371 			/* Timeout */
5372 			break;
5373 		}
5374 	}
5375 	mutex_exit(&ill->ill_lock);
5376 
5377 	/*
5378 	 * Forcibly enter the ipsq after some delay. This is to take
5379 	 * care of the case when some ioctl does not complete because
5380 	 * we sent a control message to the driver and it did not
5381 	 * send us a reply. We want to be able to at least unplumb
5382 	 * and replumb rather than force the user to reboot the system.
5383 	 */
5384 	success = ipsq_enter(ill, B_FALSE);
5385 
5386 	/*
5387 	 * Open/close/push/pop is guaranteed to be single threaded
5388 	 * per stream by STREAMS. FS guarantees that all references
5389 	 * from top are gone before close is called. So there can't
5390 	 * be another close thread that has set CONDEMNED on this ill.
5391 	 * and cause ipsq_enter to return failure.
5392 	 */
5393 	ASSERT(success);
5394 	ipsq = ill->ill_phyint->phyint_ipsq;
5395 
5396 	/*
5397 	 * Mark it condemned. No new reference will be made to this ill.
5398 	 * Lookup functions will return an error. Threads that try to
5399 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5400 	 * that the refcnt will drop down to zero.
5401 	 */
5402 	mutex_enter(&ill->ill_lock);
5403 	ill->ill_state_flags |= ILL_CONDEMNED;
5404 	for (ipif = ill->ill_ipif; ipif != NULL;
5405 	    ipif = ipif->ipif_next) {
5406 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5407 	}
5408 	/*
5409 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5410 	 * returns  error if ILL_CONDEMNED is set
5411 	 */
5412 	cv_broadcast(&ill->ill_cv);
5413 	mutex_exit(&ill->ill_lock);
5414 
5415 	/*
5416 	 * Send all the deferred DLPI messages downstream which came in
5417 	 * during the small window right before ipsq_enter(). We do this
5418 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5419 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5420 	 */
5421 	ill_dlpi_send_deferred(ill);
5422 
5423 	/*
5424 	 * Shut down fragmentation reassembly.
5425 	 * ill_frag_timer won't start a timer again.
5426 	 * Now cancel any existing timer
5427 	 */
5428 	(void) untimeout(ill->ill_frag_timer_id);
5429 	(void) ill_frag_timeout(ill, 0);
5430 
5431 	/*
5432 	 * If MOVE was in progress, clear the
5433 	 * move_in_progress fields also.
5434 	 */
5435 	if (ill->ill_move_in_progress) {
5436 		ILL_CLEAR_MOVE(ill);
5437 	}
5438 
5439 	/*
5440 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5441 	 * this ill. Then wait for the refcnts to drop to zero.
5442 	 * ill_is_quiescent checks whether the ill is really quiescent.
5443 	 * Then make sure that threads that are waiting to enter the
5444 	 * ipsq have seen the error returned by ipsq_enter and have
5445 	 * gone away. Then we call ill_delete_tail which does the
5446 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5447 	 */
5448 	ill_delete(ill);
5449 	mutex_enter(&ill->ill_lock);
5450 	while (!ill_is_quiescent(ill))
5451 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5452 	while (ill->ill_waiters)
5453 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5454 
5455 	mutex_exit(&ill->ill_lock);
5456 
5457 	/*
5458 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5459 	 * it held until the end of the function since the cleanup
5460 	 * below needs to be able to use the ip_stack_t.
5461 	 */
5462 	netstack_hold(ipst->ips_netstack);
5463 
5464 	/* qprocsoff is called in ill_delete_tail */
5465 	ill_delete_tail(ill);
5466 	ASSERT(ill->ill_ipst == NULL);
5467 
5468 	/*
5469 	 * Walk through all upper (conn) streams and qenable
5470 	 * those that have queued data.
5471 	 * close synchronization needs this to
5472 	 * be done to ensure that all upper layers blocked
5473 	 * due to flow control to the closing device
5474 	 * get unblocked.
5475 	 */
5476 	ip1dbg(("ip_wsrv: walking\n"));
5477 	conn_walk_drain(ipst);
5478 
5479 	mutex_enter(&ipst->ips_ip_mi_lock);
5480 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5481 	mutex_exit(&ipst->ips_ip_mi_lock);
5482 
5483 	/*
5484 	 * credp could be null if the open didn't succeed and ip_modopen
5485 	 * itself calls ip_close.
5486 	 */
5487 	if (ill->ill_credp != NULL)
5488 		crfree(ill->ill_credp);
5489 
5490 	mutex_enter(&ill->ill_lock);
5491 	ill_nic_info_dispatch(ill);
5492 	mutex_exit(&ill->ill_lock);
5493 
5494 	/*
5495 	 * Now we are done with the module close pieces that
5496 	 * need the netstack_t.
5497 	 */
5498 	netstack_rele(ipst->ips_netstack);
5499 
5500 	mi_close_free((IDP)ill);
5501 	q->q_ptr = WR(q)->q_ptr = NULL;
5502 
5503 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5504 
5505 	return (0);
5506 }
5507 
5508 /*
5509  * This is called as part of close() for IP, UDP, ICMP, and RTS
5510  * in order to quiesce the conn.
5511  */
5512 void
5513 ip_quiesce_conn(conn_t *connp)
5514 {
5515 	boolean_t	drain_cleanup_reqd = B_FALSE;
5516 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5517 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5518 	ip_stack_t	*ipst;
5519 
5520 	ASSERT(!IPCL_IS_TCP(connp));
5521 	ipst = connp->conn_netstack->netstack_ip;
5522 
5523 	/*
5524 	 * Mark the conn as closing, and this conn must not be
5525 	 * inserted in future into any list. Eg. conn_drain_insert(),
5526 	 * won't insert this conn into the conn_drain_list.
5527 	 * Similarly ill_pending_mp_add() will not add any mp to
5528 	 * the pending mp list, after this conn has started closing.
5529 	 *
5530 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5531 	 * cannot get set henceforth.
5532 	 */
5533 	mutex_enter(&connp->conn_lock);
5534 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5535 	connp->conn_state_flags |= CONN_CLOSING;
5536 	if (connp->conn_idl != NULL)
5537 		drain_cleanup_reqd = B_TRUE;
5538 	if (connp->conn_oper_pending_ill != NULL)
5539 		conn_ioctl_cleanup_reqd = B_TRUE;
5540 	if (connp->conn_dhcpinit_ill != NULL) {
5541 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5542 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5543 		connp->conn_dhcpinit_ill = NULL;
5544 	}
5545 	if (connp->conn_ilg_inuse != 0)
5546 		ilg_cleanup_reqd = B_TRUE;
5547 	mutex_exit(&connp->conn_lock);
5548 
5549 	if (conn_ioctl_cleanup_reqd)
5550 		conn_ioctl_cleanup(connp);
5551 
5552 	if (is_system_labeled() && connp->conn_anon_port) {
5553 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5554 		    connp->conn_mlp_type, connp->conn_ulp,
5555 		    ntohs(connp->conn_lport), B_FALSE);
5556 		connp->conn_anon_port = 0;
5557 	}
5558 	connp->conn_mlp_type = mlptSingle;
5559 
5560 	/*
5561 	 * Remove this conn from any fanout list it is on.
5562 	 * and then wait for any threads currently operating
5563 	 * on this endpoint to finish
5564 	 */
5565 	ipcl_hash_remove(connp);
5566 
5567 	/*
5568 	 * Remove this conn from the drain list, and do
5569 	 * any other cleanup that may be required.
5570 	 * (Only non-tcp streams may have a non-null conn_idl.
5571 	 * TCP streams are never flow controlled, and
5572 	 * conn_idl will be null)
5573 	 */
5574 	if (drain_cleanup_reqd)
5575 		conn_drain_tail(connp, B_TRUE);
5576 
5577 	if (connp == ipst->ips_ip_g_mrouter)
5578 		(void) ip_mrouter_done(NULL, ipst);
5579 
5580 	if (ilg_cleanup_reqd)
5581 		ilg_delete_all(connp);
5582 
5583 	conn_delete_ire(connp, NULL);
5584 
5585 	/*
5586 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5587 	 * callers from write side can't be there now because close
5588 	 * is in progress. The only other caller is ipcl_walk
5589 	 * which checks for the condemned flag.
5590 	 */
5591 	mutex_enter(&connp->conn_lock);
5592 	connp->conn_state_flags |= CONN_CONDEMNED;
5593 	while (connp->conn_ref != 1)
5594 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5595 	connp->conn_state_flags |= CONN_QUIESCED;
5596 	mutex_exit(&connp->conn_lock);
5597 }
5598 
5599 /* ARGSUSED */
5600 int
5601 ip_close(queue_t *q, int flags)
5602 {
5603 	conn_t		*connp;
5604 
5605 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5606 
5607 	/*
5608 	 * Call the appropriate delete routine depending on whether this is
5609 	 * a module or device.
5610 	 */
5611 	if (WR(q)->q_next != NULL) {
5612 		/* This is a module close */
5613 		return (ip_modclose((ill_t *)q->q_ptr));
5614 	}
5615 
5616 	connp = q->q_ptr;
5617 	ip_quiesce_conn(connp);
5618 
5619 	qprocsoff(q);
5620 
5621 	/*
5622 	 * Now we are truly single threaded on this stream, and can
5623 	 * delete the things hanging off the connp, and finally the connp.
5624 	 * We removed this connp from the fanout list, it cannot be
5625 	 * accessed thru the fanouts, and we already waited for the
5626 	 * conn_ref to drop to 0. We are already in close, so
5627 	 * there cannot be any other thread from the top. qprocsoff
5628 	 * has completed, and service has completed or won't run in
5629 	 * future.
5630 	 */
5631 	ASSERT(connp->conn_ref == 1);
5632 
5633 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5634 
5635 	connp->conn_ref--;
5636 	ipcl_conn_destroy(connp);
5637 
5638 	q->q_ptr = WR(q)->q_ptr = NULL;
5639 	return (0);
5640 }
5641 
5642 /*
5643  * Wapper around putnext() so that ip_rts_request can merely use
5644  * conn_recv.
5645  */
5646 /*ARGSUSED2*/
5647 static void
5648 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5649 {
5650 	conn_t *connp = (conn_t *)arg1;
5651 
5652 	putnext(connp->conn_rq, mp);
5653 }
5654 
5655 /* Return the IP checksum for the IP header at "iph". */
5656 uint16_t
5657 ip_csum_hdr(ipha_t *ipha)
5658 {
5659 	uint16_t	*uph;
5660 	uint32_t	sum;
5661 	int		opt_len;
5662 
5663 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5664 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5665 	uph = (uint16_t *)ipha;
5666 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5667 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5668 	if (opt_len > 0) {
5669 		do {
5670 			sum += uph[10];
5671 			sum += uph[11];
5672 			uph += 2;
5673 		} while (--opt_len);
5674 	}
5675 	sum = (sum & 0xFFFF) + (sum >> 16);
5676 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5677 	if (sum == 0xffff)
5678 		sum = 0;
5679 	return ((uint16_t)sum);
5680 }
5681 
5682 /*
5683  * Called when the module is about to be unloaded
5684  */
5685 void
5686 ip_ddi_destroy(void)
5687 {
5688 	tnet_fini();
5689 
5690 	icmp_ddi_destroy();
5691 	rts_ddi_destroy();
5692 	udp_ddi_destroy();
5693 	sctp_ddi_g_destroy();
5694 	tcp_ddi_g_destroy();
5695 	ipsec_policy_g_destroy();
5696 	ipcl_g_destroy();
5697 	ip_net_g_destroy();
5698 	ip_ire_g_fini();
5699 	inet_minor_destroy(ip_minor_arena_sa);
5700 #if defined(_LP64)
5701 	inet_minor_destroy(ip_minor_arena_la);
5702 #endif
5703 
5704 #ifdef DEBUG
5705 	list_destroy(&ip_thread_list);
5706 	rw_destroy(&ip_thread_rwlock);
5707 	tsd_destroy(&ip_thread_data);
5708 #endif
5709 
5710 	netstack_unregister(NS_IP);
5711 }
5712 
5713 /*
5714  * First step in cleanup.
5715  */
5716 /* ARGSUSED */
5717 static void
5718 ip_stack_shutdown(netstackid_t stackid, void *arg)
5719 {
5720 	ip_stack_t *ipst = (ip_stack_t *)arg;
5721 
5722 #ifdef NS_DEBUG
5723 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5724 #endif
5725 
5726 	/* Get rid of loopback interfaces and their IREs */
5727 	ip_loopback_cleanup(ipst);
5728 }
5729 
5730 /*
5731  * Free the IP stack instance.
5732  */
5733 static void
5734 ip_stack_fini(netstackid_t stackid, void *arg)
5735 {
5736 	ip_stack_t *ipst = (ip_stack_t *)arg;
5737 	int ret;
5738 
5739 #ifdef NS_DEBUG
5740 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5741 #endif
5742 	ipv4_hook_destroy(ipst);
5743 	ipv6_hook_destroy(ipst);
5744 	ip_net_destroy(ipst);
5745 
5746 	rw_destroy(&ipst->ips_srcid_lock);
5747 
5748 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5749 	ipst->ips_ip_mibkp = NULL;
5750 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5751 	ipst->ips_icmp_mibkp = NULL;
5752 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5753 	ipst->ips_ip_kstat = NULL;
5754 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5755 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5756 	ipst->ips_ip6_kstat = NULL;
5757 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5758 
5759 	nd_free(&ipst->ips_ip_g_nd);
5760 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5761 	ipst->ips_param_arr = NULL;
5762 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5763 	ipst->ips_ndp_arr = NULL;
5764 
5765 	ip_mrouter_stack_destroy(ipst);
5766 
5767 	mutex_destroy(&ipst->ips_ip_mi_lock);
5768 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5769 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5770 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5771 
5772 	ret = untimeout(ipst->ips_igmp_timeout_id);
5773 	if (ret == -1) {
5774 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5775 	} else {
5776 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5777 		ipst->ips_igmp_timeout_id = 0;
5778 	}
5779 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5780 	if (ret == -1) {
5781 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5782 	} else {
5783 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5784 		ipst->ips_igmp_slowtimeout_id = 0;
5785 	}
5786 	ret = untimeout(ipst->ips_mld_timeout_id);
5787 	if (ret == -1) {
5788 		ASSERT(ipst->ips_mld_timeout_id == 0);
5789 	} else {
5790 		ASSERT(ipst->ips_mld_timeout_id != 0);
5791 		ipst->ips_mld_timeout_id = 0;
5792 	}
5793 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5794 	if (ret == -1) {
5795 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5796 	} else {
5797 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5798 		ipst->ips_mld_slowtimeout_id = 0;
5799 	}
5800 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5801 	if (ret == -1) {
5802 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5803 	} else {
5804 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5805 		ipst->ips_ip_ire_expire_id = 0;
5806 	}
5807 
5808 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5809 	mutex_destroy(&ipst->ips_mld_timer_lock);
5810 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5811 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5812 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5813 	rw_destroy(&ipst->ips_ill_g_lock);
5814 
5815 	ip_ire_fini(ipst);
5816 	ip6_asp_free(ipst);
5817 	conn_drain_fini(ipst);
5818 	ipcl_destroy(ipst);
5819 
5820 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5821 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5822 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5823 	ipst->ips_ndp4 = NULL;
5824 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5825 	ipst->ips_ndp6 = NULL;
5826 
5827 	if (ipst->ips_loopback_ksp != NULL) {
5828 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5829 		ipst->ips_loopback_ksp = NULL;
5830 	}
5831 
5832 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5833 	ipst->ips_phyint_g_list = NULL;
5834 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5835 	ipst->ips_ill_g_heads = NULL;
5836 
5837 	kmem_free(ipst, sizeof (*ipst));
5838 }
5839 
5840 /*
5841  * This function is called from the TSD destructor, and is used to debug
5842  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5843  * details.
5844  */
5845 static void
5846 ip_thread_exit(void *phash)
5847 {
5848 	th_hash_t *thh = phash;
5849 
5850 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5851 	list_remove(&ip_thread_list, thh);
5852 	rw_exit(&ip_thread_rwlock);
5853 	mod_hash_destroy_hash(thh->thh_hash);
5854 	kmem_free(thh, sizeof (*thh));
5855 }
5856 
5857 /*
5858  * Called when the IP kernel module is loaded into the kernel
5859  */
5860 void
5861 ip_ddi_init(void)
5862 {
5863 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5864 
5865 	/*
5866 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5867 	 * initial devices: ip, ip6, tcp, tcp6.
5868 	 */
5869 	/*
5870 	 * If this is a 64-bit kernel, then create two separate arenas -
5871 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5872 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5873 	 */
5874 	ip_minor_arena_la = NULL;
5875 	ip_minor_arena_sa = NULL;
5876 #if defined(_LP64)
5877 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5878 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5879 		cmn_err(CE_PANIC,
5880 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5881 	}
5882 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5883 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5884 		cmn_err(CE_PANIC,
5885 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5886 	}
5887 #else
5888 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5889 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5890 		cmn_err(CE_PANIC,
5891 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5892 	}
5893 #endif
5894 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5895 
5896 	ipcl_g_init();
5897 	ip_ire_g_init();
5898 	ip_net_g_init();
5899 
5900 #ifdef DEBUG
5901 	tsd_create(&ip_thread_data, ip_thread_exit);
5902 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5903 	list_create(&ip_thread_list, sizeof (th_hash_t),
5904 	    offsetof(th_hash_t, thh_link));
5905 #endif
5906 
5907 	/*
5908 	 * We want to be informed each time a stack is created or
5909 	 * destroyed in the kernel, so we can maintain the
5910 	 * set of udp_stack_t's.
5911 	 */
5912 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5913 	    ip_stack_fini);
5914 
5915 	ipsec_policy_g_init();
5916 	tcp_ddi_g_init();
5917 	sctp_ddi_g_init();
5918 
5919 	tnet_init();
5920 
5921 	udp_ddi_init();
5922 	rts_ddi_init();
5923 	icmp_ddi_init();
5924 }
5925 
5926 /*
5927  * Initialize the IP stack instance.
5928  */
5929 static void *
5930 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5931 {
5932 	ip_stack_t	*ipst;
5933 	ipparam_t	*pa;
5934 	ipndp_t		*na;
5935 
5936 #ifdef NS_DEBUG
5937 	printf("ip_stack_init(stack %d)\n", stackid);
5938 #endif
5939 
5940 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5941 	ipst->ips_netstack = ns;
5942 
5943 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5944 	    KM_SLEEP);
5945 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5946 	    KM_SLEEP);
5947 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5948 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5949 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5950 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5951 
5952 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5953 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5954 	ipst->ips_igmp_deferred_next = INFINITY;
5955 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5956 	ipst->ips_mld_deferred_next = INFINITY;
5957 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5958 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5959 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5960 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5961 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5962 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5963 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5964 
5965 	ipcl_init(ipst);
5966 	ip_ire_init(ipst);
5967 	ip6_asp_init(ipst);
5968 	ipif_init(ipst);
5969 	conn_drain_init(ipst);
5970 	ip_mrouter_stack_init(ipst);
5971 
5972 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5973 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5974 
5975 	ipst->ips_ip_multirt_log_interval = 1000;
5976 
5977 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5978 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5979 	ipst->ips_ill_index = 1;
5980 
5981 	ipst->ips_saved_ip_g_forward = -1;
5982 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5983 
5984 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5985 	ipst->ips_param_arr = pa;
5986 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5987 
5988 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5989 	ipst->ips_ndp_arr = na;
5990 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5991 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5992 	    (caddr_t)&ipst->ips_ip_g_forward;
5993 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5994 	    (caddr_t)&ipst->ips_ipv6_forward;
5995 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5996 	    "ip_cgtp_filter") == 0);
5997 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5998 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5999 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
6000 	    "ipmp_hook_emulation") == 0);
6001 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
6002 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
6003 
6004 	(void) ip_param_register(&ipst->ips_ip_g_nd,
6005 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
6006 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
6007 
6008 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6009 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6010 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6011 	ipst->ips_ip6_kstat =
6012 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6013 
6014 	ipst->ips_ipmp_enable_failback = B_TRUE;
6015 
6016 	ipst->ips_ip_src_id = 1;
6017 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6018 
6019 	ip_net_init(ipst, ns);
6020 	ipv4_hook_init(ipst);
6021 	ipv6_hook_init(ipst);
6022 
6023 	return (ipst);
6024 }
6025 
6026 /*
6027  * Allocate and initialize a DLPI template of the specified length.  (May be
6028  * called as writer.)
6029  */
6030 mblk_t *
6031 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6032 {
6033 	mblk_t	*mp;
6034 
6035 	mp = allocb(len, BPRI_MED);
6036 	if (!mp)
6037 		return (NULL);
6038 
6039 	/*
6040 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6041 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6042 	 * that other DLPI are M_PROTO.
6043 	 */
6044 	if (prim == DL_INFO_REQ) {
6045 		mp->b_datap->db_type = M_PCPROTO;
6046 	} else {
6047 		mp->b_datap->db_type = M_PROTO;
6048 	}
6049 
6050 	mp->b_wptr = mp->b_rptr + len;
6051 	bzero(mp->b_rptr, len);
6052 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6053 	return (mp);
6054 }
6055 
6056 const char *
6057 dlpi_prim_str(int prim)
6058 {
6059 	switch (prim) {
6060 	case DL_INFO_REQ:	return ("DL_INFO_REQ");
6061 	case DL_INFO_ACK:	return ("DL_INFO_ACK");
6062 	case DL_ATTACH_REQ:	return ("DL_ATTACH_REQ");
6063 	case DL_DETACH_REQ:	return ("DL_DETACH_REQ");
6064 	case DL_BIND_REQ:	return ("DL_BIND_REQ");
6065 	case DL_BIND_ACK:	return ("DL_BIND_ACK");
6066 	case DL_UNBIND_REQ:	return ("DL_UNBIND_REQ");
6067 	case DL_OK_ACK:		return ("DL_OK_ACK");
6068 	case DL_ERROR_ACK:	return ("DL_ERROR_ACK");
6069 	case DL_ENABMULTI_REQ:	return ("DL_ENABMULTI_REQ");
6070 	case DL_DISABMULTI_REQ:	return ("DL_DISABMULTI_REQ");
6071 	case DL_PROMISCON_REQ:	return ("DL_PROMISCON_REQ");
6072 	case DL_PROMISCOFF_REQ:	return ("DL_PROMISCOFF_REQ");
6073 	case DL_UNITDATA_REQ:	return ("DL_UNITDATA_REQ");
6074 	case DL_UNITDATA_IND:	return ("DL_UNITDATA_IND");
6075 	case DL_UDERROR_IND:	return ("DL_UDERROR_IND");
6076 	case DL_PHYS_ADDR_REQ:	return ("DL_PHYS_ADDR_REQ");
6077 	case DL_PHYS_ADDR_ACK:	return ("DL_PHYS_ADDR_ACK");
6078 	case DL_SET_PHYS_ADDR_REQ:	return ("DL_SET_PHYS_ADDR_REQ");
6079 	case DL_NOTIFY_REQ:	return ("DL_NOTIFY_REQ");
6080 	case DL_NOTIFY_ACK:	return ("DL_NOTIFY_ACK");
6081 	case DL_NOTIFY_IND:	return ("DL_NOTIFY_IND");
6082 	case DL_CAPABILITY_REQ:	return ("DL_CAPABILITY_REQ");
6083 	case DL_CAPABILITY_ACK:	return ("DL_CAPABILITY_ACK");
6084 	case DL_CONTROL_REQ:	return ("DL_CONTROL_REQ");
6085 	case DL_CONTROL_ACK:	return ("DL_CONTROL_ACK");
6086 	default:		return ("<unknown primitive>");
6087 	}
6088 }
6089 
6090 const char *
6091 dlpi_err_str(int err)
6092 {
6093 	switch (err) {
6094 	case DL_ACCESS:		return ("DL_ACCESS");
6095 	case DL_BADADDR:	return ("DL_BADADDR");
6096 	case DL_BADCORR:	return ("DL_BADCORR");
6097 	case DL_BADDATA:	return ("DL_BADDATA");
6098 	case DL_BADPPA:		return ("DL_BADPPA");
6099 	case DL_BADPRIM:	return ("DL_BADPRIM");
6100 	case DL_BADQOSPARAM:	return ("DL_BADQOSPARAM");
6101 	case DL_BADQOSTYPE:	return ("DL_BADQOSTYPE");
6102 	case DL_BADSAP:		return ("DL_BADSAP");
6103 	case DL_BADTOKEN:	return ("DL_BADTOKEN");
6104 	case DL_BOUND:		return ("DL_BOUND");
6105 	case DL_INITFAILED:	return ("DL_INITFAILED");
6106 	case DL_NOADDR:		return ("DL_NOADDR");
6107 	case DL_NOTINIT:	return ("DL_NOTINIT");
6108 	case DL_OUTSTATE:	return ("DL_OUTSTATE");
6109 	case DL_SYSERR:		return ("DL_SYSERR");
6110 	case DL_UNSUPPORTED:	return ("DL_UNSUPPORTED");
6111 	case DL_UNDELIVERABLE:	return ("DL_UNDELIVERABLE");
6112 	case DL_NOTSUPPORTED :	return ("DL_NOTSUPPORTED ");
6113 	case DL_TOOMANY:	return ("DL_TOOMANY");
6114 	case DL_NOTENAB:	return ("DL_NOTENAB");
6115 	case DL_BUSY:		return ("DL_BUSY");
6116 	case DL_NOAUTO:		return ("DL_NOAUTO");
6117 	case DL_NOXIDAUTO:	return ("DL_NOXIDAUTO");
6118 	case DL_NOTESTAUTO:	return ("DL_NOTESTAUTO");
6119 	case DL_XIDAUTO:	return ("DL_XIDAUTO");
6120 	case DL_TESTAUTO:	return ("DL_TESTAUTO");
6121 	case DL_PENDING:	return ("DL_PENDING");
6122 	default:		return ("<unknown error>");
6123 	}
6124 }
6125 
6126 /*
6127  * Debug formatting routine.  Returns a character string representation of the
6128  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6129  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6130  *
6131  * Once the ndd table-printing interfaces are removed, this can be changed to
6132  * standard dotted-decimal form.
6133  */
6134 char *
6135 ip_dot_addr(ipaddr_t addr, char *buf)
6136 {
6137 	uint8_t *ap = (uint8_t *)&addr;
6138 
6139 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6140 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6141 	return (buf);
6142 }
6143 
6144 /*
6145  * Write the given MAC address as a printable string in the usual colon-
6146  * separated format.
6147  */
6148 const char *
6149 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6150 {
6151 	char *bp;
6152 
6153 	if (alen == 0 || buflen < 4)
6154 		return ("?");
6155 	bp = buf;
6156 	for (;;) {
6157 		/*
6158 		 * If there are more MAC address bytes available, but we won't
6159 		 * have any room to print them, then add "..." to the string
6160 		 * instead.  See below for the 'magic number' explanation.
6161 		 */
6162 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6163 			(void) strcpy(bp, "...");
6164 			break;
6165 		}
6166 		(void) sprintf(bp, "%02x", *addr++);
6167 		bp += 2;
6168 		if (--alen == 0)
6169 			break;
6170 		*bp++ = ':';
6171 		buflen -= 3;
6172 		/*
6173 		 * At this point, based on the first 'if' statement above,
6174 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6175 		 * buflen >= 4.  The first case leaves room for the final "xx"
6176 		 * number and trailing NUL byte.  The second leaves room for at
6177 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6178 		 * that statement.
6179 		 */
6180 	}
6181 	return (buf);
6182 }
6183 
6184 /*
6185  * Send an ICMP error after patching up the packet appropriately.  Returns
6186  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6187  */
6188 static boolean_t
6189 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6190     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6191     zoneid_t zoneid, ip_stack_t *ipst)
6192 {
6193 	ipha_t *ipha;
6194 	mblk_t *first_mp;
6195 	boolean_t secure;
6196 	unsigned char db_type;
6197 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6198 
6199 	first_mp = mp;
6200 	if (mctl_present) {
6201 		mp = mp->b_cont;
6202 		secure = ipsec_in_is_secure(first_mp);
6203 		ASSERT(mp != NULL);
6204 	} else {
6205 		/*
6206 		 * If this is an ICMP error being reported - which goes
6207 		 * up as M_CTLs, we need to convert them to M_DATA till
6208 		 * we finish checking with global policy because
6209 		 * ipsec_check_global_policy() assumes M_DATA as clear
6210 		 * and M_CTL as secure.
6211 		 */
6212 		db_type = DB_TYPE(mp);
6213 		DB_TYPE(mp) = M_DATA;
6214 		secure = B_FALSE;
6215 	}
6216 	/*
6217 	 * We are generating an icmp error for some inbound packet.
6218 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6219 	 * Before we generate an error, check with global policy
6220 	 * to see whether this is allowed to enter the system. As
6221 	 * there is no "conn", we are checking with global policy.
6222 	 */
6223 	ipha = (ipha_t *)mp->b_rptr;
6224 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6225 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6226 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6227 		if (first_mp == NULL)
6228 			return (B_FALSE);
6229 	}
6230 
6231 	if (!mctl_present)
6232 		DB_TYPE(mp) = db_type;
6233 
6234 	if (flags & IP_FF_SEND_ICMP) {
6235 		if (flags & IP_FF_HDR_COMPLETE) {
6236 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6237 				freemsg(first_mp);
6238 				return (B_TRUE);
6239 			}
6240 		}
6241 		if (flags & IP_FF_CKSUM) {
6242 			/*
6243 			 * Have to correct checksum since
6244 			 * the packet might have been
6245 			 * fragmented and the reassembly code in ip_rput
6246 			 * does not restore the IP checksum.
6247 			 */
6248 			ipha->ipha_hdr_checksum = 0;
6249 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6250 		}
6251 		switch (icmp_type) {
6252 		case ICMP_DEST_UNREACHABLE:
6253 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6254 			    ipst);
6255 			break;
6256 		default:
6257 			freemsg(first_mp);
6258 			break;
6259 		}
6260 	} else {
6261 		freemsg(first_mp);
6262 		return (B_FALSE);
6263 	}
6264 
6265 	return (B_TRUE);
6266 }
6267 
6268 /*
6269  * Used to send an ICMP error message when a packet is received for
6270  * a protocol that is not supported. The mblk passed as argument
6271  * is consumed by this function.
6272  */
6273 void
6274 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6275     ip_stack_t *ipst)
6276 {
6277 	mblk_t *mp;
6278 	ipha_t *ipha;
6279 	ill_t *ill;
6280 	ipsec_in_t *ii;
6281 
6282 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6283 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6284 
6285 	mp = ipsec_mp->b_cont;
6286 	ipsec_mp->b_cont = NULL;
6287 	ipha = (ipha_t *)mp->b_rptr;
6288 	/* Get ill from index in ipsec_in_t. */
6289 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6290 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6291 	    ipst);
6292 	if (ill != NULL) {
6293 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6294 			if (ip_fanout_send_icmp(q, mp, flags,
6295 			    ICMP_DEST_UNREACHABLE,
6296 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6297 				BUMP_MIB(ill->ill_ip_mib,
6298 				    ipIfStatsInUnknownProtos);
6299 			}
6300 		} else {
6301 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6302 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6303 			    0, B_FALSE, zoneid, ipst)) {
6304 				BUMP_MIB(ill->ill_ip_mib,
6305 				    ipIfStatsInUnknownProtos);
6306 			}
6307 		}
6308 		ill_refrele(ill);
6309 	} else { /* re-link for the freemsg() below. */
6310 		ipsec_mp->b_cont = mp;
6311 	}
6312 
6313 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6314 	freemsg(ipsec_mp);
6315 }
6316 
6317 /*
6318  * See if the inbound datagram has had IPsec processing applied to it.
6319  */
6320 boolean_t
6321 ipsec_in_is_secure(mblk_t *ipsec_mp)
6322 {
6323 	ipsec_in_t *ii;
6324 
6325 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6326 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6327 
6328 	if (ii->ipsec_in_loopback) {
6329 		return (ii->ipsec_in_secure);
6330 	} else {
6331 		return (ii->ipsec_in_ah_sa != NULL ||
6332 		    ii->ipsec_in_esp_sa != NULL ||
6333 		    ii->ipsec_in_decaps);
6334 	}
6335 }
6336 
6337 /*
6338  * Handle protocols with which IP is less intimate.  There
6339  * can be more than one stream bound to a particular
6340  * protocol.  When this is the case, normally each one gets a copy
6341  * of any incoming packets.
6342  *
6343  * IPsec NOTE :
6344  *
6345  * Don't allow a secure packet going up a non-secure connection.
6346  * We don't allow this because
6347  *
6348  * 1) Reply might go out in clear which will be dropped at
6349  *    the sending side.
6350  * 2) If the reply goes out in clear it will give the
6351  *    adversary enough information for getting the key in
6352  *    most of the cases.
6353  *
6354  * Moreover getting a secure packet when we expect clear
6355  * implies that SA's were added without checking for
6356  * policy on both ends. This should not happen once ISAKMP
6357  * is used to negotiate SAs as SAs will be added only after
6358  * verifying the policy.
6359  *
6360  * NOTE : If the packet was tunneled and not multicast we only send
6361  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6362  * back to delivering packets to AF_INET6 raw sockets.
6363  *
6364  * IPQoS Notes:
6365  * Once we have determined the client, invoke IPPF processing.
6366  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6367  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6368  * ip_policy will be false.
6369  *
6370  * Zones notes:
6371  * Currently only applications in the global zone can create raw sockets for
6372  * protocols other than ICMP. So unlike the broadcast / multicast case of
6373  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6374  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6375  */
6376 static void
6377 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6378     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6379     zoneid_t zoneid)
6380 {
6381 	queue_t	*rq;
6382 	mblk_t	*mp1, *first_mp1;
6383 	uint_t	protocol = ipha->ipha_protocol;
6384 	ipaddr_t dst;
6385 	boolean_t one_only;
6386 	mblk_t *first_mp = mp;
6387 	boolean_t secure;
6388 	uint32_t ill_index;
6389 	conn_t	*connp, *first_connp, *next_connp;
6390 	connf_t	*connfp;
6391 	boolean_t shared_addr;
6392 	mib2_ipIfStatsEntry_t *mibptr;
6393 	ip_stack_t *ipst = recv_ill->ill_ipst;
6394 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6395 
6396 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6397 	if (mctl_present) {
6398 		mp = first_mp->b_cont;
6399 		secure = ipsec_in_is_secure(first_mp);
6400 		ASSERT(mp != NULL);
6401 	} else {
6402 		secure = B_FALSE;
6403 	}
6404 	dst = ipha->ipha_dst;
6405 	/*
6406 	 * If the packet was tunneled and not multicast we only send to it
6407 	 * the first match.
6408 	 */
6409 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6410 	    !CLASSD(dst));
6411 
6412 	shared_addr = (zoneid == ALL_ZONES);
6413 	if (shared_addr) {
6414 		/*
6415 		 * We don't allow multilevel ports for raw IP, so no need to
6416 		 * check for that here.
6417 		 */
6418 		zoneid = tsol_packet_to_zoneid(mp);
6419 	}
6420 
6421 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6422 	mutex_enter(&connfp->connf_lock);
6423 	connp = connfp->connf_head;
6424 	for (connp = connfp->connf_head; connp != NULL;
6425 	    connp = connp->conn_next) {
6426 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6427 		    zoneid) &&
6428 		    (!is_system_labeled() ||
6429 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6430 		    connp))) {
6431 			break;
6432 		}
6433 	}
6434 
6435 	if (connp == NULL || connp->conn_upq == NULL) {
6436 		/*
6437 		 * No one bound to these addresses.  Is
6438 		 * there a client that wants all
6439 		 * unclaimed datagrams?
6440 		 */
6441 		mutex_exit(&connfp->connf_lock);
6442 		/*
6443 		 * Check for IPPROTO_ENCAP...
6444 		 */
6445 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6446 			/*
6447 			 * If an IPsec mblk is here on a multicast
6448 			 * tunnel (using ip_mroute stuff), check policy here,
6449 			 * THEN ship off to ip_mroute_decap().
6450 			 *
6451 			 * BTW,  If I match a configured IP-in-IP
6452 			 * tunnel, this path will not be reached, and
6453 			 * ip_mroute_decap will never be called.
6454 			 */
6455 			first_mp = ipsec_check_global_policy(first_mp, connp,
6456 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6457 			if (first_mp != NULL) {
6458 				if (mctl_present)
6459 					freeb(first_mp);
6460 				ip_mroute_decap(q, mp, ill);
6461 			} /* Else we already freed everything! */
6462 		} else {
6463 			/*
6464 			 * Otherwise send an ICMP protocol unreachable.
6465 			 */
6466 			if (ip_fanout_send_icmp(q, first_mp, flags,
6467 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6468 			    mctl_present, zoneid, ipst)) {
6469 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6470 			}
6471 		}
6472 		return;
6473 	}
6474 	CONN_INC_REF(connp);
6475 	first_connp = connp;
6476 
6477 	/*
6478 	 * Only send message to one tunnel driver by immediately
6479 	 * terminating the loop.
6480 	 */
6481 	connp = one_only ? NULL : connp->conn_next;
6482 
6483 	for (;;) {
6484 		while (connp != NULL) {
6485 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6486 			    flags, zoneid) &&
6487 			    (!is_system_labeled() ||
6488 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6489 			    shared_addr, connp)))
6490 				break;
6491 			connp = connp->conn_next;
6492 		}
6493 
6494 		/*
6495 		 * Copy the packet.
6496 		 */
6497 		if (connp == NULL || connp->conn_upq == NULL ||
6498 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6499 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6500 			/*
6501 			 * No more interested clients or memory
6502 			 * allocation failed
6503 			 */
6504 			connp = first_connp;
6505 			break;
6506 		}
6507 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6508 		CONN_INC_REF(connp);
6509 		mutex_exit(&connfp->connf_lock);
6510 		rq = connp->conn_rq;
6511 		if (!canputnext(rq)) {
6512 			if (flags & IP_FF_RAWIP) {
6513 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6514 			} else {
6515 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6516 			}
6517 
6518 			freemsg(first_mp1);
6519 		} else {
6520 			/*
6521 			 * Don't enforce here if we're an actual tunnel -
6522 			 * let "tun" do it instead.
6523 			 */
6524 			if (!IPCL_IS_IPTUN(connp) &&
6525 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6526 			    secure)) {
6527 				first_mp1 = ipsec_check_inbound_policy
6528 				    (first_mp1, connp, ipha, NULL,
6529 				    mctl_present);
6530 			}
6531 			if (first_mp1 != NULL) {
6532 				int in_flags = 0;
6533 				/*
6534 				 * ip_fanout_proto also gets called from
6535 				 * icmp_inbound_error_fanout, in which case
6536 				 * the msg type is M_CTL.  Don't add info
6537 				 * in this case for the time being. In future
6538 				 * when there is a need for knowing the
6539 				 * inbound iface index for ICMP error msgs,
6540 				 * then this can be changed.
6541 				 */
6542 				if (connp->conn_recvif)
6543 					in_flags = IPF_RECVIF;
6544 				/*
6545 				 * The ULP may support IP_RECVPKTINFO for both
6546 				 * IP v4 and v6 so pass the appropriate argument
6547 				 * based on conn IP version.
6548 				 */
6549 				if (connp->conn_ip_recvpktinfo) {
6550 					if (connp->conn_af_isv6) {
6551 						/*
6552 						 * V6 only needs index
6553 						 */
6554 						in_flags |= IPF_RECVIF;
6555 					} else {
6556 						/*
6557 						 * V4 needs index +
6558 						 * matching address.
6559 						 */
6560 						in_flags |= IPF_RECVADDR;
6561 					}
6562 				}
6563 				if ((in_flags != 0) &&
6564 				    (mp->b_datap->db_type != M_CTL)) {
6565 					/*
6566 					 * the actual data will be
6567 					 * contained in b_cont upon
6568 					 * successful return of the
6569 					 * following call else
6570 					 * original mblk is returned
6571 					 */
6572 					ASSERT(recv_ill != NULL);
6573 					mp1 = ip_add_info(mp1, recv_ill,
6574 					    in_flags, IPCL_ZONEID(connp), ipst);
6575 				}
6576 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6577 				if (mctl_present)
6578 					freeb(first_mp1);
6579 				(connp->conn_recv)(connp, mp1, NULL);
6580 			}
6581 		}
6582 		mutex_enter(&connfp->connf_lock);
6583 		/* Follow the next pointer before releasing the conn. */
6584 		next_connp = connp->conn_next;
6585 		CONN_DEC_REF(connp);
6586 		connp = next_connp;
6587 	}
6588 
6589 	/* Last one.  Send it upstream. */
6590 	mutex_exit(&connfp->connf_lock);
6591 
6592 	/*
6593 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6594 	 * will be set to false.
6595 	 */
6596 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6597 		ill_index = ill->ill_phyint->phyint_ifindex;
6598 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6599 		if (mp == NULL) {
6600 			CONN_DEC_REF(connp);
6601 			if (mctl_present) {
6602 				freeb(first_mp);
6603 			}
6604 			return;
6605 		}
6606 	}
6607 
6608 	rq = connp->conn_rq;
6609 	if (!canputnext(rq)) {
6610 		if (flags & IP_FF_RAWIP) {
6611 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6612 		} else {
6613 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6614 		}
6615 
6616 		freemsg(first_mp);
6617 	} else {
6618 		if (IPCL_IS_IPTUN(connp)) {
6619 			/*
6620 			 * Tunneled packet.  We enforce policy in the tunnel
6621 			 * module itself.
6622 			 *
6623 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6624 			 * a policy check.
6625 			 * FIXME to use conn_recv for tun later.
6626 			 */
6627 			putnext(rq, first_mp);
6628 			CONN_DEC_REF(connp);
6629 			return;
6630 		}
6631 
6632 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6633 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6634 			    ipha, NULL, mctl_present);
6635 		}
6636 
6637 		if (first_mp != NULL) {
6638 			int in_flags = 0;
6639 
6640 			/*
6641 			 * ip_fanout_proto also gets called
6642 			 * from icmp_inbound_error_fanout, in
6643 			 * which case the msg type is M_CTL.
6644 			 * Don't add info in this case for time
6645 			 * being. In future when there is a
6646 			 * need for knowing the inbound iface
6647 			 * index for ICMP error msgs, then this
6648 			 * can be changed
6649 			 */
6650 			if (connp->conn_recvif)
6651 				in_flags = IPF_RECVIF;
6652 			if (connp->conn_ip_recvpktinfo) {
6653 				if (connp->conn_af_isv6) {
6654 					/*
6655 					 * V6 only needs index
6656 					 */
6657 					in_flags |= IPF_RECVIF;
6658 				} else {
6659 					/*
6660 					 * V4 needs index +
6661 					 * matching address.
6662 					 */
6663 					in_flags |= IPF_RECVADDR;
6664 				}
6665 			}
6666 			if ((in_flags != 0) &&
6667 			    (mp->b_datap->db_type != M_CTL)) {
6668 
6669 				/*
6670 				 * the actual data will be contained in
6671 				 * b_cont upon successful return
6672 				 * of the following call else original
6673 				 * mblk is returned
6674 				 */
6675 				ASSERT(recv_ill != NULL);
6676 				mp = ip_add_info(mp, recv_ill,
6677 				    in_flags, IPCL_ZONEID(connp), ipst);
6678 			}
6679 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6680 			(connp->conn_recv)(connp, mp, NULL);
6681 			if (mctl_present)
6682 				freeb(first_mp);
6683 		}
6684 	}
6685 	CONN_DEC_REF(connp);
6686 }
6687 
6688 /*
6689  * Fanout for TCP packets
6690  * The caller puts <fport, lport> in the ports parameter.
6691  *
6692  * IPQoS Notes
6693  * Before sending it to the client, invoke IPPF processing.
6694  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6695  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6696  * ip_policy is false.
6697  */
6698 static void
6699 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6700     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6701 {
6702 	mblk_t  *first_mp;
6703 	boolean_t secure;
6704 	uint32_t ill_index;
6705 	int	ip_hdr_len;
6706 	tcph_t	*tcph;
6707 	boolean_t syn_present = B_FALSE;
6708 	conn_t	*connp;
6709 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6710 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6711 
6712 	ASSERT(recv_ill != NULL);
6713 
6714 	first_mp = mp;
6715 	if (mctl_present) {
6716 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6717 		mp = first_mp->b_cont;
6718 		secure = ipsec_in_is_secure(first_mp);
6719 		ASSERT(mp != NULL);
6720 	} else {
6721 		secure = B_FALSE;
6722 	}
6723 
6724 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6725 
6726 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6727 	    zoneid, ipst)) == NULL) {
6728 		/*
6729 		 * No connected connection or listener. Send a
6730 		 * TH_RST via tcp_xmit_listeners_reset.
6731 		 */
6732 
6733 		/* Initiate IPPf processing, if needed. */
6734 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6735 			uint32_t ill_index;
6736 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6737 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6738 			if (first_mp == NULL)
6739 				return;
6740 		}
6741 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6742 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6743 		    zoneid));
6744 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6745 		    ipst->ips_netstack->netstack_tcp, NULL);
6746 		return;
6747 	}
6748 
6749 	/*
6750 	 * Allocate the SYN for the TCP connection here itself
6751 	 */
6752 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6753 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6754 		if (IPCL_IS_TCP(connp)) {
6755 			squeue_t *sqp;
6756 
6757 			/*
6758 			 * For fused tcp loopback, assign the eager's
6759 			 * squeue to be that of the active connect's.
6760 			 * Note that we don't check for IP_FF_LOOPBACK
6761 			 * here since this routine gets called only
6762 			 * for loopback (unlike the IPv6 counterpart).
6763 			 */
6764 			ASSERT(Q_TO_CONN(q) != NULL);
6765 			if (do_tcp_fusion &&
6766 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6767 			    !secure &&
6768 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6769 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6770 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6771 				sqp = Q_TO_CONN(q)->conn_sqp;
6772 			} else {
6773 				sqp = IP_SQUEUE_GET(lbolt);
6774 			}
6775 
6776 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6777 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6778 			syn_present = B_TRUE;
6779 		}
6780 	}
6781 
6782 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6783 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6784 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6785 		if ((flags & TH_RST) || (flags & TH_URG)) {
6786 			CONN_DEC_REF(connp);
6787 			freemsg(first_mp);
6788 			return;
6789 		}
6790 		if (flags & TH_ACK) {
6791 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6792 			    ipst->ips_netstack->netstack_tcp, connp);
6793 			CONN_DEC_REF(connp);
6794 			return;
6795 		}
6796 
6797 		CONN_DEC_REF(connp);
6798 		freemsg(first_mp);
6799 		return;
6800 	}
6801 
6802 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6803 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6804 		    NULL, mctl_present);
6805 		if (first_mp == NULL) {
6806 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6807 			CONN_DEC_REF(connp);
6808 			return;
6809 		}
6810 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6811 			ASSERT(syn_present);
6812 			if (mctl_present) {
6813 				ASSERT(first_mp != mp);
6814 				first_mp->b_datap->db_struioflag |=
6815 				    STRUIO_POLICY;
6816 			} else {
6817 				ASSERT(first_mp == mp);
6818 				mp->b_datap->db_struioflag &=
6819 				    ~STRUIO_EAGER;
6820 				mp->b_datap->db_struioflag |=
6821 				    STRUIO_POLICY;
6822 			}
6823 		} else {
6824 			/*
6825 			 * Discard first_mp early since we're dealing with a
6826 			 * fully-connected conn_t and tcp doesn't do policy in
6827 			 * this case.
6828 			 */
6829 			if (mctl_present) {
6830 				freeb(first_mp);
6831 				mctl_present = B_FALSE;
6832 			}
6833 			first_mp = mp;
6834 		}
6835 	}
6836 
6837 	/*
6838 	 * Initiate policy processing here if needed. If we get here from
6839 	 * icmp_inbound_error_fanout, ip_policy is false.
6840 	 */
6841 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6842 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6843 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6844 		if (mp == NULL) {
6845 			CONN_DEC_REF(connp);
6846 			if (mctl_present)
6847 				freeb(first_mp);
6848 			return;
6849 		} else if (mctl_present) {
6850 			ASSERT(first_mp != mp);
6851 			first_mp->b_cont = mp;
6852 		} else {
6853 			first_mp = mp;
6854 		}
6855 	}
6856 
6857 
6858 
6859 	/* Handle socket options. */
6860 	if (!syn_present &&
6861 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6862 		/* Add header */
6863 		ASSERT(recv_ill != NULL);
6864 		/*
6865 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6866 		 * IPF_RECVIF.
6867 		 */
6868 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6869 		    ipst);
6870 		if (mp == NULL) {
6871 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6872 			CONN_DEC_REF(connp);
6873 			if (mctl_present)
6874 				freeb(first_mp);
6875 			return;
6876 		} else if (mctl_present) {
6877 			/*
6878 			 * ip_add_info might return a new mp.
6879 			 */
6880 			ASSERT(first_mp != mp);
6881 			first_mp->b_cont = mp;
6882 		} else {
6883 			first_mp = mp;
6884 		}
6885 	}
6886 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6887 	if (IPCL_IS_TCP(connp)) {
6888 		/* do not drain, certain use cases can blow the stack */
6889 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6890 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6891 	} else {
6892 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6893 		(connp->conn_recv)(connp, first_mp, NULL);
6894 		CONN_DEC_REF(connp);
6895 	}
6896 }
6897 
6898 /*
6899  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6900  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6901  * is not consumed.
6902  *
6903  * One of four things can happen, all of which affect the passed-in mblk:
6904  *
6905  * 1.) ICMP messages that go through here just get returned TRUE.
6906  *
6907  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6908  *
6909  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6910  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6911  *
6912  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6913  */
6914 static boolean_t
6915 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6916     ipsec_stack_t *ipss)
6917 {
6918 	int shift, plen, iph_len;
6919 	ipha_t *ipha;
6920 	udpha_t *udpha;
6921 	uint32_t *spi;
6922 	uint8_t *orptr;
6923 	boolean_t udp_pkt, free_ire;
6924 
6925 	if (DB_TYPE(mp) == M_CTL) {
6926 		/*
6927 		 * ICMP message with UDP inside.  Don't bother stripping, just
6928 		 * send it up.
6929 		 *
6930 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6931 		 * to ignore errors set by ICMP anyway ('cause they might be
6932 		 * forged), but that's the app's decision, not ours.
6933 		 */
6934 
6935 		/* Bunch of reality checks for DEBUG kernels... */
6936 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6937 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6938 
6939 		return (B_TRUE);
6940 	}
6941 
6942 	ipha = (ipha_t *)mp->b_rptr;
6943 	iph_len = IPH_HDR_LENGTH(ipha);
6944 	plen = ntohs(ipha->ipha_length);
6945 
6946 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6947 		/*
6948 		 * Most likely a keepalive for the benefit of an intervening
6949 		 * NAT.  These aren't for us, per se, so drop it.
6950 		 *
6951 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6952 		 * byte packets (keepalives are 1-byte), but we'll drop them
6953 		 * also.
6954 		 */
6955 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6956 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6957 		return (B_FALSE);
6958 	}
6959 
6960 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6961 		/* might as well pull it all up - it might be ESP. */
6962 		if (!pullupmsg(mp, -1)) {
6963 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6964 			    DROPPER(ipss, ipds_esp_nomem),
6965 			    &ipss->ipsec_dropper);
6966 			return (B_FALSE);
6967 		}
6968 
6969 		ipha = (ipha_t *)mp->b_rptr;
6970 	}
6971 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6972 	if (*spi == 0) {
6973 		/* UDP packet - remove 0-spi. */
6974 		shift = sizeof (uint32_t);
6975 	} else {
6976 		/* ESP-in-UDP packet - reduce to ESP. */
6977 		ipha->ipha_protocol = IPPROTO_ESP;
6978 		shift = sizeof (udpha_t);
6979 	}
6980 
6981 	/* Fix IP header */
6982 	ipha->ipha_length = htons(plen - shift);
6983 	ipha->ipha_hdr_checksum = 0;
6984 
6985 	orptr = mp->b_rptr;
6986 	mp->b_rptr += shift;
6987 
6988 	if (*spi == 0) {
6989 		ASSERT((uint8_t *)ipha == orptr);
6990 		udpha = (udpha_t *)(orptr + iph_len);
6991 		udpha->uha_length = htons(plen - shift - iph_len);
6992 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6993 		udp_pkt = B_TRUE;
6994 	} else {
6995 		udp_pkt = B_FALSE;
6996 	}
6997 	ovbcopy(orptr, orptr + shift, iph_len);
6998 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6999 		ipha = (ipha_t *)(orptr + shift);
7000 
7001 		free_ire = (ire == NULL);
7002 		if (free_ire) {
7003 			/* Re-acquire ire. */
7004 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
7005 			    ipss->ipsec_netstack->netstack_ip);
7006 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
7007 				if (ire != NULL)
7008 					ire_refrele(ire);
7009 				/*
7010 				 * Do a regular freemsg(), as this is an IP
7011 				 * error (no local route) not an IPsec one.
7012 				 */
7013 				freemsg(mp);
7014 			}
7015 		}
7016 
7017 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
7018 		if (free_ire)
7019 			ire_refrele(ire);
7020 	}
7021 
7022 	return (udp_pkt);
7023 }
7024 
7025 /*
7026  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
7027  * We are responsible for disposing of mp, such as by freemsg() or putnext()
7028  * Caller is responsible for dropping references to the conn, and freeing
7029  * first_mp.
7030  *
7031  * IPQoS Notes
7032  * Before sending it to the client, invoke IPPF processing. Policy processing
7033  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
7034  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
7035  * ip_wput_local, ip_policy is false.
7036  */
7037 static void
7038 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
7039     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
7040     boolean_t ip_policy)
7041 {
7042 	boolean_t	mctl_present = (first_mp != NULL);
7043 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
7044 	uint32_t	ill_index;
7045 	ip_stack_t	*ipst = recv_ill->ill_ipst;
7046 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
7047 
7048 	ASSERT(ill != NULL);
7049 
7050 	if (mctl_present)
7051 		first_mp->b_cont = mp;
7052 	else
7053 		first_mp = mp;
7054 
7055 	if (CONN_UDP_FLOWCTLD(connp)) {
7056 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
7057 		freemsg(first_mp);
7058 		return;
7059 	}
7060 
7061 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
7062 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
7063 		    NULL, mctl_present);
7064 		if (first_mp == NULL) {
7065 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
7066 			return;	/* Freed by ipsec_check_inbound_policy(). */
7067 		}
7068 	}
7069 	if (mctl_present)
7070 		freeb(first_mp);
7071 
7072 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7073 	if (connp->conn_udp->udp_nat_t_endpoint) {
7074 		if (mctl_present) {
7075 			/* mctl_present *shouldn't* happen. */
7076 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7077 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7078 			    &ipss->ipsec_dropper);
7079 			return;
7080 		}
7081 
7082 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7083 			return;
7084 	}
7085 
7086 	/* Handle options. */
7087 	if (connp->conn_recvif)
7088 		in_flags = IPF_RECVIF;
7089 	/*
7090 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7091 	 * passed to ip_add_info is based on IP version of connp.
7092 	 */
7093 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7094 		if (connp->conn_af_isv6) {
7095 			/*
7096 			 * V6 only needs index
7097 			 */
7098 			in_flags |= IPF_RECVIF;
7099 		} else {
7100 			/*
7101 			 * V4 needs index + matching address.
7102 			 */
7103 			in_flags |= IPF_RECVADDR;
7104 		}
7105 	}
7106 
7107 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7108 		in_flags |= IPF_RECVSLLA;
7109 
7110 	/*
7111 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7112 	 * freed if the packet is dropped. The caller will do so.
7113 	 */
7114 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7115 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7116 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7117 		if (mp == NULL) {
7118 			return;
7119 		}
7120 	}
7121 	if ((in_flags != 0) &&
7122 	    (mp->b_datap->db_type != M_CTL)) {
7123 		/*
7124 		 * The actual data will be contained in b_cont
7125 		 * upon successful return of the following call
7126 		 * else original mblk is returned
7127 		 */
7128 		ASSERT(recv_ill != NULL);
7129 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7130 		    ipst);
7131 	}
7132 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7133 	/* Send it upstream */
7134 	(connp->conn_recv)(connp, mp, NULL);
7135 }
7136 
7137 /*
7138  * Fanout for UDP packets.
7139  * The caller puts <fport, lport> in the ports parameter.
7140  *
7141  * If SO_REUSEADDR is set all multicast and broadcast packets
7142  * will be delivered to all streams bound to the same port.
7143  *
7144  * Zones notes:
7145  * Multicast and broadcast packets will be distributed to streams in all zones.
7146  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7147  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7148  * packets. To maintain this behavior with multiple zones, the conns are grouped
7149  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7150  * each zone. If unset, all the following conns in the same zone are skipped.
7151  */
7152 static void
7153 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7154     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7155     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7156 {
7157 	uint32_t	dstport, srcport;
7158 	ipaddr_t	dst;
7159 	mblk_t		*first_mp;
7160 	boolean_t	secure;
7161 	in6_addr_t	v6src;
7162 	conn_t		*connp;
7163 	connf_t		*connfp;
7164 	conn_t		*first_connp;
7165 	conn_t		*next_connp;
7166 	mblk_t		*mp1, *first_mp1;
7167 	ipaddr_t	src;
7168 	zoneid_t	last_zoneid;
7169 	boolean_t	reuseaddr;
7170 	boolean_t	shared_addr;
7171 	ip_stack_t	*ipst;
7172 
7173 	ASSERT(recv_ill != NULL);
7174 	ipst = recv_ill->ill_ipst;
7175 
7176 	first_mp = mp;
7177 	if (mctl_present) {
7178 		mp = first_mp->b_cont;
7179 		first_mp->b_cont = NULL;
7180 		secure = ipsec_in_is_secure(first_mp);
7181 		ASSERT(mp != NULL);
7182 	} else {
7183 		first_mp = NULL;
7184 		secure = B_FALSE;
7185 	}
7186 
7187 	/* Extract ports in net byte order */
7188 	dstport = htons(ntohl(ports) & 0xFFFF);
7189 	srcport = htons(ntohl(ports) >> 16);
7190 	dst = ipha->ipha_dst;
7191 	src = ipha->ipha_src;
7192 
7193 	shared_addr = (zoneid == ALL_ZONES);
7194 	if (shared_addr) {
7195 		/*
7196 		 * No need to handle exclusive-stack zones since ALL_ZONES
7197 		 * only applies to the shared stack.
7198 		 */
7199 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7200 		if (zoneid == ALL_ZONES)
7201 			zoneid = tsol_packet_to_zoneid(mp);
7202 	}
7203 
7204 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7205 	mutex_enter(&connfp->connf_lock);
7206 	connp = connfp->connf_head;
7207 	if (!broadcast && !CLASSD(dst)) {
7208 		/*
7209 		 * Not broadcast or multicast. Send to the one (first)
7210 		 * client we find. No need to check conn_wantpacket()
7211 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7212 		 * IPv4 unicast packets.
7213 		 */
7214 		while ((connp != NULL) &&
7215 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7216 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7217 			connp = connp->conn_next;
7218 		}
7219 
7220 		if (connp == NULL || connp->conn_upq == NULL)
7221 			goto notfound;
7222 
7223 		if (is_system_labeled() &&
7224 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7225 		    connp))
7226 			goto notfound;
7227 
7228 		CONN_INC_REF(connp);
7229 		mutex_exit(&connfp->connf_lock);
7230 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7231 		    flags, recv_ill, ip_policy);
7232 		IP_STAT(ipst, ip_udp_fannorm);
7233 		CONN_DEC_REF(connp);
7234 		return;
7235 	}
7236 
7237 	/*
7238 	 * Broadcast and multicast case
7239 	 *
7240 	 * Need to check conn_wantpacket().
7241 	 * If SO_REUSEADDR has been set on the first we send the
7242 	 * packet to all clients that have joined the group and
7243 	 * match the port.
7244 	 */
7245 
7246 	while (connp != NULL) {
7247 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7248 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7249 		    (!is_system_labeled() ||
7250 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7251 		    connp)))
7252 			break;
7253 		connp = connp->conn_next;
7254 	}
7255 
7256 	if (connp == NULL || connp->conn_upq == NULL)
7257 		goto notfound;
7258 
7259 	first_connp = connp;
7260 	/*
7261 	 * When SO_REUSEADDR is not set, send the packet only to the first
7262 	 * matching connection in its zone by keeping track of the zoneid.
7263 	 */
7264 	reuseaddr = first_connp->conn_reuseaddr;
7265 	last_zoneid = first_connp->conn_zoneid;
7266 
7267 	CONN_INC_REF(connp);
7268 	connp = connp->conn_next;
7269 	for (;;) {
7270 		while (connp != NULL) {
7271 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7272 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7273 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7274 			    (!is_system_labeled() ||
7275 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7276 			    shared_addr, connp)))
7277 				break;
7278 			connp = connp->conn_next;
7279 		}
7280 		/*
7281 		 * Just copy the data part alone. The mctl part is
7282 		 * needed just for verifying policy and it is never
7283 		 * sent up.
7284 		 */
7285 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7286 		    ((mp1 = copymsg(mp)) == NULL))) {
7287 			/*
7288 			 * No more interested clients or memory
7289 			 * allocation failed
7290 			 */
7291 			connp = first_connp;
7292 			break;
7293 		}
7294 		if (connp->conn_zoneid != last_zoneid) {
7295 			/*
7296 			 * Update the zoneid so that the packet isn't sent to
7297 			 * any more conns in the same zone unless SO_REUSEADDR
7298 			 * is set.
7299 			 */
7300 			reuseaddr = connp->conn_reuseaddr;
7301 			last_zoneid = connp->conn_zoneid;
7302 		}
7303 		if (first_mp != NULL) {
7304 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7305 			    ipsec_info_type == IPSEC_IN);
7306 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7307 			    ipst->ips_netstack);
7308 			if (first_mp1 == NULL) {
7309 				freemsg(mp1);
7310 				connp = first_connp;
7311 				break;
7312 			}
7313 		} else {
7314 			first_mp1 = NULL;
7315 		}
7316 		CONN_INC_REF(connp);
7317 		mutex_exit(&connfp->connf_lock);
7318 		/*
7319 		 * IPQoS notes: We don't send the packet for policy
7320 		 * processing here, will do it for the last one (below).
7321 		 * i.e. we do it per-packet now, but if we do policy
7322 		 * processing per-conn, then we would need to do it
7323 		 * here too.
7324 		 */
7325 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7326 		    ipha, flags, recv_ill, B_FALSE);
7327 		mutex_enter(&connfp->connf_lock);
7328 		/* Follow the next pointer before releasing the conn. */
7329 		next_connp = connp->conn_next;
7330 		IP_STAT(ipst, ip_udp_fanmb);
7331 		CONN_DEC_REF(connp);
7332 		connp = next_connp;
7333 	}
7334 
7335 	/* Last one.  Send it upstream. */
7336 	mutex_exit(&connfp->connf_lock);
7337 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7338 	    recv_ill, ip_policy);
7339 	IP_STAT(ipst, ip_udp_fanmb);
7340 	CONN_DEC_REF(connp);
7341 	return;
7342 
7343 notfound:
7344 
7345 	mutex_exit(&connfp->connf_lock);
7346 	IP_STAT(ipst, ip_udp_fanothers);
7347 	/*
7348 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7349 	 * have already been matched above, since they live in the IPv4
7350 	 * fanout tables. This implies we only need to
7351 	 * check for IPv6 in6addr_any endpoints here.
7352 	 * Thus we compare using ipv6_all_zeros instead of the destination
7353 	 * address, except for the multicast group membership lookup which
7354 	 * uses the IPv4 destination.
7355 	 */
7356 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7357 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7358 	mutex_enter(&connfp->connf_lock);
7359 	connp = connfp->connf_head;
7360 	if (!broadcast && !CLASSD(dst)) {
7361 		while (connp != NULL) {
7362 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7363 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7364 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7365 			    !connp->conn_ipv6_v6only)
7366 				break;
7367 			connp = connp->conn_next;
7368 		}
7369 
7370 		if (connp != NULL && is_system_labeled() &&
7371 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7372 		    connp))
7373 			connp = NULL;
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].
7388 			    connf_head != NULL) {
7389 				ip_fanout_proto(q, first_mp, ill, ipha,
7390 				    flags | IP_FF_RAWIP, mctl_present,
7391 				    ip_policy, recv_ill, zoneid);
7392 			} else {
7393 				if (ip_fanout_send_icmp(q, first_mp, flags,
7394 				    ICMP_DEST_UNREACHABLE,
7395 				    ICMP_PORT_UNREACHABLE,
7396 				    mctl_present, zoneid, ipst)) {
7397 					BUMP_MIB(ill->ill_ip_mib,
7398 					    udpIfStatsNoPorts);
7399 				}
7400 			}
7401 			return;
7402 		}
7403 
7404 		CONN_INC_REF(connp);
7405 		mutex_exit(&connfp->connf_lock);
7406 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7407 		    flags, recv_ill, ip_policy);
7408 		CONN_DEC_REF(connp);
7409 		return;
7410 	}
7411 	/*
7412 	 * IPv4 multicast packet being delivered to an AF_INET6
7413 	 * in6addr_any endpoint.
7414 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7415 	 * and not conn_wantpacket_v6() since any multicast membership is
7416 	 * for an IPv4-mapped multicast address.
7417 	 * The packet is sent to all clients in all zones that have joined the
7418 	 * group and match the port.
7419 	 */
7420 	while (connp != NULL) {
7421 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7422 		    srcport, v6src) &&
7423 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7424 		    (!is_system_labeled() ||
7425 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7426 		    connp)))
7427 			break;
7428 		connp = connp->conn_next;
7429 	}
7430 
7431 	if (connp == NULL || connp->conn_upq == NULL) {
7432 		/*
7433 		 * No one bound to this port.  Is
7434 		 * there a client that wants all
7435 		 * unclaimed datagrams?
7436 		 */
7437 		mutex_exit(&connfp->connf_lock);
7438 
7439 		if (mctl_present)
7440 			first_mp->b_cont = mp;
7441 		else
7442 			first_mp = mp;
7443 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7444 		    NULL) {
7445 			ip_fanout_proto(q, first_mp, ill, ipha,
7446 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7447 			    recv_ill, zoneid);
7448 		} else {
7449 			/*
7450 			 * We used to attempt to send an icmp error here, but
7451 			 * since this is known to be a multicast packet
7452 			 * and we don't send icmp errors in response to
7453 			 * multicast, just drop the packet and give up sooner.
7454 			 */
7455 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7456 			freemsg(first_mp);
7457 		}
7458 		return;
7459 	}
7460 
7461 	first_connp = connp;
7462 
7463 	CONN_INC_REF(connp);
7464 	connp = connp->conn_next;
7465 	for (;;) {
7466 		while (connp != NULL) {
7467 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7468 			    ipv6_all_zeros, srcport, v6src) &&
7469 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7470 			    (!is_system_labeled() ||
7471 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7472 			    shared_addr, connp)))
7473 				break;
7474 			connp = connp->conn_next;
7475 		}
7476 		/*
7477 		 * Just copy the data part alone. The mctl part is
7478 		 * needed just for verifying policy and it is never
7479 		 * sent up.
7480 		 */
7481 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7482 		    ((mp1 = copymsg(mp)) == NULL))) {
7483 			/*
7484 			 * No more intested clients or memory
7485 			 * allocation failed
7486 			 */
7487 			connp = first_connp;
7488 			break;
7489 		}
7490 		if (first_mp != NULL) {
7491 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7492 			    ipsec_info_type == IPSEC_IN);
7493 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7494 			    ipst->ips_netstack);
7495 			if (first_mp1 == NULL) {
7496 				freemsg(mp1);
7497 				connp = first_connp;
7498 				break;
7499 			}
7500 		} else {
7501 			first_mp1 = NULL;
7502 		}
7503 		CONN_INC_REF(connp);
7504 		mutex_exit(&connfp->connf_lock);
7505 		/*
7506 		 * IPQoS notes: We don't send the packet for policy
7507 		 * processing here, will do it for the last one (below).
7508 		 * i.e. we do it per-packet now, but if we do policy
7509 		 * processing per-conn, then we would need to do it
7510 		 * here too.
7511 		 */
7512 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7513 		    ipha, flags, recv_ill, B_FALSE);
7514 		mutex_enter(&connfp->connf_lock);
7515 		/* Follow the next pointer before releasing the conn. */
7516 		next_connp = connp->conn_next;
7517 		CONN_DEC_REF(connp);
7518 		connp = next_connp;
7519 	}
7520 
7521 	/* Last one.  Send it upstream. */
7522 	mutex_exit(&connfp->connf_lock);
7523 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7524 	    recv_ill, ip_policy);
7525 	CONN_DEC_REF(connp);
7526 }
7527 
7528 /*
7529  * Complete the ip_wput header so that it
7530  * is possible to generate ICMP
7531  * errors.
7532  */
7533 int
7534 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7535 {
7536 	ire_t *ire;
7537 
7538 	if (ipha->ipha_src == INADDR_ANY) {
7539 		ire = ire_lookup_local(zoneid, ipst);
7540 		if (ire == NULL) {
7541 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7542 			return (1);
7543 		}
7544 		ipha->ipha_src = ire->ire_addr;
7545 		ire_refrele(ire);
7546 	}
7547 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7548 	ipha->ipha_hdr_checksum = 0;
7549 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7550 	return (0);
7551 }
7552 
7553 /*
7554  * Nobody should be sending
7555  * packets up this stream
7556  */
7557 static void
7558 ip_lrput(queue_t *q, mblk_t *mp)
7559 {
7560 	mblk_t *mp1;
7561 
7562 	switch (mp->b_datap->db_type) {
7563 	case M_FLUSH:
7564 		/* Turn around */
7565 		if (*mp->b_rptr & FLUSHW) {
7566 			*mp->b_rptr &= ~FLUSHR;
7567 			qreply(q, mp);
7568 			return;
7569 		}
7570 		break;
7571 	}
7572 	/* Could receive messages that passed through ar_rput */
7573 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7574 		mp1->b_prev = mp1->b_next = NULL;
7575 	freemsg(mp);
7576 }
7577 
7578 /* Nobody should be sending packets down this stream */
7579 /* ARGSUSED */
7580 void
7581 ip_lwput(queue_t *q, mblk_t *mp)
7582 {
7583 	freemsg(mp);
7584 }
7585 
7586 /*
7587  * Move the first hop in any source route to ipha_dst and remove that part of
7588  * the source route.  Called by other protocols.  Errors in option formatting
7589  * are ignored - will be handled by ip_wput_options Return the final
7590  * destination (either ipha_dst or the last entry in a source route.)
7591  */
7592 ipaddr_t
7593 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7594 {
7595 	ipoptp_t	opts;
7596 	uchar_t		*opt;
7597 	uint8_t		optval;
7598 	uint8_t		optlen;
7599 	ipaddr_t	dst;
7600 	int		i;
7601 	ire_t		*ire;
7602 	ip_stack_t	*ipst = ns->netstack_ip;
7603 
7604 	ip2dbg(("ip_massage_options\n"));
7605 	dst = ipha->ipha_dst;
7606 	for (optval = ipoptp_first(&opts, ipha);
7607 	    optval != IPOPT_EOL;
7608 	    optval = ipoptp_next(&opts)) {
7609 		opt = opts.ipoptp_cur;
7610 		switch (optval) {
7611 			uint8_t off;
7612 		case IPOPT_SSRR:
7613 		case IPOPT_LSRR:
7614 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7615 				ip1dbg(("ip_massage_options: bad src route\n"));
7616 				break;
7617 			}
7618 			optlen = opts.ipoptp_len;
7619 			off = opt[IPOPT_OFFSET];
7620 			off--;
7621 		redo_srr:
7622 			if (optlen < IP_ADDR_LEN ||
7623 			    off > optlen - IP_ADDR_LEN) {
7624 				/* End of source route */
7625 				ip1dbg(("ip_massage_options: end of SR\n"));
7626 				break;
7627 			}
7628 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7629 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7630 			    ntohl(dst)));
7631 			/*
7632 			 * Check if our address is present more than
7633 			 * once as consecutive hops in source route.
7634 			 * XXX verify per-interface ip_forwarding
7635 			 * for source route?
7636 			 */
7637 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7638 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7639 			if (ire != NULL) {
7640 				ire_refrele(ire);
7641 				off += IP_ADDR_LEN;
7642 				goto redo_srr;
7643 			}
7644 			if (dst == htonl(INADDR_LOOPBACK)) {
7645 				ip1dbg(("ip_massage_options: loopback addr in "
7646 				    "source route!\n"));
7647 				break;
7648 			}
7649 			/*
7650 			 * Update ipha_dst to be the first hop and remove the
7651 			 * first hop from the source route (by overwriting
7652 			 * part of the option with NOP options).
7653 			 */
7654 			ipha->ipha_dst = dst;
7655 			/* Put the last entry in dst */
7656 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7657 			    3;
7658 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7659 
7660 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7661 			    ntohl(dst)));
7662 			/* Move down and overwrite */
7663 			opt[IP_ADDR_LEN] = opt[0];
7664 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7665 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7666 			for (i = 0; i < IP_ADDR_LEN; i++)
7667 				opt[i] = IPOPT_NOP;
7668 			break;
7669 		}
7670 	}
7671 	return (dst);
7672 }
7673 
7674 /*
7675  * Return the network mask
7676  * associated with the specified address.
7677  */
7678 ipaddr_t
7679 ip_net_mask(ipaddr_t addr)
7680 {
7681 	uchar_t	*up = (uchar_t *)&addr;
7682 	ipaddr_t mask = 0;
7683 	uchar_t	*maskp = (uchar_t *)&mask;
7684 
7685 #if defined(__i386) || defined(__amd64)
7686 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7687 #endif
7688 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7689 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7690 #endif
7691 	if (CLASSD(addr)) {
7692 		maskp[0] = 0xF0;
7693 		return (mask);
7694 	}
7695 
7696 	/* We assume Class E default netmask to be 32 */
7697 	if (CLASSE(addr))
7698 		return (0xffffffffU);
7699 
7700 	if (addr == 0)
7701 		return (0);
7702 	maskp[0] = 0xFF;
7703 	if ((up[0] & 0x80) == 0)
7704 		return (mask);
7705 
7706 	maskp[1] = 0xFF;
7707 	if ((up[0] & 0xC0) == 0x80)
7708 		return (mask);
7709 
7710 	maskp[2] = 0xFF;
7711 	if ((up[0] & 0xE0) == 0xC0)
7712 		return (mask);
7713 
7714 	/* Otherwise return no mask */
7715 	return ((ipaddr_t)0);
7716 }
7717 
7718 /*
7719  * Select an ill for the packet by considering load spreading across
7720  * a different ill in the group if dst_ill is part of some group.
7721  */
7722 ill_t *
7723 ip_newroute_get_dst_ill(ill_t *dst_ill)
7724 {
7725 	ill_t *ill;
7726 
7727 	/*
7728 	 * We schedule irrespective of whether the source address is
7729 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7730 	 */
7731 	ill = illgrp_scheduler(dst_ill);
7732 	if (ill == NULL)
7733 		return (NULL);
7734 
7735 	/*
7736 	 * For groups with names ip_sioctl_groupname ensures that all
7737 	 * ills are of same type. For groups without names, ifgrp_insert
7738 	 * ensures this.
7739 	 */
7740 	ASSERT(dst_ill->ill_type == ill->ill_type);
7741 
7742 	return (ill);
7743 }
7744 
7745 /*
7746  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7747  */
7748 ill_t *
7749 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7750     ip_stack_t *ipst)
7751 {
7752 	ill_t *ret_ill;
7753 
7754 	ASSERT(ifindex != 0);
7755 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7756 	    ipst);
7757 	if (ret_ill == NULL ||
7758 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7759 		if (isv6) {
7760 			if (ill != NULL) {
7761 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7762 			} else {
7763 				BUMP_MIB(&ipst->ips_ip6_mib,
7764 				    ipIfStatsOutDiscards);
7765 			}
7766 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7767 			    "bad ifindex %d.\n", ifindex));
7768 		} else {
7769 			if (ill != NULL) {
7770 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7771 			} else {
7772 				BUMP_MIB(&ipst->ips_ip_mib,
7773 				    ipIfStatsOutDiscards);
7774 			}
7775 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7776 			    "bad ifindex %d.\n", ifindex));
7777 		}
7778 		if (ret_ill != NULL)
7779 			ill_refrele(ret_ill);
7780 		freemsg(first_mp);
7781 		return (NULL);
7782 	}
7783 
7784 	return (ret_ill);
7785 }
7786 
7787 /*
7788  * IPv4 -
7789  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7790  * out a packet to a destination address for which we do not have specific
7791  * (or sufficient) routing information.
7792  *
7793  * NOTE : These are the scopes of some of the variables that point at IRE,
7794  *	  which needs to be followed while making any future modifications
7795  *	  to avoid memory leaks.
7796  *
7797  *	- ire and sire are the entries looked up initially by
7798  *	  ire_ftable_lookup.
7799  *	- ipif_ire is used to hold the interface ire associated with
7800  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7801  *	  it before branching out to error paths.
7802  *	- save_ire is initialized before ire_create, so that ire returned
7803  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7804  *	  before breaking out of the switch.
7805  *
7806  *	Thus on failures, we have to REFRELE only ire and sire, if they
7807  *	are not NULL.
7808  */
7809 void
7810 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7811     zoneid_t zoneid, ip_stack_t *ipst)
7812 {
7813 	areq_t	*areq;
7814 	ipaddr_t gw = 0;
7815 	ire_t	*ire = NULL;
7816 	mblk_t	*res_mp;
7817 	ipaddr_t *addrp;
7818 	ipaddr_t nexthop_addr;
7819 	ipif_t  *src_ipif = NULL;
7820 	ill_t	*dst_ill = NULL;
7821 	ipha_t  *ipha;
7822 	ire_t	*sire = NULL;
7823 	mblk_t	*first_mp;
7824 	ire_t	*save_ire;
7825 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7826 	ushort_t ire_marks = 0;
7827 	boolean_t mctl_present;
7828 	ipsec_out_t *io;
7829 	mblk_t	*saved_mp;
7830 	ire_t	*first_sire = NULL;
7831 	mblk_t	*copy_mp = NULL;
7832 	mblk_t	*xmit_mp = NULL;
7833 	ipaddr_t save_dst;
7834 	uint32_t multirt_flags =
7835 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7836 	boolean_t multirt_is_resolvable;
7837 	boolean_t multirt_resolve_next;
7838 	boolean_t unspec_src;
7839 	boolean_t do_attach_ill = B_FALSE;
7840 	boolean_t ip_nexthop = B_FALSE;
7841 	tsol_ire_gw_secattr_t *attrp = NULL;
7842 	tsol_gcgrp_t *gcgrp = NULL;
7843 	tsol_gcgrp_addr_t ga;
7844 
7845 	if (ip_debug > 2) {
7846 		/* ip1dbg */
7847 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7848 	}
7849 
7850 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7851 	if (mctl_present) {
7852 		io = (ipsec_out_t *)first_mp->b_rptr;
7853 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7854 		ASSERT(zoneid == io->ipsec_out_zoneid);
7855 		ASSERT(zoneid != ALL_ZONES);
7856 	}
7857 
7858 	ipha = (ipha_t *)mp->b_rptr;
7859 
7860 	/* All multicast lookups come through ip_newroute_ipif() */
7861 	if (CLASSD(dst)) {
7862 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7863 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7864 		freemsg(first_mp);
7865 		return;
7866 	}
7867 
7868 	if (mctl_present && io->ipsec_out_attach_if) {
7869 		/* ip_grab_attach_ill returns a held ill */
7870 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7871 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7872 
7873 		/* Failure case frees things for us. */
7874 		if (attach_ill == NULL)
7875 			return;
7876 
7877 		/*
7878 		 * Check if we need an ire that will not be
7879 		 * looked up by anybody else i.e. HIDDEN.
7880 		 */
7881 		if (ill_is_probeonly(attach_ill))
7882 			ire_marks = IRE_MARK_HIDDEN;
7883 	}
7884 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7885 		ip_nexthop = B_TRUE;
7886 		nexthop_addr = io->ipsec_out_nexthop_addr;
7887 	}
7888 	/*
7889 	 * If this IRE is created for forwarding or it is not for
7890 	 * traffic for congestion controlled protocols, mark it as temporary.
7891 	 */
7892 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7893 		ire_marks |= IRE_MARK_TEMPORARY;
7894 
7895 	/*
7896 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7897 	 * chain until it gets the most specific information available.
7898 	 * For example, we know that there is no IRE_CACHE for this dest,
7899 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7900 	 * ire_ftable_lookup will look up the gateway, etc.
7901 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7902 	 * to the destination, of equal netmask length in the forward table,
7903 	 * will be recursively explored. If no information is available
7904 	 * for the final gateway of that route, we force the returned ire
7905 	 * to be equal to sire using MATCH_IRE_PARENT.
7906 	 * At least, in this case we have a starting point (in the buckets)
7907 	 * to look for other routes to the destination in the forward table.
7908 	 * This is actually used only for multirouting, where a list
7909 	 * of routes has to be processed in sequence.
7910 	 *
7911 	 * In the process of coming up with the most specific information,
7912 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7913 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7914 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7915 	 * Two caveats when handling incomplete ire's in ip_newroute:
7916 	 * - we should be careful when accessing its ire_nce (specifically
7917 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7918 	 * - not all legacy code path callers are prepared to handle
7919 	 *   incomplete ire's, so we should not create/add incomplete
7920 	 *   ire_cache entries here. (See discussion about temporary solution
7921 	 *   further below).
7922 	 *
7923 	 * In order to minimize packet dropping, and to preserve existing
7924 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7925 	 * gateway, and instead use the IF_RESOLVER ire to send out
7926 	 * another request to ARP (this is achieved by passing the
7927 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7928 	 * arp response comes back in ip_wput_nondata, we will create
7929 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7930 	 *
7931 	 * Note that this is a temporary solution; the correct solution is
7932 	 * to create an incomplete  per-dst ire_cache entry, and send the
7933 	 * packet out when the gw's nce is resolved. In order to achieve this,
7934 	 * all packet processing must have been completed prior to calling
7935 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7936 	 * to be modified to accomodate this solution.
7937 	 */
7938 	if (ip_nexthop) {
7939 		/*
7940 		 * The first time we come here, we look for an IRE_INTERFACE
7941 		 * entry for the specified nexthop, set the dst to be the
7942 		 * nexthop address and create an IRE_CACHE entry for the
7943 		 * nexthop. The next time around, we are able to find an
7944 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7945 		 * nexthop address and create an IRE_CACHE entry for the
7946 		 * destination address via the specified nexthop.
7947 		 */
7948 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7949 		    MBLK_GETLABEL(mp), ipst);
7950 		if (ire != NULL) {
7951 			gw = nexthop_addr;
7952 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7953 		} else {
7954 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7955 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7956 			    MBLK_GETLABEL(mp),
7957 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7958 			    ipst);
7959 			if (ire != NULL) {
7960 				dst = nexthop_addr;
7961 			}
7962 		}
7963 	} else if (attach_ill == NULL) {
7964 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7965 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7966 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7967 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7968 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7969 		    ipst);
7970 	} else {
7971 		/*
7972 		 * attach_ill is set only for communicating with
7973 		 * on-link hosts. So, don't look for DEFAULT.
7974 		 */
7975 		ipif_t	*attach_ipif;
7976 
7977 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7978 		if (attach_ipif == NULL) {
7979 			ill_refrele(attach_ill);
7980 			goto icmp_err_ret;
7981 		}
7982 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7983 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7984 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7985 		    MATCH_IRE_SECATTR, ipst);
7986 		ipif_refrele(attach_ipif);
7987 	}
7988 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7989 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7990 
7991 	/*
7992 	 * This loop is run only once in most cases.
7993 	 * We loop to resolve further routes only when the destination
7994 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7995 	 */
7996 	do {
7997 		/* Clear the previous iteration's values */
7998 		if (src_ipif != NULL) {
7999 			ipif_refrele(src_ipif);
8000 			src_ipif = NULL;
8001 		}
8002 		if (dst_ill != NULL) {
8003 			ill_refrele(dst_ill);
8004 			dst_ill = NULL;
8005 		}
8006 
8007 		multirt_resolve_next = B_FALSE;
8008 		/*
8009 		 * We check if packets have to be multirouted.
8010 		 * In this case, given the current <ire, sire> couple,
8011 		 * we look for the next suitable <ire, sire>.
8012 		 * This check is done in ire_multirt_lookup(),
8013 		 * which applies various criteria to find the next route
8014 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
8015 		 * unchanged if it detects it has not been tried yet.
8016 		 */
8017 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8018 			ip3dbg(("ip_newroute: starting next_resolution "
8019 			    "with first_mp %p, tag %d\n",
8020 			    (void *)first_mp,
8021 			    MULTIRT_DEBUG_TAGGED(first_mp)));
8022 
8023 			ASSERT(sire != NULL);
8024 			multirt_is_resolvable =
8025 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
8026 			    MBLK_GETLABEL(mp), ipst);
8027 
8028 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
8029 			    "ire %p, sire %p\n",
8030 			    multirt_is_resolvable,
8031 			    (void *)ire, (void *)sire));
8032 
8033 			if (!multirt_is_resolvable) {
8034 				/*
8035 				 * No more multirt route to resolve; give up
8036 				 * (all routes resolved or no more
8037 				 * resolvable routes).
8038 				 */
8039 				if (ire != NULL) {
8040 					ire_refrele(ire);
8041 					ire = NULL;
8042 				}
8043 			} else {
8044 				ASSERT(sire != NULL);
8045 				ASSERT(ire != NULL);
8046 				/*
8047 				 * We simply use first_sire as a flag that
8048 				 * indicates if a resolvable multirt route
8049 				 * has already been found.
8050 				 * If it is not the case, we may have to send
8051 				 * an ICMP error to report that the
8052 				 * destination is unreachable.
8053 				 * We do not IRE_REFHOLD first_sire.
8054 				 */
8055 				if (first_sire == NULL) {
8056 					first_sire = sire;
8057 				}
8058 			}
8059 		}
8060 		if (ire == NULL) {
8061 			if (ip_debug > 3) {
8062 				/* ip2dbg */
8063 				pr_addr_dbg("ip_newroute: "
8064 				    "can't resolve %s\n", AF_INET, &dst);
8065 			}
8066 			ip3dbg(("ip_newroute: "
8067 			    "ire %p, sire %p, first_sire %p\n",
8068 			    (void *)ire, (void *)sire, (void *)first_sire));
8069 
8070 			if (sire != NULL) {
8071 				ire_refrele(sire);
8072 				sire = NULL;
8073 			}
8074 
8075 			if (first_sire != NULL) {
8076 				/*
8077 				 * At least one multirt route has been found
8078 				 * in the same call to ip_newroute();
8079 				 * there is no need to report an ICMP error.
8080 				 * first_sire was not IRE_REFHOLDed.
8081 				 */
8082 				MULTIRT_DEBUG_UNTAG(first_mp);
8083 				freemsg(first_mp);
8084 				return;
8085 			}
8086 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8087 			    RTA_DST, ipst);
8088 			if (attach_ill != NULL)
8089 				ill_refrele(attach_ill);
8090 			goto icmp_err_ret;
8091 		}
8092 
8093 		/*
8094 		 * Verify that the returned IRE does not have either
8095 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8096 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8097 		 */
8098 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8099 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8100 			if (attach_ill != NULL)
8101 				ill_refrele(attach_ill);
8102 			goto icmp_err_ret;
8103 		}
8104 		/*
8105 		 * Increment the ire_ob_pkt_count field for ire if it is an
8106 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8107 		 * increment the same for the parent IRE, sire, if it is some
8108 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8109 		 */
8110 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8111 			UPDATE_OB_PKT_COUNT(ire);
8112 			ire->ire_last_used_time = lbolt;
8113 		}
8114 
8115 		if (sire != NULL) {
8116 			gw = sire->ire_gateway_addr;
8117 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8118 			    IRE_INTERFACE)) == 0);
8119 			UPDATE_OB_PKT_COUNT(sire);
8120 			sire->ire_last_used_time = lbolt;
8121 		}
8122 		/*
8123 		 * We have a route to reach the destination.
8124 		 *
8125 		 * 1) If the interface is part of ill group, try to get a new
8126 		 *    ill taking load spreading into account.
8127 		 *
8128 		 * 2) After selecting the ill, get a source address that
8129 		 *    might create good inbound load spreading.
8130 		 *    ipif_select_source does this for us.
8131 		 *
8132 		 * If the application specified the ill (ifindex), we still
8133 		 * load spread. Only if the packets needs to go out
8134 		 * specifically on a given ill e.g. binding to
8135 		 * IPIF_NOFAILOVER address, then we don't try to use a
8136 		 * different ill for load spreading.
8137 		 */
8138 		if (attach_ill == NULL) {
8139 			/*
8140 			 * Don't perform outbound load spreading in the
8141 			 * case of an RTF_MULTIRT route, as we actually
8142 			 * typically want to replicate outgoing packets
8143 			 * through particular interfaces.
8144 			 */
8145 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8146 				dst_ill = ire->ire_ipif->ipif_ill;
8147 				/* for uniformity */
8148 				ill_refhold(dst_ill);
8149 			} else {
8150 				/*
8151 				 * If we are here trying to create an IRE_CACHE
8152 				 * for an offlink destination and have the
8153 				 * IRE_CACHE for the next hop and the latter is
8154 				 * using virtual IP source address selection i.e
8155 				 * it's ire->ire_ipif is pointing to a virtual
8156 				 * network interface (vni) then
8157 				 * ip_newroute_get_dst_ll() will return the vni
8158 				 * interface as the dst_ill. Since the vni is
8159 				 * virtual i.e not associated with any physical
8160 				 * interface, it cannot be the dst_ill, hence
8161 				 * in such a case call ip_newroute_get_dst_ll()
8162 				 * with the stq_ill instead of the ire_ipif ILL.
8163 				 * The function returns a refheld ill.
8164 				 */
8165 				if ((ire->ire_type == IRE_CACHE) &&
8166 				    IS_VNI(ire->ire_ipif->ipif_ill))
8167 					dst_ill = ip_newroute_get_dst_ill(
8168 					    ire->ire_stq->q_ptr);
8169 				else
8170 					dst_ill = ip_newroute_get_dst_ill(
8171 					    ire->ire_ipif->ipif_ill);
8172 			}
8173 			if (dst_ill == NULL) {
8174 				if (ip_debug > 2) {
8175 					pr_addr_dbg("ip_newroute: "
8176 					    "no dst ill for dst"
8177 					    " %s\n", AF_INET, &dst);
8178 				}
8179 				goto icmp_err_ret;
8180 			}
8181 		} else {
8182 			dst_ill = ire->ire_ipif->ipif_ill;
8183 			/* for uniformity */
8184 			ill_refhold(dst_ill);
8185 			/*
8186 			 * We should have found a route matching ill as we
8187 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8188 			 * Rather than asserting, when there is a mismatch,
8189 			 * we just drop the packet.
8190 			 */
8191 			if (dst_ill != attach_ill) {
8192 				ip0dbg(("ip_newroute: Packet dropped as "
8193 				    "IPIF_NOFAILOVER ill is %s, "
8194 				    "ire->ire_ipif->ipif_ill is %s\n",
8195 				    attach_ill->ill_name,
8196 				    dst_ill->ill_name));
8197 				ill_refrele(attach_ill);
8198 				goto icmp_err_ret;
8199 			}
8200 		}
8201 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8202 		if (attach_ill != NULL) {
8203 			ill_refrele(attach_ill);
8204 			attach_ill = NULL;
8205 			do_attach_ill = B_TRUE;
8206 		}
8207 		ASSERT(dst_ill != NULL);
8208 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8209 
8210 		/*
8211 		 * Pick the best source address from dst_ill.
8212 		 *
8213 		 * 1) If it is part of a multipathing group, we would
8214 		 *    like to spread the inbound packets across different
8215 		 *    interfaces. ipif_select_source picks a random source
8216 		 *    across the different ills in the group.
8217 		 *
8218 		 * 2) If it is not part of a multipathing group, we try
8219 		 *    to pick the source address from the destination
8220 		 *    route. Clustering assumes that when we have multiple
8221 		 *    prefixes hosted on an interface, the prefix of the
8222 		 *    source address matches the prefix of the destination
8223 		 *    route. We do this only if the address is not
8224 		 *    DEPRECATED.
8225 		 *
8226 		 * 3) If the conn is in a different zone than the ire, we
8227 		 *    need to pick a source address from the right zone.
8228 		 *
8229 		 * NOTE : If we hit case (1) above, the prefix of the source
8230 		 *	  address picked may not match the prefix of the
8231 		 *	  destination routes prefix as ipif_select_source
8232 		 *	  does not look at "dst" while picking a source
8233 		 *	  address.
8234 		 *	  If we want the same behavior as (2), we will need
8235 		 *	  to change the behavior of ipif_select_source.
8236 		 */
8237 		ASSERT(src_ipif == NULL);
8238 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8239 			/*
8240 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8241 			 * Check that the ipif matching the requested source
8242 			 * address still exists.
8243 			 */
8244 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8245 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8246 		}
8247 
8248 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8249 
8250 		if (src_ipif == NULL &&
8251 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8252 			ire_marks |= IRE_MARK_USESRC_CHECK;
8253 			if ((dst_ill->ill_group != NULL) ||
8254 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8255 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8256 			    ire->ire_zoneid != ALL_ZONES) ||
8257 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8258 				/*
8259 				 * If the destination is reachable via a
8260 				 * given gateway, the selected source address
8261 				 * should be in the same subnet as the gateway.
8262 				 * Otherwise, the destination is not reachable.
8263 				 *
8264 				 * If there are no interfaces on the same subnet
8265 				 * as the destination, ipif_select_source gives
8266 				 * first non-deprecated interface which might be
8267 				 * on a different subnet than the gateway.
8268 				 * This is not desirable. Hence pass the dst_ire
8269 				 * source address to ipif_select_source.
8270 				 * It is sure that the destination is reachable
8271 				 * with the dst_ire source address subnet.
8272 				 * So passing dst_ire source address to
8273 				 * ipif_select_source will make sure that the
8274 				 * selected source will be on the same subnet
8275 				 * as dst_ire source address.
8276 				 */
8277 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8278 				src_ipif = ipif_select_source(dst_ill, saddr,
8279 				    zoneid);
8280 				if (src_ipif == NULL) {
8281 					if (ip_debug > 2) {
8282 						pr_addr_dbg("ip_newroute: "
8283 						    "no src for dst %s ",
8284 						    AF_INET, &dst);
8285 						printf("through interface %s\n",
8286 						    dst_ill->ill_name);
8287 					}
8288 					goto icmp_err_ret;
8289 				}
8290 			} else {
8291 				src_ipif = ire->ire_ipif;
8292 				ASSERT(src_ipif != NULL);
8293 				/* hold src_ipif for uniformity */
8294 				ipif_refhold(src_ipif);
8295 			}
8296 		}
8297 
8298 		/*
8299 		 * Assign a source address while we have the conn.
8300 		 * We can't have ip_wput_ire pick a source address when the
8301 		 * packet returns from arp since we need to look at
8302 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8303 		 * going through arp.
8304 		 *
8305 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8306 		 *	  it uses ip6i to store this information.
8307 		 */
8308 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8309 			ipha->ipha_src = src_ipif->ipif_src_addr;
8310 
8311 		if (ip_debug > 3) {
8312 			/* ip2dbg */
8313 			pr_addr_dbg("ip_newroute: first hop %s\n",
8314 			    AF_INET, &gw);
8315 		}
8316 		ip2dbg(("\tire type %s (%d)\n",
8317 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8318 
8319 		/*
8320 		 * The TTL of multirouted packets is bounded by the
8321 		 * ip_multirt_ttl ndd variable.
8322 		 */
8323 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8324 			/* Force TTL of multirouted packets */
8325 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8326 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8327 				ip2dbg(("ip_newroute: forcing multirt TTL "
8328 				    "to %d (was %d), dst 0x%08x\n",
8329 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8330 				    ntohl(sire->ire_addr)));
8331 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8332 			}
8333 		}
8334 		/*
8335 		 * At this point in ip_newroute(), ire is either the
8336 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8337 		 * destination or an IRE_INTERFACE type that should be used
8338 		 * to resolve an on-subnet destination or an on-subnet
8339 		 * next-hop gateway.
8340 		 *
8341 		 * In the IRE_CACHE case, we have the following :
8342 		 *
8343 		 * 1) src_ipif - used for getting a source address.
8344 		 *
8345 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8346 		 *    means packets using this IRE_CACHE will go out on
8347 		 *    dst_ill.
8348 		 *
8349 		 * 3) The IRE sire will point to the prefix that is the
8350 		 *    longest  matching route for the destination. These
8351 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8352 		 *
8353 		 *    The newly created IRE_CACHE entry for the off-subnet
8354 		 *    destination is tied to both the prefix route and the
8355 		 *    interface route used to resolve the next-hop gateway
8356 		 *    via the ire_phandle and ire_ihandle fields,
8357 		 *    respectively.
8358 		 *
8359 		 * In the IRE_INTERFACE case, we have the following :
8360 		 *
8361 		 * 1) src_ipif - used for getting a source address.
8362 		 *
8363 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8364 		 *    means packets using the IRE_CACHE that we will build
8365 		 *    here will go out on dst_ill.
8366 		 *
8367 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8368 		 *    to be created will only be tied to the IRE_INTERFACE
8369 		 *    that was derived from the ire_ihandle field.
8370 		 *
8371 		 *    If sire is non-NULL, it means the destination is
8372 		 *    off-link and we will first create the IRE_CACHE for the
8373 		 *    gateway. Next time through ip_newroute, we will create
8374 		 *    the IRE_CACHE for the final destination as described
8375 		 *    above.
8376 		 *
8377 		 * In both cases, after the current resolution has been
8378 		 * completed (or possibly initialised, in the IRE_INTERFACE
8379 		 * case), the loop may be re-entered to attempt the resolution
8380 		 * of another RTF_MULTIRT route.
8381 		 *
8382 		 * When an IRE_CACHE entry for the off-subnet destination is
8383 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8384 		 * for further processing in emission loops.
8385 		 */
8386 		save_ire = ire;
8387 		switch (ire->ire_type) {
8388 		case IRE_CACHE: {
8389 			ire_t	*ipif_ire;
8390 
8391 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8392 			if (gw == 0)
8393 				gw = ire->ire_gateway_addr;
8394 			/*
8395 			 * We need 3 ire's to create a new cache ire for an
8396 			 * off-link destination from the cache ire of the
8397 			 * gateway.
8398 			 *
8399 			 *	1. The prefix ire 'sire' (Note that this does
8400 			 *	   not apply to the conn_nexthop_set case)
8401 			 *	2. The cache ire of the gateway 'ire'
8402 			 *	3. The interface ire 'ipif_ire'
8403 			 *
8404 			 * We have (1) and (2). We lookup (3) below.
8405 			 *
8406 			 * If there is no interface route to the gateway,
8407 			 * it is a race condition, where we found the cache
8408 			 * but the interface route has been deleted.
8409 			 */
8410 			if (ip_nexthop) {
8411 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8412 			} else {
8413 				ipif_ire =
8414 				    ire_ihandle_lookup_offlink(ire, sire);
8415 			}
8416 			if (ipif_ire == NULL) {
8417 				ip1dbg(("ip_newroute: "
8418 				    "ire_ihandle_lookup_offlink failed\n"));
8419 				goto icmp_err_ret;
8420 			}
8421 
8422 			/*
8423 			 * Check cached gateway IRE for any security
8424 			 * attributes; if found, associate the gateway
8425 			 * credentials group to the destination IRE.
8426 			 */
8427 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8428 				mutex_enter(&attrp->igsa_lock);
8429 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8430 					GCGRP_REFHOLD(gcgrp);
8431 				mutex_exit(&attrp->igsa_lock);
8432 			}
8433 
8434 			/*
8435 			 * XXX For the source of the resolver mp,
8436 			 * we are using the same DL_UNITDATA_REQ
8437 			 * (from save_ire->ire_nce->nce_res_mp)
8438 			 * though the save_ire is not pointing at the same ill.
8439 			 * This is incorrect. We need to send it up to the
8440 			 * resolver to get the right res_mp. For ethernets
8441 			 * this may be okay (ill_type == DL_ETHER).
8442 			 */
8443 
8444 			ire = ire_create(
8445 			    (uchar_t *)&dst,		/* dest address */
8446 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8447 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8448 			    (uchar_t *)&gw,		/* gateway address */
8449 			    &save_ire->ire_max_frag,
8450 			    save_ire->ire_nce,		/* src nce */
8451 			    dst_ill->ill_rq,		/* recv-from queue */
8452 			    dst_ill->ill_wq,		/* send-to queue */
8453 			    IRE_CACHE,			/* IRE type */
8454 			    src_ipif,
8455 			    (sire != NULL) ?
8456 			    sire->ire_mask : 0, 	/* Parent mask */
8457 			    (sire != NULL) ?
8458 			    sire->ire_phandle : 0,	/* Parent handle */
8459 			    ipif_ire->ire_ihandle,	/* Interface handle */
8460 			    (sire != NULL) ? (sire->ire_flags &
8461 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8462 			    (sire != NULL) ?
8463 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8464 			    NULL,
8465 			    gcgrp,
8466 			    ipst);
8467 
8468 			if (ire == NULL) {
8469 				if (gcgrp != NULL) {
8470 					GCGRP_REFRELE(gcgrp);
8471 					gcgrp = NULL;
8472 				}
8473 				ire_refrele(ipif_ire);
8474 				ire_refrele(save_ire);
8475 				break;
8476 			}
8477 
8478 			/* reference now held by IRE */
8479 			gcgrp = NULL;
8480 
8481 			ire->ire_marks |= ire_marks;
8482 
8483 			/*
8484 			 * Prevent sire and ipif_ire from getting deleted.
8485 			 * The newly created ire is tied to both of them via
8486 			 * the phandle and ihandle respectively.
8487 			 */
8488 			if (sire != NULL) {
8489 				IRB_REFHOLD(sire->ire_bucket);
8490 				/* Has it been removed already ? */
8491 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8492 					IRB_REFRELE(sire->ire_bucket);
8493 					ire_refrele(ipif_ire);
8494 					ire_refrele(save_ire);
8495 					break;
8496 				}
8497 			}
8498 
8499 			IRB_REFHOLD(ipif_ire->ire_bucket);
8500 			/* Has it been removed already ? */
8501 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8502 				IRB_REFRELE(ipif_ire->ire_bucket);
8503 				if (sire != NULL)
8504 					IRB_REFRELE(sire->ire_bucket);
8505 				ire_refrele(ipif_ire);
8506 				ire_refrele(save_ire);
8507 				break;
8508 			}
8509 
8510 			xmit_mp = first_mp;
8511 			/*
8512 			 * In the case of multirouting, a copy
8513 			 * of the packet is done before its sending.
8514 			 * The copy is used to attempt another
8515 			 * route resolution, in a next loop.
8516 			 */
8517 			if (ire->ire_flags & RTF_MULTIRT) {
8518 				copy_mp = copymsg(first_mp);
8519 				if (copy_mp != NULL) {
8520 					xmit_mp = copy_mp;
8521 					MULTIRT_DEBUG_TAG(first_mp);
8522 				}
8523 			}
8524 			ire_add_then_send(q, ire, xmit_mp);
8525 			ire_refrele(save_ire);
8526 
8527 			/* Assert that sire is not deleted yet. */
8528 			if (sire != NULL) {
8529 				ASSERT(sire->ire_ptpn != NULL);
8530 				IRB_REFRELE(sire->ire_bucket);
8531 			}
8532 
8533 			/* Assert that ipif_ire is not deleted yet. */
8534 			ASSERT(ipif_ire->ire_ptpn != NULL);
8535 			IRB_REFRELE(ipif_ire->ire_bucket);
8536 			ire_refrele(ipif_ire);
8537 
8538 			/*
8539 			 * If copy_mp is not NULL, multirouting was
8540 			 * requested. We loop to initiate a next
8541 			 * route resolution attempt, starting from sire.
8542 			 */
8543 			if (copy_mp != NULL) {
8544 				/*
8545 				 * Search for the next unresolved
8546 				 * multirt route.
8547 				 */
8548 				copy_mp = NULL;
8549 				ipif_ire = NULL;
8550 				ire = NULL;
8551 				multirt_resolve_next = B_TRUE;
8552 				continue;
8553 			}
8554 			if (sire != NULL)
8555 				ire_refrele(sire);
8556 			ipif_refrele(src_ipif);
8557 			ill_refrele(dst_ill);
8558 			return;
8559 		}
8560 		case IRE_IF_NORESOLVER: {
8561 
8562 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8563 			    dst_ill->ill_resolver_mp == NULL) {
8564 				ip1dbg(("ip_newroute: dst_ill %p "
8565 				    "for IRE_IF_NORESOLVER ire %p has "
8566 				    "no ill_resolver_mp\n",
8567 				    (void *)dst_ill, (void *)ire));
8568 				break;
8569 			}
8570 
8571 			/*
8572 			 * TSol note: We are creating the ire cache for the
8573 			 * destination 'dst'. If 'dst' is offlink, going
8574 			 * through the first hop 'gw', the security attributes
8575 			 * of 'dst' must be set to point to the gateway
8576 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8577 			 * is possible that 'dst' is a potential gateway that is
8578 			 * referenced by some route that has some security
8579 			 * attributes. Thus in the former case, we need to do a
8580 			 * gcgrp_lookup of 'gw' while in the latter case we
8581 			 * need to do gcgrp_lookup of 'dst' itself.
8582 			 */
8583 			ga.ga_af = AF_INET;
8584 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8585 			    &ga.ga_addr);
8586 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8587 
8588 			ire = ire_create(
8589 			    (uchar_t *)&dst,		/* dest address */
8590 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8591 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8592 			    (uchar_t *)&gw,		/* gateway address */
8593 			    &save_ire->ire_max_frag,
8594 			    NULL,			/* no src nce */
8595 			    dst_ill->ill_rq,		/* recv-from queue */
8596 			    dst_ill->ill_wq,		/* send-to queue */
8597 			    IRE_CACHE,
8598 			    src_ipif,
8599 			    save_ire->ire_mask,		/* Parent mask */
8600 			    (sire != NULL) ?		/* Parent handle */
8601 			    sire->ire_phandle : 0,
8602 			    save_ire->ire_ihandle,	/* Interface handle */
8603 			    (sire != NULL) ? sire->ire_flags &
8604 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8605 			    &(save_ire->ire_uinfo),
8606 			    NULL,
8607 			    gcgrp,
8608 			    ipst);
8609 
8610 			if (ire == NULL) {
8611 				if (gcgrp != NULL) {
8612 					GCGRP_REFRELE(gcgrp);
8613 					gcgrp = NULL;
8614 				}
8615 				ire_refrele(save_ire);
8616 				break;
8617 			}
8618 
8619 			/* reference now held by IRE */
8620 			gcgrp = NULL;
8621 
8622 			ire->ire_marks |= ire_marks;
8623 
8624 			/* Prevent save_ire from getting deleted */
8625 			IRB_REFHOLD(save_ire->ire_bucket);
8626 			/* Has it been removed already ? */
8627 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8628 				IRB_REFRELE(save_ire->ire_bucket);
8629 				ire_refrele(save_ire);
8630 				break;
8631 			}
8632 
8633 			/*
8634 			 * In the case of multirouting, a copy
8635 			 * of the packet is made before it is sent.
8636 			 * The copy is used in the next
8637 			 * loop to attempt another resolution.
8638 			 */
8639 			xmit_mp = first_mp;
8640 			if ((sire != NULL) &&
8641 			    (sire->ire_flags & RTF_MULTIRT)) {
8642 				copy_mp = copymsg(first_mp);
8643 				if (copy_mp != NULL) {
8644 					xmit_mp = copy_mp;
8645 					MULTIRT_DEBUG_TAG(first_mp);
8646 				}
8647 			}
8648 			ire_add_then_send(q, ire, xmit_mp);
8649 
8650 			/* Assert that it is not deleted yet. */
8651 			ASSERT(save_ire->ire_ptpn != NULL);
8652 			IRB_REFRELE(save_ire->ire_bucket);
8653 			ire_refrele(save_ire);
8654 
8655 			if (copy_mp != NULL) {
8656 				/*
8657 				 * If we found a (no)resolver, we ignore any
8658 				 * trailing top priority IRE_CACHE in further
8659 				 * loops. This ensures that we do not omit any
8660 				 * (no)resolver.
8661 				 * This IRE_CACHE, if any, will be processed
8662 				 * by another thread entering ip_newroute().
8663 				 * IRE_CACHE entries, if any, will be processed
8664 				 * by another thread entering ip_newroute(),
8665 				 * (upon resolver response, for instance).
8666 				 * This aims to force parallel multirt
8667 				 * resolutions as soon as a packet must be sent.
8668 				 * In the best case, after the tx of only one
8669 				 * packet, all reachable routes are resolved.
8670 				 * Otherwise, the resolution of all RTF_MULTIRT
8671 				 * routes would require several emissions.
8672 				 */
8673 				multirt_flags &= ~MULTIRT_CACHEGW;
8674 
8675 				/*
8676 				 * Search for the next unresolved multirt
8677 				 * route.
8678 				 */
8679 				copy_mp = NULL;
8680 				save_ire = NULL;
8681 				ire = NULL;
8682 				multirt_resolve_next = B_TRUE;
8683 				continue;
8684 			}
8685 
8686 			/*
8687 			 * Don't need sire anymore
8688 			 */
8689 			if (sire != NULL)
8690 				ire_refrele(sire);
8691 
8692 			ipif_refrele(src_ipif);
8693 			ill_refrele(dst_ill);
8694 			return;
8695 		}
8696 		case IRE_IF_RESOLVER:
8697 			/*
8698 			 * We can't build an IRE_CACHE yet, but at least we
8699 			 * found a resolver that can help.
8700 			 */
8701 			res_mp = dst_ill->ill_resolver_mp;
8702 			if (!OK_RESOLVER_MP(res_mp))
8703 				break;
8704 
8705 			/*
8706 			 * To be at this point in the code with a non-zero gw
8707 			 * means that dst is reachable through a gateway that
8708 			 * we have never resolved.  By changing dst to the gw
8709 			 * addr we resolve the gateway first.
8710 			 * When ire_add_then_send() tries to put the IP dg
8711 			 * to dst, it will reenter ip_newroute() at which
8712 			 * time we will find the IRE_CACHE for the gw and
8713 			 * create another IRE_CACHE in case IRE_CACHE above.
8714 			 */
8715 			if (gw != INADDR_ANY) {
8716 				/*
8717 				 * The source ipif that was determined above was
8718 				 * relative to the destination address, not the
8719 				 * gateway's. If src_ipif was not taken out of
8720 				 * the IRE_IF_RESOLVER entry, we'll need to call
8721 				 * ipif_select_source() again.
8722 				 */
8723 				if (src_ipif != ire->ire_ipif) {
8724 					ipif_refrele(src_ipif);
8725 					src_ipif = ipif_select_source(dst_ill,
8726 					    gw, zoneid);
8727 					if (src_ipif == NULL) {
8728 						if (ip_debug > 2) {
8729 							pr_addr_dbg(
8730 							    "ip_newroute: no "
8731 							    "src for gw %s ",
8732 							    AF_INET, &gw);
8733 							printf("through "
8734 							    "interface %s\n",
8735 							    dst_ill->ill_name);
8736 						}
8737 						goto icmp_err_ret;
8738 					}
8739 				}
8740 				save_dst = dst;
8741 				dst = gw;
8742 				gw = INADDR_ANY;
8743 			}
8744 
8745 			/*
8746 			 * We obtain a partial IRE_CACHE which we will pass
8747 			 * along with the resolver query.  When the response
8748 			 * comes back it will be there ready for us to add.
8749 			 * The ire_max_frag is atomically set under the
8750 			 * irebucket lock in ire_add_v[46].
8751 			 */
8752 
8753 			ire = ire_create_mp(
8754 			    (uchar_t *)&dst,		/* dest address */
8755 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8756 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8757 			    (uchar_t *)&gw,		/* gateway address */
8758 			    NULL,			/* ire_max_frag */
8759 			    NULL,			/* no src nce */
8760 			    dst_ill->ill_rq,		/* recv-from queue */
8761 			    dst_ill->ill_wq,		/* send-to queue */
8762 			    IRE_CACHE,
8763 			    src_ipif,			/* Interface ipif */
8764 			    save_ire->ire_mask,		/* Parent mask */
8765 			    0,
8766 			    save_ire->ire_ihandle,	/* Interface handle */
8767 			    0,				/* flags if any */
8768 			    &(save_ire->ire_uinfo),
8769 			    NULL,
8770 			    NULL,
8771 			    ipst);
8772 
8773 			if (ire == NULL) {
8774 				ire_refrele(save_ire);
8775 				break;
8776 			}
8777 
8778 			if ((sire != NULL) &&
8779 			    (sire->ire_flags & RTF_MULTIRT)) {
8780 				copy_mp = copymsg(first_mp);
8781 				if (copy_mp != NULL)
8782 					MULTIRT_DEBUG_TAG(copy_mp);
8783 			}
8784 
8785 			ire->ire_marks |= ire_marks;
8786 
8787 			/*
8788 			 * Construct message chain for the resolver
8789 			 * of the form:
8790 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8791 			 * Packet could contain a IPSEC_OUT mp.
8792 			 *
8793 			 * NOTE : ire will be added later when the response
8794 			 * comes back from ARP. If the response does not
8795 			 * come back, ARP frees the packet. For this reason,
8796 			 * we can't REFHOLD the bucket of save_ire to prevent
8797 			 * deletions. We may not be able to REFRELE the bucket
8798 			 * if the response never comes back. Thus, before
8799 			 * adding the ire, ire_add_v4 will make sure that the
8800 			 * interface route does not get deleted. This is the
8801 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8802 			 * where we can always prevent deletions because of
8803 			 * the synchronous nature of adding IRES i.e
8804 			 * ire_add_then_send is called after creating the IRE.
8805 			 */
8806 			ASSERT(ire->ire_mp != NULL);
8807 			ire->ire_mp->b_cont = first_mp;
8808 			/* Have saved_mp handy, for cleanup if canput fails */
8809 			saved_mp = mp;
8810 			mp = copyb(res_mp);
8811 			if (mp == NULL) {
8812 				/* Prepare for cleanup */
8813 				mp = saved_mp; /* pkt */
8814 				ire_delete(ire); /* ire_mp */
8815 				ire = NULL;
8816 				ire_refrele(save_ire);
8817 				if (copy_mp != NULL) {
8818 					MULTIRT_DEBUG_UNTAG(copy_mp);
8819 					freemsg(copy_mp);
8820 					copy_mp = NULL;
8821 				}
8822 				break;
8823 			}
8824 			linkb(mp, ire->ire_mp);
8825 
8826 			/*
8827 			 * Fill in the source and dest addrs for the resolver.
8828 			 * NOTE: this depends on memory layouts imposed by
8829 			 * ill_init().
8830 			 */
8831 			areq = (areq_t *)mp->b_rptr;
8832 			addrp = (ipaddr_t *)((char *)areq +
8833 			    areq->areq_sender_addr_offset);
8834 			if (do_attach_ill) {
8835 				/*
8836 				 * This is bind to no failover case.
8837 				 * arp packet also must go out on attach_ill.
8838 				 */
8839 				ASSERT(ipha->ipha_src != NULL);
8840 				*addrp = ipha->ipha_src;
8841 			} else {
8842 				*addrp = save_ire->ire_src_addr;
8843 			}
8844 
8845 			ire_refrele(save_ire);
8846 			addrp = (ipaddr_t *)((char *)areq +
8847 			    areq->areq_target_addr_offset);
8848 			*addrp = dst;
8849 			/* Up to the resolver. */
8850 			if (canputnext(dst_ill->ill_rq) &&
8851 			    !(dst_ill->ill_arp_closing)) {
8852 				putnext(dst_ill->ill_rq, mp);
8853 				ire = NULL;
8854 				if (copy_mp != NULL) {
8855 					/*
8856 					 * If we found a resolver, we ignore
8857 					 * any trailing top priority IRE_CACHE
8858 					 * in the further loops. This ensures
8859 					 * that we do not omit any resolver.
8860 					 * IRE_CACHE entries, if any, will be
8861 					 * processed next time we enter
8862 					 * ip_newroute().
8863 					 */
8864 					multirt_flags &= ~MULTIRT_CACHEGW;
8865 					/*
8866 					 * Search for the next unresolved
8867 					 * multirt route.
8868 					 */
8869 					first_mp = copy_mp;
8870 					copy_mp = NULL;
8871 					/* Prepare the next resolution loop. */
8872 					mp = first_mp;
8873 					EXTRACT_PKT_MP(mp, first_mp,
8874 					    mctl_present);
8875 					if (mctl_present)
8876 						io = (ipsec_out_t *)
8877 						    first_mp->b_rptr;
8878 					ipha = (ipha_t *)mp->b_rptr;
8879 
8880 					ASSERT(sire != NULL);
8881 
8882 					dst = save_dst;
8883 					multirt_resolve_next = B_TRUE;
8884 					continue;
8885 				}
8886 
8887 				if (sire != NULL)
8888 					ire_refrele(sire);
8889 
8890 				/*
8891 				 * The response will come back in ip_wput
8892 				 * with db_type IRE_DB_TYPE.
8893 				 */
8894 				ipif_refrele(src_ipif);
8895 				ill_refrele(dst_ill);
8896 				return;
8897 			} else {
8898 				/* Prepare for cleanup */
8899 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8900 				    mp);
8901 				mp->b_cont = NULL;
8902 				freeb(mp); /* areq */
8903 				/*
8904 				 * this is an ire that is not added to the
8905 				 * cache. ire_freemblk will handle the release
8906 				 * of any resources associated with the ire.
8907 				 */
8908 				ire_delete(ire); /* ire_mp */
8909 				mp = saved_mp; /* pkt */
8910 				ire = NULL;
8911 				if (copy_mp != NULL) {
8912 					MULTIRT_DEBUG_UNTAG(copy_mp);
8913 					freemsg(copy_mp);
8914 					copy_mp = NULL;
8915 				}
8916 				break;
8917 			}
8918 		default:
8919 			break;
8920 		}
8921 	} while (multirt_resolve_next);
8922 
8923 	ip1dbg(("ip_newroute: dropped\n"));
8924 	/* Did this packet originate externally? */
8925 	if (mp->b_prev) {
8926 		mp->b_next = NULL;
8927 		mp->b_prev = NULL;
8928 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8929 	} else {
8930 		if (dst_ill != NULL) {
8931 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8932 		} else {
8933 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8934 		}
8935 	}
8936 	ASSERT(copy_mp == NULL);
8937 	MULTIRT_DEBUG_UNTAG(first_mp);
8938 	freemsg(first_mp);
8939 	if (ire != NULL)
8940 		ire_refrele(ire);
8941 	if (sire != NULL)
8942 		ire_refrele(sire);
8943 	if (src_ipif != NULL)
8944 		ipif_refrele(src_ipif);
8945 	if (dst_ill != NULL)
8946 		ill_refrele(dst_ill);
8947 	return;
8948 
8949 icmp_err_ret:
8950 	ip1dbg(("ip_newroute: no route\n"));
8951 	if (src_ipif != NULL)
8952 		ipif_refrele(src_ipif);
8953 	if (dst_ill != NULL)
8954 		ill_refrele(dst_ill);
8955 	if (sire != NULL)
8956 		ire_refrele(sire);
8957 	/* Did this packet originate externally? */
8958 	if (mp->b_prev) {
8959 		mp->b_next = NULL;
8960 		mp->b_prev = NULL;
8961 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8962 		q = WR(q);
8963 	} else {
8964 		/*
8965 		 * There is no outgoing ill, so just increment the
8966 		 * system MIB.
8967 		 */
8968 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8969 		/*
8970 		 * Since ip_wput() isn't close to finished, we fill
8971 		 * in enough of the header for credible error reporting.
8972 		 */
8973 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8974 			/* Failed */
8975 			MULTIRT_DEBUG_UNTAG(first_mp);
8976 			freemsg(first_mp);
8977 			if (ire != NULL)
8978 				ire_refrele(ire);
8979 			return;
8980 		}
8981 	}
8982 
8983 	/*
8984 	 * At this point we will have ire only if RTF_BLACKHOLE
8985 	 * or RTF_REJECT flags are set on the IRE. It will not
8986 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8987 	 */
8988 	if (ire != NULL) {
8989 		if (ire->ire_flags & RTF_BLACKHOLE) {
8990 			ire_refrele(ire);
8991 			MULTIRT_DEBUG_UNTAG(first_mp);
8992 			freemsg(first_mp);
8993 			return;
8994 		}
8995 		ire_refrele(ire);
8996 	}
8997 	if (ip_source_routed(ipha, ipst)) {
8998 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8999 		    zoneid, ipst);
9000 		return;
9001 	}
9002 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9003 }
9004 
9005 ip_opt_info_t zero_info;
9006 
9007 /*
9008  * IPv4 -
9009  * ip_newroute_ipif is called by ip_wput_multicast and
9010  * ip_rput_forward_multicast whenever we need to send
9011  * out a packet to a destination address for which we do not have specific
9012  * routing information. It is used when the packet will be sent out
9013  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
9014  * socket option is set or icmp error message wants to go out on a particular
9015  * interface for a unicast packet.
9016  *
9017  * In most cases, the destination address is resolved thanks to the ipif
9018  * intrinsic resolver. However, there are some cases where the call to
9019  * ip_newroute_ipif must take into account the potential presence of
9020  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
9021  * that uses the interface. This is specified through flags,
9022  * which can be a combination of:
9023  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
9024  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
9025  *   and flags. Additionally, the packet source address has to be set to
9026  *   the specified address. The caller is thus expected to set this flag
9027  *   if the packet has no specific source address yet.
9028  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
9029  *   flag, the resulting ire will inherit the flag. All unresolved routes
9030  *   to the destination must be explored in the same call to
9031  *   ip_newroute_ipif().
9032  */
9033 static void
9034 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
9035     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
9036 {
9037 	areq_t	*areq;
9038 	ire_t	*ire = NULL;
9039 	mblk_t	*res_mp;
9040 	ipaddr_t *addrp;
9041 	mblk_t *first_mp;
9042 	ire_t	*save_ire = NULL;
9043 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
9044 	ipif_t	*src_ipif = NULL;
9045 	ushort_t ire_marks = 0;
9046 	ill_t	*dst_ill = NULL;
9047 	boolean_t mctl_present;
9048 	ipsec_out_t *io;
9049 	ipha_t *ipha;
9050 	int	ihandle = 0;
9051 	mblk_t	*saved_mp;
9052 	ire_t   *fire = NULL;
9053 	mblk_t  *copy_mp = NULL;
9054 	boolean_t multirt_resolve_next;
9055 	boolean_t unspec_src;
9056 	ipaddr_t ipha_dst;
9057 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
9058 
9059 	/*
9060 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
9061 	 * here for uniformity
9062 	 */
9063 	ipif_refhold(ipif);
9064 
9065 	/*
9066 	 * This loop is run only once in most cases.
9067 	 * We loop to resolve further routes only when the destination
9068 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
9069 	 */
9070 	do {
9071 		if (dst_ill != NULL) {
9072 			ill_refrele(dst_ill);
9073 			dst_ill = NULL;
9074 		}
9075 		if (src_ipif != NULL) {
9076 			ipif_refrele(src_ipif);
9077 			src_ipif = NULL;
9078 		}
9079 		multirt_resolve_next = B_FALSE;
9080 
9081 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9082 		    ipif->ipif_ill->ill_name));
9083 
9084 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9085 		if (mctl_present)
9086 			io = (ipsec_out_t *)first_mp->b_rptr;
9087 
9088 		ipha = (ipha_t *)mp->b_rptr;
9089 
9090 		/*
9091 		 * Save the packet destination address, we may need it after
9092 		 * the packet has been consumed.
9093 		 */
9094 		ipha_dst = ipha->ipha_dst;
9095 
9096 		/*
9097 		 * If the interface is a pt-pt interface we look for an
9098 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9099 		 * local_address and the pt-pt destination address. Otherwise
9100 		 * we just match the local address.
9101 		 * NOTE: dst could be different than ipha->ipha_dst in case
9102 		 * of sending igmp multicast packets over a point-to-point
9103 		 * connection.
9104 		 * Thus we must be careful enough to check ipha_dst to be a
9105 		 * multicast address, otherwise it will take xmit_if path for
9106 		 * multicast packets resulting into kernel stack overflow by
9107 		 * repeated calls to ip_newroute_ipif from ire_send().
9108 		 */
9109 		if (CLASSD(ipha_dst) &&
9110 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9111 			goto err_ret;
9112 		}
9113 
9114 		/*
9115 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9116 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9117 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9118 		 * propagate its flags to the new ire.
9119 		 */
9120 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9121 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9122 			ip2dbg(("ip_newroute_ipif: "
9123 			    "ipif_lookup_multi_ire("
9124 			    "ipif %p, dst %08x) = fire %p\n",
9125 			    (void *)ipif, ntohl(dst), (void *)fire));
9126 		}
9127 
9128 		if (mctl_present && io->ipsec_out_attach_if) {
9129 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9130 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9131 
9132 			/* Failure case frees things for us. */
9133 			if (attach_ill == NULL) {
9134 				ipif_refrele(ipif);
9135 				if (fire != NULL)
9136 					ire_refrele(fire);
9137 				return;
9138 			}
9139 
9140 			/*
9141 			 * Check if we need an ire that will not be
9142 			 * looked up by anybody else i.e. HIDDEN.
9143 			 */
9144 			if (ill_is_probeonly(attach_ill)) {
9145 				ire_marks = IRE_MARK_HIDDEN;
9146 			}
9147 			/*
9148 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9149 			 * case.
9150 			 */
9151 			dst_ill = ipif->ipif_ill;
9152 			/* attach_ill has been refheld by ip_grab_attach_ill */
9153 			ASSERT(dst_ill == attach_ill);
9154 		} else {
9155 			/*
9156 			 * If the interface belongs to an interface group,
9157 			 * make sure the next possible interface in the group
9158 			 * is used.  This encourages load spreading among
9159 			 * peers in an interface group.
9160 			 * Note: load spreading is disabled for RTF_MULTIRT
9161 			 * routes.
9162 			 */
9163 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9164 			    (fire->ire_flags & RTF_MULTIRT)) {
9165 				/*
9166 				 * Don't perform outbound load spreading
9167 				 * in the case of an RTF_MULTIRT issued route,
9168 				 * we actually typically want to replicate
9169 				 * outgoing packets through particular
9170 				 * interfaces.
9171 				 */
9172 				dst_ill = ipif->ipif_ill;
9173 				ill_refhold(dst_ill);
9174 			} else {
9175 				dst_ill = ip_newroute_get_dst_ill(
9176 				    ipif->ipif_ill);
9177 			}
9178 			if (dst_ill == NULL) {
9179 				if (ip_debug > 2) {
9180 					pr_addr_dbg("ip_newroute_ipif: "
9181 					    "no dst ill for dst %s\n",
9182 					    AF_INET, &dst);
9183 				}
9184 				goto err_ret;
9185 			}
9186 		}
9187 
9188 		/*
9189 		 * Pick a source address preferring non-deprecated ones.
9190 		 * Unlike ip_newroute, we don't do any source address
9191 		 * selection here since for multicast it really does not help
9192 		 * in inbound load spreading as in the unicast case.
9193 		 */
9194 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9195 		    (fire->ire_flags & RTF_SETSRC)) {
9196 			/*
9197 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9198 			 * on that interface. This ire has RTF_SETSRC flag, so
9199 			 * the source address of the packet must be changed.
9200 			 * Check that the ipif matching the requested source
9201 			 * address still exists.
9202 			 */
9203 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9204 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9205 		}
9206 
9207 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9208 
9209 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9210 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9211 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9212 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9213 		    (src_ipif == NULL) &&
9214 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9215 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9216 			if (src_ipif == NULL) {
9217 				if (ip_debug > 2) {
9218 					/* ip1dbg */
9219 					pr_addr_dbg("ip_newroute_ipif: "
9220 					    "no src for dst %s",
9221 					    AF_INET, &dst);
9222 				}
9223 				ip1dbg((" through interface %s\n",
9224 				    dst_ill->ill_name));
9225 				goto err_ret;
9226 			}
9227 			ipif_refrele(ipif);
9228 			ipif = src_ipif;
9229 			ipif_refhold(ipif);
9230 		}
9231 		if (src_ipif == NULL) {
9232 			src_ipif = ipif;
9233 			ipif_refhold(src_ipif);
9234 		}
9235 
9236 		/*
9237 		 * Assign a source address while we have the conn.
9238 		 * We can't have ip_wput_ire pick a source address when the
9239 		 * packet returns from arp since conn_unspec_src might be set
9240 		 * and we lose the conn when going through arp.
9241 		 */
9242 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9243 			ipha->ipha_src = src_ipif->ipif_src_addr;
9244 
9245 		/*
9246 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9247 		 * that the outgoing interface does not have an interface ire.
9248 		 */
9249 		if (CLASSD(ipha_dst) && (connp == NULL ||
9250 		    connp->conn_outgoing_ill == NULL) &&
9251 		    infop->ip_opt_ill_index == 0) {
9252 			/* ipif_to_ire returns an held ire */
9253 			ire = ipif_to_ire(ipif);
9254 			if (ire == NULL)
9255 				goto err_ret;
9256 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9257 				goto err_ret;
9258 			/*
9259 			 * ihandle is needed when the ire is added to
9260 			 * cache table.
9261 			 */
9262 			save_ire = ire;
9263 			ihandle = save_ire->ire_ihandle;
9264 
9265 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9266 			    "flags %04x\n",
9267 			    (void *)ire, (void *)ipif, flags));
9268 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9269 			    (fire->ire_flags & RTF_MULTIRT)) {
9270 				/*
9271 				 * As requested by flags, an IRE_OFFSUBNET was
9272 				 * looked up on that interface. This ire has
9273 				 * RTF_MULTIRT flag, so the resolution loop will
9274 				 * be re-entered to resolve additional routes on
9275 				 * other interfaces. For that purpose, a copy of
9276 				 * the packet is performed at this point.
9277 				 */
9278 				fire->ire_last_used_time = lbolt;
9279 				copy_mp = copymsg(first_mp);
9280 				if (copy_mp) {
9281 					MULTIRT_DEBUG_TAG(copy_mp);
9282 				}
9283 			}
9284 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9285 			    (fire->ire_flags & RTF_SETSRC)) {
9286 				/*
9287 				 * As requested by flags, an IRE_OFFSUBET was
9288 				 * looked up on that interface. This ire has
9289 				 * RTF_SETSRC flag, so the source address of the
9290 				 * packet must be changed.
9291 				 */
9292 				ipha->ipha_src = fire->ire_src_addr;
9293 			}
9294 		} else {
9295 			ASSERT((connp == NULL) ||
9296 			    (connp->conn_outgoing_ill != NULL) ||
9297 			    (connp->conn_dontroute) ||
9298 			    infop->ip_opt_ill_index != 0);
9299 			/*
9300 			 * The only ways we can come here are:
9301 			 * 1) IP_BOUND_IF socket option is set
9302 			 * 2) SO_DONTROUTE socket option is set
9303 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9304 			 * In all cases, the new ire will not be added
9305 			 * into cache table.
9306 			 */
9307 			ire_marks |= IRE_MARK_NOADD;
9308 		}
9309 
9310 		switch (ipif->ipif_net_type) {
9311 		case IRE_IF_NORESOLVER: {
9312 			/* We have what we need to build an IRE_CACHE. */
9313 
9314 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9315 			    (dst_ill->ill_resolver_mp == NULL)) {
9316 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9317 				    "for IRE_IF_NORESOLVER ire %p has "
9318 				    "no ill_resolver_mp\n",
9319 				    (void *)dst_ill, (void *)ire));
9320 				break;
9321 			}
9322 
9323 			/*
9324 			 * The new ire inherits the IRE_OFFSUBNET flags
9325 			 * and source address, if this was requested.
9326 			 */
9327 			ire = ire_create(
9328 			    (uchar_t *)&dst,		/* dest address */
9329 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9330 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9331 			    NULL,			/* gateway address */
9332 			    &ipif->ipif_mtu,
9333 			    NULL,			/* no src nce */
9334 			    dst_ill->ill_rq,		/* recv-from queue */
9335 			    dst_ill->ill_wq,		/* send-to queue */
9336 			    IRE_CACHE,
9337 			    src_ipif,
9338 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9339 			    (fire != NULL) ?		/* Parent handle */
9340 			    fire->ire_phandle : 0,
9341 			    ihandle,			/* Interface handle */
9342 			    (fire != NULL) ?
9343 			    (fire->ire_flags &
9344 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9345 			    (save_ire == NULL ? &ire_uinfo_null :
9346 			    &save_ire->ire_uinfo),
9347 			    NULL,
9348 			    NULL,
9349 			    ipst);
9350 
9351 			if (ire == NULL) {
9352 				if (save_ire != NULL)
9353 					ire_refrele(save_ire);
9354 				break;
9355 			}
9356 
9357 			ire->ire_marks |= ire_marks;
9358 
9359 			/*
9360 			 * If IRE_MARK_NOADD is set then we need to convert
9361 			 * the max_fragp to a useable value now. This is
9362 			 * normally done in ire_add_v[46]. We also need to
9363 			 * associate the ire with an nce (normally would be
9364 			 * done in ip_wput_nondata()).
9365 			 *
9366 			 * Note that IRE_MARK_NOADD packets created here
9367 			 * do not have a non-null ire_mp pointer. The null
9368 			 * value of ire_bucket indicates that they were
9369 			 * never added.
9370 			 */
9371 			if (ire->ire_marks & IRE_MARK_NOADD) {
9372 				uint_t  max_frag;
9373 
9374 				max_frag = *ire->ire_max_fragp;
9375 				ire->ire_max_fragp = NULL;
9376 				ire->ire_max_frag = max_frag;
9377 
9378 				if ((ire->ire_nce = ndp_lookup_v4(
9379 				    ire_to_ill(ire),
9380 				    (ire->ire_gateway_addr != INADDR_ANY ?
9381 				    &ire->ire_gateway_addr : &ire->ire_addr),
9382 				    B_FALSE)) == NULL) {
9383 					if (save_ire != NULL)
9384 						ire_refrele(save_ire);
9385 					break;
9386 				}
9387 				ASSERT(ire->ire_nce->nce_state ==
9388 				    ND_REACHABLE);
9389 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9390 			}
9391 
9392 			/* Prevent save_ire from getting deleted */
9393 			if (save_ire != NULL) {
9394 				IRB_REFHOLD(save_ire->ire_bucket);
9395 				/* Has it been removed already ? */
9396 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9397 					IRB_REFRELE(save_ire->ire_bucket);
9398 					ire_refrele(save_ire);
9399 					break;
9400 				}
9401 			}
9402 
9403 			ire_add_then_send(q, ire, first_mp);
9404 
9405 			/* Assert that save_ire is not deleted yet. */
9406 			if (save_ire != NULL) {
9407 				ASSERT(save_ire->ire_ptpn != NULL);
9408 				IRB_REFRELE(save_ire->ire_bucket);
9409 				ire_refrele(save_ire);
9410 				save_ire = NULL;
9411 			}
9412 			if (fire != NULL) {
9413 				ire_refrele(fire);
9414 				fire = NULL;
9415 			}
9416 
9417 			/*
9418 			 * the resolution loop is re-entered if this
9419 			 * was requested through flags and if we
9420 			 * actually are in a multirouting case.
9421 			 */
9422 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9423 				boolean_t need_resolve =
9424 				    ire_multirt_need_resolve(ipha_dst,
9425 				    MBLK_GETLABEL(copy_mp), ipst);
9426 				if (!need_resolve) {
9427 					MULTIRT_DEBUG_UNTAG(copy_mp);
9428 					freemsg(copy_mp);
9429 					copy_mp = NULL;
9430 				} else {
9431 					/*
9432 					 * ipif_lookup_group() calls
9433 					 * ire_lookup_multi() that uses
9434 					 * ire_ftable_lookup() to find
9435 					 * an IRE_INTERFACE for the group.
9436 					 * In the multirt case,
9437 					 * ire_lookup_multi() then invokes
9438 					 * ire_multirt_lookup() to find
9439 					 * the next resolvable ire.
9440 					 * As a result, we obtain an new
9441 					 * interface, derived from the
9442 					 * next ire.
9443 					 */
9444 					ipif_refrele(ipif);
9445 					ipif = ipif_lookup_group(ipha_dst,
9446 					    zoneid, ipst);
9447 					ip2dbg(("ip_newroute_ipif: "
9448 					    "multirt dst %08x, ipif %p\n",
9449 					    htonl(dst), (void *)ipif));
9450 					if (ipif != NULL) {
9451 						mp = copy_mp;
9452 						copy_mp = NULL;
9453 						multirt_resolve_next = B_TRUE;
9454 						continue;
9455 					} else {
9456 						freemsg(copy_mp);
9457 					}
9458 				}
9459 			}
9460 			if (ipif != NULL)
9461 				ipif_refrele(ipif);
9462 			ill_refrele(dst_ill);
9463 			ipif_refrele(src_ipif);
9464 			return;
9465 		}
9466 		case IRE_IF_RESOLVER:
9467 			/*
9468 			 * We can't build an IRE_CACHE yet, but at least
9469 			 * we found a resolver that can help.
9470 			 */
9471 			res_mp = dst_ill->ill_resolver_mp;
9472 			if (!OK_RESOLVER_MP(res_mp))
9473 				break;
9474 
9475 			/*
9476 			 * We obtain a partial IRE_CACHE which we will pass
9477 			 * along with the resolver query.  When the response
9478 			 * comes back it will be there ready for us to add.
9479 			 * The new ire inherits the IRE_OFFSUBNET flags
9480 			 * and source address, if this was requested.
9481 			 * The ire_max_frag is atomically set under the
9482 			 * irebucket lock in ire_add_v[46]. Only in the
9483 			 * case of IRE_MARK_NOADD, we set it here itself.
9484 			 */
9485 			ire = ire_create_mp(
9486 			    (uchar_t *)&dst,		/* dest address */
9487 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9488 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9489 			    NULL,			/* gateway address */
9490 			    (ire_marks & IRE_MARK_NOADD) ?
9491 			    ipif->ipif_mtu : 0,		/* max_frag */
9492 			    NULL,			/* no src nce */
9493 			    dst_ill->ill_rq,		/* recv-from queue */
9494 			    dst_ill->ill_wq,		/* send-to queue */
9495 			    IRE_CACHE,
9496 			    src_ipif,
9497 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9498 			    (fire != NULL) ?		/* Parent handle */
9499 			    fire->ire_phandle : 0,
9500 			    ihandle,			/* Interface handle */
9501 			    (fire != NULL) ?		/* flags if any */
9502 			    (fire->ire_flags &
9503 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9504 			    (save_ire == NULL ? &ire_uinfo_null :
9505 			    &save_ire->ire_uinfo),
9506 			    NULL,
9507 			    NULL,
9508 			    ipst);
9509 
9510 			if (save_ire != NULL) {
9511 				ire_refrele(save_ire);
9512 				save_ire = NULL;
9513 			}
9514 			if (ire == NULL)
9515 				break;
9516 
9517 			ire->ire_marks |= ire_marks;
9518 			/*
9519 			 * Construct message chain for the resolver of the
9520 			 * form:
9521 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9522 			 *
9523 			 * NOTE : ire will be added later when the response
9524 			 * comes back from ARP. If the response does not
9525 			 * come back, ARP frees the packet. For this reason,
9526 			 * we can't REFHOLD the bucket of save_ire to prevent
9527 			 * deletions. We may not be able to REFRELE the
9528 			 * bucket if the response never comes back.
9529 			 * Thus, before adding the ire, ire_add_v4 will make
9530 			 * sure that the interface route does not get deleted.
9531 			 * This is the only case unlike ip_newroute_v6,
9532 			 * ip_newroute_ipif_v6 where we can always prevent
9533 			 * deletions because ire_add_then_send is called after
9534 			 * creating the IRE.
9535 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9536 			 * does not add this IRE into the IRE CACHE.
9537 			 */
9538 			ASSERT(ire->ire_mp != NULL);
9539 			ire->ire_mp->b_cont = first_mp;
9540 			/* Have saved_mp handy, for cleanup if canput fails */
9541 			saved_mp = mp;
9542 			mp = copyb(res_mp);
9543 			if (mp == NULL) {
9544 				/* Prepare for cleanup */
9545 				mp = saved_mp; /* pkt */
9546 				ire_delete(ire); /* ire_mp */
9547 				ire = NULL;
9548 				if (copy_mp != NULL) {
9549 					MULTIRT_DEBUG_UNTAG(copy_mp);
9550 					freemsg(copy_mp);
9551 					copy_mp = NULL;
9552 				}
9553 				break;
9554 			}
9555 			linkb(mp, ire->ire_mp);
9556 
9557 			/*
9558 			 * Fill in the source and dest addrs for the resolver.
9559 			 * NOTE: this depends on memory layouts imposed by
9560 			 * ill_init().
9561 			 */
9562 			areq = (areq_t *)mp->b_rptr;
9563 			addrp = (ipaddr_t *)((char *)areq +
9564 			    areq->areq_sender_addr_offset);
9565 			*addrp = ire->ire_src_addr;
9566 			addrp = (ipaddr_t *)((char *)areq +
9567 			    areq->areq_target_addr_offset);
9568 			*addrp = dst;
9569 			/* Up to the resolver. */
9570 			if (canputnext(dst_ill->ill_rq) &&
9571 			    !(dst_ill->ill_arp_closing)) {
9572 				putnext(dst_ill->ill_rq, mp);
9573 				/*
9574 				 * The response will come back in ip_wput
9575 				 * with db_type IRE_DB_TYPE.
9576 				 */
9577 			} else {
9578 				mp->b_cont = NULL;
9579 				freeb(mp); /* areq */
9580 				ire_delete(ire); /* ire_mp */
9581 				saved_mp->b_next = NULL;
9582 				saved_mp->b_prev = NULL;
9583 				freemsg(first_mp); /* pkt */
9584 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9585 			}
9586 
9587 			if (fire != NULL) {
9588 				ire_refrele(fire);
9589 				fire = NULL;
9590 			}
9591 
9592 
9593 			/*
9594 			 * The resolution loop is re-entered if this was
9595 			 * requested through flags and we actually are
9596 			 * in a multirouting case.
9597 			 */
9598 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9599 				boolean_t need_resolve =
9600 				    ire_multirt_need_resolve(ipha_dst,
9601 				    MBLK_GETLABEL(copy_mp), ipst);
9602 				if (!need_resolve) {
9603 					MULTIRT_DEBUG_UNTAG(copy_mp);
9604 					freemsg(copy_mp);
9605 					copy_mp = NULL;
9606 				} else {
9607 					/*
9608 					 * ipif_lookup_group() calls
9609 					 * ire_lookup_multi() that uses
9610 					 * ire_ftable_lookup() to find
9611 					 * an IRE_INTERFACE for the group.
9612 					 * In the multirt case,
9613 					 * ire_lookup_multi() then invokes
9614 					 * ire_multirt_lookup() to find
9615 					 * the next resolvable ire.
9616 					 * As a result, we obtain an new
9617 					 * interface, derived from the
9618 					 * next ire.
9619 					 */
9620 					ipif_refrele(ipif);
9621 					ipif = ipif_lookup_group(ipha_dst,
9622 					    zoneid, ipst);
9623 					if (ipif != NULL) {
9624 						mp = copy_mp;
9625 						copy_mp = NULL;
9626 						multirt_resolve_next = B_TRUE;
9627 						continue;
9628 					} else {
9629 						freemsg(copy_mp);
9630 					}
9631 				}
9632 			}
9633 			if (ipif != NULL)
9634 				ipif_refrele(ipif);
9635 			ill_refrele(dst_ill);
9636 			ipif_refrele(src_ipif);
9637 			return;
9638 		default:
9639 			break;
9640 		}
9641 	} while (multirt_resolve_next);
9642 
9643 err_ret:
9644 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9645 	if (fire != NULL)
9646 		ire_refrele(fire);
9647 	ipif_refrele(ipif);
9648 	/* Did this packet originate externally? */
9649 	if (dst_ill != NULL)
9650 		ill_refrele(dst_ill);
9651 	if (src_ipif != NULL)
9652 		ipif_refrele(src_ipif);
9653 	if (mp->b_prev || mp->b_next) {
9654 		mp->b_next = NULL;
9655 		mp->b_prev = NULL;
9656 	} else {
9657 		/*
9658 		 * Since ip_wput() isn't close to finished, we fill
9659 		 * in enough of the header for credible error reporting.
9660 		 */
9661 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9662 			/* Failed */
9663 			freemsg(first_mp);
9664 			if (ire != NULL)
9665 				ire_refrele(ire);
9666 			return;
9667 		}
9668 	}
9669 	/*
9670 	 * At this point we will have ire only if RTF_BLACKHOLE
9671 	 * or RTF_REJECT flags are set on the IRE. It will not
9672 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9673 	 */
9674 	if (ire != NULL) {
9675 		if (ire->ire_flags & RTF_BLACKHOLE) {
9676 			ire_refrele(ire);
9677 			freemsg(first_mp);
9678 			return;
9679 		}
9680 		ire_refrele(ire);
9681 	}
9682 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9683 }
9684 
9685 /* Name/Value Table Lookup Routine */
9686 char *
9687 ip_nv_lookup(nv_t *nv, int value)
9688 {
9689 	if (!nv)
9690 		return (NULL);
9691 	for (; nv->nv_name; nv++) {
9692 		if (nv->nv_value == value)
9693 			return (nv->nv_name);
9694 	}
9695 	return ("unknown");
9696 }
9697 
9698 /*
9699  * This is a module open, i.e. this is a control stream for access
9700  * to a DLPI device.  We allocate an ill_t as the instance data in
9701  * this case.
9702  */
9703 int
9704 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9705 {
9706 	ill_t	*ill;
9707 	int	err;
9708 	zoneid_t zoneid;
9709 	netstack_t *ns;
9710 	ip_stack_t *ipst;
9711 
9712 	/*
9713 	 * Prevent unprivileged processes from pushing IP so that
9714 	 * they can't send raw IP.
9715 	 */
9716 	if (secpolicy_net_rawaccess(credp) != 0)
9717 		return (EPERM);
9718 
9719 	ns = netstack_find_by_cred(credp);
9720 	ASSERT(ns != NULL);
9721 	ipst = ns->netstack_ip;
9722 	ASSERT(ipst != NULL);
9723 
9724 	/*
9725 	 * For exclusive stacks we set the zoneid to zero
9726 	 * to make IP operate as if in the global zone.
9727 	 */
9728 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9729 		zoneid = GLOBAL_ZONEID;
9730 	else
9731 		zoneid = crgetzoneid(credp);
9732 
9733 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9734 	q->q_ptr = WR(q)->q_ptr = ill;
9735 	ill->ill_ipst = ipst;
9736 	ill->ill_zoneid = zoneid;
9737 
9738 	/*
9739 	 * ill_init initializes the ill fields and then sends down
9740 	 * down a DL_INFO_REQ after calling qprocson.
9741 	 */
9742 	err = ill_init(q, ill);
9743 	if (err != 0) {
9744 		mi_free(ill);
9745 		netstack_rele(ipst->ips_netstack);
9746 		q->q_ptr = NULL;
9747 		WR(q)->q_ptr = NULL;
9748 		return (err);
9749 	}
9750 
9751 	/* ill_init initializes the ipsq marking this thread as writer */
9752 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9753 	/* Wait for the DL_INFO_ACK */
9754 	mutex_enter(&ill->ill_lock);
9755 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9756 		/*
9757 		 * Return value of 0 indicates a pending signal.
9758 		 */
9759 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9760 		if (err == 0) {
9761 			mutex_exit(&ill->ill_lock);
9762 			(void) ip_close(q, 0);
9763 			return (EINTR);
9764 		}
9765 	}
9766 	mutex_exit(&ill->ill_lock);
9767 
9768 	/*
9769 	 * ip_rput_other could have set an error  in ill_error on
9770 	 * receipt of M_ERROR.
9771 	 */
9772 
9773 	err = ill->ill_error;
9774 	if (err != 0) {
9775 		(void) ip_close(q, 0);
9776 		return (err);
9777 	}
9778 
9779 	ill->ill_credp = credp;
9780 	crhold(credp);
9781 
9782 	mutex_enter(&ipst->ips_ip_mi_lock);
9783 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9784 	    credp);
9785 	mutex_exit(&ipst->ips_ip_mi_lock);
9786 	if (err) {
9787 		(void) ip_close(q, 0);
9788 		return (err);
9789 	}
9790 	return (0);
9791 }
9792 
9793 /* For /dev/ip aka AF_INET open */
9794 int
9795 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9796 {
9797 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9798 }
9799 
9800 /* For /dev/ip6 aka AF_INET6 open */
9801 int
9802 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9803 {
9804 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9805 }
9806 
9807 /* IP open routine. */
9808 int
9809 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9810     boolean_t isv6)
9811 {
9812 	conn_t 		*connp;
9813 	major_t		maj;
9814 	zoneid_t	zoneid;
9815 	netstack_t	*ns;
9816 	ip_stack_t	*ipst;
9817 
9818 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9819 
9820 	/* Allow reopen. */
9821 	if (q->q_ptr != NULL)
9822 		return (0);
9823 
9824 	if (sflag & MODOPEN) {
9825 		/* This is a module open */
9826 		return (ip_modopen(q, devp, flag, sflag, credp));
9827 	}
9828 
9829 	ns = netstack_find_by_cred(credp);
9830 	ASSERT(ns != NULL);
9831 	ipst = ns->netstack_ip;
9832 	ASSERT(ipst != NULL);
9833 
9834 	/*
9835 	 * For exclusive stacks we set the zoneid to zero
9836 	 * to make IP operate as if in the global zone.
9837 	 */
9838 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9839 		zoneid = GLOBAL_ZONEID;
9840 	else
9841 		zoneid = crgetzoneid(credp);
9842 
9843 	/*
9844 	 * We are opening as a device. This is an IP client stream, and we
9845 	 * allocate an conn_t as the instance data.
9846 	 */
9847 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9848 
9849 	/*
9850 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9851 	 * done by netstack_find_by_cred()
9852 	 */
9853 	netstack_rele(ipst->ips_netstack);
9854 
9855 	connp->conn_zoneid = zoneid;
9856 
9857 	connp->conn_upq = q;
9858 	q->q_ptr = WR(q)->q_ptr = connp;
9859 
9860 	if (flag & SO_SOCKSTR)
9861 		connp->conn_flags |= IPCL_SOCKET;
9862 
9863 	/* Minor tells us which /dev entry was opened */
9864 	if (isv6) {
9865 		connp->conn_flags |= IPCL_ISV6;
9866 		connp->conn_af_isv6 = B_TRUE;
9867 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9868 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9869 	} else {
9870 		connp->conn_af_isv6 = B_FALSE;
9871 		connp->conn_pkt_isv6 = B_FALSE;
9872 	}
9873 
9874 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9875 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9876 		connp->conn_minor_arena = ip_minor_arena_la;
9877 	} else {
9878 		/*
9879 		 * Either minor numbers in the large arena were exhausted
9880 		 * or a non socket application is doing the open.
9881 		 * Try to allocate from the small arena.
9882 		 */
9883 		if ((connp->conn_dev =
9884 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9885 			/* CONN_DEC_REF takes care of netstack_rele() */
9886 			q->q_ptr = WR(q)->q_ptr = NULL;
9887 			CONN_DEC_REF(connp);
9888 			return (EBUSY);
9889 		}
9890 		connp->conn_minor_arena = ip_minor_arena_sa;
9891 	}
9892 
9893 	maj = getemajor(*devp);
9894 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9895 
9896 	/*
9897 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9898 	 */
9899 	connp->conn_cred = credp;
9900 
9901 	/*
9902 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9903 	 */
9904 	connp->conn_recv = ip_conn_input;
9905 
9906 	crhold(connp->conn_cred);
9907 
9908 	/*
9909 	 * If the caller has the process-wide flag set, then default to MAC
9910 	 * exempt mode.  This allows read-down to unlabeled hosts.
9911 	 */
9912 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9913 		connp->conn_mac_exempt = B_TRUE;
9914 
9915 	connp->conn_rq = q;
9916 	connp->conn_wq = WR(q);
9917 
9918 	/* Non-zero default values */
9919 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9920 
9921 	/*
9922 	 * Make the conn globally visible to walkers
9923 	 */
9924 	ASSERT(connp->conn_ref == 1);
9925 	mutex_enter(&connp->conn_lock);
9926 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9927 	mutex_exit(&connp->conn_lock);
9928 
9929 	qprocson(q);
9930 
9931 	return (0);
9932 }
9933 
9934 /*
9935  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9936  * Note that there is no race since either ip_output function works - it
9937  * is just an optimization to enter the best ip_output routine directly.
9938  */
9939 void
9940 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9941     ip_stack_t *ipst)
9942 {
9943 	if (isv6)  {
9944 		if (bump_mib) {
9945 			BUMP_MIB(&ipst->ips_ip6_mib,
9946 			    ipIfStatsOutSwitchIPVersion);
9947 		}
9948 		connp->conn_send = ip_output_v6;
9949 		connp->conn_pkt_isv6 = B_TRUE;
9950 	} else {
9951 		if (bump_mib) {
9952 			BUMP_MIB(&ipst->ips_ip_mib,
9953 			    ipIfStatsOutSwitchIPVersion);
9954 		}
9955 		connp->conn_send = ip_output;
9956 		connp->conn_pkt_isv6 = B_FALSE;
9957 	}
9958 
9959 }
9960 
9961 /*
9962  * See if IPsec needs loading because of the options in mp.
9963  */
9964 static boolean_t
9965 ipsec_opt_present(mblk_t *mp)
9966 {
9967 	uint8_t *optcp, *next_optcp, *opt_endcp;
9968 	struct opthdr *opt;
9969 	struct T_opthdr *topt;
9970 	int opthdr_len;
9971 	t_uscalar_t optname, optlevel;
9972 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9973 	ipsec_req_t *ipsr;
9974 
9975 	/*
9976 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9977 	 * return TRUE.
9978 	 */
9979 
9980 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9981 	opt_endcp = optcp + tor->OPT_length;
9982 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9983 		opthdr_len = sizeof (struct T_opthdr);
9984 	} else {		/* O_OPTMGMT_REQ */
9985 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9986 		opthdr_len = sizeof (struct opthdr);
9987 	}
9988 	for (; optcp < opt_endcp; optcp = next_optcp) {
9989 		if (optcp + opthdr_len > opt_endcp)
9990 			return (B_FALSE);	/* Not enough option header. */
9991 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9992 			topt = (struct T_opthdr *)optcp;
9993 			optlevel = topt->level;
9994 			optname = topt->name;
9995 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9996 		} else {
9997 			opt = (struct opthdr *)optcp;
9998 			optlevel = opt->level;
9999 			optname = opt->name;
10000 			next_optcp = optcp + opthdr_len +
10001 			    _TPI_ALIGN_OPT(opt->len);
10002 		}
10003 		if ((next_optcp < optcp) || /* wraparound pointer space */
10004 		    ((next_optcp >= opt_endcp) && /* last option bad len */
10005 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
10006 			return (B_FALSE); /* bad option buffer */
10007 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
10008 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
10009 			/*
10010 			 * Check to see if it's an all-bypass or all-zeroes
10011 			 * IPsec request.  Don't bother loading IPsec if
10012 			 * the socket doesn't want to use it.  (A good example
10013 			 * is a bypass request.)
10014 			 *
10015 			 * Basically, if any of the non-NEVER bits are set,
10016 			 * load IPsec.
10017 			 */
10018 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
10019 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
10020 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
10021 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
10022 			    != 0)
10023 				return (B_TRUE);
10024 		}
10025 	}
10026 	return (B_FALSE);
10027 }
10028 
10029 /*
10030  * If conn is is waiting for ipsec to finish loading, kick it.
10031  */
10032 /* ARGSUSED */
10033 static void
10034 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
10035 {
10036 	t_scalar_t	optreq_prim;
10037 	mblk_t		*mp;
10038 	cred_t		*cr;
10039 	int		err = 0;
10040 
10041 	/*
10042 	 * This function is called, after ipsec loading is complete.
10043 	 * Since IP checks exclusively and atomically (i.e it prevents
10044 	 * ipsec load from completing until ip_optcom_req completes)
10045 	 * whether ipsec load is complete, there cannot be a race with IP
10046 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
10047 	 */
10048 	mutex_enter(&connp->conn_lock);
10049 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
10050 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
10051 		mp = connp->conn_ipsec_opt_mp;
10052 		connp->conn_ipsec_opt_mp = NULL;
10053 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
10054 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
10055 		mutex_exit(&connp->conn_lock);
10056 
10057 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
10058 
10059 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
10060 		if (optreq_prim == T_OPTMGMT_REQ) {
10061 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10062 			    &ip_opt_obj, B_FALSE);
10063 		} else {
10064 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
10065 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
10066 			    &ip_opt_obj, B_FALSE);
10067 		}
10068 		if (err != EINPROGRESS)
10069 			CONN_OPER_PENDING_DONE(connp);
10070 		return;
10071 	}
10072 	mutex_exit(&connp->conn_lock);
10073 }
10074 
10075 /*
10076  * Called from the ipsec_loader thread, outside any perimeter, to tell
10077  * ip qenable any of the queues waiting for the ipsec loader to
10078  * complete.
10079  */
10080 void
10081 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10082 {
10083 	netstack_t *ns = ipss->ipsec_netstack;
10084 
10085 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10086 }
10087 
10088 /*
10089  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10090  * determines the grp on which it has to become exclusive, queues the mp
10091  * and sq draining restarts the optmgmt
10092  */
10093 static boolean_t
10094 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10095 {
10096 	conn_t *connp = Q_TO_CONN(q);
10097 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10098 
10099 	/*
10100 	 * Take IPsec requests and treat them special.
10101 	 */
10102 	if (ipsec_opt_present(mp)) {
10103 		/* First check if IPsec is loaded. */
10104 		mutex_enter(&ipss->ipsec_loader_lock);
10105 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10106 			mutex_exit(&ipss->ipsec_loader_lock);
10107 			return (B_FALSE);
10108 		}
10109 		mutex_enter(&connp->conn_lock);
10110 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10111 
10112 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10113 		connp->conn_ipsec_opt_mp = mp;
10114 		mutex_exit(&connp->conn_lock);
10115 		mutex_exit(&ipss->ipsec_loader_lock);
10116 
10117 		ipsec_loader_loadnow(ipss);
10118 		return (B_TRUE);
10119 	}
10120 	return (B_FALSE);
10121 }
10122 
10123 /*
10124  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10125  * all of them are copied to the conn_t. If the req is "zero", the policy is
10126  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10127  * fields.
10128  * We keep only the latest setting of the policy and thus policy setting
10129  * is not incremental/cumulative.
10130  *
10131  * Requests to set policies with multiple alternative actions will
10132  * go through a different API.
10133  */
10134 int
10135 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10136 {
10137 	uint_t ah_req = 0;
10138 	uint_t esp_req = 0;
10139 	uint_t se_req = 0;
10140 	ipsec_selkey_t sel;
10141 	ipsec_act_t *actp = NULL;
10142 	uint_t nact;
10143 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10144 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10145 	ipsec_policy_root_t *pr;
10146 	ipsec_policy_head_t *ph;
10147 	int fam;
10148 	boolean_t is_pol_reset;
10149 	int error = 0;
10150 	netstack_t	*ns = connp->conn_netstack;
10151 	ip_stack_t	*ipst = ns->netstack_ip;
10152 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10153 
10154 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10155 
10156 	/*
10157 	 * The IP_SEC_OPT option does not allow variable length parameters,
10158 	 * hence a request cannot be NULL.
10159 	 */
10160 	if (req == NULL)
10161 		return (EINVAL);
10162 
10163 	ah_req = req->ipsr_ah_req;
10164 	esp_req = req->ipsr_esp_req;
10165 	se_req = req->ipsr_self_encap_req;
10166 
10167 	/*
10168 	 * Are we dealing with a request to reset the policy (i.e.
10169 	 * zero requests).
10170 	 */
10171 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10172 	    (esp_req & REQ_MASK) == 0 &&
10173 	    (se_req & REQ_MASK) == 0);
10174 
10175 	if (!is_pol_reset) {
10176 		/*
10177 		 * If we couldn't load IPsec, fail with "protocol
10178 		 * not supported".
10179 		 * IPsec may not have been loaded for a request with zero
10180 		 * policies, so we don't fail in this case.
10181 		 */
10182 		mutex_enter(&ipss->ipsec_loader_lock);
10183 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10184 			mutex_exit(&ipss->ipsec_loader_lock);
10185 			return (EPROTONOSUPPORT);
10186 		}
10187 		mutex_exit(&ipss->ipsec_loader_lock);
10188 
10189 		/*
10190 		 * Test for valid requests. Invalid algorithms
10191 		 * need to be tested by IPsec code because new
10192 		 * algorithms can be added dynamically.
10193 		 */
10194 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10195 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10196 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10197 			return (EINVAL);
10198 		}
10199 
10200 		/*
10201 		 * Only privileged users can issue these
10202 		 * requests.
10203 		 */
10204 		if (((ah_req & IPSEC_PREF_NEVER) ||
10205 		    (esp_req & IPSEC_PREF_NEVER) ||
10206 		    (se_req & IPSEC_PREF_NEVER)) &&
10207 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10208 			return (EPERM);
10209 		}
10210 
10211 		/*
10212 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10213 		 * are mutually exclusive.
10214 		 */
10215 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10216 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10217 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10218 			/* Both of them are set */
10219 			return (EINVAL);
10220 		}
10221 	}
10222 
10223 	mutex_enter(&connp->conn_lock);
10224 
10225 	/*
10226 	 * If we have already cached policies in ip_bind_connected*(), don't
10227 	 * let them change now. We cache policies for connections
10228 	 * whose src,dst [addr, port] is known.
10229 	 */
10230 	if (connp->conn_policy_cached) {
10231 		mutex_exit(&connp->conn_lock);
10232 		return (EINVAL);
10233 	}
10234 
10235 	/*
10236 	 * We have a zero policies, reset the connection policy if already
10237 	 * set. This will cause the connection to inherit the
10238 	 * global policy, if any.
10239 	 */
10240 	if (is_pol_reset) {
10241 		if (connp->conn_policy != NULL) {
10242 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10243 			connp->conn_policy = NULL;
10244 		}
10245 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10246 		connp->conn_in_enforce_policy = B_FALSE;
10247 		connp->conn_out_enforce_policy = B_FALSE;
10248 		mutex_exit(&connp->conn_lock);
10249 		return (0);
10250 	}
10251 
10252 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10253 	    ipst->ips_netstack);
10254 	if (ph == NULL)
10255 		goto enomem;
10256 
10257 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10258 	if (actp == NULL)
10259 		goto enomem;
10260 
10261 	/*
10262 	 * Always allocate IPv4 policy entries, since they can also
10263 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10264 	 */
10265 	bzero(&sel, sizeof (sel));
10266 	sel.ipsl_valid = IPSL_IPV4;
10267 
10268 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10269 	    ipst->ips_netstack);
10270 	if (pin4 == NULL)
10271 		goto enomem;
10272 
10273 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10274 	    ipst->ips_netstack);
10275 	if (pout4 == NULL)
10276 		goto enomem;
10277 
10278 	if (connp->conn_af_isv6) {
10279 		/*
10280 		 * We're looking at a v6 socket, also allocate the
10281 		 * v6-specific entries...
10282 		 */
10283 		sel.ipsl_valid = IPSL_IPV6;
10284 		pin6 = ipsec_policy_create(&sel, actp, nact,
10285 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10286 		if (pin6 == NULL)
10287 			goto enomem;
10288 
10289 		pout6 = ipsec_policy_create(&sel, actp, nact,
10290 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10291 		if (pout6 == NULL)
10292 			goto enomem;
10293 
10294 		/*
10295 		 * .. and file them away in the right place.
10296 		 */
10297 		fam = IPSEC_AF_V6;
10298 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10299 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10300 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10301 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10302 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10303 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10304 	}
10305 
10306 	ipsec_actvec_free(actp, nact);
10307 
10308 	/*
10309 	 * File the v4 policies.
10310 	 */
10311 	fam = IPSEC_AF_V4;
10312 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10313 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10314 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10315 
10316 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10317 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10318 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10319 
10320 	/*
10321 	 * If the requests need security, set enforce_policy.
10322 	 * If the requests are IPSEC_PREF_NEVER, one should
10323 	 * still set conn_out_enforce_policy so that an ipsec_out
10324 	 * gets attached in ip_wput. This is needed so that
10325 	 * for connections that we don't cache policy in ip_bind,
10326 	 * if global policy matches in ip_wput_attach_policy, we
10327 	 * don't wrongly inherit global policy. Similarly, we need
10328 	 * to set conn_in_enforce_policy also so that we don't verify
10329 	 * policy wrongly.
10330 	 */
10331 	if ((ah_req & REQ_MASK) != 0 ||
10332 	    (esp_req & REQ_MASK) != 0 ||
10333 	    (se_req & REQ_MASK) != 0) {
10334 		connp->conn_in_enforce_policy = B_TRUE;
10335 		connp->conn_out_enforce_policy = B_TRUE;
10336 		connp->conn_flags |= IPCL_CHECK_POLICY;
10337 	}
10338 
10339 	mutex_exit(&connp->conn_lock);
10340 	return (error);
10341 #undef REQ_MASK
10342 
10343 	/*
10344 	 * Common memory-allocation-failure exit path.
10345 	 */
10346 enomem:
10347 	mutex_exit(&connp->conn_lock);
10348 	if (actp != NULL)
10349 		ipsec_actvec_free(actp, nact);
10350 	if (pin4 != NULL)
10351 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10352 	if (pout4 != NULL)
10353 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10354 	if (pin6 != NULL)
10355 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10356 	if (pout6 != NULL)
10357 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10358 	return (ENOMEM);
10359 }
10360 
10361 /*
10362  * Only for options that pass in an IP addr. Currently only V4 options
10363  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10364  * So this function assumes level is IPPROTO_IP
10365  */
10366 int
10367 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10368     mblk_t *first_mp)
10369 {
10370 	ipif_t *ipif = NULL;
10371 	int error;
10372 	ill_t *ill;
10373 	int zoneid;
10374 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10375 
10376 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10377 
10378 	if (addr != INADDR_ANY || checkonly) {
10379 		ASSERT(connp != NULL);
10380 		zoneid = IPCL_ZONEID(connp);
10381 		if (option == IP_NEXTHOP) {
10382 			ipif = ipif_lookup_onlink_addr(addr,
10383 			    connp->conn_zoneid, ipst);
10384 		} else {
10385 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10386 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10387 			    &error, ipst);
10388 		}
10389 		if (ipif == NULL) {
10390 			if (error == EINPROGRESS)
10391 				return (error);
10392 			else if ((option == IP_MULTICAST_IF) ||
10393 			    (option == IP_NEXTHOP))
10394 				return (EHOSTUNREACH);
10395 			else
10396 				return (EINVAL);
10397 		} else if (checkonly) {
10398 			if (option == IP_MULTICAST_IF) {
10399 				ill = ipif->ipif_ill;
10400 				/* not supported by the virtual network iface */
10401 				if (IS_VNI(ill)) {
10402 					ipif_refrele(ipif);
10403 					return (EINVAL);
10404 				}
10405 			}
10406 			ipif_refrele(ipif);
10407 			return (0);
10408 		}
10409 		ill = ipif->ipif_ill;
10410 		mutex_enter(&connp->conn_lock);
10411 		mutex_enter(&ill->ill_lock);
10412 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10413 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10414 			mutex_exit(&ill->ill_lock);
10415 			mutex_exit(&connp->conn_lock);
10416 			ipif_refrele(ipif);
10417 			return (option == IP_MULTICAST_IF ?
10418 			    EHOSTUNREACH : EINVAL);
10419 		}
10420 	} else {
10421 		mutex_enter(&connp->conn_lock);
10422 	}
10423 
10424 	/* None of the options below are supported on the VNI */
10425 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10426 		mutex_exit(&ill->ill_lock);
10427 		mutex_exit(&connp->conn_lock);
10428 		ipif_refrele(ipif);
10429 		return (EINVAL);
10430 	}
10431 
10432 	switch (option) {
10433 	case IP_DONTFAILOVER_IF:
10434 		/*
10435 		 * This option is used by in.mpathd to ensure
10436 		 * that IPMP probe packets only go out on the
10437 		 * test interfaces. in.mpathd sets this option
10438 		 * on the non-failover interfaces.
10439 		 * For backward compatibility, this option
10440 		 * implicitly sets IP_MULTICAST_IF, as used
10441 		 * be done in bind(), so that ip_wput gets
10442 		 * this ipif to send mcast packets.
10443 		 */
10444 		if (ipif != NULL) {
10445 			ASSERT(addr != INADDR_ANY);
10446 			connp->conn_nofailover_ill = ipif->ipif_ill;
10447 			connp->conn_multicast_ipif = ipif;
10448 		} else {
10449 			ASSERT(addr == INADDR_ANY);
10450 			connp->conn_nofailover_ill = NULL;
10451 			connp->conn_multicast_ipif = NULL;
10452 		}
10453 		break;
10454 
10455 	case IP_MULTICAST_IF:
10456 		connp->conn_multicast_ipif = ipif;
10457 		break;
10458 	case IP_NEXTHOP:
10459 		connp->conn_nexthop_v4 = addr;
10460 		connp->conn_nexthop_set = B_TRUE;
10461 		break;
10462 	}
10463 
10464 	if (ipif != NULL) {
10465 		mutex_exit(&ill->ill_lock);
10466 		mutex_exit(&connp->conn_lock);
10467 		ipif_refrele(ipif);
10468 		return (0);
10469 	}
10470 	mutex_exit(&connp->conn_lock);
10471 	/* We succeded in cleared the option */
10472 	return (0);
10473 }
10474 
10475 /*
10476  * For options that pass in an ifindex specifying the ill. V6 options always
10477  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10478  */
10479 int
10480 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10481     int level, int option, mblk_t *first_mp)
10482 {
10483 	ill_t *ill = NULL;
10484 	int error = 0;
10485 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10486 
10487 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10488 	if (ifindex != 0) {
10489 		ASSERT(connp != NULL);
10490 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10491 		    first_mp, ip_restart_optmgmt, &error, ipst);
10492 		if (ill != NULL) {
10493 			if (checkonly) {
10494 				/* not supported by the virtual network iface */
10495 				if (IS_VNI(ill)) {
10496 					ill_refrele(ill);
10497 					return (EINVAL);
10498 				}
10499 				ill_refrele(ill);
10500 				return (0);
10501 			}
10502 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10503 			    0, NULL)) {
10504 				ill_refrele(ill);
10505 				ill = NULL;
10506 				mutex_enter(&connp->conn_lock);
10507 				goto setit;
10508 			}
10509 			mutex_enter(&connp->conn_lock);
10510 			mutex_enter(&ill->ill_lock);
10511 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10512 				mutex_exit(&ill->ill_lock);
10513 				mutex_exit(&connp->conn_lock);
10514 				ill_refrele(ill);
10515 				ill = NULL;
10516 				mutex_enter(&connp->conn_lock);
10517 			}
10518 			goto setit;
10519 		} else if (error == EINPROGRESS) {
10520 			return (error);
10521 		} else {
10522 			error = 0;
10523 		}
10524 	}
10525 	mutex_enter(&connp->conn_lock);
10526 setit:
10527 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10528 
10529 	/*
10530 	 * The options below assume that the ILL (if any) transmits and/or
10531 	 * receives traffic. Neither of which is true for the virtual network
10532 	 * interface, so fail setting these on a VNI.
10533 	 */
10534 	if (IS_VNI(ill)) {
10535 		ASSERT(ill != NULL);
10536 		mutex_exit(&ill->ill_lock);
10537 		mutex_exit(&connp->conn_lock);
10538 		ill_refrele(ill);
10539 		return (EINVAL);
10540 	}
10541 
10542 	if (level == IPPROTO_IP) {
10543 		switch (option) {
10544 		case IP_BOUND_IF:
10545 			connp->conn_incoming_ill = ill;
10546 			connp->conn_outgoing_ill = ill;
10547 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10548 			    0 : ifindex;
10549 			break;
10550 
10551 		case IP_MULTICAST_IF:
10552 			/*
10553 			 * This option is an internal special. The socket
10554 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10555 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10556 			 * specifies an ifindex and we try first on V6 ill's.
10557 			 * If we don't find one, we they try using on v4 ill's
10558 			 * intenally and we come here.
10559 			 */
10560 			if (!checkonly && ill != NULL) {
10561 				ipif_t	*ipif;
10562 				ipif = ill->ill_ipif;
10563 
10564 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10565 					mutex_exit(&ill->ill_lock);
10566 					mutex_exit(&connp->conn_lock);
10567 					ill_refrele(ill);
10568 					ill = NULL;
10569 					mutex_enter(&connp->conn_lock);
10570 				} else {
10571 					connp->conn_multicast_ipif = ipif;
10572 				}
10573 			}
10574 			break;
10575 
10576 		case IP_DHCPINIT_IF:
10577 			if (connp->conn_dhcpinit_ill != NULL) {
10578 				/*
10579 				 * We've locked the conn so conn_cleanup_ill()
10580 				 * cannot clear conn_dhcpinit_ill -- so it's
10581 				 * safe to access the ill.
10582 				 */
10583 				ill_t *oill = connp->conn_dhcpinit_ill;
10584 
10585 				ASSERT(oill->ill_dhcpinit != 0);
10586 				atomic_dec_32(&oill->ill_dhcpinit);
10587 				connp->conn_dhcpinit_ill = NULL;
10588 			}
10589 
10590 			if (ill != NULL) {
10591 				connp->conn_dhcpinit_ill = ill;
10592 				atomic_inc_32(&ill->ill_dhcpinit);
10593 			}
10594 			break;
10595 		}
10596 	} else {
10597 		switch (option) {
10598 		case IPV6_BOUND_IF:
10599 			connp->conn_incoming_ill = ill;
10600 			connp->conn_outgoing_ill = ill;
10601 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10602 			    0 : ifindex;
10603 			break;
10604 
10605 		case IPV6_BOUND_PIF:
10606 			/*
10607 			 * Limit all transmit to this ill.
10608 			 * Unlike IPV6_BOUND_IF, using this option
10609 			 * prevents load spreading and failover from
10610 			 * happening when the interface is part of the
10611 			 * group. That's why we don't need to remember
10612 			 * the ifindex in orig_bound_ifindex as in
10613 			 * IPV6_BOUND_IF.
10614 			 */
10615 			connp->conn_outgoing_pill = ill;
10616 			break;
10617 
10618 		case IPV6_DONTFAILOVER_IF:
10619 			/*
10620 			 * This option is used by in.mpathd to ensure
10621 			 * that IPMP probe packets only go out on the
10622 			 * test interfaces. in.mpathd sets this option
10623 			 * on the non-failover interfaces.
10624 			 */
10625 			connp->conn_nofailover_ill = ill;
10626 			/*
10627 			 * For backward compatibility, this option
10628 			 * implicitly sets ip_multicast_ill as used in
10629 			 * IPV6_MULTICAST_IF so that ip_wput gets
10630 			 * this ill to send mcast packets.
10631 			 */
10632 			connp->conn_multicast_ill = ill;
10633 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10634 			    0 : ifindex;
10635 			break;
10636 
10637 		case IPV6_MULTICAST_IF:
10638 			/*
10639 			 * Set conn_multicast_ill to be the IPv6 ill.
10640 			 * Set conn_multicast_ipif to be an IPv4 ipif
10641 			 * for ifindex to make IPv4 mapped addresses
10642 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10643 			 * Even if no IPv6 ill exists for the ifindex
10644 			 * we need to check for an IPv4 ifindex in order
10645 			 * for this to work with mapped addresses. In that
10646 			 * case only set conn_multicast_ipif.
10647 			 */
10648 			if (!checkonly) {
10649 				if (ifindex == 0) {
10650 					connp->conn_multicast_ill = NULL;
10651 					connp->conn_orig_multicast_ifindex = 0;
10652 					connp->conn_multicast_ipif = NULL;
10653 				} else if (ill != NULL) {
10654 					connp->conn_multicast_ill = ill;
10655 					connp->conn_orig_multicast_ifindex =
10656 					    ifindex;
10657 				}
10658 			}
10659 			break;
10660 		}
10661 	}
10662 
10663 	if (ill != NULL) {
10664 		mutex_exit(&ill->ill_lock);
10665 		mutex_exit(&connp->conn_lock);
10666 		ill_refrele(ill);
10667 		return (0);
10668 	}
10669 	mutex_exit(&connp->conn_lock);
10670 	/*
10671 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10672 	 * locate the ill and could not set the option (ifindex != 0)
10673 	 */
10674 	return (ifindex == 0 ? 0 : EINVAL);
10675 }
10676 
10677 /* This routine sets socket options. */
10678 /* ARGSUSED */
10679 int
10680 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10681     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10682     void *dummy, cred_t *cr, mblk_t *first_mp)
10683 {
10684 	int		*i1 = (int *)invalp;
10685 	conn_t		*connp = Q_TO_CONN(q);
10686 	int		error = 0;
10687 	boolean_t	checkonly;
10688 	ire_t		*ire;
10689 	boolean_t	found;
10690 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10691 
10692 	switch (optset_context) {
10693 
10694 	case SETFN_OPTCOM_CHECKONLY:
10695 		checkonly = B_TRUE;
10696 		/*
10697 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10698 		 * inlen != 0 implies value supplied and
10699 		 * 	we have to "pretend" to set it.
10700 		 * inlen == 0 implies that there is no
10701 		 * 	value part in T_CHECK request and just validation
10702 		 * done elsewhere should be enough, we just return here.
10703 		 */
10704 		if (inlen == 0) {
10705 			*outlenp = 0;
10706 			return (0);
10707 		}
10708 		break;
10709 	case SETFN_OPTCOM_NEGOTIATE:
10710 	case SETFN_UD_NEGOTIATE:
10711 	case SETFN_CONN_NEGOTIATE:
10712 		checkonly = B_FALSE;
10713 		break;
10714 	default:
10715 		/*
10716 		 * We should never get here
10717 		 */
10718 		*outlenp = 0;
10719 		return (EINVAL);
10720 	}
10721 
10722 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10723 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10724 
10725 	/*
10726 	 * For fixed length options, no sanity check
10727 	 * of passed in length is done. It is assumed *_optcom_req()
10728 	 * routines do the right thing.
10729 	 */
10730 
10731 	switch (level) {
10732 	case SOL_SOCKET:
10733 		/*
10734 		 * conn_lock protects the bitfields, and is used to
10735 		 * set the fields atomically.
10736 		 */
10737 		switch (name) {
10738 		case SO_BROADCAST:
10739 			if (!checkonly) {
10740 				/* TODO: use value someplace? */
10741 				mutex_enter(&connp->conn_lock);
10742 				connp->conn_broadcast = *i1 ? 1 : 0;
10743 				mutex_exit(&connp->conn_lock);
10744 			}
10745 			break;	/* goto sizeof (int) option return */
10746 		case SO_USELOOPBACK:
10747 			if (!checkonly) {
10748 				/* TODO: use value someplace? */
10749 				mutex_enter(&connp->conn_lock);
10750 				connp->conn_loopback = *i1 ? 1 : 0;
10751 				mutex_exit(&connp->conn_lock);
10752 			}
10753 			break;	/* goto sizeof (int) option return */
10754 		case SO_DONTROUTE:
10755 			if (!checkonly) {
10756 				mutex_enter(&connp->conn_lock);
10757 				connp->conn_dontroute = *i1 ? 1 : 0;
10758 				mutex_exit(&connp->conn_lock);
10759 			}
10760 			break;	/* goto sizeof (int) option return */
10761 		case SO_REUSEADDR:
10762 			if (!checkonly) {
10763 				mutex_enter(&connp->conn_lock);
10764 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10765 				mutex_exit(&connp->conn_lock);
10766 			}
10767 			break;	/* goto sizeof (int) option return */
10768 		case SO_PROTOTYPE:
10769 			if (!checkonly) {
10770 				mutex_enter(&connp->conn_lock);
10771 				connp->conn_proto = *i1;
10772 				mutex_exit(&connp->conn_lock);
10773 			}
10774 			break;	/* goto sizeof (int) option return */
10775 		case SO_ALLZONES:
10776 			if (!checkonly) {
10777 				mutex_enter(&connp->conn_lock);
10778 				if (IPCL_IS_BOUND(connp)) {
10779 					mutex_exit(&connp->conn_lock);
10780 					return (EINVAL);
10781 				}
10782 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10783 				mutex_exit(&connp->conn_lock);
10784 			}
10785 			break;	/* goto sizeof (int) option return */
10786 		case SO_ANON_MLP:
10787 			if (!checkonly) {
10788 				mutex_enter(&connp->conn_lock);
10789 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10790 				mutex_exit(&connp->conn_lock);
10791 			}
10792 			break;	/* goto sizeof (int) option return */
10793 		case SO_MAC_EXEMPT:
10794 			if (secpolicy_net_mac_aware(cr) != 0 ||
10795 			    IPCL_IS_BOUND(connp))
10796 				return (EACCES);
10797 			if (!checkonly) {
10798 				mutex_enter(&connp->conn_lock);
10799 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10800 				mutex_exit(&connp->conn_lock);
10801 			}
10802 			break;	/* goto sizeof (int) option return */
10803 		default:
10804 			/*
10805 			 * "soft" error (negative)
10806 			 * option not handled at this level
10807 			 * Note: Do not modify *outlenp
10808 			 */
10809 			return (-EINVAL);
10810 		}
10811 		break;
10812 	case IPPROTO_IP:
10813 		switch (name) {
10814 		case IP_NEXTHOP:
10815 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10816 				return (EPERM);
10817 			/* FALLTHRU */
10818 		case IP_MULTICAST_IF:
10819 		case IP_DONTFAILOVER_IF: {
10820 			ipaddr_t addr = *i1;
10821 
10822 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10823 			    first_mp);
10824 			if (error != 0)
10825 				return (error);
10826 			break;	/* goto sizeof (int) option return */
10827 		}
10828 
10829 		case IP_MULTICAST_TTL:
10830 			/* Recorded in transport above IP */
10831 			*outvalp = *invalp;
10832 			*outlenp = sizeof (uchar_t);
10833 			return (0);
10834 		case IP_MULTICAST_LOOP:
10835 			if (!checkonly) {
10836 				mutex_enter(&connp->conn_lock);
10837 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10838 				mutex_exit(&connp->conn_lock);
10839 			}
10840 			*outvalp = *invalp;
10841 			*outlenp = sizeof (uchar_t);
10842 			return (0);
10843 		case IP_ADD_MEMBERSHIP:
10844 		case MCAST_JOIN_GROUP:
10845 		case IP_DROP_MEMBERSHIP:
10846 		case MCAST_LEAVE_GROUP: {
10847 			struct ip_mreq *mreqp;
10848 			struct group_req *greqp;
10849 			ire_t *ire;
10850 			boolean_t done = B_FALSE;
10851 			ipaddr_t group, ifaddr;
10852 			struct sockaddr_in *sin;
10853 			uint32_t *ifindexp;
10854 			boolean_t mcast_opt = B_TRUE;
10855 			mcast_record_t fmode;
10856 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10857 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10858 
10859 			switch (name) {
10860 			case IP_ADD_MEMBERSHIP:
10861 				mcast_opt = B_FALSE;
10862 				/* FALLTHRU */
10863 			case MCAST_JOIN_GROUP:
10864 				fmode = MODE_IS_EXCLUDE;
10865 				optfn = ip_opt_add_group;
10866 				break;
10867 
10868 			case IP_DROP_MEMBERSHIP:
10869 				mcast_opt = B_FALSE;
10870 				/* FALLTHRU */
10871 			case MCAST_LEAVE_GROUP:
10872 				fmode = MODE_IS_INCLUDE;
10873 				optfn = ip_opt_delete_group;
10874 				break;
10875 			}
10876 
10877 			if (mcast_opt) {
10878 				greqp = (struct group_req *)i1;
10879 				sin = (struct sockaddr_in *)&greqp->gr_group;
10880 				if (sin->sin_family != AF_INET) {
10881 					*outlenp = 0;
10882 					return (ENOPROTOOPT);
10883 				}
10884 				group = (ipaddr_t)sin->sin_addr.s_addr;
10885 				ifaddr = INADDR_ANY;
10886 				ifindexp = &greqp->gr_interface;
10887 			} else {
10888 				mreqp = (struct ip_mreq *)i1;
10889 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10890 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10891 				ifindexp = NULL;
10892 			}
10893 
10894 			/*
10895 			 * In the multirouting case, we need to replicate
10896 			 * the request on all interfaces that will take part
10897 			 * in replication.  We do so because multirouting is
10898 			 * reflective, thus we will probably receive multi-
10899 			 * casts on those interfaces.
10900 			 * The ip_multirt_apply_membership() succeeds if the
10901 			 * operation succeeds on at least one interface.
10902 			 */
10903 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10904 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10905 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10906 			if (ire != NULL) {
10907 				if (ire->ire_flags & RTF_MULTIRT) {
10908 					error = ip_multirt_apply_membership(
10909 					    optfn, ire, connp, checkonly, group,
10910 					    fmode, INADDR_ANY, first_mp);
10911 					done = B_TRUE;
10912 				}
10913 				ire_refrele(ire);
10914 			}
10915 			if (!done) {
10916 				error = optfn(connp, checkonly, group, ifaddr,
10917 				    ifindexp, fmode, INADDR_ANY, first_mp);
10918 			}
10919 			if (error) {
10920 				/*
10921 				 * EINPROGRESS is a soft error, needs retry
10922 				 * so don't make *outlenp zero.
10923 				 */
10924 				if (error != EINPROGRESS)
10925 					*outlenp = 0;
10926 				return (error);
10927 			}
10928 			/* OK return - copy input buffer into output buffer */
10929 			if (invalp != outvalp) {
10930 				/* don't trust bcopy for identical src/dst */
10931 				bcopy(invalp, outvalp, inlen);
10932 			}
10933 			*outlenp = inlen;
10934 			return (0);
10935 		}
10936 		case IP_BLOCK_SOURCE:
10937 		case IP_UNBLOCK_SOURCE:
10938 		case IP_ADD_SOURCE_MEMBERSHIP:
10939 		case IP_DROP_SOURCE_MEMBERSHIP:
10940 		case MCAST_BLOCK_SOURCE:
10941 		case MCAST_UNBLOCK_SOURCE:
10942 		case MCAST_JOIN_SOURCE_GROUP:
10943 		case MCAST_LEAVE_SOURCE_GROUP: {
10944 			struct ip_mreq_source *imreqp;
10945 			struct group_source_req *gsreqp;
10946 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10947 			uint32_t ifindex = 0;
10948 			mcast_record_t fmode;
10949 			struct sockaddr_in *sin;
10950 			ire_t *ire;
10951 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10952 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10953 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10954 
10955 			switch (name) {
10956 			case IP_BLOCK_SOURCE:
10957 				mcast_opt = B_FALSE;
10958 				/* FALLTHRU */
10959 			case MCAST_BLOCK_SOURCE:
10960 				fmode = MODE_IS_EXCLUDE;
10961 				optfn = ip_opt_add_group;
10962 				break;
10963 
10964 			case IP_UNBLOCK_SOURCE:
10965 				mcast_opt = B_FALSE;
10966 				/* FALLTHRU */
10967 			case MCAST_UNBLOCK_SOURCE:
10968 				fmode = MODE_IS_EXCLUDE;
10969 				optfn = ip_opt_delete_group;
10970 				break;
10971 
10972 			case IP_ADD_SOURCE_MEMBERSHIP:
10973 				mcast_opt = B_FALSE;
10974 				/* FALLTHRU */
10975 			case MCAST_JOIN_SOURCE_GROUP:
10976 				fmode = MODE_IS_INCLUDE;
10977 				optfn = ip_opt_add_group;
10978 				break;
10979 
10980 			case IP_DROP_SOURCE_MEMBERSHIP:
10981 				mcast_opt = B_FALSE;
10982 				/* FALLTHRU */
10983 			case MCAST_LEAVE_SOURCE_GROUP:
10984 				fmode = MODE_IS_INCLUDE;
10985 				optfn = ip_opt_delete_group;
10986 				break;
10987 			}
10988 
10989 			if (mcast_opt) {
10990 				gsreqp = (struct group_source_req *)i1;
10991 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10992 					*outlenp = 0;
10993 					return (ENOPROTOOPT);
10994 				}
10995 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10996 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10997 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10998 				src = (ipaddr_t)sin->sin_addr.s_addr;
10999 				ifindex = gsreqp->gsr_interface;
11000 			} else {
11001 				imreqp = (struct ip_mreq_source *)i1;
11002 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
11003 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
11004 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
11005 			}
11006 
11007 			/*
11008 			 * In the multirouting case, we need to replicate
11009 			 * the request as noted in the mcast cases above.
11010 			 */
11011 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
11012 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11013 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11014 			if (ire != NULL) {
11015 				if (ire->ire_flags & RTF_MULTIRT) {
11016 					error = ip_multirt_apply_membership(
11017 					    optfn, ire, connp, checkonly, grp,
11018 					    fmode, src, first_mp);
11019 					done = B_TRUE;
11020 				}
11021 				ire_refrele(ire);
11022 			}
11023 			if (!done) {
11024 				error = optfn(connp, checkonly, grp, ifaddr,
11025 				    &ifindex, fmode, src, first_mp);
11026 			}
11027 			if (error != 0) {
11028 				/*
11029 				 * EINPROGRESS is a soft error, needs retry
11030 				 * so don't make *outlenp zero.
11031 				 */
11032 				if (error != EINPROGRESS)
11033 					*outlenp = 0;
11034 				return (error);
11035 			}
11036 			/* OK return - copy input buffer into output buffer */
11037 			if (invalp != outvalp) {
11038 				bcopy(invalp, outvalp, inlen);
11039 			}
11040 			*outlenp = inlen;
11041 			return (0);
11042 		}
11043 		case IP_SEC_OPT:
11044 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11045 			if (error != 0) {
11046 				*outlenp = 0;
11047 				return (error);
11048 			}
11049 			break;
11050 		case IP_HDRINCL:
11051 		case IP_OPTIONS:
11052 		case T_IP_OPTIONS:
11053 		case IP_TOS:
11054 		case T_IP_TOS:
11055 		case IP_TTL:
11056 		case IP_RECVDSTADDR:
11057 		case IP_RECVOPTS:
11058 			/* OK return - copy input buffer into output buffer */
11059 			if (invalp != outvalp) {
11060 				/* don't trust bcopy for identical src/dst */
11061 				bcopy(invalp, outvalp, inlen);
11062 			}
11063 			*outlenp = inlen;
11064 			return (0);
11065 		case IP_RECVIF:
11066 			/* Retrieve the inbound interface index */
11067 			if (!checkonly) {
11068 				mutex_enter(&connp->conn_lock);
11069 				connp->conn_recvif = *i1 ? 1 : 0;
11070 				mutex_exit(&connp->conn_lock);
11071 			}
11072 			break;	/* goto sizeof (int) option return */
11073 		case IP_RECVPKTINFO:
11074 			if (!checkonly) {
11075 				mutex_enter(&connp->conn_lock);
11076 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11077 				mutex_exit(&connp->conn_lock);
11078 			}
11079 			break;	/* goto sizeof (int) option return */
11080 		case IP_RECVSLLA:
11081 			/* Retrieve the source link layer address */
11082 			if (!checkonly) {
11083 				mutex_enter(&connp->conn_lock);
11084 				connp->conn_recvslla = *i1 ? 1 : 0;
11085 				mutex_exit(&connp->conn_lock);
11086 			}
11087 			break;	/* goto sizeof (int) option return */
11088 		case MRT_INIT:
11089 		case MRT_DONE:
11090 		case MRT_ADD_VIF:
11091 		case MRT_DEL_VIF:
11092 		case MRT_ADD_MFC:
11093 		case MRT_DEL_MFC:
11094 		case MRT_ASSERT:
11095 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11096 				*outlenp = 0;
11097 				return (error);
11098 			}
11099 			error = ip_mrouter_set((int)name, q, checkonly,
11100 			    (uchar_t *)invalp, inlen, first_mp);
11101 			if (error) {
11102 				*outlenp = 0;
11103 				return (error);
11104 			}
11105 			/* OK return - copy input buffer into output buffer */
11106 			if (invalp != outvalp) {
11107 				/* don't trust bcopy for identical src/dst */
11108 				bcopy(invalp, outvalp, inlen);
11109 			}
11110 			*outlenp = inlen;
11111 			return (0);
11112 		case IP_BOUND_IF:
11113 		case IP_DHCPINIT_IF:
11114 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11115 			    level, name, first_mp);
11116 			if (error != 0)
11117 				return (error);
11118 			break; 		/* goto sizeof (int) option return */
11119 
11120 		case IP_UNSPEC_SRC:
11121 			/* Allow sending with a zero source address */
11122 			if (!checkonly) {
11123 				mutex_enter(&connp->conn_lock);
11124 				connp->conn_unspec_src = *i1 ? 1 : 0;
11125 				mutex_exit(&connp->conn_lock);
11126 			}
11127 			break;	/* goto sizeof (int) option return */
11128 		default:
11129 			/*
11130 			 * "soft" error (negative)
11131 			 * option not handled at this level
11132 			 * Note: Do not modify *outlenp
11133 			 */
11134 			return (-EINVAL);
11135 		}
11136 		break;
11137 	case IPPROTO_IPV6:
11138 		switch (name) {
11139 		case IPV6_BOUND_IF:
11140 		case IPV6_BOUND_PIF:
11141 		case IPV6_DONTFAILOVER_IF:
11142 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11143 			    level, name, first_mp);
11144 			if (error != 0)
11145 				return (error);
11146 			break; 		/* goto sizeof (int) option return */
11147 
11148 		case IPV6_MULTICAST_IF:
11149 			/*
11150 			 * The only possible errors are EINPROGRESS and
11151 			 * EINVAL. EINPROGRESS will be restarted and is not
11152 			 * a hard error. We call this option on both V4 and V6
11153 			 * If both return EINVAL, then this call returns
11154 			 * EINVAL. If at least one of them succeeds we
11155 			 * return success.
11156 			 */
11157 			found = B_FALSE;
11158 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11159 			    level, name, first_mp);
11160 			if (error == EINPROGRESS)
11161 				return (error);
11162 			if (error == 0)
11163 				found = B_TRUE;
11164 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11165 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11166 			if (error == 0)
11167 				found = B_TRUE;
11168 			if (!found)
11169 				return (error);
11170 			break; 		/* goto sizeof (int) option return */
11171 
11172 		case IPV6_MULTICAST_HOPS:
11173 			/* Recorded in transport above IP */
11174 			break;	/* goto sizeof (int) option return */
11175 		case IPV6_MULTICAST_LOOP:
11176 			if (!checkonly) {
11177 				mutex_enter(&connp->conn_lock);
11178 				connp->conn_multicast_loop = *i1;
11179 				mutex_exit(&connp->conn_lock);
11180 			}
11181 			break;	/* goto sizeof (int) option return */
11182 		case IPV6_JOIN_GROUP:
11183 		case MCAST_JOIN_GROUP:
11184 		case IPV6_LEAVE_GROUP:
11185 		case MCAST_LEAVE_GROUP: {
11186 			struct ipv6_mreq *ip_mreqp;
11187 			struct group_req *greqp;
11188 			ire_t *ire;
11189 			boolean_t done = B_FALSE;
11190 			in6_addr_t groupv6;
11191 			uint32_t ifindex;
11192 			boolean_t mcast_opt = B_TRUE;
11193 			mcast_record_t fmode;
11194 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11195 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11196 
11197 			switch (name) {
11198 			case IPV6_JOIN_GROUP:
11199 				mcast_opt = B_FALSE;
11200 				/* FALLTHRU */
11201 			case MCAST_JOIN_GROUP:
11202 				fmode = MODE_IS_EXCLUDE;
11203 				optfn = ip_opt_add_group_v6;
11204 				break;
11205 
11206 			case IPV6_LEAVE_GROUP:
11207 				mcast_opt = B_FALSE;
11208 				/* FALLTHRU */
11209 			case MCAST_LEAVE_GROUP:
11210 				fmode = MODE_IS_INCLUDE;
11211 				optfn = ip_opt_delete_group_v6;
11212 				break;
11213 			}
11214 
11215 			if (mcast_opt) {
11216 				struct sockaddr_in *sin;
11217 				struct sockaddr_in6 *sin6;
11218 				greqp = (struct group_req *)i1;
11219 				if (greqp->gr_group.ss_family == AF_INET) {
11220 					sin = (struct sockaddr_in *)
11221 					    &(greqp->gr_group);
11222 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11223 					    &groupv6);
11224 				} else {
11225 					sin6 = (struct sockaddr_in6 *)
11226 					    &(greqp->gr_group);
11227 					groupv6 = sin6->sin6_addr;
11228 				}
11229 				ifindex = greqp->gr_interface;
11230 			} else {
11231 				ip_mreqp = (struct ipv6_mreq *)i1;
11232 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11233 				ifindex = ip_mreqp->ipv6mr_interface;
11234 			}
11235 			/*
11236 			 * In the multirouting case, we need to replicate
11237 			 * the request on all interfaces that will take part
11238 			 * in replication.  We do so because multirouting is
11239 			 * reflective, thus we will probably receive multi-
11240 			 * casts on those interfaces.
11241 			 * The ip_multirt_apply_membership_v6() succeeds if
11242 			 * the operation succeeds on at least one interface.
11243 			 */
11244 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11245 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11246 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11247 			if (ire != NULL) {
11248 				if (ire->ire_flags & RTF_MULTIRT) {
11249 					error = ip_multirt_apply_membership_v6(
11250 					    optfn, ire, connp, checkonly,
11251 					    &groupv6, fmode, &ipv6_all_zeros,
11252 					    first_mp);
11253 					done = B_TRUE;
11254 				}
11255 				ire_refrele(ire);
11256 			}
11257 			if (!done) {
11258 				error = optfn(connp, checkonly, &groupv6,
11259 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11260 			}
11261 			if (error) {
11262 				/*
11263 				 * EINPROGRESS is a soft error, needs retry
11264 				 * so don't make *outlenp zero.
11265 				 */
11266 				if (error != EINPROGRESS)
11267 					*outlenp = 0;
11268 				return (error);
11269 			}
11270 			/* OK return - copy input buffer into output buffer */
11271 			if (invalp != outvalp) {
11272 				/* don't trust bcopy for identical src/dst */
11273 				bcopy(invalp, outvalp, inlen);
11274 			}
11275 			*outlenp = inlen;
11276 			return (0);
11277 		}
11278 		case MCAST_BLOCK_SOURCE:
11279 		case MCAST_UNBLOCK_SOURCE:
11280 		case MCAST_JOIN_SOURCE_GROUP:
11281 		case MCAST_LEAVE_SOURCE_GROUP: {
11282 			struct group_source_req *gsreqp;
11283 			in6_addr_t v6grp, v6src;
11284 			uint32_t ifindex;
11285 			mcast_record_t fmode;
11286 			ire_t *ire;
11287 			boolean_t done = B_FALSE;
11288 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11289 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11290 
11291 			switch (name) {
11292 			case MCAST_BLOCK_SOURCE:
11293 				fmode = MODE_IS_EXCLUDE;
11294 				optfn = ip_opt_add_group_v6;
11295 				break;
11296 			case MCAST_UNBLOCK_SOURCE:
11297 				fmode = MODE_IS_EXCLUDE;
11298 				optfn = ip_opt_delete_group_v6;
11299 				break;
11300 			case MCAST_JOIN_SOURCE_GROUP:
11301 				fmode = MODE_IS_INCLUDE;
11302 				optfn = ip_opt_add_group_v6;
11303 				break;
11304 			case MCAST_LEAVE_SOURCE_GROUP:
11305 				fmode = MODE_IS_INCLUDE;
11306 				optfn = ip_opt_delete_group_v6;
11307 				break;
11308 			}
11309 
11310 			gsreqp = (struct group_source_req *)i1;
11311 			ifindex = gsreqp->gsr_interface;
11312 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11313 				struct sockaddr_in *s;
11314 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11315 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11316 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11317 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11318 			} else {
11319 				struct sockaddr_in6 *s6;
11320 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11321 				v6grp = s6->sin6_addr;
11322 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11323 				v6src = s6->sin6_addr;
11324 			}
11325 
11326 			/*
11327 			 * In the multirouting case, we need to replicate
11328 			 * the request as noted in the mcast cases above.
11329 			 */
11330 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11331 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11332 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11333 			if (ire != NULL) {
11334 				if (ire->ire_flags & RTF_MULTIRT) {
11335 					error = ip_multirt_apply_membership_v6(
11336 					    optfn, ire, connp, checkonly,
11337 					    &v6grp, fmode, &v6src, first_mp);
11338 					done = B_TRUE;
11339 				}
11340 				ire_refrele(ire);
11341 			}
11342 			if (!done) {
11343 				error = optfn(connp, checkonly, &v6grp,
11344 				    ifindex, fmode, &v6src, first_mp);
11345 			}
11346 			if (error != 0) {
11347 				/*
11348 				 * EINPROGRESS is a soft error, needs retry
11349 				 * so don't make *outlenp zero.
11350 				 */
11351 				if (error != EINPROGRESS)
11352 					*outlenp = 0;
11353 				return (error);
11354 			}
11355 			/* OK return - copy input buffer into output buffer */
11356 			if (invalp != outvalp) {
11357 				bcopy(invalp, outvalp, inlen);
11358 			}
11359 			*outlenp = inlen;
11360 			return (0);
11361 		}
11362 		case IPV6_UNICAST_HOPS:
11363 			/* Recorded in transport above IP */
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_UNSPEC_SRC:
11366 			/* Allow sending with a zero source address */
11367 			if (!checkonly) {
11368 				mutex_enter(&connp->conn_lock);
11369 				connp->conn_unspec_src = *i1 ? 1 : 0;
11370 				mutex_exit(&connp->conn_lock);
11371 			}
11372 			break;	/* goto sizeof (int) option return */
11373 		case IPV6_RECVPKTINFO:
11374 			if (!checkonly) {
11375 				mutex_enter(&connp->conn_lock);
11376 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11377 				mutex_exit(&connp->conn_lock);
11378 			}
11379 			break;	/* goto sizeof (int) option return */
11380 		case IPV6_RECVTCLASS:
11381 			if (!checkonly) {
11382 				if (*i1 < 0 || *i1 > 1) {
11383 					return (EINVAL);
11384 				}
11385 				mutex_enter(&connp->conn_lock);
11386 				connp->conn_ipv6_recvtclass = *i1;
11387 				mutex_exit(&connp->conn_lock);
11388 			}
11389 			break;
11390 		case IPV6_RECVPATHMTU:
11391 			if (!checkonly) {
11392 				if (*i1 < 0 || *i1 > 1) {
11393 					return (EINVAL);
11394 				}
11395 				mutex_enter(&connp->conn_lock);
11396 				connp->conn_ipv6_recvpathmtu = *i1;
11397 				mutex_exit(&connp->conn_lock);
11398 			}
11399 			break;
11400 		case IPV6_RECVHOPLIMIT:
11401 			if (!checkonly) {
11402 				mutex_enter(&connp->conn_lock);
11403 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11404 				mutex_exit(&connp->conn_lock);
11405 			}
11406 			break;	/* goto sizeof (int) option return */
11407 		case IPV6_RECVHOPOPTS:
11408 			if (!checkonly) {
11409 				mutex_enter(&connp->conn_lock);
11410 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11411 				mutex_exit(&connp->conn_lock);
11412 			}
11413 			break;	/* goto sizeof (int) option return */
11414 		case IPV6_RECVDSTOPTS:
11415 			if (!checkonly) {
11416 				mutex_enter(&connp->conn_lock);
11417 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11418 				mutex_exit(&connp->conn_lock);
11419 			}
11420 			break;	/* goto sizeof (int) option return */
11421 		case IPV6_RECVRTHDR:
11422 			if (!checkonly) {
11423 				mutex_enter(&connp->conn_lock);
11424 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11425 				mutex_exit(&connp->conn_lock);
11426 			}
11427 			break;	/* goto sizeof (int) option return */
11428 		case IPV6_RECVRTHDRDSTOPTS:
11429 			if (!checkonly) {
11430 				mutex_enter(&connp->conn_lock);
11431 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11432 				mutex_exit(&connp->conn_lock);
11433 			}
11434 			break;	/* goto sizeof (int) option return */
11435 		case IPV6_PKTINFO:
11436 			if (inlen == 0)
11437 				return (-EINVAL);	/* clearing option */
11438 			error = ip6_set_pktinfo(cr, connp,
11439 			    (struct in6_pktinfo *)invalp, first_mp);
11440 			if (error != 0)
11441 				*outlenp = 0;
11442 			else
11443 				*outlenp = inlen;
11444 			return (error);
11445 		case IPV6_NEXTHOP: {
11446 			struct sockaddr_in6 *sin6;
11447 
11448 			/* Verify that the nexthop is reachable */
11449 			if (inlen == 0)
11450 				return (-EINVAL);	/* clearing option */
11451 
11452 			sin6 = (struct sockaddr_in6 *)invalp;
11453 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11454 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11455 			    NULL, MATCH_IRE_DEFAULT, ipst);
11456 
11457 			if (ire == NULL) {
11458 				*outlenp = 0;
11459 				return (EHOSTUNREACH);
11460 			}
11461 			ire_refrele(ire);
11462 			return (-EINVAL);
11463 		}
11464 		case IPV6_SEC_OPT:
11465 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11466 			if (error != 0) {
11467 				*outlenp = 0;
11468 				return (error);
11469 			}
11470 			break;
11471 		case IPV6_SRC_PREFERENCES: {
11472 			/*
11473 			 * This is implemented strictly in the ip module
11474 			 * (here and in tcp_opt_*() to accomodate tcp
11475 			 * sockets).  Modules above ip pass this option
11476 			 * down here since ip is the only one that needs to
11477 			 * be aware of source address preferences.
11478 			 *
11479 			 * This socket option only affects connected
11480 			 * sockets that haven't already bound to a specific
11481 			 * IPv6 address.  In other words, sockets that
11482 			 * don't call bind() with an address other than the
11483 			 * unspecified address and that call connect().
11484 			 * ip_bind_connected_v6() passes these preferences
11485 			 * to the ipif_select_source_v6() function.
11486 			 */
11487 			if (inlen != sizeof (uint32_t))
11488 				return (EINVAL);
11489 			error = ip6_set_src_preferences(connp,
11490 			    *(uint32_t *)invalp);
11491 			if (error != 0) {
11492 				*outlenp = 0;
11493 				return (error);
11494 			} else {
11495 				*outlenp = sizeof (uint32_t);
11496 			}
11497 			break;
11498 		}
11499 		case IPV6_V6ONLY:
11500 			if (*i1 < 0 || *i1 > 1) {
11501 				return (EINVAL);
11502 			}
11503 			mutex_enter(&connp->conn_lock);
11504 			connp->conn_ipv6_v6only = *i1;
11505 			mutex_exit(&connp->conn_lock);
11506 			break;
11507 		default:
11508 			return (-EINVAL);
11509 		}
11510 		break;
11511 	default:
11512 		/*
11513 		 * "soft" error (negative)
11514 		 * option not handled at this level
11515 		 * Note: Do not modify *outlenp
11516 		 */
11517 		return (-EINVAL);
11518 	}
11519 	/*
11520 	 * Common case of return from an option that is sizeof (int)
11521 	 */
11522 	*(int *)outvalp = *i1;
11523 	*outlenp = sizeof (int);
11524 	return (0);
11525 }
11526 
11527 /*
11528  * This routine gets default values of certain options whose default
11529  * values are maintained by protocol specific code
11530  */
11531 /* ARGSUSED */
11532 int
11533 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11534 {
11535 	int *i1 = (int *)ptr;
11536 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11537 
11538 	switch (level) {
11539 	case IPPROTO_IP:
11540 		switch (name) {
11541 		case IP_MULTICAST_TTL:
11542 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11543 			return (sizeof (uchar_t));
11544 		case IP_MULTICAST_LOOP:
11545 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11546 			return (sizeof (uchar_t));
11547 		default:
11548 			return (-1);
11549 		}
11550 	case IPPROTO_IPV6:
11551 		switch (name) {
11552 		case IPV6_UNICAST_HOPS:
11553 			*i1 = ipst->ips_ipv6_def_hops;
11554 			return (sizeof (int));
11555 		case IPV6_MULTICAST_HOPS:
11556 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11557 			return (sizeof (int));
11558 		case IPV6_MULTICAST_LOOP:
11559 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11560 			return (sizeof (int));
11561 		case IPV6_V6ONLY:
11562 			*i1 = 1;
11563 			return (sizeof (int));
11564 		default:
11565 			return (-1);
11566 		}
11567 	default:
11568 		return (-1);
11569 	}
11570 	/* NOTREACHED */
11571 }
11572 
11573 /*
11574  * Given a destination address and a pointer to where to put the information
11575  * this routine fills in the mtuinfo.
11576  */
11577 int
11578 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11579     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11580 {
11581 	ire_t *ire;
11582 	ip_stack_t	*ipst = ns->netstack_ip;
11583 
11584 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11585 		return (-1);
11586 
11587 	bzero(mtuinfo, sizeof (*mtuinfo));
11588 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11589 	mtuinfo->ip6m_addr.sin6_port = port;
11590 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11591 
11592 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11593 	if (ire != NULL) {
11594 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11595 		ire_refrele(ire);
11596 	} else {
11597 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11598 	}
11599 	return (sizeof (struct ip6_mtuinfo));
11600 }
11601 
11602 /*
11603  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11604  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11605  * isn't.  This doesn't matter as the error checking is done properly for the
11606  * other MRT options coming in through ip_opt_set.
11607  */
11608 int
11609 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11610 {
11611 	conn_t		*connp = Q_TO_CONN(q);
11612 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11613 
11614 	switch (level) {
11615 	case IPPROTO_IP:
11616 		switch (name) {
11617 		case MRT_VERSION:
11618 		case MRT_ASSERT:
11619 			(void) ip_mrouter_get(name, q, ptr);
11620 			return (sizeof (int));
11621 		case IP_SEC_OPT:
11622 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11623 		case IP_NEXTHOP:
11624 			if (connp->conn_nexthop_set) {
11625 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11626 				return (sizeof (ipaddr_t));
11627 			} else
11628 				return (0);
11629 		case IP_RECVPKTINFO:
11630 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11631 			return (sizeof (int));
11632 		default:
11633 			break;
11634 		}
11635 		break;
11636 	case IPPROTO_IPV6:
11637 		switch (name) {
11638 		case IPV6_SEC_OPT:
11639 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11640 		case IPV6_SRC_PREFERENCES: {
11641 			return (ip6_get_src_preferences(connp,
11642 			    (uint32_t *)ptr));
11643 		}
11644 		case IPV6_V6ONLY:
11645 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11646 			return (sizeof (int));
11647 		case IPV6_PATHMTU:
11648 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11649 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11650 		default:
11651 			break;
11652 		}
11653 		break;
11654 	default:
11655 		break;
11656 	}
11657 	return (-1);
11658 }
11659 
11660 /* Named Dispatch routine to get a current value out of our parameter table. */
11661 /* ARGSUSED */
11662 static int
11663 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11664 {
11665 	ipparam_t *ippa = (ipparam_t *)cp;
11666 
11667 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11668 	return (0);
11669 }
11670 
11671 /* ARGSUSED */
11672 static int
11673 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11674 {
11675 
11676 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11677 	return (0);
11678 }
11679 
11680 /*
11681  * Set ip{,6}_forwarding values.  This means walking through all of the
11682  * ill's and toggling their forwarding values.
11683  */
11684 /* ARGSUSED */
11685 static int
11686 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11687 {
11688 	long new_value;
11689 	int *forwarding_value = (int *)cp;
11690 	ill_t *ill;
11691 	boolean_t isv6;
11692 	ill_walk_context_t ctx;
11693 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11694 
11695 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11696 
11697 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11698 	    new_value < 0 || new_value > 1) {
11699 		return (EINVAL);
11700 	}
11701 
11702 	*forwarding_value = new_value;
11703 
11704 	/*
11705 	 * Regardless of the current value of ip_forwarding, set all per-ill
11706 	 * values of ip_forwarding to the value being set.
11707 	 *
11708 	 * Bring all the ill's up to date with the new global value.
11709 	 */
11710 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11711 
11712 	if (isv6)
11713 		ill = ILL_START_WALK_V6(&ctx, ipst);
11714 	else
11715 		ill = ILL_START_WALK_V4(&ctx, ipst);
11716 
11717 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11718 		(void) ill_forward_set(ill, new_value != 0);
11719 
11720 	rw_exit(&ipst->ips_ill_g_lock);
11721 	return (0);
11722 }
11723 
11724 /*
11725  * Walk through the param array specified registering each element with the
11726  * Named Dispatch handler. This is called only during init. So it is ok
11727  * not to acquire any locks
11728  */
11729 static boolean_t
11730 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11731     ipndp_t *ipnd, size_t ipnd_cnt)
11732 {
11733 	for (; ippa_cnt-- > 0; ippa++) {
11734 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11735 			if (!nd_load(ndp, ippa->ip_param_name,
11736 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11737 				nd_free(ndp);
11738 				return (B_FALSE);
11739 			}
11740 		}
11741 	}
11742 
11743 	for (; ipnd_cnt-- > 0; ipnd++) {
11744 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11745 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11746 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11747 			    ipnd->ip_ndp_data)) {
11748 				nd_free(ndp);
11749 				return (B_FALSE);
11750 			}
11751 		}
11752 	}
11753 
11754 	return (B_TRUE);
11755 }
11756 
11757 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11758 /* ARGSUSED */
11759 static int
11760 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11761 {
11762 	long		new_value;
11763 	ipparam_t	*ippa = (ipparam_t *)cp;
11764 
11765 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11766 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11767 		return (EINVAL);
11768 	}
11769 	ippa->ip_param_value = new_value;
11770 	return (0);
11771 }
11772 
11773 /*
11774  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11775  * When an ipf is passed here for the first time, if
11776  * we already have in-order fragments on the queue, we convert from the fast-
11777  * path reassembly scheme to the hard-case scheme.  From then on, additional
11778  * fragments are reassembled here.  We keep track of the start and end offsets
11779  * of each piece, and the number of holes in the chain.  When the hole count
11780  * goes to zero, we are done!
11781  *
11782  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11783  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11784  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11785  * after the call to ip_reassemble().
11786  */
11787 int
11788 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11789     size_t msg_len)
11790 {
11791 	uint_t	end;
11792 	mblk_t	*next_mp;
11793 	mblk_t	*mp1;
11794 	uint_t	offset;
11795 	boolean_t incr_dups = B_TRUE;
11796 	boolean_t offset_zero_seen = B_FALSE;
11797 	boolean_t pkt_boundary_checked = B_FALSE;
11798 
11799 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11800 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11801 
11802 	/* Add in byte count */
11803 	ipf->ipf_count += msg_len;
11804 	if (ipf->ipf_end) {
11805 		/*
11806 		 * We were part way through in-order reassembly, but now there
11807 		 * is a hole.  We walk through messages already queued, and
11808 		 * mark them for hard case reassembly.  We know that up till
11809 		 * now they were in order starting from offset zero.
11810 		 */
11811 		offset = 0;
11812 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11813 			IP_REASS_SET_START(mp1, offset);
11814 			if (offset == 0) {
11815 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11816 				offset = -ipf->ipf_nf_hdr_len;
11817 			}
11818 			offset += mp1->b_wptr - mp1->b_rptr;
11819 			IP_REASS_SET_END(mp1, offset);
11820 		}
11821 		/* One hole at the end. */
11822 		ipf->ipf_hole_cnt = 1;
11823 		/* Brand it as a hard case, forever. */
11824 		ipf->ipf_end = 0;
11825 	}
11826 	/* Walk through all the new pieces. */
11827 	do {
11828 		end = start + (mp->b_wptr - mp->b_rptr);
11829 		/*
11830 		 * If start is 0, decrease 'end' only for the first mblk of
11831 		 * the fragment. Otherwise 'end' can get wrong value in the
11832 		 * second pass of the loop if first mblk is exactly the
11833 		 * size of ipf_nf_hdr_len.
11834 		 */
11835 		if (start == 0 && !offset_zero_seen) {
11836 			/* First segment */
11837 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11838 			end -= ipf->ipf_nf_hdr_len;
11839 			offset_zero_seen = B_TRUE;
11840 		}
11841 		next_mp = mp->b_cont;
11842 		/*
11843 		 * We are checking to see if there is any interesing data
11844 		 * to process.  If there isn't and the mblk isn't the
11845 		 * one which carries the unfragmentable header then we
11846 		 * drop it.  It's possible to have just the unfragmentable
11847 		 * header come through without any data.  That needs to be
11848 		 * saved.
11849 		 *
11850 		 * If the assert at the top of this function holds then the
11851 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11852 		 * is infrequently traveled enough that the test is left in
11853 		 * to protect against future code changes which break that
11854 		 * invariant.
11855 		 */
11856 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11857 			/* Empty.  Blast it. */
11858 			IP_REASS_SET_START(mp, 0);
11859 			IP_REASS_SET_END(mp, 0);
11860 			/*
11861 			 * If the ipf points to the mblk we are about to free,
11862 			 * update ipf to point to the next mblk (or NULL
11863 			 * if none).
11864 			 */
11865 			if (ipf->ipf_mp->b_cont == mp)
11866 				ipf->ipf_mp->b_cont = next_mp;
11867 			freeb(mp);
11868 			continue;
11869 		}
11870 		mp->b_cont = NULL;
11871 		IP_REASS_SET_START(mp, start);
11872 		IP_REASS_SET_END(mp, end);
11873 		if (!ipf->ipf_tail_mp) {
11874 			ipf->ipf_tail_mp = mp;
11875 			ipf->ipf_mp->b_cont = mp;
11876 			if (start == 0 || !more) {
11877 				ipf->ipf_hole_cnt = 1;
11878 				/*
11879 				 * if the first fragment comes in more than one
11880 				 * mblk, this loop will be executed for each
11881 				 * mblk. Need to adjust hole count so exiting
11882 				 * this routine will leave hole count at 1.
11883 				 */
11884 				if (next_mp)
11885 					ipf->ipf_hole_cnt++;
11886 			} else
11887 				ipf->ipf_hole_cnt = 2;
11888 			continue;
11889 		} else if (ipf->ipf_last_frag_seen && !more &&
11890 		    !pkt_boundary_checked) {
11891 			/*
11892 			 * We check datagram boundary only if this fragment
11893 			 * claims to be the last fragment and we have seen a
11894 			 * last fragment in the past too. We do this only
11895 			 * once for a given fragment.
11896 			 *
11897 			 * start cannot be 0 here as fragments with start=0
11898 			 * and MF=0 gets handled as a complete packet. These
11899 			 * fragments should not reach here.
11900 			 */
11901 
11902 			if (start + msgdsize(mp) !=
11903 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11904 				/*
11905 				 * We have two fragments both of which claim
11906 				 * to be the last fragment but gives conflicting
11907 				 * information about the whole datagram size.
11908 				 * Something fishy is going on. Drop the
11909 				 * fragment and free up the reassembly list.
11910 				 */
11911 				return (IP_REASS_FAILED);
11912 			}
11913 
11914 			/*
11915 			 * We shouldn't come to this code block again for this
11916 			 * particular fragment.
11917 			 */
11918 			pkt_boundary_checked = B_TRUE;
11919 		}
11920 
11921 		/* New stuff at or beyond tail? */
11922 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11923 		if (start >= offset) {
11924 			if (ipf->ipf_last_frag_seen) {
11925 				/* current fragment is beyond last fragment */
11926 				return (IP_REASS_FAILED);
11927 			}
11928 			/* Link it on end. */
11929 			ipf->ipf_tail_mp->b_cont = mp;
11930 			ipf->ipf_tail_mp = mp;
11931 			if (more) {
11932 				if (start != offset)
11933 					ipf->ipf_hole_cnt++;
11934 			} else if (start == offset && next_mp == NULL)
11935 					ipf->ipf_hole_cnt--;
11936 			continue;
11937 		}
11938 		mp1 = ipf->ipf_mp->b_cont;
11939 		offset = IP_REASS_START(mp1);
11940 		/* New stuff at the front? */
11941 		if (start < offset) {
11942 			if (start == 0) {
11943 				if (end >= offset) {
11944 					/* Nailed the hole at the begining. */
11945 					ipf->ipf_hole_cnt--;
11946 				}
11947 			} else if (end < offset) {
11948 				/*
11949 				 * A hole, stuff, and a hole where there used
11950 				 * to be just a hole.
11951 				 */
11952 				ipf->ipf_hole_cnt++;
11953 			}
11954 			mp->b_cont = mp1;
11955 			/* Check for overlap. */
11956 			while (end > offset) {
11957 				if (end < IP_REASS_END(mp1)) {
11958 					mp->b_wptr -= end - offset;
11959 					IP_REASS_SET_END(mp, offset);
11960 					BUMP_MIB(ill->ill_ip_mib,
11961 					    ipIfStatsReasmPartDups);
11962 					break;
11963 				}
11964 				/* Did we cover another hole? */
11965 				if ((mp1->b_cont &&
11966 				    IP_REASS_END(mp1) !=
11967 				    IP_REASS_START(mp1->b_cont) &&
11968 				    end >= IP_REASS_START(mp1->b_cont)) ||
11969 				    (!ipf->ipf_last_frag_seen && !more)) {
11970 					ipf->ipf_hole_cnt--;
11971 				}
11972 				/* Clip out mp1. */
11973 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11974 					/*
11975 					 * After clipping out mp1, this guy
11976 					 * is now hanging off the end.
11977 					 */
11978 					ipf->ipf_tail_mp = mp;
11979 				}
11980 				IP_REASS_SET_START(mp1, 0);
11981 				IP_REASS_SET_END(mp1, 0);
11982 				/* Subtract byte count */
11983 				ipf->ipf_count -= mp1->b_datap->db_lim -
11984 				    mp1->b_datap->db_base;
11985 				freeb(mp1);
11986 				BUMP_MIB(ill->ill_ip_mib,
11987 				    ipIfStatsReasmPartDups);
11988 				mp1 = mp->b_cont;
11989 				if (!mp1)
11990 					break;
11991 				offset = IP_REASS_START(mp1);
11992 			}
11993 			ipf->ipf_mp->b_cont = mp;
11994 			continue;
11995 		}
11996 		/*
11997 		 * The new piece starts somewhere between the start of the head
11998 		 * and before the end of the tail.
11999 		 */
12000 		for (; mp1; mp1 = mp1->b_cont) {
12001 			offset = IP_REASS_END(mp1);
12002 			if (start < offset) {
12003 				if (end <= offset) {
12004 					/* Nothing new. */
12005 					IP_REASS_SET_START(mp, 0);
12006 					IP_REASS_SET_END(mp, 0);
12007 					/* Subtract byte count */
12008 					ipf->ipf_count -= mp->b_datap->db_lim -
12009 					    mp->b_datap->db_base;
12010 					if (incr_dups) {
12011 						ipf->ipf_num_dups++;
12012 						incr_dups = B_FALSE;
12013 					}
12014 					freeb(mp);
12015 					BUMP_MIB(ill->ill_ip_mib,
12016 					    ipIfStatsReasmDuplicates);
12017 					break;
12018 				}
12019 				/*
12020 				 * Trim redundant stuff off beginning of new
12021 				 * piece.
12022 				 */
12023 				IP_REASS_SET_START(mp, offset);
12024 				mp->b_rptr += offset - start;
12025 				BUMP_MIB(ill->ill_ip_mib,
12026 				    ipIfStatsReasmPartDups);
12027 				start = offset;
12028 				if (!mp1->b_cont) {
12029 					/*
12030 					 * After trimming, this guy is now
12031 					 * hanging off the end.
12032 					 */
12033 					mp1->b_cont = mp;
12034 					ipf->ipf_tail_mp = mp;
12035 					if (!more) {
12036 						ipf->ipf_hole_cnt--;
12037 					}
12038 					break;
12039 				}
12040 			}
12041 			if (start >= IP_REASS_START(mp1->b_cont))
12042 				continue;
12043 			/* Fill a hole */
12044 			if (start > offset)
12045 				ipf->ipf_hole_cnt++;
12046 			mp->b_cont = mp1->b_cont;
12047 			mp1->b_cont = mp;
12048 			mp1 = mp->b_cont;
12049 			offset = IP_REASS_START(mp1);
12050 			if (end >= offset) {
12051 				ipf->ipf_hole_cnt--;
12052 				/* Check for overlap. */
12053 				while (end > offset) {
12054 					if (end < IP_REASS_END(mp1)) {
12055 						mp->b_wptr -= end - offset;
12056 						IP_REASS_SET_END(mp, offset);
12057 						/*
12058 						 * TODO we might bump
12059 						 * this up twice if there is
12060 						 * overlap at both ends.
12061 						 */
12062 						BUMP_MIB(ill->ill_ip_mib,
12063 						    ipIfStatsReasmPartDups);
12064 						break;
12065 					}
12066 					/* Did we cover another hole? */
12067 					if ((mp1->b_cont &&
12068 					    IP_REASS_END(mp1)
12069 					    != IP_REASS_START(mp1->b_cont) &&
12070 					    end >=
12071 					    IP_REASS_START(mp1->b_cont)) ||
12072 					    (!ipf->ipf_last_frag_seen &&
12073 					    !more)) {
12074 						ipf->ipf_hole_cnt--;
12075 					}
12076 					/* Clip out mp1. */
12077 					if ((mp->b_cont = mp1->b_cont) ==
12078 					    NULL) {
12079 						/*
12080 						 * After clipping out mp1,
12081 						 * this guy is now hanging
12082 						 * off the end.
12083 						 */
12084 						ipf->ipf_tail_mp = mp;
12085 					}
12086 					IP_REASS_SET_START(mp1, 0);
12087 					IP_REASS_SET_END(mp1, 0);
12088 					/* Subtract byte count */
12089 					ipf->ipf_count -=
12090 					    mp1->b_datap->db_lim -
12091 					    mp1->b_datap->db_base;
12092 					freeb(mp1);
12093 					BUMP_MIB(ill->ill_ip_mib,
12094 					    ipIfStatsReasmPartDups);
12095 					mp1 = mp->b_cont;
12096 					if (!mp1)
12097 						break;
12098 					offset = IP_REASS_START(mp1);
12099 				}
12100 			}
12101 			break;
12102 		}
12103 	} while (start = end, mp = next_mp);
12104 
12105 	/* Fragment just processed could be the last one. Remember this fact */
12106 	if (!more)
12107 		ipf->ipf_last_frag_seen = B_TRUE;
12108 
12109 	/* Still got holes? */
12110 	if (ipf->ipf_hole_cnt)
12111 		return (IP_REASS_PARTIAL);
12112 	/* Clean up overloaded fields to avoid upstream disasters. */
12113 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12114 		IP_REASS_SET_START(mp1, 0);
12115 		IP_REASS_SET_END(mp1, 0);
12116 	}
12117 	return (IP_REASS_COMPLETE);
12118 }
12119 
12120 /*
12121  * ipsec processing for the fast path, used for input UDP Packets
12122  * Returns true if ready for passup to UDP.
12123  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12124  * was an ESP-in-UDP packet, etc.).
12125  */
12126 static boolean_t
12127 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12128     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12129 {
12130 	uint32_t	ill_index;
12131 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12132 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12133 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12134 	udp_t		*udp = connp->conn_udp;
12135 
12136 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12137 	/* The ill_index of the incoming ILL */
12138 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12139 
12140 	/* pass packet up to the transport */
12141 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12142 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12143 		    NULL, mctl_present);
12144 		if (*first_mpp == NULL) {
12145 			return (B_FALSE);
12146 		}
12147 	}
12148 
12149 	/* Initiate IPPF processing for fastpath UDP */
12150 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12151 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12152 		if (*mpp == NULL) {
12153 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12154 			    "deferred/dropped during IPPF processing\n"));
12155 			return (B_FALSE);
12156 		}
12157 	}
12158 	/*
12159 	 * Remove 0-spi if it's 0, or move everything behind
12160 	 * the UDP header over it and forward to ESP via
12161 	 * ip_proto_input().
12162 	 */
12163 	if (udp->udp_nat_t_endpoint) {
12164 		if (mctl_present) {
12165 			/* mctl_present *shouldn't* happen. */
12166 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12167 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12168 			    &ipss->ipsec_dropper);
12169 			*first_mpp = NULL;
12170 			return (B_FALSE);
12171 		}
12172 
12173 		/* "ill" is "recv_ill" in actuality. */
12174 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12175 			return (B_FALSE);
12176 
12177 		/* Else continue like a normal UDP packet. */
12178 	}
12179 
12180 	/*
12181 	 * We make the checks as below since we are in the fast path
12182 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12183 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12184 	 */
12185 	if (connp->conn_recvif || connp->conn_recvslla ||
12186 	    connp->conn_ip_recvpktinfo) {
12187 		if (connp->conn_recvif) {
12188 			in_flags = IPF_RECVIF;
12189 		}
12190 		/*
12191 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12192 		 * so the flag passed to ip_add_info is based on IP version
12193 		 * of connp.
12194 		 */
12195 		if (connp->conn_ip_recvpktinfo) {
12196 			if (connp->conn_af_isv6) {
12197 				/*
12198 				 * V6 only needs index
12199 				 */
12200 				in_flags |= IPF_RECVIF;
12201 			} else {
12202 				/*
12203 				 * V4 needs index + matching address.
12204 				 */
12205 				in_flags |= IPF_RECVADDR;
12206 			}
12207 		}
12208 		if (connp->conn_recvslla) {
12209 			in_flags |= IPF_RECVSLLA;
12210 		}
12211 		/*
12212 		 * since in_flags are being set ill will be
12213 		 * referenced in ip_add_info, so it better not
12214 		 * be NULL.
12215 		 */
12216 		/*
12217 		 * the actual data will be contained in b_cont
12218 		 * upon successful return of the following call.
12219 		 * If the call fails then the original mblk is
12220 		 * returned.
12221 		 */
12222 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12223 		    ipst);
12224 	}
12225 
12226 	return (B_TRUE);
12227 }
12228 
12229 /*
12230  * Fragmentation reassembly.  Each ILL has a hash table for
12231  * queuing packets undergoing reassembly for all IPIFs
12232  * associated with the ILL.  The hash is based on the packet
12233  * IP ident field.  The ILL frag hash table was allocated
12234  * as a timer block at the time the ILL was created.  Whenever
12235  * there is anything on the reassembly queue, the timer will
12236  * be running.  Returns B_TRUE if successful else B_FALSE;
12237  * frees mp on failure.
12238  */
12239 static boolean_t
12240 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12241     uint32_t *cksum_val, uint16_t *cksum_flags)
12242 {
12243 	uint32_t	frag_offset_flags;
12244 	ill_t		*ill = (ill_t *)q->q_ptr;
12245 	mblk_t		*mp = *mpp;
12246 	mblk_t		*t_mp;
12247 	ipaddr_t	dst;
12248 	uint8_t		proto = ipha->ipha_protocol;
12249 	uint32_t	sum_val;
12250 	uint16_t	sum_flags;
12251 	ipf_t		*ipf;
12252 	ipf_t		**ipfp;
12253 	ipfb_t		*ipfb;
12254 	uint16_t	ident;
12255 	uint32_t	offset;
12256 	ipaddr_t	src;
12257 	uint_t		hdr_length;
12258 	uint32_t	end;
12259 	mblk_t		*mp1;
12260 	mblk_t		*tail_mp;
12261 	size_t		count;
12262 	size_t		msg_len;
12263 	uint8_t		ecn_info = 0;
12264 	uint32_t	packet_size;
12265 	boolean_t	pruned = B_FALSE;
12266 	ip_stack_t *ipst = ill->ill_ipst;
12267 
12268 	if (cksum_val != NULL)
12269 		*cksum_val = 0;
12270 	if (cksum_flags != NULL)
12271 		*cksum_flags = 0;
12272 
12273 	/*
12274 	 * Drop the fragmented as early as possible, if
12275 	 * we don't have resource(s) to re-assemble.
12276 	 */
12277 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12278 		freemsg(mp);
12279 		return (B_FALSE);
12280 	}
12281 
12282 	/* Check for fragmentation offset; return if there's none */
12283 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12284 	    (IPH_MF | IPH_OFFSET)) == 0)
12285 		return (B_TRUE);
12286 
12287 	/*
12288 	 * We utilize hardware computed checksum info only for UDP since
12289 	 * IP fragmentation is a normal occurence for the protocol.  In
12290 	 * addition, checksum offload support for IP fragments carrying
12291 	 * UDP payload is commonly implemented across network adapters.
12292 	 */
12293 	ASSERT(ill != NULL);
12294 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12295 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12296 		mblk_t *mp1 = mp->b_cont;
12297 		int32_t len;
12298 
12299 		/* Record checksum information from the packet */
12300 		sum_val = (uint32_t)DB_CKSUM16(mp);
12301 		sum_flags = DB_CKSUMFLAGS(mp);
12302 
12303 		/* IP payload offset from beginning of mblk */
12304 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12305 
12306 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12307 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12308 		    offset >= DB_CKSUMSTART(mp) &&
12309 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12310 			uint32_t adj;
12311 			/*
12312 			 * Partial checksum has been calculated by hardware
12313 			 * and attached to the packet; in addition, any
12314 			 * prepended extraneous data is even byte aligned.
12315 			 * If any such data exists, we adjust the checksum;
12316 			 * this would also handle any postpended data.
12317 			 */
12318 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12319 			    mp, mp1, len, adj);
12320 
12321 			/* One's complement subtract extraneous checksum */
12322 			if (adj >= sum_val)
12323 				sum_val = ~(adj - sum_val) & 0xFFFF;
12324 			else
12325 				sum_val -= adj;
12326 		}
12327 	} else {
12328 		sum_val = 0;
12329 		sum_flags = 0;
12330 	}
12331 
12332 	/* Clear hardware checksumming flag */
12333 	DB_CKSUMFLAGS(mp) = 0;
12334 
12335 	ident = ipha->ipha_ident;
12336 	offset = (frag_offset_flags << 3) & 0xFFFF;
12337 	src = ipha->ipha_src;
12338 	dst = ipha->ipha_dst;
12339 	hdr_length = IPH_HDR_LENGTH(ipha);
12340 	end = ntohs(ipha->ipha_length) - hdr_length;
12341 
12342 	/* If end == 0 then we have a packet with no data, so just free it */
12343 	if (end == 0) {
12344 		freemsg(mp);
12345 		return (B_FALSE);
12346 	}
12347 
12348 	/* Record the ECN field info. */
12349 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12350 	if (offset != 0) {
12351 		/*
12352 		 * If this isn't the first piece, strip the header, and
12353 		 * add the offset to the end value.
12354 		 */
12355 		mp->b_rptr += hdr_length;
12356 		end += offset;
12357 	}
12358 
12359 	msg_len = MBLKSIZE(mp);
12360 	tail_mp = mp;
12361 	while (tail_mp->b_cont != NULL) {
12362 		tail_mp = tail_mp->b_cont;
12363 		msg_len += MBLKSIZE(tail_mp);
12364 	}
12365 
12366 	/* If the reassembly list for this ILL will get too big, prune it */
12367 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12368 	    ipst->ips_ip_reass_queue_bytes) {
12369 		ill_frag_prune(ill,
12370 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12371 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12372 		pruned = B_TRUE;
12373 	}
12374 
12375 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12376 	mutex_enter(&ipfb->ipfb_lock);
12377 
12378 	ipfp = &ipfb->ipfb_ipf;
12379 	/* Try to find an existing fragment queue for this packet. */
12380 	for (;;) {
12381 		ipf = ipfp[0];
12382 		if (ipf != NULL) {
12383 			/*
12384 			 * It has to match on ident and src/dst address.
12385 			 */
12386 			if (ipf->ipf_ident == ident &&
12387 			    ipf->ipf_src == src &&
12388 			    ipf->ipf_dst == dst &&
12389 			    ipf->ipf_protocol == proto) {
12390 				/*
12391 				 * If we have received too many
12392 				 * duplicate fragments for this packet
12393 				 * free it.
12394 				 */
12395 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12396 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12397 					freemsg(mp);
12398 					mutex_exit(&ipfb->ipfb_lock);
12399 					return (B_FALSE);
12400 				}
12401 				/* Found it. */
12402 				break;
12403 			}
12404 			ipfp = &ipf->ipf_hash_next;
12405 			continue;
12406 		}
12407 
12408 		/*
12409 		 * If we pruned the list, do we want to store this new
12410 		 * fragment?. We apply an optimization here based on the
12411 		 * fact that most fragments will be received in order.
12412 		 * So if the offset of this incoming fragment is zero,
12413 		 * it is the first fragment of a new packet. We will
12414 		 * keep it.  Otherwise drop the fragment, as we have
12415 		 * probably pruned the packet already (since the
12416 		 * packet cannot be found).
12417 		 */
12418 		if (pruned && offset != 0) {
12419 			mutex_exit(&ipfb->ipfb_lock);
12420 			freemsg(mp);
12421 			return (B_FALSE);
12422 		}
12423 
12424 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12425 			/*
12426 			 * Too many fragmented packets in this hash
12427 			 * bucket. Free the oldest.
12428 			 */
12429 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12430 		}
12431 
12432 		/* New guy.  Allocate a frag message. */
12433 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12434 		if (mp1 == NULL) {
12435 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12436 			freemsg(mp);
12437 reass_done:
12438 			mutex_exit(&ipfb->ipfb_lock);
12439 			return (B_FALSE);
12440 		}
12441 
12442 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12443 		mp1->b_cont = mp;
12444 
12445 		/* Initialize the fragment header. */
12446 		ipf = (ipf_t *)mp1->b_rptr;
12447 		ipf->ipf_mp = mp1;
12448 		ipf->ipf_ptphn = ipfp;
12449 		ipfp[0] = ipf;
12450 		ipf->ipf_hash_next = NULL;
12451 		ipf->ipf_ident = ident;
12452 		ipf->ipf_protocol = proto;
12453 		ipf->ipf_src = src;
12454 		ipf->ipf_dst = dst;
12455 		ipf->ipf_nf_hdr_len = 0;
12456 		/* Record reassembly start time. */
12457 		ipf->ipf_timestamp = gethrestime_sec();
12458 		/* Record ipf generation and account for frag header */
12459 		ipf->ipf_gen = ill->ill_ipf_gen++;
12460 		ipf->ipf_count = MBLKSIZE(mp1);
12461 		ipf->ipf_last_frag_seen = B_FALSE;
12462 		ipf->ipf_ecn = ecn_info;
12463 		ipf->ipf_num_dups = 0;
12464 		ipfb->ipfb_frag_pkts++;
12465 		ipf->ipf_checksum = 0;
12466 		ipf->ipf_checksum_flags = 0;
12467 
12468 		/* Store checksum value in fragment header */
12469 		if (sum_flags != 0) {
12470 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12471 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12472 			ipf->ipf_checksum = sum_val;
12473 			ipf->ipf_checksum_flags = sum_flags;
12474 		}
12475 
12476 		/*
12477 		 * We handle reassembly two ways.  In the easy case,
12478 		 * where all the fragments show up in order, we do
12479 		 * minimal bookkeeping, and just clip new pieces on
12480 		 * the end.  If we ever see a hole, then we go off
12481 		 * to ip_reassemble which has to mark the pieces and
12482 		 * keep track of the number of holes, etc.  Obviously,
12483 		 * the point of having both mechanisms is so we can
12484 		 * handle the easy case as efficiently as possible.
12485 		 */
12486 		if (offset == 0) {
12487 			/* Easy case, in-order reassembly so far. */
12488 			ipf->ipf_count += msg_len;
12489 			ipf->ipf_tail_mp = tail_mp;
12490 			/*
12491 			 * Keep track of next expected offset in
12492 			 * ipf_end.
12493 			 */
12494 			ipf->ipf_end = end;
12495 			ipf->ipf_nf_hdr_len = hdr_length;
12496 		} else {
12497 			/* Hard case, hole at the beginning. */
12498 			ipf->ipf_tail_mp = NULL;
12499 			/*
12500 			 * ipf_end == 0 means that we have given up
12501 			 * on easy reassembly.
12502 			 */
12503 			ipf->ipf_end = 0;
12504 
12505 			/* Forget checksum offload from now on */
12506 			ipf->ipf_checksum_flags = 0;
12507 
12508 			/*
12509 			 * ipf_hole_cnt is set by ip_reassemble.
12510 			 * ipf_count is updated by ip_reassemble.
12511 			 * No need to check for return value here
12512 			 * as we don't expect reassembly to complete
12513 			 * or fail for the first fragment itself.
12514 			 */
12515 			(void) ip_reassemble(mp, ipf,
12516 			    (frag_offset_flags & IPH_OFFSET) << 3,
12517 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12518 		}
12519 		/* Update per ipfb and ill byte counts */
12520 		ipfb->ipfb_count += ipf->ipf_count;
12521 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12522 		ill->ill_frag_count += ipf->ipf_count;
12523 		/* If the frag timer wasn't already going, start it. */
12524 		mutex_enter(&ill->ill_lock);
12525 		ill_frag_timer_start(ill);
12526 		mutex_exit(&ill->ill_lock);
12527 		goto reass_done;
12528 	}
12529 
12530 	/*
12531 	 * If the packet's flag has changed (it could be coming up
12532 	 * from an interface different than the previous, therefore
12533 	 * possibly different checksum capability), then forget about
12534 	 * any stored checksum states.  Otherwise add the value to
12535 	 * the existing one stored in the fragment header.
12536 	 */
12537 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12538 		sum_val += ipf->ipf_checksum;
12539 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12540 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12541 		ipf->ipf_checksum = sum_val;
12542 	} else if (ipf->ipf_checksum_flags != 0) {
12543 		/* Forget checksum offload from now on */
12544 		ipf->ipf_checksum_flags = 0;
12545 	}
12546 
12547 	/*
12548 	 * We have a new piece of a datagram which is already being
12549 	 * reassembled.  Update the ECN info if all IP fragments
12550 	 * are ECN capable.  If there is one which is not, clear
12551 	 * all the info.  If there is at least one which has CE
12552 	 * code point, IP needs to report that up to transport.
12553 	 */
12554 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12555 		if (ecn_info == IPH_ECN_CE)
12556 			ipf->ipf_ecn = IPH_ECN_CE;
12557 	} else {
12558 		ipf->ipf_ecn = IPH_ECN_NECT;
12559 	}
12560 	if (offset && ipf->ipf_end == offset) {
12561 		/* The new fragment fits at the end */
12562 		ipf->ipf_tail_mp->b_cont = mp;
12563 		/* Update the byte count */
12564 		ipf->ipf_count += msg_len;
12565 		/* Update per ipfb and ill byte counts */
12566 		ipfb->ipfb_count += msg_len;
12567 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12568 		ill->ill_frag_count += msg_len;
12569 		if (frag_offset_flags & IPH_MF) {
12570 			/* More to come. */
12571 			ipf->ipf_end = end;
12572 			ipf->ipf_tail_mp = tail_mp;
12573 			goto reass_done;
12574 		}
12575 	} else {
12576 		/* Go do the hard cases. */
12577 		int ret;
12578 
12579 		if (offset == 0)
12580 			ipf->ipf_nf_hdr_len = hdr_length;
12581 
12582 		/* Save current byte count */
12583 		count = ipf->ipf_count;
12584 		ret = ip_reassemble(mp, ipf,
12585 		    (frag_offset_flags & IPH_OFFSET) << 3,
12586 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12587 		/* Count of bytes added and subtracted (freeb()ed) */
12588 		count = ipf->ipf_count - count;
12589 		if (count) {
12590 			/* Update per ipfb and ill byte counts */
12591 			ipfb->ipfb_count += count;
12592 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12593 			ill->ill_frag_count += count;
12594 		}
12595 		if (ret == IP_REASS_PARTIAL) {
12596 			goto reass_done;
12597 		} else if (ret == IP_REASS_FAILED) {
12598 			/* Reassembly failed. Free up all resources */
12599 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12600 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12601 				IP_REASS_SET_START(t_mp, 0);
12602 				IP_REASS_SET_END(t_mp, 0);
12603 			}
12604 			freemsg(mp);
12605 			goto reass_done;
12606 		}
12607 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12608 	}
12609 	/*
12610 	 * We have completed reassembly.  Unhook the frag header from
12611 	 * the reassembly list.
12612 	 *
12613 	 * Before we free the frag header, record the ECN info
12614 	 * to report back to the transport.
12615 	 */
12616 	ecn_info = ipf->ipf_ecn;
12617 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12618 	ipfp = ipf->ipf_ptphn;
12619 
12620 	/* We need to supply these to caller */
12621 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12622 		sum_val = ipf->ipf_checksum;
12623 	else
12624 		sum_val = 0;
12625 
12626 	mp1 = ipf->ipf_mp;
12627 	count = ipf->ipf_count;
12628 	ipf = ipf->ipf_hash_next;
12629 	if (ipf != NULL)
12630 		ipf->ipf_ptphn = ipfp;
12631 	ipfp[0] = ipf;
12632 	ill->ill_frag_count -= count;
12633 	ASSERT(ipfb->ipfb_count >= count);
12634 	ipfb->ipfb_count -= count;
12635 	ipfb->ipfb_frag_pkts--;
12636 	mutex_exit(&ipfb->ipfb_lock);
12637 	/* Ditch the frag header. */
12638 	mp = mp1->b_cont;
12639 
12640 	freeb(mp1);
12641 
12642 	/* Restore original IP length in header. */
12643 	packet_size = (uint32_t)msgdsize(mp);
12644 	if (packet_size > IP_MAXPACKET) {
12645 		freemsg(mp);
12646 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12647 		return (B_FALSE);
12648 	}
12649 
12650 	if (DB_REF(mp) > 1) {
12651 		mblk_t *mp2 = copymsg(mp);
12652 
12653 		freemsg(mp);
12654 		if (mp2 == NULL) {
12655 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12656 			return (B_FALSE);
12657 		}
12658 		mp = mp2;
12659 	}
12660 	ipha = (ipha_t *)mp->b_rptr;
12661 
12662 	ipha->ipha_length = htons((uint16_t)packet_size);
12663 	/* We're now complete, zip the frag state */
12664 	ipha->ipha_fragment_offset_and_flags = 0;
12665 	/* Record the ECN info. */
12666 	ipha->ipha_type_of_service &= 0xFC;
12667 	ipha->ipha_type_of_service |= ecn_info;
12668 	*mpp = mp;
12669 
12670 	/* Reassembly is successful; return checksum information if needed */
12671 	if (cksum_val != NULL)
12672 		*cksum_val = sum_val;
12673 	if (cksum_flags != NULL)
12674 		*cksum_flags = sum_flags;
12675 
12676 	return (B_TRUE);
12677 }
12678 
12679 /*
12680  * Perform ip header check sum update local options.
12681  * return B_TRUE if all is well, else return B_FALSE and release
12682  * the mp. caller is responsible for decrementing ire ref cnt.
12683  */
12684 static boolean_t
12685 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12686     ip_stack_t *ipst)
12687 {
12688 	mblk_t		*first_mp;
12689 	boolean_t	mctl_present;
12690 	uint16_t	sum;
12691 
12692 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12693 	/*
12694 	 * Don't do the checksum if it has gone through AH/ESP
12695 	 * processing.
12696 	 */
12697 	if (!mctl_present) {
12698 		sum = ip_csum_hdr(ipha);
12699 		if (sum != 0) {
12700 			if (ill != NULL) {
12701 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12702 			} else {
12703 				BUMP_MIB(&ipst->ips_ip_mib,
12704 				    ipIfStatsInCksumErrs);
12705 			}
12706 			freemsg(first_mp);
12707 			return (B_FALSE);
12708 		}
12709 	}
12710 
12711 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12712 		if (mctl_present)
12713 			freeb(first_mp);
12714 		return (B_FALSE);
12715 	}
12716 
12717 	return (B_TRUE);
12718 }
12719 
12720 /*
12721  * All udp packet are delivered to the local host via this routine.
12722  */
12723 void
12724 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12725     ill_t *recv_ill)
12726 {
12727 	uint32_t	sum;
12728 	uint32_t	u1;
12729 	boolean_t	mctl_present;
12730 	conn_t		*connp;
12731 	mblk_t		*first_mp;
12732 	uint16_t	*up;
12733 	ill_t		*ill = (ill_t *)q->q_ptr;
12734 	uint16_t	reass_hck_flags = 0;
12735 	ip_stack_t	*ipst;
12736 
12737 	ASSERT(recv_ill != NULL);
12738 	ipst = recv_ill->ill_ipst;
12739 
12740 #define	rptr    ((uchar_t *)ipha)
12741 
12742 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12743 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12744 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12745 	ASSERT(ill != NULL);
12746 
12747 	/*
12748 	 * FAST PATH for udp packets
12749 	 */
12750 
12751 	/* u1 is # words of IP options */
12752 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12753 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12754 
12755 	/* IP options present */
12756 	if (u1 != 0)
12757 		goto ipoptions;
12758 
12759 	/* Check the IP header checksum.  */
12760 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12761 		/* Clear the IP header h/w cksum flag */
12762 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12763 	} else if (!mctl_present) {
12764 		/*
12765 		 * Don't verify header checksum if this packet is coming
12766 		 * back from AH/ESP as we already did it.
12767 		 */
12768 #define	uph	((uint16_t *)ipha)
12769 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12770 		    uph[6] + uph[7] + uph[8] + uph[9];
12771 #undef	uph
12772 		/* finish doing IP checksum */
12773 		sum = (sum & 0xFFFF) + (sum >> 16);
12774 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12775 		if (sum != 0 && sum != 0xFFFF) {
12776 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12777 			freemsg(first_mp);
12778 			return;
12779 		}
12780 	}
12781 
12782 	/*
12783 	 * Count for SNMP of inbound packets for ire.
12784 	 * if mctl is present this might be a secure packet and
12785 	 * has already been counted for in ip_proto_input().
12786 	 */
12787 	if (!mctl_present) {
12788 		UPDATE_IB_PKT_COUNT(ire);
12789 		ire->ire_last_used_time = lbolt;
12790 	}
12791 
12792 	/* packet part of fragmented IP packet? */
12793 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12794 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12795 		goto fragmented;
12796 	}
12797 
12798 	/* u1 = IP header length (20 bytes) */
12799 	u1 = IP_SIMPLE_HDR_LENGTH;
12800 
12801 	/* packet does not contain complete IP & UDP headers */
12802 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12803 		goto udppullup;
12804 
12805 	/* up points to UDP header */
12806 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12807 #define	iphs    ((uint16_t *)ipha)
12808 
12809 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12810 	if (up[3] != 0) {
12811 		mblk_t *mp1 = mp->b_cont;
12812 		boolean_t cksum_err;
12813 		uint16_t hck_flags = 0;
12814 
12815 		/* Pseudo-header checksum */
12816 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12817 		    iphs[9] + up[2];
12818 
12819 		/*
12820 		 * Revert to software checksum calculation if the interface
12821 		 * isn't capable of checksum offload or if IPsec is present.
12822 		 */
12823 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12824 			hck_flags = DB_CKSUMFLAGS(mp);
12825 
12826 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12827 			IP_STAT(ipst, ip_in_sw_cksum);
12828 
12829 		IP_CKSUM_RECV(hck_flags, u1,
12830 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12831 		    (int32_t)((uchar_t *)up - rptr),
12832 		    mp, mp1, cksum_err);
12833 
12834 		if (cksum_err) {
12835 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12836 			if (hck_flags & HCK_FULLCKSUM)
12837 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12838 			else if (hck_flags & HCK_PARTIALCKSUM)
12839 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12840 			else
12841 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12842 
12843 			freemsg(first_mp);
12844 			return;
12845 		}
12846 	}
12847 
12848 	/* Non-fragmented broadcast or multicast packet? */
12849 	if (ire->ire_type == IRE_BROADCAST)
12850 		goto udpslowpath;
12851 
12852 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12853 	    ire->ire_zoneid, ipst)) != NULL) {
12854 		ASSERT(connp->conn_upq != NULL);
12855 		IP_STAT(ipst, ip_udp_fast_path);
12856 
12857 		if (CONN_UDP_FLOWCTLD(connp)) {
12858 			freemsg(mp);
12859 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12860 		} else {
12861 			if (!mctl_present) {
12862 				BUMP_MIB(ill->ill_ip_mib,
12863 				    ipIfStatsHCInDelivers);
12864 			}
12865 			/*
12866 			 * mp and first_mp can change.
12867 			 */
12868 			if (ip_udp_check(q, connp, recv_ill,
12869 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12870 				/* Send it upstream */
12871 				(connp->conn_recv)(connp, mp, NULL);
12872 			}
12873 		}
12874 		/*
12875 		 * freeb() cannot deal with null mblk being passed
12876 		 * in and first_mp can be set to null in the call
12877 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12878 		 */
12879 		if (mctl_present && first_mp != NULL) {
12880 			freeb(first_mp);
12881 		}
12882 		CONN_DEC_REF(connp);
12883 		return;
12884 	}
12885 
12886 	/*
12887 	 * if we got here we know the packet is not fragmented and
12888 	 * has no options. The classifier could not find a conn_t and
12889 	 * most likely its an icmp packet so send it through slow path.
12890 	 */
12891 
12892 	goto udpslowpath;
12893 
12894 ipoptions:
12895 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12896 		goto slow_done;
12897 	}
12898 
12899 	UPDATE_IB_PKT_COUNT(ire);
12900 	ire->ire_last_used_time = lbolt;
12901 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12902 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12903 fragmented:
12904 		/*
12905 		 * "sum" and "reass_hck_flags" are non-zero if the
12906 		 * reassembled packet has a valid hardware computed
12907 		 * checksum information associated with it.
12908 		 */
12909 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12910 			goto slow_done;
12911 		/*
12912 		 * Make sure that first_mp points back to mp as
12913 		 * the mp we came in with could have changed in
12914 		 * ip_rput_fragment().
12915 		 */
12916 		ASSERT(!mctl_present);
12917 		ipha = (ipha_t *)mp->b_rptr;
12918 		first_mp = mp;
12919 	}
12920 
12921 	/* Now we have a complete datagram, destined for this machine. */
12922 	u1 = IPH_HDR_LENGTH(ipha);
12923 	/* Pull up the UDP header, if necessary. */
12924 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12925 udppullup:
12926 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12927 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12928 			freemsg(first_mp);
12929 			goto slow_done;
12930 		}
12931 		ipha = (ipha_t *)mp->b_rptr;
12932 	}
12933 
12934 	/*
12935 	 * Validate the checksum for the reassembled packet; for the
12936 	 * pullup case we calculate the payload checksum in software.
12937 	 */
12938 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12939 	if (up[3] != 0) {
12940 		boolean_t cksum_err;
12941 
12942 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12943 			IP_STAT(ipst, ip_in_sw_cksum);
12944 
12945 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12946 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12947 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12948 		    iphs[9] + up[2], sum, cksum_err);
12949 
12950 		if (cksum_err) {
12951 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12952 
12953 			if (reass_hck_flags & HCK_FULLCKSUM)
12954 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12955 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12956 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12957 			else
12958 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12959 
12960 			freemsg(first_mp);
12961 			goto slow_done;
12962 		}
12963 	}
12964 udpslowpath:
12965 
12966 	/* Clear hardware checksum flag to be safe */
12967 	DB_CKSUMFLAGS(mp) = 0;
12968 
12969 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12970 	    (ire->ire_type == IRE_BROADCAST),
12971 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12972 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12973 
12974 slow_done:
12975 	IP_STAT(ipst, ip_udp_slow_path);
12976 	return;
12977 
12978 #undef  iphs
12979 #undef  rptr
12980 }
12981 
12982 /* ARGSUSED */
12983 static mblk_t *
12984 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12985     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12986     ill_rx_ring_t *ill_ring)
12987 {
12988 	conn_t		*connp;
12989 	uint32_t	sum;
12990 	uint32_t	u1;
12991 	uint16_t	*up;
12992 	int		offset;
12993 	ssize_t		len;
12994 	mblk_t		*mp1;
12995 	boolean_t	syn_present = B_FALSE;
12996 	tcph_t		*tcph;
12997 	uint_t		ip_hdr_len;
12998 	ill_t		*ill = (ill_t *)q->q_ptr;
12999 	zoneid_t	zoneid = ire->ire_zoneid;
13000 	boolean_t	cksum_err;
13001 	uint16_t	hck_flags = 0;
13002 	ip_stack_t	*ipst = recv_ill->ill_ipst;
13003 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
13004 
13005 #define	rptr	((uchar_t *)ipha)
13006 
13007 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
13008 	ASSERT(ill != NULL);
13009 
13010 	/*
13011 	 * FAST PATH for tcp packets
13012 	 */
13013 
13014 	/* u1 is # words of IP options */
13015 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13016 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13017 
13018 	/* IP options present */
13019 	if (u1) {
13020 		goto ipoptions;
13021 	} else if (!mctl_present) {
13022 		/* Check the IP header checksum.  */
13023 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
13024 			/* Clear the IP header h/w cksum flag */
13025 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
13026 		} else if (!mctl_present) {
13027 			/*
13028 			 * Don't verify header checksum if this packet
13029 			 * is coming back from AH/ESP as we already did it.
13030 			 */
13031 #define	uph	((uint16_t *)ipha)
13032 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13033 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13034 #undef	uph
13035 			/* finish doing IP checksum */
13036 			sum = (sum & 0xFFFF) + (sum >> 16);
13037 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13038 			if (sum != 0 && sum != 0xFFFF) {
13039 				BUMP_MIB(ill->ill_ip_mib,
13040 				    ipIfStatsInCksumErrs);
13041 				goto error;
13042 			}
13043 		}
13044 	}
13045 
13046 	if (!mctl_present) {
13047 		UPDATE_IB_PKT_COUNT(ire);
13048 		ire->ire_last_used_time = lbolt;
13049 	}
13050 
13051 	/* packet part of fragmented IP packet? */
13052 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13053 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13054 		goto fragmented;
13055 	}
13056 
13057 	/* u1 = IP header length (20 bytes) */
13058 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
13059 
13060 	/* does packet contain IP+TCP headers? */
13061 	len = mp->b_wptr - rptr;
13062 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
13063 		IP_STAT(ipst, ip_tcppullup);
13064 		goto tcppullup;
13065 	}
13066 
13067 	/* TCP options present? */
13068 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
13069 
13070 	/*
13071 	 * If options need to be pulled up, then goto tcpoptions.
13072 	 * otherwise we are still in the fast path
13073 	 */
13074 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13075 		IP_STAT(ipst, ip_tcpoptions);
13076 		goto tcpoptions;
13077 	}
13078 
13079 	/* multiple mblks of tcp data? */
13080 	if ((mp1 = mp->b_cont) != NULL) {
13081 		/* more then two? */
13082 		if (mp1->b_cont != NULL) {
13083 			IP_STAT(ipst, ip_multipkttcp);
13084 			goto multipkttcp;
13085 		}
13086 		len += mp1->b_wptr - mp1->b_rptr;
13087 	}
13088 
13089 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13090 
13091 	/* part of pseudo checksum */
13092 
13093 	/* TCP datagram length */
13094 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13095 
13096 #define	iphs    ((uint16_t *)ipha)
13097 
13098 #ifdef	_BIG_ENDIAN
13099 	u1 += IPPROTO_TCP;
13100 #else
13101 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13102 #endif
13103 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13104 
13105 	/*
13106 	 * Revert to software checksum calculation if the interface
13107 	 * isn't capable of checksum offload or if IPsec is present.
13108 	 */
13109 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13110 		hck_flags = DB_CKSUMFLAGS(mp);
13111 
13112 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13113 		IP_STAT(ipst, ip_in_sw_cksum);
13114 
13115 	IP_CKSUM_RECV(hck_flags, u1,
13116 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13117 	    (int32_t)((uchar_t *)up - rptr),
13118 	    mp, mp1, cksum_err);
13119 
13120 	if (cksum_err) {
13121 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13122 
13123 		if (hck_flags & HCK_FULLCKSUM)
13124 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13125 		else if (hck_flags & HCK_PARTIALCKSUM)
13126 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13127 		else
13128 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13129 
13130 		goto error;
13131 	}
13132 
13133 try_again:
13134 
13135 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13136 	    zoneid, ipst)) == NULL) {
13137 		/* Send the TH_RST */
13138 		goto no_conn;
13139 	}
13140 
13141 	/*
13142 	 * TCP FAST PATH for AF_INET socket.
13143 	 *
13144 	 * TCP fast path to avoid extra work. An AF_INET socket type
13145 	 * does not have facility to receive extra information via
13146 	 * ip_process or ip_add_info. Also, when the connection was
13147 	 * established, we made a check if this connection is impacted
13148 	 * by any global IPsec policy or per connection policy (a
13149 	 * policy that comes in effect later will not apply to this
13150 	 * connection). Since all this can be determined at the
13151 	 * connection establishment time, a quick check of flags
13152 	 * can avoid extra work.
13153 	 */
13154 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13155 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13156 		ASSERT(first_mp == mp);
13157 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13158 		SET_SQUEUE(mp, tcp_rput_data, connp);
13159 		return (mp);
13160 	}
13161 
13162 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13163 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13164 		if (IPCL_IS_TCP(connp)) {
13165 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13166 			DB_CKSUMSTART(mp) =
13167 			    (intptr_t)ip_squeue_get(ill_ring);
13168 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13169 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13170 				BUMP_MIB(ill->ill_ip_mib,
13171 				    ipIfStatsHCInDelivers);
13172 				SET_SQUEUE(mp, connp->conn_recv, connp);
13173 				return (mp);
13174 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13175 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13176 				BUMP_MIB(ill->ill_ip_mib,
13177 				    ipIfStatsHCInDelivers);
13178 				ip_squeue_enter_unbound++;
13179 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13180 				    connp);
13181 				return (mp);
13182 			}
13183 			syn_present = B_TRUE;
13184 		}
13185 
13186 	}
13187 
13188 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13189 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13190 
13191 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13192 		/* No need to send this packet to TCP */
13193 		if ((flags & TH_RST) || (flags & TH_URG)) {
13194 			CONN_DEC_REF(connp);
13195 			freemsg(first_mp);
13196 			return (NULL);
13197 		}
13198 		if (flags & TH_ACK) {
13199 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13200 			    ipst->ips_netstack->netstack_tcp, connp);
13201 			CONN_DEC_REF(connp);
13202 			return (NULL);
13203 		}
13204 
13205 		CONN_DEC_REF(connp);
13206 		freemsg(first_mp);
13207 		return (NULL);
13208 	}
13209 
13210 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13211 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13212 		    ipha, NULL, mctl_present);
13213 		if (first_mp == NULL) {
13214 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13215 			CONN_DEC_REF(connp);
13216 			return (NULL);
13217 		}
13218 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13219 			ASSERT(syn_present);
13220 			if (mctl_present) {
13221 				ASSERT(first_mp != mp);
13222 				first_mp->b_datap->db_struioflag |=
13223 				    STRUIO_POLICY;
13224 			} else {
13225 				ASSERT(first_mp == mp);
13226 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13227 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13228 			}
13229 		} else {
13230 			/*
13231 			 * Discard first_mp early since we're dealing with a
13232 			 * fully-connected conn_t and tcp doesn't do policy in
13233 			 * this case.
13234 			 */
13235 			if (mctl_present) {
13236 				freeb(first_mp);
13237 				mctl_present = B_FALSE;
13238 			}
13239 			first_mp = mp;
13240 		}
13241 	}
13242 
13243 	/* Initiate IPPF processing for fastpath */
13244 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13245 		uint32_t	ill_index;
13246 
13247 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13248 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13249 		if (mp == NULL) {
13250 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13251 			    "deferred/dropped during IPPF processing\n"));
13252 			CONN_DEC_REF(connp);
13253 			if (mctl_present)
13254 				freeb(first_mp);
13255 			return (NULL);
13256 		} else if (mctl_present) {
13257 			/*
13258 			 * ip_process might return a new mp.
13259 			 */
13260 			ASSERT(first_mp != mp);
13261 			first_mp->b_cont = mp;
13262 		} else {
13263 			first_mp = mp;
13264 		}
13265 
13266 	}
13267 
13268 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13269 		/*
13270 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13271 		 * make sure IPF_RECVIF is passed to ip_add_info.
13272 		 */
13273 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13274 		    IPCL_ZONEID(connp), ipst);
13275 		if (mp == NULL) {
13276 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13277 			CONN_DEC_REF(connp);
13278 			if (mctl_present)
13279 				freeb(first_mp);
13280 			return (NULL);
13281 		} else if (mctl_present) {
13282 			/*
13283 			 * ip_add_info might return a new mp.
13284 			 */
13285 			ASSERT(first_mp != mp);
13286 			first_mp->b_cont = mp;
13287 		} else {
13288 			first_mp = mp;
13289 		}
13290 	}
13291 
13292 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13293 	if (IPCL_IS_TCP(connp)) {
13294 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13295 		return (first_mp);
13296 	} else {
13297 		/* SOCK_RAW, IPPROTO_TCP case */
13298 		(connp->conn_recv)(connp, first_mp, NULL);
13299 		CONN_DEC_REF(connp);
13300 		return (NULL);
13301 	}
13302 
13303 no_conn:
13304 	/* Initiate IPPf processing, if needed. */
13305 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13306 		uint32_t ill_index;
13307 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13308 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13309 		if (first_mp == NULL) {
13310 			return (NULL);
13311 		}
13312 	}
13313 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13314 
13315 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13316 	    ipst->ips_netstack->netstack_tcp, NULL);
13317 	return (NULL);
13318 ipoptions:
13319 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13320 		goto slow_done;
13321 	}
13322 
13323 	UPDATE_IB_PKT_COUNT(ire);
13324 	ire->ire_last_used_time = lbolt;
13325 
13326 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13327 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13328 fragmented:
13329 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13330 			if (mctl_present)
13331 				freeb(first_mp);
13332 			goto slow_done;
13333 		}
13334 		/*
13335 		 * Make sure that first_mp points back to mp as
13336 		 * the mp we came in with could have changed in
13337 		 * ip_rput_fragment().
13338 		 */
13339 		ASSERT(!mctl_present);
13340 		ipha = (ipha_t *)mp->b_rptr;
13341 		first_mp = mp;
13342 	}
13343 
13344 	/* Now we have a complete datagram, destined for this machine. */
13345 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13346 
13347 	len = mp->b_wptr - mp->b_rptr;
13348 	/* Pull up a minimal TCP header, if necessary. */
13349 	if (len < (u1 + 20)) {
13350 tcppullup:
13351 		if (!pullupmsg(mp, u1 + 20)) {
13352 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13353 			goto error;
13354 		}
13355 		ipha = (ipha_t *)mp->b_rptr;
13356 		len = mp->b_wptr - mp->b_rptr;
13357 	}
13358 
13359 	/*
13360 	 * Extract the offset field from the TCP header.  As usual, we
13361 	 * try to help the compiler more than the reader.
13362 	 */
13363 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13364 	if (offset != 5) {
13365 tcpoptions:
13366 		if (offset < 5) {
13367 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13368 			goto error;
13369 		}
13370 		/*
13371 		 * There must be TCP options.
13372 		 * Make sure we can grab them.
13373 		 */
13374 		offset <<= 2;
13375 		offset += u1;
13376 		if (len < offset) {
13377 			if (!pullupmsg(mp, offset)) {
13378 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13379 				goto error;
13380 			}
13381 			ipha = (ipha_t *)mp->b_rptr;
13382 			len = mp->b_wptr - rptr;
13383 		}
13384 	}
13385 
13386 	/* Get the total packet length in len, including headers. */
13387 	if (mp->b_cont) {
13388 multipkttcp:
13389 		len = msgdsize(mp);
13390 	}
13391 
13392 	/*
13393 	 * Check the TCP checksum by pulling together the pseudo-
13394 	 * header checksum, and passing it to ip_csum to be added in
13395 	 * with the TCP datagram.
13396 	 *
13397 	 * Since we are not using the hwcksum if available we must
13398 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13399 	 * If either of these fails along the way the mblk is freed.
13400 	 * If this logic ever changes and mblk is reused to say send
13401 	 * ICMP's back, then this flag may need to be cleared in
13402 	 * other places as well.
13403 	 */
13404 	DB_CKSUMFLAGS(mp) = 0;
13405 
13406 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13407 
13408 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13409 #ifdef	_BIG_ENDIAN
13410 	u1 += IPPROTO_TCP;
13411 #else
13412 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13413 #endif
13414 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13415 	/*
13416 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13417 	 */
13418 	IP_STAT(ipst, ip_in_sw_cksum);
13419 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13420 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13421 		goto error;
13422 	}
13423 
13424 	IP_STAT(ipst, ip_tcp_slow_path);
13425 	goto try_again;
13426 #undef  iphs
13427 #undef  rptr
13428 
13429 error:
13430 	freemsg(first_mp);
13431 slow_done:
13432 	return (NULL);
13433 }
13434 
13435 /* ARGSUSED */
13436 static void
13437 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13438     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13439 {
13440 	conn_t		*connp;
13441 	uint32_t	sum;
13442 	uint32_t	u1;
13443 	ssize_t		len;
13444 	sctp_hdr_t	*sctph;
13445 	zoneid_t	zoneid = ire->ire_zoneid;
13446 	uint32_t	pktsum;
13447 	uint32_t	calcsum;
13448 	uint32_t	ports;
13449 	in6_addr_t	map_src, map_dst;
13450 	ill_t		*ill = (ill_t *)q->q_ptr;
13451 	ip_stack_t	*ipst;
13452 	sctp_stack_t	*sctps;
13453 	boolean_t	sctp_csum_err = B_FALSE;
13454 
13455 	ASSERT(recv_ill != NULL);
13456 	ipst = recv_ill->ill_ipst;
13457 	sctps = ipst->ips_netstack->netstack_sctp;
13458 
13459 #define	rptr	((uchar_t *)ipha)
13460 
13461 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13462 	ASSERT(ill != NULL);
13463 
13464 	/* u1 is # words of IP options */
13465 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13466 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13467 
13468 	/* IP options present */
13469 	if (u1 > 0) {
13470 		goto ipoptions;
13471 	} else {
13472 		/* Check the IP header checksum.  */
13473 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13474 		    !mctl_present) {
13475 #define	uph	((uint16_t *)ipha)
13476 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13477 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13478 #undef	uph
13479 			/* finish doing IP checksum */
13480 			sum = (sum & 0xFFFF) + (sum >> 16);
13481 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13482 			/*
13483 			 * Don't verify header checksum if this packet
13484 			 * is coming back from AH/ESP as we already did it.
13485 			 */
13486 			if (sum != 0 && sum != 0xFFFF) {
13487 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13488 				goto error;
13489 			}
13490 		}
13491 		/*
13492 		 * Since there is no SCTP h/w cksum support yet, just
13493 		 * clear the flag.
13494 		 */
13495 		DB_CKSUMFLAGS(mp) = 0;
13496 	}
13497 
13498 	/*
13499 	 * Don't verify header checksum if this packet is coming
13500 	 * back from AH/ESP as we already did it.
13501 	 */
13502 	if (!mctl_present) {
13503 		UPDATE_IB_PKT_COUNT(ire);
13504 		ire->ire_last_used_time = lbolt;
13505 	}
13506 
13507 	/* packet part of fragmented IP packet? */
13508 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13509 	if (u1 & (IPH_MF | IPH_OFFSET))
13510 		goto fragmented;
13511 
13512 	/* u1 = IP header length (20 bytes) */
13513 	u1 = IP_SIMPLE_HDR_LENGTH;
13514 
13515 find_sctp_client:
13516 	/* Pullup if we don't have the sctp common header. */
13517 	len = MBLKL(mp);
13518 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13519 		if (mp->b_cont == NULL ||
13520 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13521 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13522 			goto error;
13523 		}
13524 		ipha = (ipha_t *)mp->b_rptr;
13525 		len = MBLKL(mp);
13526 	}
13527 
13528 	sctph = (sctp_hdr_t *)(rptr + u1);
13529 #ifdef	DEBUG
13530 	if (!skip_sctp_cksum) {
13531 #endif
13532 		pktsum = sctph->sh_chksum;
13533 		sctph->sh_chksum = 0;
13534 		calcsum = sctp_cksum(mp, u1);
13535 		sctph->sh_chksum = pktsum;
13536 		if (calcsum != pktsum)
13537 			sctp_csum_err = B_TRUE;
13538 #ifdef	DEBUG	/* skip_sctp_cksum */
13539 	}
13540 #endif
13541 	/* get the ports */
13542 	ports = *(uint32_t *)&sctph->sh_sport;
13543 
13544 	IRE_REFRELE(ire);
13545 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13546 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13547 	if (sctp_csum_err) {
13548 		/*
13549 		 * No potential sctp checksum errors go to the Sun
13550 		 * sctp stack however they might be Adler-32 summed
13551 		 * packets a userland stack bound to a raw IP socket
13552 		 * could reasonably use. Note though that Adler-32 is
13553 		 * a long deprecated algorithm and customer sctp
13554 		 * networks should eventually migrate to CRC-32 at
13555 		 * which time this facility should be removed.
13556 		 */
13557 		flags |= IP_FF_SCTP_CSUM_ERR;
13558 		goto no_conn;
13559 	}
13560 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13561 	    sctps)) == NULL) {
13562 		/* Check for raw socket or OOTB handling */
13563 		goto no_conn;
13564 	}
13565 
13566 	/* Found a client; up it goes */
13567 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13568 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13569 	return;
13570 
13571 no_conn:
13572 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13573 	    ports, mctl_present, flags, B_TRUE, zoneid);
13574 	return;
13575 
13576 ipoptions:
13577 	DB_CKSUMFLAGS(mp) = 0;
13578 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13579 		goto slow_done;
13580 
13581 	UPDATE_IB_PKT_COUNT(ire);
13582 	ire->ire_last_used_time = lbolt;
13583 
13584 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13585 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13586 fragmented:
13587 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13588 			goto slow_done;
13589 		/*
13590 		 * Make sure that first_mp points back to mp as
13591 		 * the mp we came in with could have changed in
13592 		 * ip_rput_fragment().
13593 		 */
13594 		ASSERT(!mctl_present);
13595 		ipha = (ipha_t *)mp->b_rptr;
13596 		first_mp = mp;
13597 	}
13598 
13599 	/* Now we have a complete datagram, destined for this machine. */
13600 	u1 = IPH_HDR_LENGTH(ipha);
13601 	goto find_sctp_client;
13602 #undef  iphs
13603 #undef  rptr
13604 
13605 error:
13606 	freemsg(first_mp);
13607 slow_done:
13608 	IRE_REFRELE(ire);
13609 }
13610 
13611 #define	VER_BITS	0xF0
13612 #define	VERSION_6	0x60
13613 
13614 static boolean_t
13615 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13616     ipaddr_t *dstp, ip_stack_t *ipst)
13617 {
13618 	uint_t	opt_len;
13619 	ipha_t *ipha;
13620 	ssize_t len;
13621 	uint_t	pkt_len;
13622 
13623 	ASSERT(ill != NULL);
13624 	IP_STAT(ipst, ip_ipoptions);
13625 	ipha = *iphapp;
13626 
13627 #define	rptr    ((uchar_t *)ipha)
13628 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13629 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13630 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13631 		freemsg(mp);
13632 		return (B_FALSE);
13633 	}
13634 
13635 	/* multiple mblk or too short */
13636 	pkt_len = ntohs(ipha->ipha_length);
13637 
13638 	/* Get the number of words of IP options in the IP header. */
13639 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13640 	if (opt_len) {
13641 		/* IP Options present!  Validate and process. */
13642 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13643 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13644 			goto done;
13645 		}
13646 		/*
13647 		 * Recompute complete header length and make sure we
13648 		 * have access to all of it.
13649 		 */
13650 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13651 		if (len > (mp->b_wptr - rptr)) {
13652 			if (len > pkt_len) {
13653 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13654 				goto done;
13655 			}
13656 			if (!pullupmsg(mp, len)) {
13657 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13658 				goto done;
13659 			}
13660 			ipha = (ipha_t *)mp->b_rptr;
13661 		}
13662 		/*
13663 		 * Go off to ip_rput_options which returns the next hop
13664 		 * destination address, which may have been affected
13665 		 * by source routing.
13666 		 */
13667 		IP_STAT(ipst, ip_opt);
13668 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13669 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13670 			return (B_FALSE);
13671 		}
13672 	}
13673 	*iphapp = ipha;
13674 	return (B_TRUE);
13675 done:
13676 	/* clear b_prev - used by ip_mroute_decap */
13677 	mp->b_prev = NULL;
13678 	freemsg(mp);
13679 	return (B_FALSE);
13680 #undef  rptr
13681 }
13682 
13683 /*
13684  * Deal with the fact that there is no ire for the destination.
13685  */
13686 static ire_t *
13687 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13688 {
13689 	ipha_t	*ipha;
13690 	ill_t	*ill;
13691 	ire_t	*ire;
13692 	boolean_t	check_multirt = B_FALSE;
13693 	ip_stack_t *ipst;
13694 
13695 	ipha = (ipha_t *)mp->b_rptr;
13696 	ill = (ill_t *)q->q_ptr;
13697 
13698 	ASSERT(ill != NULL);
13699 	ipst = ill->ill_ipst;
13700 
13701 	/*
13702 	 * No IRE for this destination, so it can't be for us.
13703 	 * Unless we are forwarding, drop the packet.
13704 	 * We have to let source routed packets through
13705 	 * since we don't yet know if they are 'ping -l'
13706 	 * packets i.e. if they will go out over the
13707 	 * same interface as they came in on.
13708 	 */
13709 	if (ll_multicast) {
13710 		freemsg(mp);
13711 		return (NULL);
13712 	}
13713 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13714 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13715 		freemsg(mp);
13716 		return (NULL);
13717 	}
13718 
13719 	/*
13720 	 * Mark this packet as having originated externally.
13721 	 *
13722 	 * For non-forwarding code path, ire_send later double
13723 	 * checks this interface to see if it is still exists
13724 	 * post-ARP resolution.
13725 	 *
13726 	 * Also, IPQOS uses this to differentiate between
13727 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13728 	 * QOS packet processing in ip_wput_attach_llhdr().
13729 	 * The QoS module can mark the b_band for a fastpath message
13730 	 * or the dl_priority field in a unitdata_req header for
13731 	 * CoS marking. This info can only be found in
13732 	 * ip_wput_attach_llhdr().
13733 	 */
13734 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13735 	/*
13736 	 * Clear the indication that this may have a hardware checksum
13737 	 * as we are not using it
13738 	 */
13739 	DB_CKSUMFLAGS(mp) = 0;
13740 
13741 	ire = ire_forward(dst, &check_multirt, NULL, NULL,
13742 	    MBLK_GETLABEL(mp), ipst);
13743 
13744 	if (ire == NULL && check_multirt) {
13745 		/* Let ip_newroute handle CGTP  */
13746 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13747 		return (NULL);
13748 	}
13749 
13750 	if (ire != NULL)
13751 		return (ire);
13752 
13753 	mp->b_prev = mp->b_next = 0;
13754 	/* send icmp unreachable */
13755 	q = WR(q);
13756 	/* Sent by forwarding path, and router is global zone */
13757 	if (ip_source_routed(ipha, ipst)) {
13758 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13759 		    GLOBAL_ZONEID, ipst);
13760 	} else {
13761 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13762 		    ipst);
13763 	}
13764 
13765 	return (NULL);
13766 
13767 }
13768 
13769 /*
13770  * check ip header length and align it.
13771  */
13772 static boolean_t
13773 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13774 {
13775 	ssize_t len;
13776 	ill_t *ill;
13777 	ipha_t	*ipha;
13778 
13779 	len = MBLKL(mp);
13780 
13781 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13782 		ill = (ill_t *)q->q_ptr;
13783 
13784 		if (!OK_32PTR(mp->b_rptr))
13785 			IP_STAT(ipst, ip_notaligned1);
13786 		else
13787 			IP_STAT(ipst, ip_notaligned2);
13788 		/* Guard against bogus device drivers */
13789 		if (len < 0) {
13790 			/* clear b_prev - used by ip_mroute_decap */
13791 			mp->b_prev = NULL;
13792 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13793 			freemsg(mp);
13794 			return (B_FALSE);
13795 		}
13796 
13797 		if (ip_rput_pullups++ == 0) {
13798 			ipha = (ipha_t *)mp->b_rptr;
13799 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13800 			    "ip_check_and_align_header: %s forced us to "
13801 			    " pullup pkt, hdr len %ld, hdr addr %p",
13802 			    ill->ill_name, len, ipha);
13803 		}
13804 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13805 			/* clear b_prev - used by ip_mroute_decap */
13806 			mp->b_prev = NULL;
13807 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13808 			freemsg(mp);
13809 			return (B_FALSE);
13810 		}
13811 	}
13812 	return (B_TRUE);
13813 }
13814 
13815 ire_t *
13816 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13817 {
13818 	ire_t		*new_ire;
13819 	ill_t		*ire_ill;
13820 	uint_t		ifindex;
13821 	ip_stack_t	*ipst = ill->ill_ipst;
13822 	boolean_t	strict_check = B_FALSE;
13823 
13824 	/*
13825 	 * This packet came in on an interface other than the one associated
13826 	 * with the first ire we found for the destination address. We do
13827 	 * another ire lookup here, using the ingress ill, to see if the
13828 	 * interface is in an interface group.
13829 	 * As long as the ills belong to the same group, we don't consider
13830 	 * them to be arriving on the wrong interface. Thus, if the switch
13831 	 * is doing inbound load spreading, we won't drop packets when the
13832 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13833 	 * for 'usesrc groups' where the destination address may belong to
13834 	 * another interface to allow multipathing to happen.
13835 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13836 	 * where the local address may not be unique. In this case we were
13837 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13838 	 * actually returned. The new lookup, which is more specific, should
13839 	 * only find the IRE_LOCAL associated with the ingress ill if one
13840 	 * exists.
13841 	 */
13842 
13843 	if (ire->ire_ipversion == IPV4_VERSION) {
13844 		if (ipst->ips_ip_strict_dst_multihoming)
13845 			strict_check = B_TRUE;
13846 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13847 		    ill->ill_ipif, ALL_ZONES, NULL,
13848 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13849 	} else {
13850 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13851 		if (ipst->ips_ipv6_strict_dst_multihoming)
13852 			strict_check = B_TRUE;
13853 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13854 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13855 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13856 	}
13857 	/*
13858 	 * If the same ire that was returned in ip_input() is found then this
13859 	 * is an indication that interface groups are in use. The packet
13860 	 * arrived on a different ill in the group than the one associated with
13861 	 * the destination address.  If a different ire was found then the same
13862 	 * IP address must be hosted on multiple ills. This is possible with
13863 	 * unnumbered point2point interfaces. We switch to use this new ire in
13864 	 * order to have accurate interface statistics.
13865 	 */
13866 	if (new_ire != NULL) {
13867 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13868 			ire_refrele(ire);
13869 			ire = new_ire;
13870 		} else {
13871 			ire_refrele(new_ire);
13872 		}
13873 		return (ire);
13874 	} else if ((ire->ire_rfq == NULL) &&
13875 	    (ire->ire_ipversion == IPV4_VERSION)) {
13876 		/*
13877 		 * The best match could have been the original ire which
13878 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13879 		 * the strict multihoming checks are irrelevant as we consider
13880 		 * local addresses hosted on lo0 to be interface agnostic. We
13881 		 * only expect a null ire_rfq on IREs which are associated with
13882 		 * lo0 hence we can return now.
13883 		 */
13884 		return (ire);
13885 	}
13886 
13887 	/*
13888 	 * Chase pointers once and store locally.
13889 	 */
13890 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13891 	    (ill_t *)(ire->ire_rfq->q_ptr);
13892 	ifindex = ill->ill_usesrc_ifindex;
13893 
13894 	/*
13895 	 * Check if it's a legal address on the 'usesrc' interface.
13896 	 */
13897 	if ((ifindex != 0) && (ire_ill != NULL) &&
13898 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13899 		return (ire);
13900 	}
13901 
13902 	/*
13903 	 * If the ip*_strict_dst_multihoming switch is on then we can
13904 	 * only accept this packet if the interface is marked as routing.
13905 	 */
13906 	if (!(strict_check))
13907 		return (ire);
13908 
13909 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13910 	    ILLF_ROUTER) != 0) {
13911 		return (ire);
13912 	}
13913 
13914 	ire_refrele(ire);
13915 	return (NULL);
13916 }
13917 
13918 ire_t *
13919 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13920 {
13921 	ipha_t	*ipha;
13922 	ire_t	*src_ire;
13923 	ill_t	*stq_ill;
13924 	uint_t	hlen;
13925 	uint_t	pkt_len;
13926 	uint32_t sum;
13927 	queue_t	*dev_q;
13928 	ip_stack_t *ipst = ill->ill_ipst;
13929 	mblk_t *fpmp;
13930 
13931 	ipha = (ipha_t *)mp->b_rptr;
13932 
13933 	/*
13934 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13935 	 * The loopback address check for both src and dst has already
13936 	 * been checked in ip_input
13937 	 */
13938 
13939 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13940 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13941 		goto drop;
13942 	}
13943 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13944 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13945 
13946 	if (src_ire != NULL) {
13947 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13948 		ire_refrele(src_ire);
13949 		goto drop;
13950 	}
13951 
13952 
13953 	/* No ire cache of nexthop. So first create one  */
13954 	if (ire == NULL) {
13955 		boolean_t check_multirt;
13956 
13957 		ire = ire_forward(dst, &check_multirt, NULL, NULL, NULL, ipst);
13958 		/*
13959 		 * We only come to ip_fast_forward if ip_cgtp_filter is
13960 		 * is not set. So upon return from ire_forward
13961 		 * check_multirt should remain as false.
13962 		 */
13963 		if (ire == NULL) {
13964 			/* An attempt was made to forward the packet */
13965 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13966 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13967 			mp->b_prev = mp->b_next = 0;
13968 			/* send icmp unreachable */
13969 			/* Sent by forwarding path, and router is global zone */
13970 			if (ip_source_routed(ipha, ipst)) {
13971 				icmp_unreachable(ill->ill_wq, mp,
13972 				    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID,
13973 				    ipst);
13974 			} else {
13975 				icmp_unreachable(ill->ill_wq, mp,
13976 				    ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13977 				    ipst);
13978 			}
13979 			return (ire);
13980 		}
13981 	}
13982 
13983 	/*
13984 	 * Forwarding fastpath exception case:
13985 	 * If either of the follwoing case is true, we take
13986 	 * the slowpath
13987 	 *	o forwarding is not enabled
13988 	 *	o incoming and outgoing interface are the same, or the same
13989 	 *	  IPMP group
13990 	 *	o corresponding ire is in incomplete state
13991 	 *	o packet needs fragmentation
13992 	 *	o ARP cache is not resolved
13993 	 *
13994 	 * The codeflow from here on is thus:
13995 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13996 	 */
13997 	pkt_len = ntohs(ipha->ipha_length);
13998 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13999 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
14000 	    !(ill->ill_flags & ILLF_ROUTER) ||
14001 	    (ill == stq_ill) ||
14002 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
14003 	    (ire->ire_nce == NULL) ||
14004 	    (pkt_len > ire->ire_max_frag) ||
14005 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
14006 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
14007 	    ipha->ipha_ttl <= 1) {
14008 		ip_rput_process_forward(ill->ill_rq, mp, ire,
14009 		    ipha, ill, B_FALSE);
14010 		return (ire);
14011 	}
14012 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14013 
14014 	DTRACE_PROBE4(ip4__forwarding__start,
14015 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
14016 
14017 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
14018 	    ipst->ips_ipv4firewall_forwarding,
14019 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
14020 
14021 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
14022 
14023 	if (mp == NULL)
14024 		goto drop;
14025 
14026 	mp->b_datap->db_struioun.cksum.flags = 0;
14027 	/* Adjust the checksum to reflect the ttl decrement. */
14028 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
14029 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
14030 	ipha->ipha_ttl--;
14031 
14032 	/*
14033 	 * Write the link layer header.  We can do this safely here,
14034 	 * because we have already tested to make sure that the IP
14035 	 * policy is not set, and that we have a fast path destination
14036 	 * header.
14037 	 */
14038 	mp->b_rptr -= hlen;
14039 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
14040 
14041 	UPDATE_IB_PKT_COUNT(ire);
14042 	ire->ire_last_used_time = lbolt;
14043 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
14044 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
14045 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
14046 
14047 	dev_q = ire->ire_stq->q_next;
14048 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
14049 	    !canputnext(ire->ire_stq)) {
14050 		goto indiscard;
14051 	}
14052 	if (ILL_DLS_CAPABLE(stq_ill)) {
14053 		/*
14054 		 * Send the packet directly to DLD, where it
14055 		 * may be queued depending on the availability
14056 		 * of transmit resources at the media layer.
14057 		 */
14058 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14059 	} else {
14060 		DTRACE_PROBE4(ip4__physical__out__start,
14061 		    ill_t *, NULL, ill_t *, stq_ill,
14062 		    ipha_t *, ipha, mblk_t *, mp);
14063 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14064 		    ipst->ips_ipv4firewall_physical_out,
14065 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14066 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14067 		if (mp == NULL)
14068 			goto drop;
14069 		putnext(ire->ire_stq, mp);
14070 	}
14071 	return (ire);
14072 
14073 indiscard:
14074 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14075 drop:
14076 	if (mp != NULL)
14077 		freemsg(mp);
14078 	return (ire);
14079 
14080 }
14081 
14082 /*
14083  * This function is called in the forwarding slowpath, when
14084  * either the ire lacks the link-layer address, or the packet needs
14085  * further processing(eg. fragmentation), before transmission.
14086  */
14087 
14088 static void
14089 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14090     ill_t *ill, boolean_t ll_multicast)
14091 {
14092 	ill_group_t	*ill_group;
14093 	ill_group_t	*ire_group;
14094 	queue_t		*dev_q;
14095 	ire_t		*src_ire;
14096 	ip_stack_t	*ipst = ill->ill_ipst;
14097 
14098 	ASSERT(ire->ire_stq != NULL);
14099 
14100 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14101 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14102 
14103 	if (ll_multicast != 0) {
14104 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14105 		goto drop_pkt;
14106 	}
14107 
14108 	/*
14109 	 * check if ipha_src is a broadcast address. Note that this
14110 	 * check is redundant when we get here from ip_fast_forward()
14111 	 * which has already done this check. However, since we can
14112 	 * also get here from ip_rput_process_broadcast() or, for
14113 	 * for the slow path through ip_fast_forward(), we perform
14114 	 * the check again for code-reusability
14115 	 */
14116 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14117 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14118 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14119 		if (src_ire != NULL)
14120 			ire_refrele(src_ire);
14121 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14122 		ip2dbg(("ip_rput_process_forward: Received packet with"
14123 		    " bad src/dst address on %s\n", ill->ill_name));
14124 		goto drop_pkt;
14125 	}
14126 
14127 	ill_group = ill->ill_group;
14128 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14129 	/*
14130 	 * Check if we want to forward this one at this time.
14131 	 * We allow source routed packets on a host provided that
14132 	 * they go out the same interface or same interface group
14133 	 * as they came in on.
14134 	 *
14135 	 * XXX To be quicker, we may wish to not chase pointers to
14136 	 * get the ILLF_ROUTER flag and instead store the
14137 	 * forwarding policy in the ire.  An unfortunate
14138 	 * side-effect of that would be requiring an ire flush
14139 	 * whenever the ILLF_ROUTER flag changes.
14140 	 */
14141 	if (((ill->ill_flags &
14142 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14143 	    ILLF_ROUTER) == 0) &&
14144 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14145 	    (ill_group != NULL && ill_group == ire_group)))) {
14146 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14147 		if (ip_source_routed(ipha, ipst)) {
14148 			q = WR(q);
14149 			/*
14150 			 * Clear the indication that this may have
14151 			 * hardware checksum as we are not using it.
14152 			 */
14153 			DB_CKSUMFLAGS(mp) = 0;
14154 			/* Sent by forwarding path, and router is global zone */
14155 			icmp_unreachable(q, mp,
14156 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14157 			return;
14158 		}
14159 		goto drop_pkt;
14160 	}
14161 
14162 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14163 
14164 	/* Packet is being forwarded. Turning off hwcksum flag. */
14165 	DB_CKSUMFLAGS(mp) = 0;
14166 	if (ipst->ips_ip_g_send_redirects) {
14167 		/*
14168 		 * Check whether the incoming interface and outgoing
14169 		 * interface is part of the same group. If so,
14170 		 * send redirects.
14171 		 *
14172 		 * Check the source address to see if it originated
14173 		 * on the same logical subnet it is going back out on.
14174 		 * If so, we should be able to send it a redirect.
14175 		 * Avoid sending a redirect if the destination
14176 		 * is directly connected (i.e., ipha_dst is the same
14177 		 * as ire_gateway_addr or the ire_addr of the
14178 		 * nexthop IRE_CACHE ), or if the packet was source
14179 		 * routed out this interface.
14180 		 */
14181 		ipaddr_t src, nhop;
14182 		mblk_t	*mp1;
14183 		ire_t	*nhop_ire = NULL;
14184 
14185 		/*
14186 		 * Check whether ire_rfq and q are from the same ill
14187 		 * or if they are not same, they at least belong
14188 		 * to the same group. If so, send redirects.
14189 		 */
14190 		if ((ire->ire_rfq == q ||
14191 		    (ill_group != NULL && ill_group == ire_group)) &&
14192 		    !ip_source_routed(ipha, ipst)) {
14193 
14194 			nhop = (ire->ire_gateway_addr != 0 ?
14195 			    ire->ire_gateway_addr : ire->ire_addr);
14196 
14197 			if (ipha->ipha_dst == nhop) {
14198 				/*
14199 				 * We avoid sending a redirect if the
14200 				 * destination is directly connected
14201 				 * because it is possible that multiple
14202 				 * IP subnets may have been configured on
14203 				 * the link, and the source may not
14204 				 * be on the same subnet as ip destination,
14205 				 * even though they are on the same
14206 				 * physical link.
14207 				 */
14208 				goto sendit;
14209 			}
14210 
14211 			src = ipha->ipha_src;
14212 
14213 			/*
14214 			 * We look up the interface ire for the nexthop,
14215 			 * to see if ipha_src is in the same subnet
14216 			 * as the nexthop.
14217 			 *
14218 			 * Note that, if, in the future, IRE_CACHE entries
14219 			 * are obsoleted,  this lookup will not be needed,
14220 			 * as the ire passed to this function will be the
14221 			 * same as the nhop_ire computed below.
14222 			 */
14223 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14224 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14225 			    0, NULL, MATCH_IRE_TYPE, ipst);
14226 
14227 			if (nhop_ire != NULL) {
14228 				if ((src & nhop_ire->ire_mask) ==
14229 				    (nhop & nhop_ire->ire_mask)) {
14230 					/*
14231 					 * The source is directly connected.
14232 					 * Just copy the ip header (which is
14233 					 * in the first mblk)
14234 					 */
14235 					mp1 = copyb(mp);
14236 					if (mp1 != NULL) {
14237 						icmp_send_redirect(WR(q), mp1,
14238 						    nhop, ipst);
14239 					}
14240 				}
14241 				ire_refrele(nhop_ire);
14242 			}
14243 		}
14244 	}
14245 sendit:
14246 	dev_q = ire->ire_stq->q_next;
14247 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14248 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14249 		freemsg(mp);
14250 		return;
14251 	}
14252 
14253 	ip_rput_forward(ire, ipha, mp, ill);
14254 	return;
14255 
14256 drop_pkt:
14257 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14258 	freemsg(mp);
14259 }
14260 
14261 ire_t *
14262 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14263     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14264 {
14265 	queue_t		*q;
14266 	uint16_t	hcksumflags;
14267 	ip_stack_t	*ipst = ill->ill_ipst;
14268 
14269 	q = *qp;
14270 
14271 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14272 
14273 	/*
14274 	 * Clear the indication that this may have hardware
14275 	 * checksum as we are not using it for forwarding.
14276 	 */
14277 	hcksumflags = DB_CKSUMFLAGS(mp);
14278 	DB_CKSUMFLAGS(mp) = 0;
14279 
14280 	/*
14281 	 * Directed broadcast forwarding: if the packet came in over a
14282 	 * different interface then it is routed out over we can forward it.
14283 	 */
14284 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14285 		ire_refrele(ire);
14286 		freemsg(mp);
14287 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14288 		return (NULL);
14289 	}
14290 	/*
14291 	 * For multicast we have set dst to be INADDR_BROADCAST
14292 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14293 	 * only for broadcast packets.
14294 	 */
14295 	if (!CLASSD(ipha->ipha_dst)) {
14296 		ire_t *new_ire;
14297 		ipif_t *ipif;
14298 		/*
14299 		 * For ill groups, as the switch duplicates broadcasts
14300 		 * across all the ports, we need to filter out and
14301 		 * send up only one copy. There is one copy for every
14302 		 * broadcast address on each ill. Thus, we look for a
14303 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14304 		 * later to see whether this ill is eligible to receive
14305 		 * them or not. ill_nominate_bcast_rcv() nominates only
14306 		 * one set of IREs for receiving.
14307 		 */
14308 
14309 		ipif = ipif_get_next_ipif(NULL, ill);
14310 		if (ipif == NULL) {
14311 			ire_refrele(ire);
14312 			freemsg(mp);
14313 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14314 			return (NULL);
14315 		}
14316 		new_ire = ire_ctable_lookup(dst, 0, 0,
14317 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14318 		ipif_refrele(ipif);
14319 
14320 		if (new_ire != NULL) {
14321 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14322 				ire_refrele(ire);
14323 				ire_refrele(new_ire);
14324 				freemsg(mp);
14325 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14326 				return (NULL);
14327 			}
14328 			/*
14329 			 * In the special case of multirouted broadcast
14330 			 * packets, we unconditionally need to "gateway"
14331 			 * them to the appropriate interface here.
14332 			 * In the normal case, this cannot happen, because
14333 			 * there is no broadcast IRE tagged with the
14334 			 * RTF_MULTIRT flag.
14335 			 */
14336 			if (new_ire->ire_flags & RTF_MULTIRT) {
14337 				ire_refrele(new_ire);
14338 				if (ire->ire_rfq != NULL) {
14339 					q = ire->ire_rfq;
14340 					*qp = q;
14341 				}
14342 			} else {
14343 				ire_refrele(ire);
14344 				ire = new_ire;
14345 			}
14346 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14347 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14348 				/*
14349 				 * Free the message if
14350 				 * ip_g_forward_directed_bcast is turned
14351 				 * off for non-local broadcast.
14352 				 */
14353 				ire_refrele(ire);
14354 				freemsg(mp);
14355 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14356 				return (NULL);
14357 			}
14358 		} else {
14359 			/*
14360 			 * This CGTP packet successfully passed the
14361 			 * CGTP filter, but the related CGTP
14362 			 * broadcast IRE has not been found,
14363 			 * meaning that the redundant ipif is
14364 			 * probably down. However, if we discarded
14365 			 * this packet, its duplicate would be
14366 			 * filtered out by the CGTP filter so none
14367 			 * of them would get through. So we keep
14368 			 * going with this one.
14369 			 */
14370 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14371 			if (ire->ire_rfq != NULL) {
14372 				q = ire->ire_rfq;
14373 				*qp = q;
14374 			}
14375 		}
14376 	}
14377 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14378 		/*
14379 		 * Verify that there are not more then one
14380 		 * IRE_BROADCAST with this broadcast address which
14381 		 * has ire_stq set.
14382 		 * TODO: simplify, loop over all IRE's
14383 		 */
14384 		ire_t	*ire1;
14385 		int	num_stq = 0;
14386 		mblk_t	*mp1;
14387 
14388 		/* Find the first one with ire_stq set */
14389 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14390 		for (ire1 = ire; ire1 &&
14391 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14392 		    ire1 = ire1->ire_next)
14393 			;
14394 		if (ire1) {
14395 			ire_refrele(ire);
14396 			ire = ire1;
14397 			IRE_REFHOLD(ire);
14398 		}
14399 
14400 		/* Check if there are additional ones with stq set */
14401 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14402 			if (ire->ire_addr != ire1->ire_addr)
14403 				break;
14404 			if (ire1->ire_stq) {
14405 				num_stq++;
14406 				break;
14407 			}
14408 		}
14409 		rw_exit(&ire->ire_bucket->irb_lock);
14410 		if (num_stq == 1 && ire->ire_stq != NULL) {
14411 			ip1dbg(("ip_rput_process_broadcast: directed "
14412 			    "broadcast to 0x%x\n",
14413 			    ntohl(ire->ire_addr)));
14414 			mp1 = copymsg(mp);
14415 			if (mp1) {
14416 				switch (ipha->ipha_protocol) {
14417 				case IPPROTO_UDP:
14418 					ip_udp_input(q, mp1, ipha, ire, ill);
14419 					break;
14420 				default:
14421 					ip_proto_input(q, mp1, ipha, ire, ill,
14422 					    B_FALSE);
14423 					break;
14424 				}
14425 			}
14426 			/*
14427 			 * Adjust ttl to 2 (1+1 - the forward engine
14428 			 * will decrement it by one.
14429 			 */
14430 			if (ip_csum_hdr(ipha)) {
14431 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14432 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14433 				freemsg(mp);
14434 				ire_refrele(ire);
14435 				return (NULL);
14436 			}
14437 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14438 			ipha->ipha_hdr_checksum = 0;
14439 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14440 			ip_rput_process_forward(q, mp, ire, ipha,
14441 			    ill, ll_multicast);
14442 			ire_refrele(ire);
14443 			return (NULL);
14444 		}
14445 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14446 		    ntohl(ire->ire_addr)));
14447 	}
14448 
14449 
14450 	/* Restore any hardware checksum flags */
14451 	DB_CKSUMFLAGS(mp) = hcksumflags;
14452 	return (ire);
14453 }
14454 
14455 /* ARGSUSED */
14456 static boolean_t
14457 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14458     int *ll_multicast, ipaddr_t *dstp)
14459 {
14460 	ip_stack_t	*ipst = ill->ill_ipst;
14461 
14462 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14463 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14464 	    ntohs(ipha->ipha_length));
14465 
14466 	/*
14467 	 * Forward packets only if we have joined the allmulti
14468 	 * group on this interface.
14469 	 */
14470 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14471 		int retval;
14472 
14473 		/*
14474 		 * Clear the indication that this may have hardware
14475 		 * checksum as we are not using it.
14476 		 */
14477 		DB_CKSUMFLAGS(mp) = 0;
14478 		retval = ip_mforward(ill, ipha, mp);
14479 		/* ip_mforward updates mib variables if needed */
14480 		/* clear b_prev - used by ip_mroute_decap */
14481 		mp->b_prev = NULL;
14482 
14483 		switch (retval) {
14484 		case 0:
14485 			/*
14486 			 * pkt is okay and arrived on phyint.
14487 			 *
14488 			 * If we are running as a multicast router
14489 			 * we need to see all IGMP and/or PIM packets.
14490 			 */
14491 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14492 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14493 				goto done;
14494 			}
14495 			break;
14496 		case -1:
14497 			/* pkt is mal-formed, toss it */
14498 			goto drop_pkt;
14499 		case 1:
14500 			/* pkt is okay and arrived on a tunnel */
14501 			/*
14502 			 * If we are running a multicast router
14503 			 *  we need to see all igmp packets.
14504 			 */
14505 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14506 				*dstp = INADDR_BROADCAST;
14507 				*ll_multicast = 1;
14508 				return (B_FALSE);
14509 			}
14510 
14511 			goto drop_pkt;
14512 		}
14513 	}
14514 
14515 	ILM_WALKER_HOLD(ill);
14516 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14517 		/*
14518 		 * This might just be caused by the fact that
14519 		 * multiple IP Multicast addresses map to the same
14520 		 * link layer multicast - no need to increment counter!
14521 		 */
14522 		ILM_WALKER_RELE(ill);
14523 		freemsg(mp);
14524 		return (B_TRUE);
14525 	}
14526 	ILM_WALKER_RELE(ill);
14527 done:
14528 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14529 	/*
14530 	 * This assumes the we deliver to all streams for multicast
14531 	 * and broadcast packets.
14532 	 */
14533 	*dstp = INADDR_BROADCAST;
14534 	*ll_multicast = 1;
14535 	return (B_FALSE);
14536 drop_pkt:
14537 	ip2dbg(("ip_rput: drop pkt\n"));
14538 	freemsg(mp);
14539 	return (B_TRUE);
14540 }
14541 
14542 /*
14543  * This function is used to both return an indication of whether or not
14544  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14545  * and in doing so, determine whether or not it is broadcast vs multicast.
14546  * For it to be a broadcast packet, we must have the appropriate mblk_t
14547  * hanging off the ill_t.  If this is either not present or doesn't match
14548  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14549  * to be multicast.  Thus NICs that have no broadcast address (or no
14550  * capability for one, such as point to point links) cannot return as
14551  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14552  * the return values simplifies the current use of the return value of this
14553  * function, which is to pass through the multicast/broadcast characteristic
14554  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14555  * changing the return value to some other symbol demands the appropriate
14556  * "translation" when hpe_flags is set prior to calling hook_run() for
14557  * packet events.
14558  */
14559 int
14560 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14561 {
14562 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14563 	mblk_t *bmp;
14564 
14565 	if (ind->dl_group_address) {
14566 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14567 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14568 		    MBLKL(mb) &&
14569 		    (bmp = ill->ill_bcast_mp) != NULL) {
14570 			dl_unitdata_req_t *dlur;
14571 			uint8_t *bphys_addr;
14572 
14573 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14574 			if (ill->ill_sap_length < 0)
14575 				bphys_addr = (uchar_t *)dlur +
14576 				    dlur->dl_dest_addr_offset;
14577 			else
14578 				bphys_addr = (uchar_t *)dlur +
14579 				    dlur->dl_dest_addr_offset +
14580 				    ill->ill_sap_length;
14581 
14582 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14583 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14584 				return (HPE_BROADCAST);
14585 			}
14586 			return (HPE_MULTICAST);
14587 		}
14588 		return (HPE_MULTICAST);
14589 	}
14590 	return (0);
14591 }
14592 
14593 static boolean_t
14594 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14595     int *ll_multicast, mblk_t **mpp)
14596 {
14597 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14598 	boolean_t must_copy = B_FALSE;
14599 	struct iocblk   *iocp;
14600 	ipha_t		*ipha;
14601 	ip_stack_t	*ipst = ill->ill_ipst;
14602 
14603 #define	rptr    ((uchar_t *)ipha)
14604 
14605 	first_mp = *first_mpp;
14606 	mp = *mpp;
14607 
14608 	ASSERT(first_mp == mp);
14609 
14610 	/*
14611 	 * if db_ref > 1 then copymsg and free original. Packet may be
14612 	 * changed and do not want other entity who has a reference to this
14613 	 * message to trip over the changes. This is a blind change because
14614 	 * trying to catch all places that might change packet is too
14615 	 * difficult (since it may be a module above this one)
14616 	 *
14617 	 * This corresponds to the non-fast path case. We walk down the full
14618 	 * chain in this case, and check the db_ref count of all the dblks,
14619 	 * and do a copymsg if required. It is possible that the db_ref counts
14620 	 * of the data blocks in the mblk chain can be different.
14621 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14622 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14623 	 * 'snoop' is running.
14624 	 */
14625 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14626 		if (mp1->b_datap->db_ref > 1) {
14627 			must_copy = B_TRUE;
14628 			break;
14629 		}
14630 	}
14631 
14632 	if (must_copy) {
14633 		mp1 = copymsg(mp);
14634 		if (mp1 == NULL) {
14635 			for (mp1 = mp; mp1 != NULL;
14636 			    mp1 = mp1->b_cont) {
14637 				mp1->b_next = NULL;
14638 				mp1->b_prev = NULL;
14639 			}
14640 			freemsg(mp);
14641 			if (ill != NULL) {
14642 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14643 			} else {
14644 				BUMP_MIB(&ipst->ips_ip_mib,
14645 				    ipIfStatsInDiscards);
14646 			}
14647 			return (B_TRUE);
14648 		}
14649 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14650 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14651 			/* Copy b_prev - used by ip_mroute_decap */
14652 			to_mp->b_prev = from_mp->b_prev;
14653 			from_mp->b_prev = NULL;
14654 		}
14655 		*first_mpp = first_mp = mp1;
14656 		freemsg(mp);
14657 		mp = mp1;
14658 		*mpp = mp1;
14659 	}
14660 
14661 	ipha = (ipha_t *)mp->b_rptr;
14662 
14663 	/*
14664 	 * previous code has a case for M_DATA.
14665 	 * We want to check how that happens.
14666 	 */
14667 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14668 	switch (first_mp->b_datap->db_type) {
14669 	case M_PROTO:
14670 	case M_PCPROTO:
14671 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14672 		    DL_UNITDATA_IND) {
14673 			/* Go handle anything other than data elsewhere. */
14674 			ip_rput_dlpi(q, mp);
14675 			return (B_TRUE);
14676 		}
14677 
14678 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14679 		/* Ditch the DLPI header. */
14680 		mp1 = mp->b_cont;
14681 		ASSERT(first_mp == mp);
14682 		*first_mpp = mp1;
14683 		freeb(mp);
14684 		*mpp = mp1;
14685 		return (B_FALSE);
14686 	case M_IOCACK:
14687 		ip1dbg(("got iocack "));
14688 		iocp = (struct iocblk *)mp->b_rptr;
14689 		switch (iocp->ioc_cmd) {
14690 		case DL_IOC_HDR_INFO:
14691 			ill = (ill_t *)q->q_ptr;
14692 			ill_fastpath_ack(ill, mp);
14693 			return (B_TRUE);
14694 		case SIOCSTUNPARAM:
14695 		case OSIOCSTUNPARAM:
14696 			/* Go through qwriter_ip */
14697 			break;
14698 		case SIOCGTUNPARAM:
14699 		case OSIOCGTUNPARAM:
14700 			ip_rput_other(NULL, q, mp, NULL);
14701 			return (B_TRUE);
14702 		default:
14703 			putnext(q, mp);
14704 			return (B_TRUE);
14705 		}
14706 		/* FALLTHRU */
14707 	case M_ERROR:
14708 	case M_HANGUP:
14709 		/*
14710 		 * Since this is on the ill stream we unconditionally
14711 		 * bump up the refcount
14712 		 */
14713 		ill_refhold(ill);
14714 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14715 		return (B_TRUE);
14716 	case M_CTL:
14717 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14718 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14719 		    IPHADA_M_CTL)) {
14720 			/*
14721 			 * It's an IPsec accelerated packet.
14722 			 * Make sure that the ill from which we received the
14723 			 * packet has enabled IPsec hardware acceleration.
14724 			 */
14725 			if (!(ill->ill_capabilities &
14726 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14727 				/* IPsec kstats: bean counter */
14728 				freemsg(mp);
14729 				return (B_TRUE);
14730 			}
14731 
14732 			/*
14733 			 * Make mp point to the mblk following the M_CTL,
14734 			 * then process according to type of mp.
14735 			 * After this processing, first_mp will point to
14736 			 * the data-attributes and mp to the pkt following
14737 			 * the M_CTL.
14738 			 */
14739 			mp = first_mp->b_cont;
14740 			if (mp == NULL) {
14741 				freemsg(first_mp);
14742 				return (B_TRUE);
14743 			}
14744 			/*
14745 			 * A Hardware Accelerated packet can only be M_DATA
14746 			 * ESP or AH packet.
14747 			 */
14748 			if (mp->b_datap->db_type != M_DATA) {
14749 				/* non-M_DATA IPsec accelerated packet */
14750 				IPSECHW_DEBUG(IPSECHW_PKT,
14751 				    ("non-M_DATA IPsec accelerated pkt\n"));
14752 				freemsg(first_mp);
14753 				return (B_TRUE);
14754 			}
14755 			ipha = (ipha_t *)mp->b_rptr;
14756 			if (ipha->ipha_protocol != IPPROTO_AH &&
14757 			    ipha->ipha_protocol != IPPROTO_ESP) {
14758 				IPSECHW_DEBUG(IPSECHW_PKT,
14759 				    ("non-M_DATA IPsec accelerated pkt\n"));
14760 				freemsg(first_mp);
14761 				return (B_TRUE);
14762 			}
14763 			*mpp = mp;
14764 			return (B_FALSE);
14765 		}
14766 		putnext(q, mp);
14767 		return (B_TRUE);
14768 	case M_IOCNAK:
14769 		ip1dbg(("got iocnak "));
14770 		iocp = (struct iocblk *)mp->b_rptr;
14771 		switch (iocp->ioc_cmd) {
14772 		case SIOCSTUNPARAM:
14773 		case OSIOCSTUNPARAM:
14774 			/*
14775 			 * Since this is on the ill stream we unconditionally
14776 			 * bump up the refcount
14777 			 */
14778 			ill_refhold(ill);
14779 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14780 			return (B_TRUE);
14781 		case DL_IOC_HDR_INFO:
14782 		case SIOCGTUNPARAM:
14783 		case OSIOCGTUNPARAM:
14784 			ip_rput_other(NULL, q, mp, NULL);
14785 			return (B_TRUE);
14786 		default:
14787 			break;
14788 		}
14789 		/* FALLTHRU */
14790 	default:
14791 		putnext(q, mp);
14792 		return (B_TRUE);
14793 	}
14794 }
14795 
14796 /* Read side put procedure.  Packets coming from the wire arrive here. */
14797 void
14798 ip_rput(queue_t *q, mblk_t *mp)
14799 {
14800 	ill_t	*ill;
14801 	union DL_primitives *dl;
14802 
14803 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14804 
14805 	ill = (ill_t *)q->q_ptr;
14806 
14807 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14808 		/*
14809 		 * If things are opening or closing, only accept high-priority
14810 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14811 		 * created; on close, things hanging off the ill may have been
14812 		 * freed already.)
14813 		 */
14814 		dl = (union DL_primitives *)mp->b_rptr;
14815 		if (DB_TYPE(mp) != M_PCPROTO ||
14816 		    dl->dl_primitive == DL_UNITDATA_IND) {
14817 			/*
14818 			 * SIOC[GS]TUNPARAM ioctls can come here.
14819 			 */
14820 			inet_freemsg(mp);
14821 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14822 			    "ip_rput_end: q %p (%S)", q, "uninit");
14823 			return;
14824 		}
14825 	}
14826 
14827 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14828 	    "ip_rput_end: q %p (%S)", q, "end");
14829 
14830 	ip_input(ill, NULL, mp, NULL);
14831 }
14832 
14833 static mblk_t *
14834 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14835 {
14836 	mblk_t *mp1;
14837 	boolean_t adjusted = B_FALSE;
14838 	ip_stack_t *ipst = ill->ill_ipst;
14839 
14840 	IP_STAT(ipst, ip_db_ref);
14841 	/*
14842 	 * The IP_RECVSLLA option depends on having the
14843 	 * link layer header. First check that:
14844 	 * a> the underlying device is of type ether,
14845 	 * since this option is currently supported only
14846 	 * over ethernet.
14847 	 * b> there is enough room to copy over the link
14848 	 * layer header.
14849 	 *
14850 	 * Once the checks are done, adjust rptr so that
14851 	 * the link layer header will be copied via
14852 	 * copymsg. Note that, IFT_ETHER may be returned
14853 	 * by some non-ethernet drivers but in this case
14854 	 * the second check will fail.
14855 	 */
14856 	if (ill->ill_type == IFT_ETHER &&
14857 	    (mp->b_rptr - mp->b_datap->db_base) >=
14858 	    sizeof (struct ether_header)) {
14859 		mp->b_rptr -= sizeof (struct ether_header);
14860 		adjusted = B_TRUE;
14861 	}
14862 	mp1 = copymsg(mp);
14863 
14864 	if (mp1 == NULL) {
14865 		mp->b_next = NULL;
14866 		/* clear b_prev - used by ip_mroute_decap */
14867 		mp->b_prev = NULL;
14868 		freemsg(mp);
14869 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14870 		return (NULL);
14871 	}
14872 
14873 	if (adjusted) {
14874 		/*
14875 		 * Copy is done. Restore the pointer in
14876 		 * the _new_ mblk
14877 		 */
14878 		mp1->b_rptr += sizeof (struct ether_header);
14879 	}
14880 
14881 	/* Copy b_prev - used by ip_mroute_decap */
14882 	mp1->b_prev = mp->b_prev;
14883 	mp->b_prev = NULL;
14884 
14885 	/* preserve the hardware checksum flags and data, if present */
14886 	if (DB_CKSUMFLAGS(mp) != 0) {
14887 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14888 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14889 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14890 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14891 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14892 	}
14893 
14894 	freemsg(mp);
14895 	return (mp1);
14896 }
14897 
14898 /*
14899  * Direct read side procedure capable of dealing with chains. GLDv3 based
14900  * drivers call this function directly with mblk chains while STREAMS
14901  * read side procedure ip_rput() calls this for single packet with ip_ring
14902  * set to NULL to process one packet at a time.
14903  *
14904  * The ill will always be valid if this function is called directly from
14905  * the driver.
14906  *
14907  * If ip_input() is called from GLDv3:
14908  *
14909  *   - This must be a non-VLAN IP stream.
14910  *   - 'mp' is either an untagged or a special priority-tagged packet.
14911  *   - Any VLAN tag that was in the MAC header has been stripped.
14912  *
14913  * If the IP header in packet is not 32-bit aligned, every message in the
14914  * chain will be aligned before further operations. This is required on SPARC
14915  * platform.
14916  */
14917 /* ARGSUSED */
14918 void
14919 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14920     struct mac_header_info_s *mhip)
14921 {
14922 	ipaddr_t		dst = NULL;
14923 	ipaddr_t		prev_dst;
14924 	ire_t			*ire = NULL;
14925 	ipha_t			*ipha;
14926 	uint_t			pkt_len;
14927 	ssize_t			len;
14928 	uint_t			opt_len;
14929 	int			ll_multicast;
14930 	int			cgtp_flt_pkt;
14931 	queue_t			*q = ill->ill_rq;
14932 	squeue_t		*curr_sqp = NULL;
14933 	mblk_t 			*head = NULL;
14934 	mblk_t			*tail = NULL;
14935 	mblk_t			*first_mp;
14936 	mblk_t 			*mp;
14937 	mblk_t			*dmp;
14938 	int			cnt = 0;
14939 	ip_stack_t		*ipst = ill->ill_ipst;
14940 
14941 	ASSERT(mp_chain != NULL);
14942 	ASSERT(ill != NULL);
14943 
14944 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14945 
14946 #define	rptr	((uchar_t *)ipha)
14947 
14948 	while (mp_chain != NULL) {
14949 		first_mp = mp = mp_chain;
14950 		mp_chain = mp_chain->b_next;
14951 		mp->b_next = NULL;
14952 		ll_multicast = 0;
14953 
14954 		/*
14955 		 * We do ire caching from one iteration to
14956 		 * another. In the event the packet chain contains
14957 		 * all packets from the same dst, this caching saves
14958 		 * an ire_cache_lookup for each of the succeeding
14959 		 * packets in a packet chain.
14960 		 */
14961 		prev_dst = dst;
14962 
14963 		/*
14964 		 * if db_ref > 1 then copymsg and free original. Packet
14965 		 * may be changed and we do not want the other entity
14966 		 * who has a reference to this message to trip over the
14967 		 * changes. This is a blind change because trying to
14968 		 * catch all places that might change the packet is too
14969 		 * difficult.
14970 		 *
14971 		 * This corresponds to the fast path case, where we have
14972 		 * a chain of M_DATA mblks.  We check the db_ref count
14973 		 * of only the 1st data block in the mblk chain. There
14974 		 * doesn't seem to be a reason why a device driver would
14975 		 * send up data with varying db_ref counts in the mblk
14976 		 * chain. In any case the Fast path is a private
14977 		 * interface, and our drivers don't do such a thing.
14978 		 * Given the above assumption, there is no need to walk
14979 		 * down the entire mblk chain (which could have a
14980 		 * potential performance problem)
14981 		 */
14982 
14983 		if (DB_REF(mp) > 1) {
14984 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14985 				continue;
14986 		}
14987 
14988 		/*
14989 		 * Check and align the IP header.
14990 		 */
14991 		first_mp = mp;
14992 		if (DB_TYPE(mp) == M_DATA) {
14993 			dmp = mp;
14994 		} else if (DB_TYPE(mp) == M_PROTO &&
14995 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14996 			dmp = mp->b_cont;
14997 		} else {
14998 			dmp = NULL;
14999 		}
15000 		if (dmp != NULL) {
15001 			/*
15002 			 * IP header ptr not aligned?
15003 			 * OR IP header not complete in first mblk
15004 			 */
15005 			if (!OK_32PTR(dmp->b_rptr) ||
15006 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
15007 				if (!ip_check_and_align_header(q, dmp, ipst))
15008 					continue;
15009 			}
15010 		}
15011 
15012 		/*
15013 		 * ip_input fast path
15014 		 */
15015 
15016 		/* mblk type is not M_DATA */
15017 		if (DB_TYPE(mp) != M_DATA) {
15018 			if (ip_rput_process_notdata(q, &first_mp, ill,
15019 			    &ll_multicast, &mp))
15020 				continue;
15021 
15022 			/*
15023 			 * The only way we can get here is if we had a
15024 			 * packet that was either a DL_UNITDATA_IND or
15025 			 * an M_CTL for an IPsec accelerated packet.
15026 			 *
15027 			 * In either case, the first_mp will point to
15028 			 * the leading M_PROTO or M_CTL.
15029 			 */
15030 			ASSERT(first_mp != NULL);
15031 		} else if (mhip != NULL) {
15032 			/*
15033 			 * ll_multicast is set here so that it is ready
15034 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
15035 			 * manipulates ll_multicast in the same fashion when
15036 			 * called from ip_rput_process_notdata.
15037 			 */
15038 			switch (mhip->mhi_dsttype) {
15039 			case MAC_ADDRTYPE_MULTICAST :
15040 				ll_multicast = HPE_MULTICAST;
15041 				break;
15042 			case MAC_ADDRTYPE_BROADCAST :
15043 				ll_multicast = HPE_BROADCAST;
15044 				break;
15045 			default :
15046 				break;
15047 			}
15048 		}
15049 
15050 		/* Make sure its an M_DATA and that its aligned */
15051 		ASSERT(DB_TYPE(mp) == M_DATA);
15052 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
15053 
15054 		ipha = (ipha_t *)mp->b_rptr;
15055 		len = mp->b_wptr - rptr;
15056 		pkt_len = ntohs(ipha->ipha_length);
15057 
15058 		/*
15059 		 * We must count all incoming packets, even if they end
15060 		 * up being dropped later on.
15061 		 */
15062 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15063 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15064 
15065 		/* multiple mblk or too short */
15066 		len -= pkt_len;
15067 		if (len != 0) {
15068 			/*
15069 			 * Make sure we have data length consistent
15070 			 * with the IP header.
15071 			 */
15072 			if (mp->b_cont == NULL) {
15073 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15074 					BUMP_MIB(ill->ill_ip_mib,
15075 					    ipIfStatsInHdrErrors);
15076 					ip2dbg(("ip_input: drop pkt\n"));
15077 					freemsg(mp);
15078 					continue;
15079 				}
15080 				mp->b_wptr = rptr + pkt_len;
15081 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15082 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15083 					BUMP_MIB(ill->ill_ip_mib,
15084 					    ipIfStatsInHdrErrors);
15085 					ip2dbg(("ip_input: drop pkt\n"));
15086 					freemsg(mp);
15087 					continue;
15088 				}
15089 				(void) adjmsg(mp, -len);
15090 				IP_STAT(ipst, ip_multimblk3);
15091 			}
15092 		}
15093 
15094 		/* Obtain the dst of the current packet */
15095 		dst = ipha->ipha_dst;
15096 
15097 		/*
15098 		 * The following test for loopback is faster than
15099 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15100 		 * operations.
15101 		 * Note that these addresses are always in network byte order
15102 		 */
15103 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15104 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15105 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15106 			freemsg(mp);
15107 			continue;
15108 		}
15109 
15110 		/*
15111 		 * The event for packets being received from a 'physical'
15112 		 * interface is placed after validation of the source and/or
15113 		 * destination address as being local so that packets can be
15114 		 * redirected to loopback addresses using ipnat.
15115 		 */
15116 		DTRACE_PROBE4(ip4__physical__in__start,
15117 		    ill_t *, ill, ill_t *, NULL,
15118 		    ipha_t *, ipha, mblk_t *, first_mp);
15119 
15120 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15121 		    ipst->ips_ipv4firewall_physical_in,
15122 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15123 
15124 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15125 
15126 		if (first_mp == NULL) {
15127 			continue;
15128 		}
15129 		dst = ipha->ipha_dst;
15130 
15131 		/*
15132 		 * Attach any necessary label information to
15133 		 * this packet
15134 		 */
15135 		if (is_system_labeled() &&
15136 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15137 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15138 			freemsg(mp);
15139 			continue;
15140 		}
15141 
15142 		/*
15143 		 * Reuse the cached ire only if the ipha_dst of the previous
15144 		 * packet is the same as the current packet AND it is not
15145 		 * INADDR_ANY.
15146 		 */
15147 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15148 		    (ire != NULL)) {
15149 			ire_refrele(ire);
15150 			ire = NULL;
15151 		}
15152 		opt_len = ipha->ipha_version_and_hdr_length -
15153 		    IP_SIMPLE_HDR_VERSION;
15154 
15155 		/*
15156 		 * Check to see if we can take the fastpath.
15157 		 * That is possible if the following conditions are met
15158 		 *	o Tsol disabled
15159 		 *	o CGTP disabled
15160 		 *	o ipp_action_count is 0
15161 		 *	o no options in the packet
15162 		 *	o not a RSVP packet
15163 		 * 	o not a multicast packet
15164 		 *	o ill not in IP_DHCPINIT_IF mode
15165 		 */
15166 		if (!is_system_labeled() &&
15167 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15168 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15169 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15170 			if (ire == NULL)
15171 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15172 				    ipst);
15173 
15174 			/* incoming packet is for forwarding */
15175 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15176 				ire = ip_fast_forward(ire, dst, ill, mp);
15177 				continue;
15178 			}
15179 			/* incoming packet is for local consumption */
15180 			if (ire->ire_type & IRE_LOCAL)
15181 				goto local;
15182 		}
15183 
15184 		/*
15185 		 * Disable ire caching for anything more complex
15186 		 * than the simple fast path case we checked for above.
15187 		 */
15188 		if (ire != NULL) {
15189 			ire_refrele(ire);
15190 			ire = NULL;
15191 		}
15192 
15193 		/*
15194 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15195 		 * server to unicast DHCP packets to a DHCP client using the
15196 		 * IP address it is offering to the client.  This can be
15197 		 * disabled through the "broadcast bit", but not all DHCP
15198 		 * servers honor that bit.  Therefore, to interoperate with as
15199 		 * many DHCP servers as possible, the DHCP client allows the
15200 		 * server to unicast, but we treat those packets as broadcast
15201 		 * here.  Note that we don't rewrite the packet itself since
15202 		 * (a) that would mess up the checksums and (b) the DHCP
15203 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15204 		 * hand it the packet regardless.
15205 		 */
15206 		if (ill->ill_dhcpinit != 0 &&
15207 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15208 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15209 			udpha_t *udpha;
15210 
15211 			/*
15212 			 * Reload ipha since pullupmsg() can change b_rptr.
15213 			 */
15214 			ipha = (ipha_t *)mp->b_rptr;
15215 			udpha = (udpha_t *)&ipha[1];
15216 
15217 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15218 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15219 				    mblk_t *, mp);
15220 				dst = INADDR_BROADCAST;
15221 			}
15222 		}
15223 
15224 		/* Full-blown slow path */
15225 		if (opt_len != 0) {
15226 			if (len != 0)
15227 				IP_STAT(ipst, ip_multimblk4);
15228 			else
15229 				IP_STAT(ipst, ip_ipoptions);
15230 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15231 			    &dst, ipst))
15232 				continue;
15233 		}
15234 
15235 		/*
15236 		 * Invoke the CGTP (multirouting) filtering module to process
15237 		 * the incoming packet. Packets identified as duplicates
15238 		 * must be discarded. Filtering is active only if the
15239 		 * the ip_cgtp_filter ndd variable is non-zero.
15240 		 */
15241 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15242 		if (ipst->ips_ip_cgtp_filter &&
15243 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15244 			netstackid_t stackid;
15245 
15246 			stackid = ipst->ips_netstack->netstack_stackid;
15247 			cgtp_flt_pkt =
15248 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15249 			    ill->ill_phyint->phyint_ifindex, mp);
15250 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15251 				freemsg(first_mp);
15252 				continue;
15253 			}
15254 		}
15255 
15256 		/*
15257 		 * If rsvpd is running, let RSVP daemon handle its processing
15258 		 * and forwarding of RSVP multicast/unicast packets.
15259 		 * If rsvpd is not running but mrouted is running, RSVP
15260 		 * multicast packets are forwarded as multicast traffic
15261 		 * and RSVP unicast packets are forwarded by unicast router.
15262 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15263 		 * packets are not forwarded, but the unicast packets are
15264 		 * forwarded like unicast traffic.
15265 		 */
15266 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15267 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15268 		    NULL) {
15269 			/* RSVP packet and rsvpd running. Treat as ours */
15270 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15271 			/*
15272 			 * This assumes that we deliver to all streams for
15273 			 * multicast and broadcast packets.
15274 			 * We have to force ll_multicast to 1 to handle the
15275 			 * M_DATA messages passed in from ip_mroute_decap.
15276 			 */
15277 			dst = INADDR_BROADCAST;
15278 			ll_multicast = 1;
15279 		} else if (CLASSD(dst)) {
15280 			/* packet is multicast */
15281 			mp->b_next = NULL;
15282 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15283 			    &ll_multicast, &dst))
15284 				continue;
15285 		}
15286 
15287 		if (ire == NULL) {
15288 			ire = ire_cache_lookup(dst, ALL_ZONES,
15289 			    MBLK_GETLABEL(mp), ipst);
15290 		}
15291 
15292 		if (ire == NULL) {
15293 			/*
15294 			 * No IRE for this destination, so it can't be for us.
15295 			 * Unless we are forwarding, drop the packet.
15296 			 * We have to let source routed packets through
15297 			 * since we don't yet know if they are 'ping -l'
15298 			 * packets i.e. if they will go out over the
15299 			 * same interface as they came in on.
15300 			 */
15301 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15302 			if (ire == NULL)
15303 				continue;
15304 		}
15305 
15306 		/*
15307 		 * Broadcast IRE may indicate either broadcast or
15308 		 * multicast packet
15309 		 */
15310 		if (ire->ire_type == IRE_BROADCAST) {
15311 			/*
15312 			 * Skip broadcast checks if packet is UDP multicast;
15313 			 * we'd rather not enter ip_rput_process_broadcast()
15314 			 * unless the packet is broadcast for real, since
15315 			 * that routine is a no-op for multicast.
15316 			 */
15317 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15318 			    !CLASSD(ipha->ipha_dst)) {
15319 				ire = ip_rput_process_broadcast(&q, mp,
15320 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15321 				    ll_multicast);
15322 				if (ire == NULL)
15323 					continue;
15324 			}
15325 		} else if (ire->ire_stq != NULL) {
15326 			/* fowarding? */
15327 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15328 			    ll_multicast);
15329 			/* ip_rput_process_forward consumed the packet */
15330 			continue;
15331 		}
15332 
15333 local:
15334 		/*
15335 		 * If the queue in the ire is different to the ingress queue
15336 		 * then we need to check to see if we can accept the packet.
15337 		 * Note that for multicast packets and broadcast packets sent
15338 		 * to a broadcast address which is shared between multiple
15339 		 * interfaces we should not do this since we just got a random
15340 		 * broadcast ire.
15341 		 */
15342 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15343 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15344 			    ill)) == NULL) {
15345 				/* Drop packet */
15346 				BUMP_MIB(ill->ill_ip_mib,
15347 				    ipIfStatsForwProhibits);
15348 				freemsg(mp);
15349 				continue;
15350 			}
15351 			if (ire->ire_rfq != NULL)
15352 				q = ire->ire_rfq;
15353 		}
15354 
15355 		switch (ipha->ipha_protocol) {
15356 		case IPPROTO_TCP:
15357 			ASSERT(first_mp == mp);
15358 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15359 			    mp, 0, q, ip_ring)) != NULL) {
15360 				if (curr_sqp == NULL) {
15361 					curr_sqp = GET_SQUEUE(mp);
15362 					ASSERT(cnt == 0);
15363 					cnt++;
15364 					head = tail = mp;
15365 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15366 					ASSERT(tail != NULL);
15367 					cnt++;
15368 					tail->b_next = mp;
15369 					tail = mp;
15370 				} else {
15371 					/*
15372 					 * A different squeue. Send the
15373 					 * chain for the previous squeue on
15374 					 * its way. This shouldn't happen
15375 					 * often unless interrupt binding
15376 					 * changes.
15377 					 */
15378 					IP_STAT(ipst, ip_input_multi_squeue);
15379 					squeue_enter_chain(curr_sqp, head,
15380 					    tail, cnt, SQTAG_IP_INPUT);
15381 					curr_sqp = GET_SQUEUE(mp);
15382 					head = mp;
15383 					tail = mp;
15384 					cnt = 1;
15385 				}
15386 			}
15387 			continue;
15388 		case IPPROTO_UDP:
15389 			ASSERT(first_mp == mp);
15390 			ip_udp_input(q, mp, ipha, ire, ill);
15391 			continue;
15392 		case IPPROTO_SCTP:
15393 			ASSERT(first_mp == mp);
15394 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15395 			    q, dst);
15396 			/* ire has been released by ip_sctp_input */
15397 			ire = NULL;
15398 			continue;
15399 		default:
15400 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15401 			continue;
15402 		}
15403 	}
15404 
15405 	if (ire != NULL)
15406 		ire_refrele(ire);
15407 
15408 	if (head != NULL)
15409 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15410 
15411 	/*
15412 	 * This code is there just to make netperf/ttcp look good.
15413 	 *
15414 	 * Its possible that after being in polling mode (and having cleared
15415 	 * the backlog), squeues have turned the interrupt frequency higher
15416 	 * to improve latency at the expense of more CPU utilization (less
15417 	 * packets per interrupts or more number of interrupts). Workloads
15418 	 * like ttcp/netperf do manage to tickle polling once in a while
15419 	 * but for the remaining time, stay in higher interrupt mode since
15420 	 * their packet arrival rate is pretty uniform and this shows up
15421 	 * as higher CPU utilization. Since people care about CPU utilization
15422 	 * while running netperf/ttcp, turn the interrupt frequency back to
15423 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15424 	 */
15425 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15426 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15427 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15428 			ip_ring->rr_blank(ip_ring->rr_handle,
15429 			    ip_ring->rr_normal_blank_time,
15430 			    ip_ring->rr_normal_pkt_cnt);
15431 		}
15432 		}
15433 
15434 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15435 	    "ip_input_end: q %p (%S)", q, "end");
15436 #undef  rptr
15437 }
15438 
15439 static void
15440 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15441     t_uscalar_t err)
15442 {
15443 	if (dl_err == DL_SYSERR) {
15444 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15445 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15446 		    ill->ill_name, dlpi_prim_str(prim), err);
15447 		return;
15448 	}
15449 
15450 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15451 	    "%s: %s failed: %s\n", ill->ill_name, dlpi_prim_str(prim),
15452 	    dlpi_err_str(dl_err));
15453 }
15454 
15455 /*
15456  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15457  * than DL_UNITDATA_IND messages. If we need to process this message
15458  * exclusively, we call qwriter_ip, in which case we also need to call
15459  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15460  */
15461 void
15462 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15463 {
15464 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15465 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15466 	ill_t		*ill = (ill_t *)q->q_ptr;
15467 	boolean_t	pending;
15468 
15469 	ip1dbg(("ip_rput_dlpi"));
15470 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15471 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15472 		    "%s (0x%x), unix %u\n", ill->ill_name,
15473 		    dlpi_prim_str(dlea->dl_error_primitive),
15474 		    dlea->dl_error_primitive,
15475 		    dlpi_err_str(dlea->dl_errno),
15476 		    dlea->dl_errno,
15477 		    dlea->dl_unix_errno));
15478 	}
15479 
15480 	/*
15481 	 * If we received an ACK but didn't send a request for it, then it
15482 	 * can't be part of any pending operation; discard up-front.
15483 	 */
15484 	switch (dloa->dl_primitive) {
15485 	case DL_NOTIFY_IND:
15486 		pending = B_TRUE;
15487 		break;
15488 	case DL_ERROR_ACK:
15489 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15490 		break;
15491 	case DL_OK_ACK:
15492 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15493 		break;
15494 	case DL_INFO_ACK:
15495 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15496 		break;
15497 	case DL_BIND_ACK:
15498 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15499 		break;
15500 	case DL_PHYS_ADDR_ACK:
15501 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15502 		break;
15503 	case DL_NOTIFY_ACK:
15504 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15505 		break;
15506 	case DL_CONTROL_ACK:
15507 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15508 		break;
15509 	case DL_CAPABILITY_ACK:
15510 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15511 		break;
15512 	default:
15513 		/* Not a DLPI message we support or were expecting */
15514 		freemsg(mp);
15515 		return;
15516 	}
15517 
15518 	if (!pending) {
15519 		freemsg(mp);
15520 		return;
15521 	}
15522 
15523 	switch (dloa->dl_primitive) {
15524 	case DL_ERROR_ACK:
15525 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15526 			mutex_enter(&ill->ill_lock);
15527 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15528 			cv_signal(&ill->ill_cv);
15529 			mutex_exit(&ill->ill_lock);
15530 		}
15531 		break;
15532 
15533 	case DL_OK_ACK:
15534 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15535 		    dlpi_prim_str((int)dloa->dl_correct_primitive)));
15536 		switch (dloa->dl_correct_primitive) {
15537 		case DL_UNBIND_REQ:
15538 			mutex_enter(&ill->ill_lock);
15539 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15540 			cv_signal(&ill->ill_cv);
15541 			mutex_exit(&ill->ill_lock);
15542 			break;
15543 
15544 		case DL_ENABMULTI_REQ:
15545 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15546 				ill->ill_dlpi_multicast_state = IDS_OK;
15547 			break;
15548 		}
15549 		break;
15550 	default:
15551 		break;
15552 	}
15553 
15554 	/*
15555 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15556 	 * and we need to become writer to continue to process it. If it's not
15557 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15558 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15559 	 * some work as part of the current exclusive operation that actually
15560 	 * is not part of it -- which is wrong, but better than the
15561 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15562 	 * should track which DLPI requests have ACKs that we wait on
15563 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15564 	 *
15565 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15566 	 * Since this is on the ill stream we unconditionally bump up the
15567 	 * refcount without doing ILL_CAN_LOOKUP().
15568 	 */
15569 	ill_refhold(ill);
15570 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15571 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15572 	else
15573 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15574 }
15575 
15576 /*
15577  * Handling of DLPI messages that require exclusive access to the ipsq.
15578  *
15579  * Need to do ill_pending_mp_release on ioctl completion, which could
15580  * happen here. (along with mi_copy_done)
15581  */
15582 /* ARGSUSED */
15583 static void
15584 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15585 {
15586 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15587 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15588 	int		err = 0;
15589 	ill_t		*ill;
15590 	ipif_t		*ipif = NULL;
15591 	mblk_t		*mp1 = NULL;
15592 	conn_t		*connp = NULL;
15593 	t_uscalar_t	paddrreq;
15594 	mblk_t		*mp_hw;
15595 	boolean_t	success;
15596 	boolean_t	ioctl_aborted = B_FALSE;
15597 	boolean_t	log = B_TRUE;
15598 	hook_nic_event_t	*info;
15599 	ip_stack_t		*ipst;
15600 
15601 	ip1dbg(("ip_rput_dlpi_writer .."));
15602 	ill = (ill_t *)q->q_ptr;
15603 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15604 
15605 	ASSERT(IAM_WRITER_ILL(ill));
15606 
15607 	ipst = ill->ill_ipst;
15608 
15609 	/*
15610 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15611 	 * both are null or non-null. However we can assert that only
15612 	 * after grabbing the ipsq_lock. So we don't make any assertion
15613 	 * here and in other places in the code.
15614 	 */
15615 	ipif = ipsq->ipsq_pending_ipif;
15616 	/*
15617 	 * The current ioctl could have been aborted by the user and a new
15618 	 * ioctl to bring up another ill could have started. We could still
15619 	 * get a response from the driver later.
15620 	 */
15621 	if (ipif != NULL && ipif->ipif_ill != ill)
15622 		ioctl_aborted = B_TRUE;
15623 
15624 	switch (dloa->dl_primitive) {
15625 	case DL_ERROR_ACK:
15626 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15627 		    dlpi_prim_str(dlea->dl_error_primitive)));
15628 
15629 		switch (dlea->dl_error_primitive) {
15630 		case DL_PROMISCON_REQ:
15631 		case DL_PROMISCOFF_REQ:
15632 		case DL_DISABMULTI_REQ:
15633 		case DL_UNBIND_REQ:
15634 		case DL_ATTACH_REQ:
15635 		case DL_INFO_REQ:
15636 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15637 			break;
15638 		case DL_NOTIFY_REQ:
15639 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15640 			log = B_FALSE;
15641 			break;
15642 		case DL_PHYS_ADDR_REQ:
15643 			/*
15644 			 * For IPv6 only, there are two additional
15645 			 * phys_addr_req's sent to the driver to get the
15646 			 * IPv6 token and lla. This allows IP to acquire
15647 			 * the hardware address format for a given interface
15648 			 * without having built in knowledge of the hardware
15649 			 * address. ill_phys_addr_pend keeps track of the last
15650 			 * DL_PAR sent so we know which response we are
15651 			 * dealing with. ill_dlpi_done will update
15652 			 * ill_phys_addr_pend when it sends the next req.
15653 			 * We don't complete the IOCTL until all three DL_PARs
15654 			 * have been attempted, so set *_len to 0 and break.
15655 			 */
15656 			paddrreq = ill->ill_phys_addr_pend;
15657 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15658 			if (paddrreq == DL_IPV6_TOKEN) {
15659 				ill->ill_token_length = 0;
15660 				log = B_FALSE;
15661 				break;
15662 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15663 				ill->ill_nd_lla_len = 0;
15664 				log = B_FALSE;
15665 				break;
15666 			}
15667 			/*
15668 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15669 			 * We presumably have an IOCTL hanging out waiting
15670 			 * for completion. Find it and complete the IOCTL
15671 			 * with the error noted.
15672 			 * However, ill_dl_phys was called on an ill queue
15673 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15674 			 * set. But the ioctl is known to be pending on ill_wq.
15675 			 */
15676 			if (!ill->ill_ifname_pending)
15677 				break;
15678 			ill->ill_ifname_pending = 0;
15679 			if (!ioctl_aborted)
15680 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15681 			if (mp1 != NULL) {
15682 				/*
15683 				 * This operation (SIOCSLIFNAME) must have
15684 				 * happened on the ill. Assert there is no conn
15685 				 */
15686 				ASSERT(connp == NULL);
15687 				q = ill->ill_wq;
15688 			}
15689 			break;
15690 		case DL_BIND_REQ:
15691 			ill_dlpi_done(ill, DL_BIND_REQ);
15692 			if (ill->ill_ifname_pending)
15693 				break;
15694 			/*
15695 			 * Something went wrong with the bind.  We presumably
15696 			 * have an IOCTL hanging out waiting for completion.
15697 			 * Find it, take down the interface that was coming
15698 			 * up, and complete the IOCTL with the error noted.
15699 			 */
15700 			if (!ioctl_aborted)
15701 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15702 			if (mp1 != NULL) {
15703 				/*
15704 				 * This operation (SIOCSLIFFLAGS) must have
15705 				 * happened from a conn.
15706 				 */
15707 				ASSERT(connp != NULL);
15708 				q = CONNP_TO_WQ(connp);
15709 				if (ill->ill_move_in_progress) {
15710 					ILL_CLEAR_MOVE(ill);
15711 				}
15712 				(void) ipif_down(ipif, NULL, NULL);
15713 				/* error is set below the switch */
15714 			}
15715 			break;
15716 		case DL_ENABMULTI_REQ:
15717 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15718 
15719 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15720 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15721 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15722 				ipif_t *ipif;
15723 
15724 				printf("ip: joining multicasts failed (%d)"
15725 				    " on %s - will use link layer "
15726 				    "broadcasts for multicast\n",
15727 				    dlea->dl_errno, ill->ill_name);
15728 
15729 				/*
15730 				 * Set up the multicast mapping alone.
15731 				 * writer, so ok to access ill->ill_ipif
15732 				 * without any lock.
15733 				 */
15734 				ipif = ill->ill_ipif;
15735 				mutex_enter(&ill->ill_phyint->phyint_lock);
15736 				ill->ill_phyint->phyint_flags |=
15737 				    PHYI_MULTI_BCAST;
15738 				mutex_exit(&ill->ill_phyint->phyint_lock);
15739 
15740 				if (!ill->ill_isv6) {
15741 					(void) ipif_arp_setup_multicast(ipif,
15742 					    NULL);
15743 				} else {
15744 					(void) ipif_ndp_setup_multicast(ipif,
15745 					    NULL);
15746 				}
15747 			}
15748 			freemsg(mp);	/* Don't want to pass this up */
15749 			return;
15750 
15751 		case DL_CAPABILITY_REQ:
15752 		case DL_CONTROL_REQ:
15753 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15754 			ill->ill_dlpi_capab_state = IDS_FAILED;
15755 			freemsg(mp);
15756 			return;
15757 		}
15758 		/*
15759 		 * Note the error for IOCTL completion (mp1 is set when
15760 		 * ready to complete ioctl). If ill_ifname_pending_err is
15761 		 * set, an error occured during plumbing (ill_ifname_pending),
15762 		 * so we want to report that error.
15763 		 *
15764 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15765 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15766 		 * expected to get errack'd if the driver doesn't support
15767 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15768 		 * if these error conditions are encountered.
15769 		 */
15770 		if (mp1 != NULL) {
15771 			if (ill->ill_ifname_pending_err != 0)  {
15772 				err = ill->ill_ifname_pending_err;
15773 				ill->ill_ifname_pending_err = 0;
15774 			} else {
15775 				err = dlea->dl_unix_errno ?
15776 				    dlea->dl_unix_errno : ENXIO;
15777 			}
15778 		/*
15779 		 * If we're plumbing an interface and an error hasn't already
15780 		 * been saved, set ill_ifname_pending_err to the error passed
15781 		 * up. Ignore the error if log is B_FALSE (see comment above).
15782 		 */
15783 		} else if (log && ill->ill_ifname_pending &&
15784 		    ill->ill_ifname_pending_err == 0) {
15785 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15786 			    dlea->dl_unix_errno : ENXIO;
15787 		}
15788 
15789 		if (log)
15790 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15791 			    dlea->dl_errno, dlea->dl_unix_errno);
15792 		break;
15793 	case DL_CAPABILITY_ACK:
15794 		/* Call a routine to handle this one. */
15795 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15796 		ill_capability_ack(ill, mp);
15797 
15798 		/*
15799 		 * If the ack is due to renegotiation, we will need to send
15800 		 * a new CAPABILITY_REQ to start the renegotiation.
15801 		 */
15802 		if (ill->ill_capab_reneg) {
15803 			ill->ill_capab_reneg = B_FALSE;
15804 			ill_capability_probe(ill);
15805 		}
15806 		break;
15807 	case DL_CONTROL_ACK:
15808 		/* We treat all of these as "fire and forget" */
15809 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15810 		break;
15811 	case DL_INFO_ACK:
15812 		/* Call a routine to handle this one. */
15813 		ill_dlpi_done(ill, DL_INFO_REQ);
15814 		ip_ll_subnet_defaults(ill, mp);
15815 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15816 		return;
15817 	case DL_BIND_ACK:
15818 		/*
15819 		 * We should have an IOCTL waiting on this unless
15820 		 * sent by ill_dl_phys, in which case just return
15821 		 */
15822 		ill_dlpi_done(ill, DL_BIND_REQ);
15823 		if (ill->ill_ifname_pending)
15824 			break;
15825 
15826 		if (!ioctl_aborted)
15827 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15828 		if (mp1 == NULL)
15829 			break;
15830 		/*
15831 		 * Because mp1 was added by ill_dl_up(), and it always
15832 		 * passes a valid connp, connp must be valid here.
15833 		 */
15834 		ASSERT(connp != NULL);
15835 		q = CONNP_TO_WQ(connp);
15836 
15837 		/*
15838 		 * We are exclusive. So nothing can change even after
15839 		 * we get the pending mp. If need be we can put it back
15840 		 * and restart, as in calling ipif_arp_up()  below.
15841 		 */
15842 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15843 
15844 		mutex_enter(&ill->ill_lock);
15845 
15846 		ill->ill_dl_up = 1;
15847 
15848 		if ((info = ill->ill_nic_event_info) != NULL) {
15849 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15850 			    "attached for %s\n", info->hne_event,
15851 			    ill->ill_name));
15852 			if (info->hne_data != NULL)
15853 				kmem_free(info->hne_data, info->hne_datalen);
15854 			kmem_free(info, sizeof (hook_nic_event_t));
15855 		}
15856 
15857 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15858 		if (info != NULL) {
15859 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15860 			info->hne_lif = 0;
15861 			info->hne_event = NE_UP;
15862 			info->hne_data = NULL;
15863 			info->hne_datalen = 0;
15864 			info->hne_family = ill->ill_isv6 ?
15865 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15866 		} else
15867 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15868 			    "event information for %s (ENOMEM)\n",
15869 			    ill->ill_name));
15870 
15871 		ill->ill_nic_event_info = info;
15872 
15873 		mutex_exit(&ill->ill_lock);
15874 
15875 		/*
15876 		 * Now bring up the resolver; when that is complete, we'll
15877 		 * create IREs.  Note that we intentionally mirror what
15878 		 * ipif_up() would have done, because we got here by way of
15879 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15880 		 */
15881 		if (ill->ill_isv6) {
15882 			/*
15883 			 * v6 interfaces.
15884 			 * Unlike ARP which has to do another bind
15885 			 * and attach, once we get here we are
15886 			 * done with NDP. Except in the case of
15887 			 * ILLF_XRESOLV, in which case we send an
15888 			 * AR_INTERFACE_UP to the external resolver.
15889 			 * If all goes well, the ioctl will complete
15890 			 * in ip_rput(). If there's an error, we
15891 			 * complete it here.
15892 			 */
15893 			if ((err = ipif_ndp_up(ipif)) == 0) {
15894 				if (ill->ill_flags & ILLF_XRESOLV) {
15895 					mutex_enter(&connp->conn_lock);
15896 					mutex_enter(&ill->ill_lock);
15897 					success = ipsq_pending_mp_add(
15898 					    connp, ipif, q, mp1, 0);
15899 					mutex_exit(&ill->ill_lock);
15900 					mutex_exit(&connp->conn_lock);
15901 					if (success) {
15902 						err = ipif_resolver_up(ipif,
15903 						    Res_act_initial);
15904 						if (err == EINPROGRESS) {
15905 							freemsg(mp);
15906 							return;
15907 						}
15908 						ASSERT(err != 0);
15909 						mp1 = ipsq_pending_mp_get(ipsq,
15910 						    &connp);
15911 						ASSERT(mp1 != NULL);
15912 					} else {
15913 						/* conn has started closing */
15914 						err = EINTR;
15915 					}
15916 				} else { /* Non XRESOLV interface */
15917 					(void) ipif_resolver_up(ipif,
15918 					    Res_act_initial);
15919 					err = ipif_up_done_v6(ipif);
15920 				}
15921 			}
15922 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15923 			/*
15924 			 * ARP and other v4 external resolvers.
15925 			 * Leave the pending mblk intact so that
15926 			 * the ioctl completes in ip_rput().
15927 			 */
15928 			mutex_enter(&connp->conn_lock);
15929 			mutex_enter(&ill->ill_lock);
15930 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15931 			mutex_exit(&ill->ill_lock);
15932 			mutex_exit(&connp->conn_lock);
15933 			if (success) {
15934 				err = ipif_resolver_up(ipif, Res_act_initial);
15935 				if (err == EINPROGRESS) {
15936 					freemsg(mp);
15937 					return;
15938 				}
15939 				ASSERT(err != 0);
15940 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15941 			} else {
15942 				/* The conn has started closing */
15943 				err = EINTR;
15944 			}
15945 		} else {
15946 			/*
15947 			 * This one is complete. Reply to pending ioctl.
15948 			 */
15949 			(void) ipif_resolver_up(ipif, Res_act_initial);
15950 			err = ipif_up_done(ipif);
15951 		}
15952 
15953 		if ((err == 0) && (ill->ill_up_ipifs)) {
15954 			err = ill_up_ipifs(ill, q, mp1);
15955 			if (err == EINPROGRESS) {
15956 				freemsg(mp);
15957 				return;
15958 			}
15959 		}
15960 
15961 		if (ill->ill_up_ipifs) {
15962 			ill_group_cleanup(ill);
15963 		}
15964 
15965 		break;
15966 	case DL_NOTIFY_IND: {
15967 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15968 		ire_t *ire;
15969 		boolean_t need_ire_walk_v4 = B_FALSE;
15970 		boolean_t need_ire_walk_v6 = B_FALSE;
15971 
15972 		switch (notify->dl_notification) {
15973 		case DL_NOTE_PHYS_ADDR:
15974 			err = ill_set_phys_addr(ill, mp);
15975 			break;
15976 
15977 		case DL_NOTE_FASTPATH_FLUSH:
15978 			ill_fastpath_flush(ill);
15979 			break;
15980 
15981 		case DL_NOTE_SDU_SIZE:
15982 			/*
15983 			 * Change the MTU size of the interface, of all
15984 			 * attached ipif's, and of all relevant ire's.  The
15985 			 * new value's a uint32_t at notify->dl_data.
15986 			 * Mtu change Vs. new ire creation - protocol below.
15987 			 *
15988 			 * a Mark the ipif as IPIF_CHANGING.
15989 			 * b Set the new mtu in the ipif.
15990 			 * c Change the ire_max_frag on all affected ires
15991 			 * d Unmark the IPIF_CHANGING
15992 			 *
15993 			 * To see how the protocol works, assume an interface
15994 			 * route is also being added simultaneously by
15995 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15996 			 * the ire. If the ire is created before step a,
15997 			 * it will be cleaned up by step c. If the ire is
15998 			 * created after step d, it will see the new value of
15999 			 * ipif_mtu. Any attempt to create the ire between
16000 			 * steps a to d will fail because of the IPIF_CHANGING
16001 			 * flag. Note that ire_create() is passed a pointer to
16002 			 * the ipif_mtu, and not the value. During ire_add
16003 			 * under the bucket lock, the ire_max_frag of the
16004 			 * new ire being created is set from the ipif/ire from
16005 			 * which it is being derived.
16006 			 */
16007 			mutex_enter(&ill->ill_lock);
16008 			ill->ill_max_frag = (uint_t)notify->dl_data;
16009 
16010 			/*
16011 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
16012 			 * leave it alone
16013 			 */
16014 			if (ill->ill_mtu_userspecified) {
16015 				mutex_exit(&ill->ill_lock);
16016 				break;
16017 			}
16018 			ill->ill_max_mtu = ill->ill_max_frag;
16019 			if (ill->ill_isv6) {
16020 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
16021 					ill->ill_max_mtu = IPV6_MIN_MTU;
16022 			} else {
16023 				if (ill->ill_max_mtu < IP_MIN_MTU)
16024 					ill->ill_max_mtu = IP_MIN_MTU;
16025 			}
16026 			for (ipif = ill->ill_ipif; ipif != NULL;
16027 			    ipif = ipif->ipif_next) {
16028 				/*
16029 				 * Don't override the mtu if the user
16030 				 * has explicitly set it.
16031 				 */
16032 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
16033 					continue;
16034 				ipif->ipif_mtu = (uint_t)notify->dl_data;
16035 				if (ipif->ipif_isv6)
16036 					ire = ipif_to_ire_v6(ipif);
16037 				else
16038 					ire = ipif_to_ire(ipif);
16039 				if (ire != NULL) {
16040 					ire->ire_max_frag = ipif->ipif_mtu;
16041 					ire_refrele(ire);
16042 				}
16043 				if (ipif->ipif_flags & IPIF_UP) {
16044 					if (ill->ill_isv6)
16045 						need_ire_walk_v6 = B_TRUE;
16046 					else
16047 						need_ire_walk_v4 = B_TRUE;
16048 				}
16049 			}
16050 			mutex_exit(&ill->ill_lock);
16051 			if (need_ire_walk_v4)
16052 				ire_walk_v4(ill_mtu_change, (char *)ill,
16053 				    ALL_ZONES, ipst);
16054 			if (need_ire_walk_v6)
16055 				ire_walk_v6(ill_mtu_change, (char *)ill,
16056 				    ALL_ZONES, ipst);
16057 			break;
16058 		case DL_NOTE_LINK_UP:
16059 		case DL_NOTE_LINK_DOWN: {
16060 			/*
16061 			 * We are writer. ill / phyint / ipsq assocs stable.
16062 			 * The RUNNING flag reflects the state of the link.
16063 			 */
16064 			phyint_t *phyint = ill->ill_phyint;
16065 			uint64_t new_phyint_flags;
16066 			boolean_t changed = B_FALSE;
16067 			boolean_t went_up;
16068 
16069 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16070 			mutex_enter(&phyint->phyint_lock);
16071 			new_phyint_flags = went_up ?
16072 			    phyint->phyint_flags | PHYI_RUNNING :
16073 			    phyint->phyint_flags & ~PHYI_RUNNING;
16074 			if (new_phyint_flags != phyint->phyint_flags) {
16075 				phyint->phyint_flags = new_phyint_flags;
16076 				changed = B_TRUE;
16077 			}
16078 			mutex_exit(&phyint->phyint_lock);
16079 			/*
16080 			 * ill_restart_dad handles the DAD restart and routing
16081 			 * socket notification logic.
16082 			 */
16083 			if (changed) {
16084 				ill_restart_dad(phyint->phyint_illv4, went_up);
16085 				ill_restart_dad(phyint->phyint_illv6, went_up);
16086 			}
16087 			break;
16088 		}
16089 		case DL_NOTE_PROMISC_ON_PHYS:
16090 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16091 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16092 			mutex_enter(&ill->ill_lock);
16093 			ill->ill_promisc_on_phys = B_TRUE;
16094 			mutex_exit(&ill->ill_lock);
16095 			break;
16096 		case DL_NOTE_PROMISC_OFF_PHYS:
16097 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16098 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16099 			mutex_enter(&ill->ill_lock);
16100 			ill->ill_promisc_on_phys = B_FALSE;
16101 			mutex_exit(&ill->ill_lock);
16102 			break;
16103 		case DL_NOTE_CAPAB_RENEG:
16104 			/*
16105 			 * Something changed on the driver side.
16106 			 * It wants us to renegotiate the capabilities
16107 			 * on this ill. One possible cause is the aggregation
16108 			 * interface under us where a port got added or
16109 			 * went away.
16110 			 *
16111 			 * If the capability negotiation is already done
16112 			 * or is in progress, reset the capabilities and
16113 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16114 			 * so that when the ack comes back, we can start
16115 			 * the renegotiation process.
16116 			 *
16117 			 * Note that if ill_capab_reneg is already B_TRUE
16118 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16119 			 * the capability resetting request has been sent
16120 			 * and the renegotiation has not been started yet;
16121 			 * nothing needs to be done in this case.
16122 			 */
16123 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16124 				ill_capability_reset(ill);
16125 				ill->ill_capab_reneg = B_TRUE;
16126 			}
16127 			break;
16128 		default:
16129 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16130 			    "type 0x%x for DL_NOTIFY_IND\n",
16131 			    notify->dl_notification));
16132 			break;
16133 		}
16134 
16135 		/*
16136 		 * As this is an asynchronous operation, we
16137 		 * should not call ill_dlpi_done
16138 		 */
16139 		break;
16140 	}
16141 	case DL_NOTIFY_ACK: {
16142 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16143 
16144 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16145 			ill->ill_note_link = 1;
16146 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16147 		break;
16148 	}
16149 	case DL_PHYS_ADDR_ACK: {
16150 		/*
16151 		 * As part of plumbing the interface via SIOCSLIFNAME,
16152 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16153 		 * whose answers we receive here.  As each answer is received,
16154 		 * we call ill_dlpi_done() to dispatch the next request as
16155 		 * we're processing the current one.  Once all answers have
16156 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16157 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16158 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16159 		 * available, but we know the ioctl is pending on ill_wq.)
16160 		 */
16161 		uint_t paddrlen, paddroff;
16162 
16163 		paddrreq = ill->ill_phys_addr_pend;
16164 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16165 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16166 
16167 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16168 		if (paddrreq == DL_IPV6_TOKEN) {
16169 			/*
16170 			 * bcopy to low-order bits of ill_token
16171 			 *
16172 			 * XXX Temporary hack - currently, all known tokens
16173 			 * are 64 bits, so I'll cheat for the moment.
16174 			 */
16175 			bcopy(mp->b_rptr + paddroff,
16176 			    &ill->ill_token.s6_addr32[2], paddrlen);
16177 			ill->ill_token_length = paddrlen;
16178 			break;
16179 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16180 			ASSERT(ill->ill_nd_lla_mp == NULL);
16181 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16182 			mp = NULL;
16183 			break;
16184 		}
16185 
16186 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16187 		ASSERT(ill->ill_phys_addr_mp == NULL);
16188 		if (!ill->ill_ifname_pending)
16189 			break;
16190 		ill->ill_ifname_pending = 0;
16191 		if (!ioctl_aborted)
16192 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16193 		if (mp1 != NULL) {
16194 			ASSERT(connp == NULL);
16195 			q = ill->ill_wq;
16196 		}
16197 		/*
16198 		 * If any error acks received during the plumbing sequence,
16199 		 * ill_ifname_pending_err will be set. Break out and send up
16200 		 * the error to the pending ioctl.
16201 		 */
16202 		if (ill->ill_ifname_pending_err != 0) {
16203 			err = ill->ill_ifname_pending_err;
16204 			ill->ill_ifname_pending_err = 0;
16205 			break;
16206 		}
16207 
16208 		ill->ill_phys_addr_mp = mp;
16209 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16210 		mp = NULL;
16211 
16212 		/*
16213 		 * If paddrlen is zero, the DLPI provider doesn't support
16214 		 * physical addresses.  The other two tests were historical
16215 		 * workarounds for bugs in our former PPP implementation, but
16216 		 * now other things have grown dependencies on them -- e.g.,
16217 		 * the tun module specifies a dl_addr_length of zero in its
16218 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16219 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16220 		 * but only after careful testing ensures that all dependent
16221 		 * broken DLPI providers have been fixed.
16222 		 */
16223 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16224 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16225 			ill->ill_phys_addr = NULL;
16226 		} else if (paddrlen != ill->ill_phys_addr_length) {
16227 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16228 			    paddrlen, ill->ill_phys_addr_length));
16229 			err = EINVAL;
16230 			break;
16231 		}
16232 
16233 		if (ill->ill_nd_lla_mp == NULL) {
16234 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16235 				err = ENOMEM;
16236 				break;
16237 			}
16238 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16239 		}
16240 
16241 		/*
16242 		 * Set the interface token.  If the zeroth interface address
16243 		 * is unspecified, then set it to the link local address.
16244 		 */
16245 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16246 			(void) ill_setdefaulttoken(ill);
16247 
16248 		ASSERT(ill->ill_ipif->ipif_id == 0);
16249 		if (ipif != NULL &&
16250 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16251 			(void) ipif_setlinklocal(ipif);
16252 		}
16253 		break;
16254 	}
16255 	case DL_OK_ACK:
16256 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16257 		    dlpi_prim_str((int)dloa->dl_correct_primitive),
16258 		    dloa->dl_correct_primitive));
16259 		switch (dloa->dl_correct_primitive) {
16260 		case DL_PROMISCON_REQ:
16261 		case DL_PROMISCOFF_REQ:
16262 		case DL_ENABMULTI_REQ:
16263 		case DL_DISABMULTI_REQ:
16264 		case DL_UNBIND_REQ:
16265 		case DL_ATTACH_REQ:
16266 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16267 			break;
16268 		}
16269 		break;
16270 	default:
16271 		break;
16272 	}
16273 
16274 	freemsg(mp);
16275 	if (mp1 != NULL) {
16276 		/*
16277 		 * The operation must complete without EINPROGRESS
16278 		 * since ipsq_pending_mp_get() has removed the mblk
16279 		 * from ipsq_pending_mp.  Otherwise, the operation
16280 		 * will be stuck forever in the ipsq.
16281 		 */
16282 		ASSERT(err != EINPROGRESS);
16283 
16284 		switch (ipsq->ipsq_current_ioctl) {
16285 		case 0:
16286 			ipsq_current_finish(ipsq);
16287 			break;
16288 
16289 		case SIOCLIFADDIF:
16290 		case SIOCSLIFNAME:
16291 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16292 			break;
16293 
16294 		default:
16295 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16296 			break;
16297 		}
16298 	}
16299 }
16300 
16301 /*
16302  * ip_rput_other is called by ip_rput to handle messages modifying the global
16303  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16304  */
16305 /* ARGSUSED */
16306 void
16307 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16308 {
16309 	ill_t		*ill;
16310 	struct iocblk	*iocp;
16311 	mblk_t		*mp1;
16312 	conn_t		*connp = NULL;
16313 
16314 	ip1dbg(("ip_rput_other "));
16315 	ill = (ill_t *)q->q_ptr;
16316 	/*
16317 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16318 	 * in which case ipsq is NULL.
16319 	 */
16320 	if (ipsq != NULL) {
16321 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16322 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16323 	}
16324 
16325 	switch (mp->b_datap->db_type) {
16326 	case M_ERROR:
16327 	case M_HANGUP:
16328 		/*
16329 		 * The device has a problem.  We force the ILL down.  It can
16330 		 * be brought up again manually using SIOCSIFFLAGS (via
16331 		 * ifconfig or equivalent).
16332 		 */
16333 		ASSERT(ipsq != NULL);
16334 		if (mp->b_rptr < mp->b_wptr)
16335 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16336 		if (ill->ill_error == 0)
16337 			ill->ill_error = ENXIO;
16338 		if (!ill_down_start(q, mp))
16339 			return;
16340 		ipif_all_down_tail(ipsq, q, mp, NULL);
16341 		break;
16342 	case M_IOCACK:
16343 		iocp = (struct iocblk *)mp->b_rptr;
16344 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16345 		switch (iocp->ioc_cmd) {
16346 		case SIOCSTUNPARAM:
16347 		case OSIOCSTUNPARAM:
16348 			ASSERT(ipsq != NULL);
16349 			/*
16350 			 * Finish socket ioctl passed through to tun.
16351 			 * We should have an IOCTL waiting on this.
16352 			 */
16353 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16354 			if (ill->ill_isv6) {
16355 				struct iftun_req *ta;
16356 
16357 				/*
16358 				 * if a source or destination is
16359 				 * being set, try and set the link
16360 				 * local address for the tunnel
16361 				 */
16362 				ta = (struct iftun_req *)mp->b_cont->
16363 				    b_cont->b_rptr;
16364 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16365 					ipif_set_tun_llink(ill, ta);
16366 				}
16367 
16368 			}
16369 			if (mp1 != NULL) {
16370 				/*
16371 				 * Now copy back the b_next/b_prev used by
16372 				 * mi code for the mi_copy* functions.
16373 				 * See ip_sioctl_tunparam() for the reason.
16374 				 * Also protect against missing b_cont.
16375 				 */
16376 				if (mp->b_cont != NULL) {
16377 					mp->b_cont->b_next =
16378 					    mp1->b_cont->b_next;
16379 					mp->b_cont->b_prev =
16380 					    mp1->b_cont->b_prev;
16381 				}
16382 				inet_freemsg(mp1);
16383 				ASSERT(connp != NULL);
16384 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16385 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16386 			} else {
16387 				ASSERT(connp == NULL);
16388 				putnext(q, mp);
16389 			}
16390 			break;
16391 		case SIOCGTUNPARAM:
16392 		case OSIOCGTUNPARAM:
16393 			/*
16394 			 * This is really M_IOCDATA from the tunnel driver.
16395 			 * convert back and complete the ioctl.
16396 			 * We should have an IOCTL waiting on this.
16397 			 */
16398 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16399 			if (mp1) {
16400 				/*
16401 				 * Now copy back the b_next/b_prev used by
16402 				 * mi code for the mi_copy* functions.
16403 				 * See ip_sioctl_tunparam() for the reason.
16404 				 * Also protect against missing b_cont.
16405 				 */
16406 				if (mp->b_cont != NULL) {
16407 					mp->b_cont->b_next =
16408 					    mp1->b_cont->b_next;
16409 					mp->b_cont->b_prev =
16410 					    mp1->b_cont->b_prev;
16411 				}
16412 				inet_freemsg(mp1);
16413 				if (iocp->ioc_error == 0)
16414 					mp->b_datap->db_type = M_IOCDATA;
16415 				ASSERT(connp != NULL);
16416 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16417 				    iocp->ioc_error, COPYOUT, NULL);
16418 			} else {
16419 				ASSERT(connp == NULL);
16420 				putnext(q, mp);
16421 			}
16422 			break;
16423 		default:
16424 			break;
16425 		}
16426 		break;
16427 	case M_IOCNAK:
16428 		iocp = (struct iocblk *)mp->b_rptr;
16429 
16430 		switch (iocp->ioc_cmd) {
16431 		int mode;
16432 
16433 		case DL_IOC_HDR_INFO:
16434 			/*
16435 			 * If this was the first attempt turn of the
16436 			 * fastpath probing.
16437 			 */
16438 			mutex_enter(&ill->ill_lock);
16439 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16440 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16441 				mutex_exit(&ill->ill_lock);
16442 				ill_fastpath_nack(ill);
16443 				ip1dbg(("ip_rput: DLPI fastpath off on "
16444 				    "interface %s\n",
16445 				    ill->ill_name));
16446 			} else {
16447 				mutex_exit(&ill->ill_lock);
16448 			}
16449 			freemsg(mp);
16450 			break;
16451 		case SIOCSTUNPARAM:
16452 		case OSIOCSTUNPARAM:
16453 			ASSERT(ipsq != NULL);
16454 			/*
16455 			 * Finish socket ioctl passed through to tun
16456 			 * We should have an IOCTL waiting on this.
16457 			 */
16458 			/* FALLTHRU */
16459 		case SIOCGTUNPARAM:
16460 		case OSIOCGTUNPARAM:
16461 			/*
16462 			 * This is really M_IOCDATA from the tunnel driver.
16463 			 * convert back and complete the ioctl.
16464 			 * We should have an IOCTL waiting on this.
16465 			 */
16466 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16467 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16468 				mp1 = ill_pending_mp_get(ill, &connp,
16469 				    iocp->ioc_id);
16470 				mode = COPYOUT;
16471 				ipsq = NULL;
16472 			} else {
16473 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16474 				mode = NO_COPYOUT;
16475 			}
16476 			if (mp1 != NULL) {
16477 				/*
16478 				 * Now copy back the b_next/b_prev used by
16479 				 * mi code for the mi_copy* functions.
16480 				 * See ip_sioctl_tunparam() for the reason.
16481 				 * Also protect against missing b_cont.
16482 				 */
16483 				if (mp->b_cont != NULL) {
16484 					mp->b_cont->b_next =
16485 					    mp1->b_cont->b_next;
16486 					mp->b_cont->b_prev =
16487 					    mp1->b_cont->b_prev;
16488 				}
16489 				inet_freemsg(mp1);
16490 				if (iocp->ioc_error == 0)
16491 					iocp->ioc_error = EINVAL;
16492 				ASSERT(connp != NULL);
16493 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16494 				    iocp->ioc_error, mode, ipsq);
16495 			} else {
16496 				ASSERT(connp == NULL);
16497 				putnext(q, mp);
16498 			}
16499 			break;
16500 		default:
16501 			break;
16502 		}
16503 	default:
16504 		break;
16505 	}
16506 }
16507 
16508 /*
16509  * NOTE : This function does not ire_refrele the ire argument passed in.
16510  *
16511  * IPQoS notes
16512  * IP policy is invoked twice for a forwarded packet, once on the read side
16513  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16514  * enabled. An additional parameter, in_ill, has been added for this purpose.
16515  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16516  * because ip_mroute drops this information.
16517  *
16518  */
16519 void
16520 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16521 {
16522 	uint32_t	old_pkt_len;
16523 	uint32_t	pkt_len;
16524 	queue_t	*q;
16525 	uint32_t	sum;
16526 #define	rptr	((uchar_t *)ipha)
16527 	uint32_t	max_frag;
16528 	uint32_t	ill_index;
16529 	ill_t		*out_ill;
16530 	mib2_ipIfStatsEntry_t *mibptr;
16531 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16532 
16533 	/* Get the ill_index of the incoming ILL */
16534 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16535 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16536 
16537 	/* Initiate Read side IPPF processing */
16538 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16539 		ip_process(IPP_FWD_IN, &mp, ill_index);
16540 		if (mp == NULL) {
16541 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16542 			    "during IPPF processing\n"));
16543 			return;
16544 		}
16545 	}
16546 
16547 	/* Adjust the checksum to reflect the ttl decrement. */
16548 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16549 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16550 
16551 	if (ipha->ipha_ttl-- <= 1) {
16552 		if (ip_csum_hdr(ipha)) {
16553 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16554 			goto drop_pkt;
16555 		}
16556 		/*
16557 		 * Note: ire_stq this will be NULL for multicast
16558 		 * datagrams using the long path through arp (the IRE
16559 		 * is not an IRE_CACHE). This should not cause
16560 		 * problems since we don't generate ICMP errors for
16561 		 * multicast packets.
16562 		 */
16563 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16564 		q = ire->ire_stq;
16565 		if (q != NULL) {
16566 			/* Sent by forwarding path, and router is global zone */
16567 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16568 			    GLOBAL_ZONEID, ipst);
16569 		} else
16570 			freemsg(mp);
16571 		return;
16572 	}
16573 
16574 	/*
16575 	 * Don't forward if the interface is down
16576 	 */
16577 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16578 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16579 		ip2dbg(("ip_rput_forward:interface is down\n"));
16580 		goto drop_pkt;
16581 	}
16582 
16583 	/* Get the ill_index of the outgoing ILL */
16584 	out_ill = ire_to_ill(ire);
16585 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16586 
16587 	DTRACE_PROBE4(ip4__forwarding__start,
16588 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16589 
16590 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16591 	    ipst->ips_ipv4firewall_forwarding,
16592 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16593 
16594 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16595 
16596 	if (mp == NULL)
16597 		return;
16598 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16599 
16600 	if (is_system_labeled()) {
16601 		mblk_t *mp1;
16602 
16603 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16604 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16605 			goto drop_pkt;
16606 		}
16607 		/* Size may have changed */
16608 		mp = mp1;
16609 		ipha = (ipha_t *)mp->b_rptr;
16610 		pkt_len = ntohs(ipha->ipha_length);
16611 	}
16612 
16613 	/* Check if there are options to update */
16614 	if (!IS_SIMPLE_IPH(ipha)) {
16615 		if (ip_csum_hdr(ipha)) {
16616 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16617 			goto drop_pkt;
16618 		}
16619 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16620 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16621 			return;
16622 		}
16623 
16624 		ipha->ipha_hdr_checksum = 0;
16625 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16626 	}
16627 	max_frag = ire->ire_max_frag;
16628 	if (pkt_len > max_frag) {
16629 		/*
16630 		 * It needs fragging on its way out.  We haven't
16631 		 * verified the header checksum yet.  Since we
16632 		 * are going to put a surely good checksum in the
16633 		 * outgoing header, we have to make sure that it
16634 		 * was good coming in.
16635 		 */
16636 		if (ip_csum_hdr(ipha)) {
16637 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16638 			goto drop_pkt;
16639 		}
16640 		/* Initiate Write side IPPF processing */
16641 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16642 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16643 			if (mp == NULL) {
16644 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16645 				    " during IPPF processing\n"));
16646 				return;
16647 			}
16648 		}
16649 		/*
16650 		 * Handle labeled packet resizing.
16651 		 *
16652 		 * If we have added a label, inform ip_wput_frag() of its
16653 		 * effect on the MTU for ICMP messages.
16654 		 */
16655 		if (pkt_len > old_pkt_len) {
16656 			uint32_t secopt_size;
16657 
16658 			secopt_size = pkt_len - old_pkt_len;
16659 			if (secopt_size < max_frag)
16660 				max_frag -= secopt_size;
16661 		}
16662 
16663 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16664 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16665 		return;
16666 	}
16667 
16668 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16669 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16670 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16671 	    ipst->ips_ipv4firewall_physical_out,
16672 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16673 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16674 	if (mp == NULL)
16675 		return;
16676 
16677 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16678 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16679 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16680 	/* ip_xmit_v4 always consumes the packet */
16681 	return;
16682 
16683 drop_pkt:;
16684 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16685 	freemsg(mp);
16686 #undef	rptr
16687 }
16688 
16689 void
16690 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16691 {
16692 	ire_t	*ire;
16693 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16694 
16695 	ASSERT(!ipif->ipif_isv6);
16696 	/*
16697 	 * Find an IRE which matches the destination and the outgoing
16698 	 * queue in the cache table. All we need is an IRE_CACHE which
16699 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16700 	 * then it is enough to have some IRE_CACHE in the group.
16701 	 */
16702 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16703 		dst = ipif->ipif_pp_dst_addr;
16704 
16705 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16706 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16707 	if (ire == NULL) {
16708 		/*
16709 		 * Mark this packet to make it be delivered to
16710 		 * ip_rput_forward after the new ire has been
16711 		 * created.
16712 		 */
16713 		mp->b_prev = NULL;
16714 		mp->b_next = mp;
16715 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16716 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16717 	} else {
16718 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16719 		IRE_REFRELE(ire);
16720 	}
16721 }
16722 
16723 /* Update any source route, record route or timestamp options */
16724 static int
16725 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16726 {
16727 	ipoptp_t	opts;
16728 	uchar_t		*opt;
16729 	uint8_t		optval;
16730 	uint8_t		optlen;
16731 	ipaddr_t	dst;
16732 	uint32_t	ts;
16733 	ire_t		*dst_ire = NULL;
16734 	ire_t		*tmp_ire = NULL;
16735 	timestruc_t	now;
16736 
16737 	ip2dbg(("ip_rput_forward_options\n"));
16738 	dst = ipha->ipha_dst;
16739 	for (optval = ipoptp_first(&opts, ipha);
16740 	    optval != IPOPT_EOL;
16741 	    optval = ipoptp_next(&opts)) {
16742 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16743 		opt = opts.ipoptp_cur;
16744 		optlen = opts.ipoptp_len;
16745 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16746 		    optval, opts.ipoptp_len));
16747 		switch (optval) {
16748 			uint32_t off;
16749 		case IPOPT_SSRR:
16750 		case IPOPT_LSRR:
16751 			/* Check if adminstratively disabled */
16752 			if (!ipst->ips_ip_forward_src_routed) {
16753 				if (ire->ire_stq != NULL) {
16754 					/*
16755 					 * Sent by forwarding path, and router
16756 					 * is global zone
16757 					 */
16758 					icmp_unreachable(ire->ire_stq, mp,
16759 					    ICMP_SOURCE_ROUTE_FAILED,
16760 					    GLOBAL_ZONEID, ipst);
16761 				} else {
16762 					ip0dbg(("ip_rput_forward_options: "
16763 					    "unable to send unreach\n"));
16764 					freemsg(mp);
16765 				}
16766 				return (-1);
16767 			}
16768 
16769 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16770 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16771 			if (dst_ire == NULL) {
16772 				/*
16773 				 * Must be partial since ip_rput_options
16774 				 * checked for strict.
16775 				 */
16776 				break;
16777 			}
16778 			off = opt[IPOPT_OFFSET];
16779 			off--;
16780 		redo_srr:
16781 			if (optlen < IP_ADDR_LEN ||
16782 			    off > optlen - IP_ADDR_LEN) {
16783 				/* End of source route */
16784 				ip1dbg((
16785 				    "ip_rput_forward_options: end of SR\n"));
16786 				ire_refrele(dst_ire);
16787 				break;
16788 			}
16789 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16790 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16791 			    IP_ADDR_LEN);
16792 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16793 			    ntohl(dst)));
16794 
16795 			/*
16796 			 * Check if our address is present more than
16797 			 * once as consecutive hops in source route.
16798 			 */
16799 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16800 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16801 			if (tmp_ire != NULL) {
16802 				ire_refrele(tmp_ire);
16803 				off += IP_ADDR_LEN;
16804 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16805 				goto redo_srr;
16806 			}
16807 			ipha->ipha_dst = dst;
16808 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16809 			ire_refrele(dst_ire);
16810 			break;
16811 		case IPOPT_RR:
16812 			off = opt[IPOPT_OFFSET];
16813 			off--;
16814 			if (optlen < IP_ADDR_LEN ||
16815 			    off > optlen - IP_ADDR_LEN) {
16816 				/* No more room - ignore */
16817 				ip1dbg((
16818 				    "ip_rput_forward_options: end of RR\n"));
16819 				break;
16820 			}
16821 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16822 			    IP_ADDR_LEN);
16823 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16824 			break;
16825 		case IPOPT_TS:
16826 			/* Insert timestamp if there is room */
16827 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16828 			case IPOPT_TS_TSONLY:
16829 				off = IPOPT_TS_TIMELEN;
16830 				break;
16831 			case IPOPT_TS_PRESPEC:
16832 			case IPOPT_TS_PRESPEC_RFC791:
16833 				/* Verify that the address matched */
16834 				off = opt[IPOPT_OFFSET] - 1;
16835 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16836 				dst_ire = ire_ctable_lookup(dst, 0,
16837 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16838 				    MATCH_IRE_TYPE, ipst);
16839 				if (dst_ire == NULL) {
16840 					/* Not for us */
16841 					break;
16842 				}
16843 				ire_refrele(dst_ire);
16844 				/* FALLTHRU */
16845 			case IPOPT_TS_TSANDADDR:
16846 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16847 				break;
16848 			default:
16849 				/*
16850 				 * ip_*put_options should have already
16851 				 * dropped this packet.
16852 				 */
16853 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16854 				    "unknown IT - bug in ip_rput_options?\n");
16855 				return (0);	/* Keep "lint" happy */
16856 			}
16857 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16858 				/* Increase overflow counter */
16859 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16860 				opt[IPOPT_POS_OV_FLG] =
16861 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16862 				    (off << 4));
16863 				break;
16864 			}
16865 			off = opt[IPOPT_OFFSET] - 1;
16866 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16867 			case IPOPT_TS_PRESPEC:
16868 			case IPOPT_TS_PRESPEC_RFC791:
16869 			case IPOPT_TS_TSANDADDR:
16870 				bcopy(&ire->ire_src_addr,
16871 				    (char *)opt + off, IP_ADDR_LEN);
16872 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16873 				/* FALLTHRU */
16874 			case IPOPT_TS_TSONLY:
16875 				off = opt[IPOPT_OFFSET] - 1;
16876 				/* Compute # of milliseconds since midnight */
16877 				gethrestime(&now);
16878 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16879 				    now.tv_nsec / (NANOSEC / MILLISEC);
16880 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16881 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16882 				break;
16883 			}
16884 			break;
16885 		}
16886 	}
16887 	return (0);
16888 }
16889 
16890 /*
16891  * This is called after processing at least one of AH/ESP headers.
16892  *
16893  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16894  * the actual, physical interface on which the packet was received,
16895  * but, when ip_strict_dst_multihoming is set to 1, could be the
16896  * interface which had the ipha_dst configured when the packet went
16897  * through ip_rput. The ill_index corresponding to the recv_ill
16898  * is saved in ipsec_in_rill_index
16899  *
16900  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16901  * cannot assume "ire" points to valid data for any IPv6 cases.
16902  */
16903 void
16904 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16905 {
16906 	mblk_t *mp;
16907 	ipaddr_t dst;
16908 	in6_addr_t *v6dstp;
16909 	ipha_t *ipha;
16910 	ip6_t *ip6h;
16911 	ipsec_in_t *ii;
16912 	boolean_t ill_need_rele = B_FALSE;
16913 	boolean_t rill_need_rele = B_FALSE;
16914 	boolean_t ire_need_rele = B_FALSE;
16915 	netstack_t	*ns;
16916 	ip_stack_t	*ipst;
16917 
16918 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16919 	ASSERT(ii->ipsec_in_ill_index != 0);
16920 	ns = ii->ipsec_in_ns;
16921 	ASSERT(ii->ipsec_in_ns != NULL);
16922 	ipst = ns->netstack_ip;
16923 
16924 	mp = ipsec_mp->b_cont;
16925 	ASSERT(mp != NULL);
16926 
16927 
16928 	if (ill == NULL) {
16929 		ASSERT(recv_ill == NULL);
16930 		/*
16931 		 * We need to get the original queue on which ip_rput_local
16932 		 * or ip_rput_data_v6 was called.
16933 		 */
16934 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16935 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16936 		ill_need_rele = B_TRUE;
16937 
16938 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16939 			recv_ill = ill_lookup_on_ifindex(
16940 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16941 			    NULL, NULL, NULL, NULL, ipst);
16942 			rill_need_rele = B_TRUE;
16943 		} else {
16944 			recv_ill = ill;
16945 		}
16946 
16947 		if ((ill == NULL) || (recv_ill == NULL)) {
16948 			ip0dbg(("ip_fanout_proto_again: interface "
16949 			    "disappeared\n"));
16950 			if (ill != NULL)
16951 				ill_refrele(ill);
16952 			if (recv_ill != NULL)
16953 				ill_refrele(recv_ill);
16954 			freemsg(ipsec_mp);
16955 			return;
16956 		}
16957 	}
16958 
16959 	ASSERT(ill != NULL && recv_ill != NULL);
16960 
16961 	if (mp->b_datap->db_type == M_CTL) {
16962 		/*
16963 		 * AH/ESP is returning the ICMP message after
16964 		 * removing their headers. Fanout again till
16965 		 * it gets to the right protocol.
16966 		 */
16967 		if (ii->ipsec_in_v4) {
16968 			icmph_t *icmph;
16969 			int iph_hdr_length;
16970 			int hdr_length;
16971 
16972 			ipha = (ipha_t *)mp->b_rptr;
16973 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16974 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16975 			ipha = (ipha_t *)&icmph[1];
16976 			hdr_length = IPH_HDR_LENGTH(ipha);
16977 			/*
16978 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16979 			 * Reset the type to M_DATA.
16980 			 */
16981 			mp->b_datap->db_type = M_DATA;
16982 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16983 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16984 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16985 		} else {
16986 			icmp6_t *icmp6;
16987 			int hdr_length;
16988 
16989 			ip6h = (ip6_t *)mp->b_rptr;
16990 			/* Don't call hdr_length_v6() unless you have to. */
16991 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16992 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16993 			else
16994 				hdr_length = IPV6_HDR_LEN;
16995 
16996 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16997 			/*
16998 			 * icmp_inbound_error_fanout_v6 may need to do
16999 			 * pullupmsg.  Reset the type to M_DATA.
17000 			 */
17001 			mp->b_datap->db_type = M_DATA;
17002 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
17003 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
17004 		}
17005 		if (ill_need_rele)
17006 			ill_refrele(ill);
17007 		if (rill_need_rele)
17008 			ill_refrele(recv_ill);
17009 		return;
17010 	}
17011 
17012 	if (ii->ipsec_in_v4) {
17013 		ipha = (ipha_t *)mp->b_rptr;
17014 		dst = ipha->ipha_dst;
17015 		if (CLASSD(dst)) {
17016 			/*
17017 			 * Multicast has to be delivered to all streams.
17018 			 */
17019 			dst = INADDR_BROADCAST;
17020 		}
17021 
17022 		if (ire == NULL) {
17023 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
17024 			    MBLK_GETLABEL(mp), ipst);
17025 			if (ire == NULL) {
17026 				if (ill_need_rele)
17027 					ill_refrele(ill);
17028 				if (rill_need_rele)
17029 					ill_refrele(recv_ill);
17030 				ip1dbg(("ip_fanout_proto_again: "
17031 				    "IRE not found"));
17032 				freemsg(ipsec_mp);
17033 				return;
17034 			}
17035 			ire_need_rele = B_TRUE;
17036 		}
17037 
17038 		switch (ipha->ipha_protocol) {
17039 			case IPPROTO_UDP:
17040 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
17041 				    recv_ill);
17042 				if (ire_need_rele)
17043 					ire_refrele(ire);
17044 				break;
17045 			case IPPROTO_TCP:
17046 				if (!ire_need_rele)
17047 					IRE_REFHOLD(ire);
17048 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
17049 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
17050 				IRE_REFRELE(ire);
17051 				if (mp != NULL)
17052 					squeue_enter_chain(GET_SQUEUE(mp), mp,
17053 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
17054 				break;
17055 			case IPPROTO_SCTP:
17056 				if (!ire_need_rele)
17057 					IRE_REFHOLD(ire);
17058 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17059 				    ipsec_mp, 0, ill->ill_rq, dst);
17060 				break;
17061 			default:
17062 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17063 				    recv_ill, B_FALSE);
17064 				if (ire_need_rele)
17065 					ire_refrele(ire);
17066 				break;
17067 		}
17068 	} else {
17069 		uint32_t rput_flags = 0;
17070 
17071 		ip6h = (ip6_t *)mp->b_rptr;
17072 		v6dstp = &ip6h->ip6_dst;
17073 		/*
17074 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17075 		 * address.
17076 		 *
17077 		 * Currently, we don't store that state in the IPSEC_IN
17078 		 * message, and we may need to.
17079 		 */
17080 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17081 		    IP6_IN_LLMCAST : 0);
17082 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17083 		    NULL, NULL);
17084 	}
17085 	if (ill_need_rele)
17086 		ill_refrele(ill);
17087 	if (rill_need_rele)
17088 		ill_refrele(recv_ill);
17089 }
17090 
17091 /*
17092  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17093  * returns 'true' if there are still fragments left on the queue, in
17094  * which case we restart the timer.
17095  */
17096 void
17097 ill_frag_timer(void *arg)
17098 {
17099 	ill_t	*ill = (ill_t *)arg;
17100 	boolean_t frag_pending;
17101 	ip_stack_t	*ipst = ill->ill_ipst;
17102 
17103 	mutex_enter(&ill->ill_lock);
17104 	ASSERT(!ill->ill_fragtimer_executing);
17105 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17106 		ill->ill_frag_timer_id = 0;
17107 		mutex_exit(&ill->ill_lock);
17108 		return;
17109 	}
17110 	ill->ill_fragtimer_executing = 1;
17111 	mutex_exit(&ill->ill_lock);
17112 
17113 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17114 
17115 	/*
17116 	 * Restart the timer, if we have fragments pending or if someone
17117 	 * wanted us to be scheduled again.
17118 	 */
17119 	mutex_enter(&ill->ill_lock);
17120 	ill->ill_fragtimer_executing = 0;
17121 	ill->ill_frag_timer_id = 0;
17122 	if (frag_pending || ill->ill_fragtimer_needrestart)
17123 		ill_frag_timer_start(ill);
17124 	mutex_exit(&ill->ill_lock);
17125 }
17126 
17127 void
17128 ill_frag_timer_start(ill_t *ill)
17129 {
17130 	ip_stack_t	*ipst = ill->ill_ipst;
17131 
17132 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17133 
17134 	/* If the ill is closing or opening don't proceed */
17135 	if (ill->ill_state_flags & ILL_CONDEMNED)
17136 		return;
17137 
17138 	if (ill->ill_fragtimer_executing) {
17139 		/*
17140 		 * ill_frag_timer is currently executing. Just record the
17141 		 * the fact that we want the timer to be restarted.
17142 		 * ill_frag_timer will post a timeout before it returns,
17143 		 * ensuring it will be called again.
17144 		 */
17145 		ill->ill_fragtimer_needrestart = 1;
17146 		return;
17147 	}
17148 
17149 	if (ill->ill_frag_timer_id == 0) {
17150 		/*
17151 		 * The timer is neither running nor is the timeout handler
17152 		 * executing. Post a timeout so that ill_frag_timer will be
17153 		 * called
17154 		 */
17155 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17156 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17157 		ill->ill_fragtimer_needrestart = 0;
17158 	}
17159 }
17160 
17161 /*
17162  * This routine is needed for loopback when forwarding multicasts.
17163  *
17164  * IPQoS Notes:
17165  * IPPF processing is done in fanout routines.
17166  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17167  * processing for IPsec packets is done when it comes back in clear.
17168  * NOTE : The callers of this function need to do the ire_refrele for the
17169  *	  ire that is being passed in.
17170  */
17171 void
17172 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17173     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17174 {
17175 	ill_t	*ill = (ill_t *)q->q_ptr;
17176 	uint32_t	sum;
17177 	uint32_t	u1;
17178 	uint32_t	u2;
17179 	int		hdr_length;
17180 	boolean_t	mctl_present;
17181 	mblk_t		*first_mp = mp;
17182 	mblk_t		*hada_mp = NULL;
17183 	ipha_t		*inner_ipha;
17184 	ip_stack_t	*ipst;
17185 
17186 	ASSERT(recv_ill != NULL);
17187 	ipst = recv_ill->ill_ipst;
17188 
17189 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17190 	    "ip_rput_locl_start: q %p", q);
17191 
17192 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17193 	ASSERT(ill != NULL);
17194 
17195 
17196 #define	rptr	((uchar_t *)ipha)
17197 #define	iphs	((uint16_t *)ipha)
17198 
17199 	/*
17200 	 * no UDP or TCP packet should come here anymore.
17201 	 */
17202 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17203 	    ipha->ipha_protocol != IPPROTO_UDP);
17204 
17205 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17206 	if (mctl_present &&
17207 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17208 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17209 
17210 		/*
17211 		 * It's an IPsec accelerated packet.
17212 		 * Keep a pointer to the data attributes around until
17213 		 * we allocate the ipsec_info_t.
17214 		 */
17215 		IPSECHW_DEBUG(IPSECHW_PKT,
17216 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17217 		hada_mp = first_mp;
17218 		hada_mp->b_cont = NULL;
17219 		/*
17220 		 * Since it is accelerated, it comes directly from
17221 		 * the ill and the data attributes is followed by
17222 		 * the packet data.
17223 		 */
17224 		ASSERT(mp->b_datap->db_type != M_CTL);
17225 		first_mp = mp;
17226 		mctl_present = B_FALSE;
17227 	}
17228 
17229 	/*
17230 	 * IF M_CTL is not present, then ipsec_in_is_secure
17231 	 * should return B_TRUE. There is a case where loopback
17232 	 * packets has an M_CTL in the front with all the
17233 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17234 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17235 	 * packets never comes here, it is safe to ASSERT the
17236 	 * following.
17237 	 */
17238 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17239 
17240 	/*
17241 	 * Also, we should never have an mctl_present if this is an
17242 	 * ESP-in-UDP packet.
17243 	 */
17244 	ASSERT(!mctl_present || !esp_in_udp_packet);
17245 
17246 
17247 	/* u1 is # words of IP options */
17248 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17249 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17250 
17251 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17252 		if (u1) {
17253 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17254 				if (hada_mp != NULL)
17255 					freemsg(hada_mp);
17256 				return;
17257 			}
17258 		} else {
17259 			/* Check the IP header checksum.  */
17260 #define	uph	((uint16_t *)ipha)
17261 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17262 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17263 #undef  uph
17264 			/* finish doing IP checksum */
17265 			sum = (sum & 0xFFFF) + (sum >> 16);
17266 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17267 			if (sum && sum != 0xFFFF) {
17268 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17269 				goto drop_pkt;
17270 			}
17271 		}
17272 	}
17273 
17274 	/*
17275 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17276 	 * might be called more than once for secure packets, count only
17277 	 * the first time.
17278 	 */
17279 	if (!mctl_present) {
17280 		UPDATE_IB_PKT_COUNT(ire);
17281 		ire->ire_last_used_time = lbolt;
17282 	}
17283 
17284 	/* Check for fragmentation offset. */
17285 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17286 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17287 	if (u1) {
17288 		/*
17289 		 * We re-assemble fragments before we do the AH/ESP
17290 		 * processing. Thus, M_CTL should not be present
17291 		 * while we are re-assembling.
17292 		 */
17293 		ASSERT(!mctl_present);
17294 		ASSERT(first_mp == mp);
17295 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17296 			return;
17297 		}
17298 		/*
17299 		 * Make sure that first_mp points back to mp as
17300 		 * the mp we came in with could have changed in
17301 		 * ip_rput_fragment().
17302 		 */
17303 		ipha = (ipha_t *)mp->b_rptr;
17304 		first_mp = mp;
17305 	}
17306 
17307 	/*
17308 	 * Clear hardware checksumming flag as it is currently only
17309 	 * used by TCP and UDP.
17310 	 */
17311 	DB_CKSUMFLAGS(mp) = 0;
17312 
17313 	/* Now we have a complete datagram, destined for this machine. */
17314 	u1 = IPH_HDR_LENGTH(ipha);
17315 	switch (ipha->ipha_protocol) {
17316 	case IPPROTO_ICMP: {
17317 		ire_t		*ire_zone;
17318 		ilm_t		*ilm;
17319 		mblk_t		*mp1;
17320 		zoneid_t	last_zoneid;
17321 
17322 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17323 			ASSERT(ire->ire_type == IRE_BROADCAST);
17324 			/*
17325 			 * In the multicast case, applications may have joined
17326 			 * the group from different zones, so we need to deliver
17327 			 * the packet to each of them. Loop through the
17328 			 * multicast memberships structures (ilm) on the receive
17329 			 * ill and send a copy of the packet up each matching
17330 			 * one. However, we don't do this for multicasts sent on
17331 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17332 			 * they must stay in the sender's zone.
17333 			 *
17334 			 * ilm_add_v6() ensures that ilms in the same zone are
17335 			 * contiguous in the ill_ilm list. We use this property
17336 			 * to avoid sending duplicates needed when two
17337 			 * applications in the same zone join the same group on
17338 			 * different logical interfaces: we ignore the ilm if
17339 			 * its zoneid is the same as the last matching one.
17340 			 * In addition, the sending of the packet for
17341 			 * ire_zoneid is delayed until all of the other ilms
17342 			 * have been exhausted.
17343 			 */
17344 			last_zoneid = -1;
17345 			ILM_WALKER_HOLD(recv_ill);
17346 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17347 			    ilm = ilm->ilm_next) {
17348 				if ((ilm->ilm_flags & ILM_DELETED) ||
17349 				    ipha->ipha_dst != ilm->ilm_addr ||
17350 				    ilm->ilm_zoneid == last_zoneid ||
17351 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17352 				    ilm->ilm_zoneid == ALL_ZONES ||
17353 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17354 					continue;
17355 				mp1 = ip_copymsg(first_mp);
17356 				if (mp1 == NULL)
17357 					continue;
17358 				icmp_inbound(q, mp1, B_TRUE, ill,
17359 				    0, sum, mctl_present, B_TRUE,
17360 				    recv_ill, ilm->ilm_zoneid);
17361 				last_zoneid = ilm->ilm_zoneid;
17362 			}
17363 			ILM_WALKER_RELE(recv_ill);
17364 		} else if (ire->ire_type == IRE_BROADCAST) {
17365 			/*
17366 			 * In the broadcast case, there may be many zones
17367 			 * which need a copy of the packet delivered to them.
17368 			 * There is one IRE_BROADCAST per broadcast address
17369 			 * and per zone; we walk those using a helper function.
17370 			 * In addition, the sending of the packet for ire is
17371 			 * delayed until all of the other ires have been
17372 			 * processed.
17373 			 */
17374 			IRB_REFHOLD(ire->ire_bucket);
17375 			ire_zone = NULL;
17376 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17377 			    ire)) != NULL) {
17378 				mp1 = ip_copymsg(first_mp);
17379 				if (mp1 == NULL)
17380 					continue;
17381 
17382 				UPDATE_IB_PKT_COUNT(ire_zone);
17383 				ire_zone->ire_last_used_time = lbolt;
17384 				icmp_inbound(q, mp1, B_TRUE, ill,
17385 				    0, sum, mctl_present, B_TRUE,
17386 				    recv_ill, ire_zone->ire_zoneid);
17387 			}
17388 			IRB_REFRELE(ire->ire_bucket);
17389 		}
17390 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17391 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17392 		    ire->ire_zoneid);
17393 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17394 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17395 		return;
17396 	}
17397 	case IPPROTO_IGMP:
17398 		/*
17399 		 * If we are not willing to accept IGMP packets in clear,
17400 		 * then check with global policy.
17401 		 */
17402 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17403 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17404 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17405 			if (first_mp == NULL)
17406 				return;
17407 		}
17408 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17409 			freemsg(first_mp);
17410 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17411 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17412 			return;
17413 		}
17414 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17415 			/* Bad packet - discarded by igmp_input */
17416 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17417 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17418 			if (mctl_present)
17419 				freeb(first_mp);
17420 			return;
17421 		}
17422 		/*
17423 		 * igmp_input() may have returned the pulled up message.
17424 		 * So first_mp and ipha need to be reinitialized.
17425 		 */
17426 		ipha = (ipha_t *)mp->b_rptr;
17427 		if (mctl_present)
17428 			first_mp->b_cont = mp;
17429 		else
17430 			first_mp = mp;
17431 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17432 		    connf_head != NULL) {
17433 			/* No user-level listener for IGMP packets */
17434 			goto drop_pkt;
17435 		}
17436 		/* deliver to local raw users */
17437 		break;
17438 	case IPPROTO_PIM:
17439 		/*
17440 		 * If we are not willing to accept PIM packets in clear,
17441 		 * then check with global policy.
17442 		 */
17443 		if (ipst->ips_pim_accept_clear_messages == 0) {
17444 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17445 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17446 			if (first_mp == NULL)
17447 				return;
17448 		}
17449 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17450 			freemsg(first_mp);
17451 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17452 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17453 			return;
17454 		}
17455 		if (pim_input(q, mp, ill) != 0) {
17456 			/* Bad packet - discarded by pim_input */
17457 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17458 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17459 			if (mctl_present)
17460 				freeb(first_mp);
17461 			return;
17462 		}
17463 
17464 		/*
17465 		 * pim_input() may have pulled up the message so ipha needs to
17466 		 * be reinitialized.
17467 		 */
17468 		ipha = (ipha_t *)mp->b_rptr;
17469 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17470 		    connf_head != NULL) {
17471 			/* No user-level listener for PIM packets */
17472 			goto drop_pkt;
17473 		}
17474 		/* deliver to local raw users */
17475 		break;
17476 	case IPPROTO_ENCAP:
17477 		/*
17478 		 * Handle self-encapsulated packets (IP-in-IP where
17479 		 * the inner addresses == the outer addresses).
17480 		 */
17481 		hdr_length = IPH_HDR_LENGTH(ipha);
17482 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17483 		    mp->b_wptr) {
17484 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17485 			    sizeof (ipha_t) - mp->b_rptr)) {
17486 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17487 				freemsg(first_mp);
17488 				return;
17489 			}
17490 			ipha = (ipha_t *)mp->b_rptr;
17491 		}
17492 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17493 		/*
17494 		 * Check the sanity of the inner IP header.
17495 		 */
17496 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17497 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17498 			freemsg(first_mp);
17499 			return;
17500 		}
17501 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17502 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17503 			freemsg(first_mp);
17504 			return;
17505 		}
17506 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17507 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17508 			ipsec_in_t *ii;
17509 
17510 			/*
17511 			 * Self-encapsulated tunnel packet. Remove
17512 			 * the outer IP header and fanout again.
17513 			 * We also need to make sure that the inner
17514 			 * header is pulled up until options.
17515 			 */
17516 			mp->b_rptr = (uchar_t *)inner_ipha;
17517 			ipha = inner_ipha;
17518 			hdr_length = IPH_HDR_LENGTH(ipha);
17519 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17520 				if (!pullupmsg(mp, (uchar_t *)ipha +
17521 				    + hdr_length - mp->b_rptr)) {
17522 					freemsg(first_mp);
17523 					return;
17524 				}
17525 				ipha = (ipha_t *)mp->b_rptr;
17526 			}
17527 			if (!mctl_present) {
17528 				ASSERT(first_mp == mp);
17529 				/*
17530 				 * This means that somebody is sending
17531 				 * Self-encapsualted packets without AH/ESP.
17532 				 * If AH/ESP was present, we would have already
17533 				 * allocated the first_mp.
17534 				 */
17535 				first_mp = ipsec_in_alloc(B_TRUE,
17536 				    ipst->ips_netstack);
17537 				if (first_mp == NULL) {
17538 					ip1dbg(("ip_proto_input: IPSEC_IN "
17539 					    "allocation failure.\n"));
17540 					BUMP_MIB(ill->ill_ip_mib,
17541 					    ipIfStatsInDiscards);
17542 					freemsg(mp);
17543 					return;
17544 				}
17545 				first_mp->b_cont = mp;
17546 			}
17547 			/*
17548 			 * We generally store the ill_index if we need to
17549 			 * do IPsec processing as we lose the ill queue when
17550 			 * we come back. But in this case, we never should
17551 			 * have to store the ill_index here as it should have
17552 			 * been stored previously when we processed the
17553 			 * AH/ESP header in this routine or for non-ipsec
17554 			 * cases, we still have the queue. But for some bad
17555 			 * packets from the wire, we can get to IPsec after
17556 			 * this and we better store the index for that case.
17557 			 */
17558 			ill = (ill_t *)q->q_ptr;
17559 			ii = (ipsec_in_t *)first_mp->b_rptr;
17560 			ii->ipsec_in_ill_index =
17561 			    ill->ill_phyint->phyint_ifindex;
17562 			ii->ipsec_in_rill_index =
17563 			    recv_ill->ill_phyint->phyint_ifindex;
17564 			if (ii->ipsec_in_decaps) {
17565 				/*
17566 				 * This packet is self-encapsulated multiple
17567 				 * times. We don't want to recurse infinitely.
17568 				 * To keep it simple, drop the packet.
17569 				 */
17570 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17571 				freemsg(first_mp);
17572 				return;
17573 			}
17574 			ii->ipsec_in_decaps = B_TRUE;
17575 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17576 			    ire);
17577 			return;
17578 		}
17579 		break;
17580 	case IPPROTO_AH:
17581 	case IPPROTO_ESP: {
17582 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17583 
17584 		/*
17585 		 * Fast path for AH/ESP. If this is the first time
17586 		 * we are sending a datagram to AH/ESP, allocate
17587 		 * a IPSEC_IN message and prepend it. Otherwise,
17588 		 * just fanout.
17589 		 */
17590 
17591 		int ipsec_rc;
17592 		ipsec_in_t *ii;
17593 		netstack_t *ns = ipst->ips_netstack;
17594 
17595 		IP_STAT(ipst, ipsec_proto_ahesp);
17596 		if (!mctl_present) {
17597 			ASSERT(first_mp == mp);
17598 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17599 			if (first_mp == NULL) {
17600 				ip1dbg(("ip_proto_input: IPSEC_IN "
17601 				    "allocation failure.\n"));
17602 				freemsg(hada_mp); /* okay ifnull */
17603 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17604 				freemsg(mp);
17605 				return;
17606 			}
17607 			/*
17608 			 * Store the ill_index so that when we come back
17609 			 * from IPsec we ride on the same queue.
17610 			 */
17611 			ill = (ill_t *)q->q_ptr;
17612 			ii = (ipsec_in_t *)first_mp->b_rptr;
17613 			ii->ipsec_in_ill_index =
17614 			    ill->ill_phyint->phyint_ifindex;
17615 			ii->ipsec_in_rill_index =
17616 			    recv_ill->ill_phyint->phyint_ifindex;
17617 			first_mp->b_cont = mp;
17618 			/*
17619 			 * Cache hardware acceleration info.
17620 			 */
17621 			if (hada_mp != NULL) {
17622 				IPSECHW_DEBUG(IPSECHW_PKT,
17623 				    ("ip_rput_local: caching data attr.\n"));
17624 				ii->ipsec_in_accelerated = B_TRUE;
17625 				ii->ipsec_in_da = hada_mp;
17626 				hada_mp = NULL;
17627 			}
17628 		} else {
17629 			ii = (ipsec_in_t *)first_mp->b_rptr;
17630 		}
17631 
17632 		if (!ipsec_loaded(ipss)) {
17633 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17634 			    ire->ire_zoneid, ipst);
17635 			return;
17636 		}
17637 
17638 		ns = ipst->ips_netstack;
17639 		/* select inbound SA and have IPsec process the pkt */
17640 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17641 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17642 			boolean_t esp_in_udp_sa;
17643 			if (esph == NULL)
17644 				return;
17645 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17646 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17647 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17648 			    IPSA_F_NATT) != 0);
17649 			/*
17650 			 * The following is a fancy, but quick, way of saying:
17651 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17652 			 *    OR
17653 			 * ESP SA and ESP-in-UDP packet --> drop
17654 			 */
17655 			if (esp_in_udp_sa != esp_in_udp_packet) {
17656 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17657 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17658 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17659 				    &ns->netstack_ipsec->ipsec_dropper);
17660 				return;
17661 			}
17662 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17663 			    first_mp, esph);
17664 		} else {
17665 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17666 			if (ah == NULL)
17667 				return;
17668 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17669 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17670 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17671 			    first_mp, ah);
17672 		}
17673 
17674 		switch (ipsec_rc) {
17675 		case IPSEC_STATUS_SUCCESS:
17676 			break;
17677 		case IPSEC_STATUS_FAILED:
17678 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17679 			/* FALLTHRU */
17680 		case IPSEC_STATUS_PENDING:
17681 			return;
17682 		}
17683 		/* we're done with IPsec processing, send it up */
17684 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17685 		return;
17686 	}
17687 	default:
17688 		break;
17689 	}
17690 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17691 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17692 		    ire->ire_zoneid));
17693 		goto drop_pkt;
17694 	}
17695 	/*
17696 	 * Handle protocols with which IP is less intimate.  There
17697 	 * can be more than one stream bound to a particular
17698 	 * protocol.  When this is the case, each one gets a copy
17699 	 * of any incoming packets.
17700 	 */
17701 	ip_fanout_proto(q, first_mp, ill, ipha,
17702 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17703 	    B_TRUE, recv_ill, ire->ire_zoneid);
17704 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17705 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17706 	return;
17707 
17708 drop_pkt:
17709 	freemsg(first_mp);
17710 	if (hada_mp != NULL)
17711 		freeb(hada_mp);
17712 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17713 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17714 #undef	rptr
17715 #undef  iphs
17716 
17717 }
17718 
17719 /*
17720  * Update any source route, record route or timestamp options.
17721  * Check that we are at end of strict source route.
17722  * The options have already been checked for sanity in ip_rput_options().
17723  */
17724 static boolean_t
17725 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17726     ip_stack_t *ipst)
17727 {
17728 	ipoptp_t	opts;
17729 	uchar_t		*opt;
17730 	uint8_t		optval;
17731 	uint8_t		optlen;
17732 	ipaddr_t	dst;
17733 	uint32_t	ts;
17734 	ire_t		*dst_ire;
17735 	timestruc_t	now;
17736 	zoneid_t	zoneid;
17737 	ill_t		*ill;
17738 
17739 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17740 
17741 	ip2dbg(("ip_rput_local_options\n"));
17742 
17743 	for (optval = ipoptp_first(&opts, ipha);
17744 	    optval != IPOPT_EOL;
17745 	    optval = ipoptp_next(&opts)) {
17746 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17747 		opt = opts.ipoptp_cur;
17748 		optlen = opts.ipoptp_len;
17749 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17750 		    optval, optlen));
17751 		switch (optval) {
17752 			uint32_t off;
17753 		case IPOPT_SSRR:
17754 		case IPOPT_LSRR:
17755 			off = opt[IPOPT_OFFSET];
17756 			off--;
17757 			if (optlen < IP_ADDR_LEN ||
17758 			    off > optlen - IP_ADDR_LEN) {
17759 				/* End of source route */
17760 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17761 				break;
17762 			}
17763 			/*
17764 			 * This will only happen if two consecutive entries
17765 			 * in the source route contains our address or if
17766 			 * it is a packet with a loose source route which
17767 			 * reaches us before consuming the whole source route
17768 			 */
17769 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17770 			if (optval == IPOPT_SSRR) {
17771 				goto bad_src_route;
17772 			}
17773 			/*
17774 			 * Hack: instead of dropping the packet truncate the
17775 			 * source route to what has been used by filling the
17776 			 * rest with IPOPT_NOP.
17777 			 */
17778 			opt[IPOPT_OLEN] = (uint8_t)off;
17779 			while (off < optlen) {
17780 				opt[off++] = IPOPT_NOP;
17781 			}
17782 			break;
17783 		case IPOPT_RR:
17784 			off = opt[IPOPT_OFFSET];
17785 			off--;
17786 			if (optlen < IP_ADDR_LEN ||
17787 			    off > optlen - IP_ADDR_LEN) {
17788 				/* No more room - ignore */
17789 				ip1dbg((
17790 				    "ip_rput_local_options: end of RR\n"));
17791 				break;
17792 			}
17793 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17794 			    IP_ADDR_LEN);
17795 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17796 			break;
17797 		case IPOPT_TS:
17798 			/* Insert timestamp if there is romm */
17799 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17800 			case IPOPT_TS_TSONLY:
17801 				off = IPOPT_TS_TIMELEN;
17802 				break;
17803 			case IPOPT_TS_PRESPEC:
17804 			case IPOPT_TS_PRESPEC_RFC791:
17805 				/* Verify that the address matched */
17806 				off = opt[IPOPT_OFFSET] - 1;
17807 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17808 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17809 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17810 				    ipst);
17811 				if (dst_ire == NULL) {
17812 					/* Not for us */
17813 					break;
17814 				}
17815 				ire_refrele(dst_ire);
17816 				/* FALLTHRU */
17817 			case IPOPT_TS_TSANDADDR:
17818 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17819 				break;
17820 			default:
17821 				/*
17822 				 * ip_*put_options should have already
17823 				 * dropped this packet.
17824 				 */
17825 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17826 				    "unknown IT - bug in ip_rput_options?\n");
17827 				return (B_TRUE);	/* Keep "lint" happy */
17828 			}
17829 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17830 				/* Increase overflow counter */
17831 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17832 				opt[IPOPT_POS_OV_FLG] =
17833 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17834 				    (off << 4));
17835 				break;
17836 			}
17837 			off = opt[IPOPT_OFFSET] - 1;
17838 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17839 			case IPOPT_TS_PRESPEC:
17840 			case IPOPT_TS_PRESPEC_RFC791:
17841 			case IPOPT_TS_TSANDADDR:
17842 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17843 				    IP_ADDR_LEN);
17844 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17845 				/* FALLTHRU */
17846 			case IPOPT_TS_TSONLY:
17847 				off = opt[IPOPT_OFFSET] - 1;
17848 				/* Compute # of milliseconds since midnight */
17849 				gethrestime(&now);
17850 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17851 				    now.tv_nsec / (NANOSEC / MILLISEC);
17852 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17853 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17854 				break;
17855 			}
17856 			break;
17857 		}
17858 	}
17859 	return (B_TRUE);
17860 
17861 bad_src_route:
17862 	q = WR(q);
17863 	if (q->q_next != NULL)
17864 		ill = q->q_ptr;
17865 	else
17866 		ill = NULL;
17867 
17868 	/* make sure we clear any indication of a hardware checksum */
17869 	DB_CKSUMFLAGS(mp) = 0;
17870 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17871 	if (zoneid == ALL_ZONES)
17872 		freemsg(mp);
17873 	else
17874 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17875 	return (B_FALSE);
17876 
17877 }
17878 
17879 /*
17880  * Process IP options in an inbound packet.  If an option affects the
17881  * effective destination address, return the next hop address via dstp.
17882  * Returns -1 if something fails in which case an ICMP error has been sent
17883  * and mp freed.
17884  */
17885 static int
17886 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17887     ip_stack_t *ipst)
17888 {
17889 	ipoptp_t	opts;
17890 	uchar_t		*opt;
17891 	uint8_t		optval;
17892 	uint8_t		optlen;
17893 	ipaddr_t	dst;
17894 	intptr_t	code = 0;
17895 	ire_t		*ire = NULL;
17896 	zoneid_t	zoneid;
17897 	ill_t		*ill;
17898 
17899 	ip2dbg(("ip_rput_options\n"));
17900 	dst = ipha->ipha_dst;
17901 	for (optval = ipoptp_first(&opts, ipha);
17902 	    optval != IPOPT_EOL;
17903 	    optval = ipoptp_next(&opts)) {
17904 		opt = opts.ipoptp_cur;
17905 		optlen = opts.ipoptp_len;
17906 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17907 		    optval, optlen));
17908 		/*
17909 		 * Note: we need to verify the checksum before we
17910 		 * modify anything thus this routine only extracts the next
17911 		 * hop dst from any source route.
17912 		 */
17913 		switch (optval) {
17914 			uint32_t off;
17915 		case IPOPT_SSRR:
17916 		case IPOPT_LSRR:
17917 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17918 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17919 			if (ire == NULL) {
17920 				if (optval == IPOPT_SSRR) {
17921 					ip1dbg(("ip_rput_options: not next"
17922 					    " strict source route 0x%x\n",
17923 					    ntohl(dst)));
17924 					code = (char *)&ipha->ipha_dst -
17925 					    (char *)ipha;
17926 					goto param_prob; /* RouterReq's */
17927 				}
17928 				ip2dbg(("ip_rput_options: "
17929 				    "not next source route 0x%x\n",
17930 				    ntohl(dst)));
17931 				break;
17932 			}
17933 			ire_refrele(ire);
17934 
17935 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17936 				ip1dbg((
17937 				    "ip_rput_options: bad option offset\n"));
17938 				code = (char *)&opt[IPOPT_OLEN] -
17939 				    (char *)ipha;
17940 				goto param_prob;
17941 			}
17942 			off = opt[IPOPT_OFFSET];
17943 			off--;
17944 		redo_srr:
17945 			if (optlen < IP_ADDR_LEN ||
17946 			    off > optlen - IP_ADDR_LEN) {
17947 				/* End of source route */
17948 				ip1dbg(("ip_rput_options: end of SR\n"));
17949 				break;
17950 			}
17951 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17952 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17953 			    ntohl(dst)));
17954 
17955 			/*
17956 			 * Check if our address is present more than
17957 			 * once as consecutive hops in source route.
17958 			 * XXX verify per-interface ip_forwarding
17959 			 * for source route?
17960 			 */
17961 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17962 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17963 
17964 			if (ire != NULL) {
17965 				ire_refrele(ire);
17966 				off += IP_ADDR_LEN;
17967 				goto redo_srr;
17968 			}
17969 
17970 			if (dst == htonl(INADDR_LOOPBACK)) {
17971 				ip1dbg(("ip_rput_options: loopback addr in "
17972 				    "source route!\n"));
17973 				goto bad_src_route;
17974 			}
17975 			/*
17976 			 * For strict: verify that dst is directly
17977 			 * reachable.
17978 			 */
17979 			if (optval == IPOPT_SSRR) {
17980 				ire = ire_ftable_lookup(dst, 0, 0,
17981 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17982 				    MBLK_GETLABEL(mp),
17983 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17984 				if (ire == NULL) {
17985 					ip1dbg(("ip_rput_options: SSRR not "
17986 					    "directly reachable: 0x%x\n",
17987 					    ntohl(dst)));
17988 					goto bad_src_route;
17989 				}
17990 				ire_refrele(ire);
17991 			}
17992 			/*
17993 			 * Defer update of the offset and the record route
17994 			 * until the packet is forwarded.
17995 			 */
17996 			break;
17997 		case IPOPT_RR:
17998 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17999 				ip1dbg((
18000 				    "ip_rput_options: bad option offset\n"));
18001 				code = (char *)&opt[IPOPT_OLEN] -
18002 				    (char *)ipha;
18003 				goto param_prob;
18004 			}
18005 			break;
18006 		case IPOPT_TS:
18007 			/*
18008 			 * Verify that length >= 5 and that there is either
18009 			 * room for another timestamp or that the overflow
18010 			 * counter is not maxed out.
18011 			 */
18012 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
18013 			if (optlen < IPOPT_MINLEN_IT) {
18014 				goto param_prob;
18015 			}
18016 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
18017 				ip1dbg((
18018 				    "ip_rput_options: bad option offset\n"));
18019 				code = (char *)&opt[IPOPT_OFFSET] -
18020 				    (char *)ipha;
18021 				goto param_prob;
18022 			}
18023 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
18024 			case IPOPT_TS_TSONLY:
18025 				off = IPOPT_TS_TIMELEN;
18026 				break;
18027 			case IPOPT_TS_TSANDADDR:
18028 			case IPOPT_TS_PRESPEC:
18029 			case IPOPT_TS_PRESPEC_RFC791:
18030 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
18031 				break;
18032 			default:
18033 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
18034 				    (char *)ipha;
18035 				goto param_prob;
18036 			}
18037 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
18038 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
18039 				/*
18040 				 * No room and the overflow counter is 15
18041 				 * already.
18042 				 */
18043 				goto param_prob;
18044 			}
18045 			break;
18046 		}
18047 	}
18048 
18049 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
18050 		*dstp = dst;
18051 		return (0);
18052 	}
18053 
18054 	ip1dbg(("ip_rput_options: error processing IP options."));
18055 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
18056 
18057 param_prob:
18058 	q = WR(q);
18059 	if (q->q_next != NULL)
18060 		ill = q->q_ptr;
18061 	else
18062 		ill = NULL;
18063 
18064 	/* make sure we clear any indication of a hardware checksum */
18065 	DB_CKSUMFLAGS(mp) = 0;
18066 	/* Don't know whether this is for non-global or global/forwarding */
18067 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18068 	if (zoneid == ALL_ZONES)
18069 		freemsg(mp);
18070 	else
18071 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18072 	return (-1);
18073 
18074 bad_src_route:
18075 	q = WR(q);
18076 	if (q->q_next != NULL)
18077 		ill = q->q_ptr;
18078 	else
18079 		ill = NULL;
18080 
18081 	/* make sure we clear any indication of a hardware checksum */
18082 	DB_CKSUMFLAGS(mp) = 0;
18083 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18084 	if (zoneid == ALL_ZONES)
18085 		freemsg(mp);
18086 	else
18087 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18088 	return (-1);
18089 }
18090 
18091 /*
18092  * IP & ICMP info in >=14 msg's ...
18093  *  - ip fixed part (mib2_ip_t)
18094  *  - icmp fixed part (mib2_icmp_t)
18095  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18096  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18097  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18098  *  - ipRouteAttributeTable (ip 102)	labeled routes
18099  *  - ip multicast membership (ip_member_t)
18100  *  - ip multicast source filtering (ip_grpsrc_t)
18101  *  - igmp fixed part (struct igmpstat)
18102  *  - multicast routing stats (struct mrtstat)
18103  *  - multicast routing vifs (array of struct vifctl)
18104  *  - multicast routing routes (array of struct mfcctl)
18105  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18106  *					One per ill plus one generic
18107  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18108  *					One per ill plus one generic
18109  *  - ipv6RouteEntry			all IPv6 IREs
18110  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18111  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18112  *  - ipv6AddrEntry			all IPv6 ipifs
18113  *  - ipv6 multicast membership (ipv6_member_t)
18114  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18115  *
18116  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18117  *
18118  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18119  * already filled in by the caller.
18120  * Return value of 0 indicates that no messages were sent and caller
18121  * should free mpctl.
18122  */
18123 int
18124 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18125 {
18126 	ip_stack_t *ipst;
18127 	sctp_stack_t *sctps;
18128 
18129 	if (q->q_next != NULL) {
18130 		ipst = ILLQ_TO_IPST(q);
18131 	} else {
18132 		ipst = CONNQ_TO_IPST(q);
18133 	}
18134 	ASSERT(ipst != NULL);
18135 	sctps = ipst->ips_netstack->netstack_sctp;
18136 
18137 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18138 		return (0);
18139 	}
18140 
18141 	/*
18142 	 * For the purposes of the (broken) packet shell use
18143 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18144 	 * to make TCP and UDP appear first in the list of mib items.
18145 	 * TBD: We could expand this and use it in netstat so that
18146 	 * the kernel doesn't have to produce large tables (connections,
18147 	 * routes, etc) when netstat only wants the statistics or a particular
18148 	 * table.
18149 	 */
18150 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18151 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18152 			return (1);
18153 		}
18154 	}
18155 
18156 	if (level != MIB2_TCP) {
18157 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18158 			return (1);
18159 		}
18160 	}
18161 
18162 	if (level != MIB2_UDP) {
18163 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18164 			return (1);
18165 		}
18166 	}
18167 
18168 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18169 	    ipst)) == NULL) {
18170 		return (1);
18171 	}
18172 
18173 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18174 		return (1);
18175 	}
18176 
18177 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18178 		return (1);
18179 	}
18180 
18181 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18182 		return (1);
18183 	}
18184 
18185 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18186 		return (1);
18187 	}
18188 
18189 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18190 		return (1);
18191 	}
18192 
18193 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18194 		return (1);
18195 	}
18196 
18197 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18198 		return (1);
18199 	}
18200 
18201 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18202 		return (1);
18203 	}
18204 
18205 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18206 		return (1);
18207 	}
18208 
18209 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18210 		return (1);
18211 	}
18212 
18213 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18214 		return (1);
18215 	}
18216 
18217 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18218 		return (1);
18219 	}
18220 
18221 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18222 		return (1);
18223 	}
18224 
18225 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18226 		return (1);
18227 	}
18228 
18229 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18230 	if (mpctl == NULL) {
18231 		return (1);
18232 	}
18233 
18234 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18235 		return (1);
18236 	}
18237 	freemsg(mpctl);
18238 	return (1);
18239 }
18240 
18241 
18242 /* Get global (legacy) IPv4 statistics */
18243 static mblk_t *
18244 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18245     ip_stack_t *ipst)
18246 {
18247 	mib2_ip_t		old_ip_mib;
18248 	struct opthdr		*optp;
18249 	mblk_t			*mp2ctl;
18250 
18251 	/*
18252 	 * make a copy of the original message
18253 	 */
18254 	mp2ctl = copymsg(mpctl);
18255 
18256 	/* fixed length IP structure... */
18257 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18258 	optp->level = MIB2_IP;
18259 	optp->name = 0;
18260 	SET_MIB(old_ip_mib.ipForwarding,
18261 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18262 	SET_MIB(old_ip_mib.ipDefaultTTL,
18263 	    (uint32_t)ipst->ips_ip_def_ttl);
18264 	SET_MIB(old_ip_mib.ipReasmTimeout,
18265 	    ipst->ips_ip_g_frag_timeout);
18266 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18267 	    sizeof (mib2_ipAddrEntry_t));
18268 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18269 	    sizeof (mib2_ipRouteEntry_t));
18270 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18271 	    sizeof (mib2_ipNetToMediaEntry_t));
18272 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18273 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18274 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18275 	    sizeof (mib2_ipAttributeEntry_t));
18276 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18277 
18278 	/*
18279 	 * Grab the statistics from the new IP MIB
18280 	 */
18281 	SET_MIB(old_ip_mib.ipInReceives,
18282 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18283 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18284 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18285 	SET_MIB(old_ip_mib.ipForwDatagrams,
18286 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18287 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18288 	    ipmib->ipIfStatsInUnknownProtos);
18289 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18290 	SET_MIB(old_ip_mib.ipInDelivers,
18291 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18292 	SET_MIB(old_ip_mib.ipOutRequests,
18293 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18294 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18295 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18296 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18297 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18298 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18299 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18300 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18301 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18302 
18303 	/* ipRoutingDiscards is not being used */
18304 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18305 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18306 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18307 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18308 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18309 	    ipmib->ipIfStatsReasmDuplicates);
18310 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18311 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18312 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18313 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18314 	SET_MIB(old_ip_mib.rawipInOverflows,
18315 	    ipmib->rawipIfStatsInOverflows);
18316 
18317 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18318 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18319 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18320 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18321 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18322 	    ipmib->ipIfStatsOutSwitchIPVersion);
18323 
18324 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18325 	    (int)sizeof (old_ip_mib))) {
18326 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18327 		    (uint_t)sizeof (old_ip_mib)));
18328 	}
18329 
18330 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18331 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18332 	    (int)optp->level, (int)optp->name, (int)optp->len));
18333 	qreply(q, mpctl);
18334 	return (mp2ctl);
18335 }
18336 
18337 /* Per interface IPv4 statistics */
18338 static mblk_t *
18339 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18340 {
18341 	struct opthdr		*optp;
18342 	mblk_t			*mp2ctl;
18343 	ill_t			*ill;
18344 	ill_walk_context_t	ctx;
18345 	mblk_t			*mp_tail = NULL;
18346 	mib2_ipIfStatsEntry_t	global_ip_mib;
18347 
18348 	/*
18349 	 * Make a copy of the original message
18350 	 */
18351 	mp2ctl = copymsg(mpctl);
18352 
18353 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18354 	optp->level = MIB2_IP;
18355 	optp->name = MIB2_IP_TRAFFIC_STATS;
18356 	/* Include "unknown interface" ip_mib */
18357 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18358 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18359 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18360 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18361 	    (ipst->ips_ip_g_forward ? 1 : 2));
18362 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18363 	    (uint32_t)ipst->ips_ip_def_ttl);
18364 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18365 	    sizeof (mib2_ipIfStatsEntry_t));
18366 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18367 	    sizeof (mib2_ipAddrEntry_t));
18368 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18369 	    sizeof (mib2_ipRouteEntry_t));
18370 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18371 	    sizeof (mib2_ipNetToMediaEntry_t));
18372 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18373 	    sizeof (ip_member_t));
18374 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18375 	    sizeof (ip_grpsrc_t));
18376 
18377 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18378 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18379 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18380 		    "failed to allocate %u bytes\n",
18381 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18382 	}
18383 
18384 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18385 
18386 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18387 	ill = ILL_START_WALK_V4(&ctx, ipst);
18388 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18389 		ill->ill_ip_mib->ipIfStatsIfIndex =
18390 		    ill->ill_phyint->phyint_ifindex;
18391 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18392 		    (ipst->ips_ip_g_forward ? 1 : 2));
18393 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18394 		    (uint32_t)ipst->ips_ip_def_ttl);
18395 
18396 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18397 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18398 		    (char *)ill->ill_ip_mib,
18399 		    (int)sizeof (*ill->ill_ip_mib))) {
18400 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18401 			    "failed to allocate %u bytes\n",
18402 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18403 		}
18404 	}
18405 	rw_exit(&ipst->ips_ill_g_lock);
18406 
18407 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18408 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18409 	    "level %d, name %d, len %d\n",
18410 	    (int)optp->level, (int)optp->name, (int)optp->len));
18411 	qreply(q, mpctl);
18412 
18413 	if (mp2ctl == NULL)
18414 		return (NULL);
18415 
18416 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18417 }
18418 
18419 /* Global IPv4 ICMP statistics */
18420 static mblk_t *
18421 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18422 {
18423 	struct opthdr		*optp;
18424 	mblk_t			*mp2ctl;
18425 
18426 	/*
18427 	 * Make a copy of the original message
18428 	 */
18429 	mp2ctl = copymsg(mpctl);
18430 
18431 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18432 	optp->level = MIB2_ICMP;
18433 	optp->name = 0;
18434 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18435 	    (int)sizeof (ipst->ips_icmp_mib))) {
18436 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18437 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18438 	}
18439 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18440 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18441 	    (int)optp->level, (int)optp->name, (int)optp->len));
18442 	qreply(q, mpctl);
18443 	return (mp2ctl);
18444 }
18445 
18446 /* Global IPv4 IGMP statistics */
18447 static mblk_t *
18448 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18449 {
18450 	struct opthdr		*optp;
18451 	mblk_t			*mp2ctl;
18452 
18453 	/*
18454 	 * make a copy of the original message
18455 	 */
18456 	mp2ctl = copymsg(mpctl);
18457 
18458 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18459 	optp->level = EXPER_IGMP;
18460 	optp->name = 0;
18461 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18462 	    (int)sizeof (ipst->ips_igmpstat))) {
18463 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18464 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18465 	}
18466 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18467 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18468 	    (int)optp->level, (int)optp->name, (int)optp->len));
18469 	qreply(q, mpctl);
18470 	return (mp2ctl);
18471 }
18472 
18473 /* Global IPv4 Multicast Routing statistics */
18474 static mblk_t *
18475 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18476 {
18477 	struct opthdr		*optp;
18478 	mblk_t			*mp2ctl;
18479 
18480 	/*
18481 	 * make a copy of the original message
18482 	 */
18483 	mp2ctl = copymsg(mpctl);
18484 
18485 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18486 	optp->level = EXPER_DVMRP;
18487 	optp->name = 0;
18488 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18489 		ip0dbg(("ip_mroute_stats: failed\n"));
18490 	}
18491 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18492 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18493 	    (int)optp->level, (int)optp->name, (int)optp->len));
18494 	qreply(q, mpctl);
18495 	return (mp2ctl);
18496 }
18497 
18498 /* IPv4 address information */
18499 static mblk_t *
18500 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18501 {
18502 	struct opthdr		*optp;
18503 	mblk_t			*mp2ctl;
18504 	mblk_t			*mp_tail = NULL;
18505 	ill_t			*ill;
18506 	ipif_t			*ipif;
18507 	uint_t			bitval;
18508 	mib2_ipAddrEntry_t	mae;
18509 	zoneid_t		zoneid;
18510 	ill_walk_context_t ctx;
18511 
18512 	/*
18513 	 * make a copy of the original message
18514 	 */
18515 	mp2ctl = copymsg(mpctl);
18516 
18517 	/* ipAddrEntryTable */
18518 
18519 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18520 	optp->level = MIB2_IP;
18521 	optp->name = MIB2_IP_ADDR;
18522 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18523 
18524 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18525 	ill = ILL_START_WALK_V4(&ctx, ipst);
18526 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18527 		for (ipif = ill->ill_ipif; ipif != NULL;
18528 		    ipif = ipif->ipif_next) {
18529 			if (ipif->ipif_zoneid != zoneid &&
18530 			    ipif->ipif_zoneid != ALL_ZONES)
18531 				continue;
18532 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18533 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18534 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18535 
18536 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18537 			    OCTET_LENGTH);
18538 			mae.ipAdEntIfIndex.o_length =
18539 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18540 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18541 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18542 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18543 			mae.ipAdEntInfo.ae_subnet_len =
18544 			    ip_mask_to_plen(ipif->ipif_net_mask);
18545 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18546 			for (bitval = 1;
18547 			    bitval &&
18548 			    !(bitval & ipif->ipif_brd_addr);
18549 			    bitval <<= 1)
18550 				noop;
18551 			mae.ipAdEntBcastAddr = bitval;
18552 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18553 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18554 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18555 			mae.ipAdEntInfo.ae_broadcast_addr =
18556 			    ipif->ipif_brd_addr;
18557 			mae.ipAdEntInfo.ae_pp_dst_addr =
18558 			    ipif->ipif_pp_dst_addr;
18559 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18560 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18561 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18562 
18563 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18564 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18565 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18566 				    "allocate %u bytes\n",
18567 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18568 			}
18569 		}
18570 	}
18571 	rw_exit(&ipst->ips_ill_g_lock);
18572 
18573 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18574 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18575 	    (int)optp->level, (int)optp->name, (int)optp->len));
18576 	qreply(q, mpctl);
18577 	return (mp2ctl);
18578 }
18579 
18580 /* IPv6 address information */
18581 static mblk_t *
18582 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18583 {
18584 	struct opthdr		*optp;
18585 	mblk_t			*mp2ctl;
18586 	mblk_t			*mp_tail = NULL;
18587 	ill_t			*ill;
18588 	ipif_t			*ipif;
18589 	mib2_ipv6AddrEntry_t	mae6;
18590 	zoneid_t		zoneid;
18591 	ill_walk_context_t	ctx;
18592 
18593 	/*
18594 	 * make a copy of the original message
18595 	 */
18596 	mp2ctl = copymsg(mpctl);
18597 
18598 	/* ipv6AddrEntryTable */
18599 
18600 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18601 	optp->level = MIB2_IP6;
18602 	optp->name = MIB2_IP6_ADDR;
18603 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18604 
18605 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18606 	ill = ILL_START_WALK_V6(&ctx, ipst);
18607 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18608 		for (ipif = ill->ill_ipif; ipif != NULL;
18609 		    ipif = ipif->ipif_next) {
18610 			if (ipif->ipif_zoneid != zoneid &&
18611 			    ipif->ipif_zoneid != ALL_ZONES)
18612 				continue;
18613 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18614 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18615 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18616 
18617 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18618 			    OCTET_LENGTH);
18619 			mae6.ipv6AddrIfIndex.o_length =
18620 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18621 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18622 			mae6.ipv6AddrPfxLength =
18623 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18624 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18625 			mae6.ipv6AddrInfo.ae_subnet_len =
18626 			    mae6.ipv6AddrPfxLength;
18627 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18628 
18629 			/* Type: stateless(1), stateful(2), unknown(3) */
18630 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18631 				mae6.ipv6AddrType = 1;
18632 			else
18633 				mae6.ipv6AddrType = 2;
18634 			/* Anycast: true(1), false(2) */
18635 			if (ipif->ipif_flags & IPIF_ANYCAST)
18636 				mae6.ipv6AddrAnycastFlag = 1;
18637 			else
18638 				mae6.ipv6AddrAnycastFlag = 2;
18639 
18640 			/*
18641 			 * Address status: preferred(1), deprecated(2),
18642 			 * invalid(3), inaccessible(4), unknown(5)
18643 			 */
18644 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18645 				mae6.ipv6AddrStatus = 3;
18646 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18647 				mae6.ipv6AddrStatus = 2;
18648 			else
18649 				mae6.ipv6AddrStatus = 1;
18650 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18651 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18652 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18653 			    ipif->ipif_v6pp_dst_addr;
18654 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18655 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18656 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18657 			mae6.ipv6AddrIdentifier = ill->ill_token;
18658 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18659 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18660 			mae6.ipv6AddrRetransmitTime =
18661 			    ill->ill_reachable_retrans_time;
18662 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18663 			    (char *)&mae6,
18664 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18665 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18666 				    "allocate %u bytes\n",
18667 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18668 			}
18669 		}
18670 	}
18671 	rw_exit(&ipst->ips_ill_g_lock);
18672 
18673 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18674 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18675 	    (int)optp->level, (int)optp->name, (int)optp->len));
18676 	qreply(q, mpctl);
18677 	return (mp2ctl);
18678 }
18679 
18680 /* IPv4 multicast group membership. */
18681 static mblk_t *
18682 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18683 {
18684 	struct opthdr		*optp;
18685 	mblk_t			*mp2ctl;
18686 	ill_t			*ill;
18687 	ipif_t			*ipif;
18688 	ilm_t			*ilm;
18689 	ip_member_t		ipm;
18690 	mblk_t			*mp_tail = NULL;
18691 	ill_walk_context_t	ctx;
18692 	zoneid_t		zoneid;
18693 
18694 	/*
18695 	 * make a copy of the original message
18696 	 */
18697 	mp2ctl = copymsg(mpctl);
18698 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18699 
18700 	/* ipGroupMember table */
18701 	optp = (struct opthdr *)&mpctl->b_rptr[
18702 	    sizeof (struct T_optmgmt_ack)];
18703 	optp->level = MIB2_IP;
18704 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18705 
18706 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18707 	ill = ILL_START_WALK_V4(&ctx, ipst);
18708 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18709 		ILM_WALKER_HOLD(ill);
18710 		for (ipif = ill->ill_ipif; ipif != NULL;
18711 		    ipif = ipif->ipif_next) {
18712 			if (ipif->ipif_zoneid != zoneid &&
18713 			    ipif->ipif_zoneid != ALL_ZONES)
18714 				continue;	/* not this zone */
18715 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18716 			    OCTET_LENGTH);
18717 			ipm.ipGroupMemberIfIndex.o_length =
18718 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18719 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18720 				ASSERT(ilm->ilm_ipif != NULL);
18721 				ASSERT(ilm->ilm_ill == NULL);
18722 				if (ilm->ilm_ipif != ipif)
18723 					continue;
18724 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18725 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18726 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18727 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18728 				    (char *)&ipm, (int)sizeof (ipm))) {
18729 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18730 					    "failed to allocate %u bytes\n",
18731 					    (uint_t)sizeof (ipm)));
18732 				}
18733 			}
18734 		}
18735 		ILM_WALKER_RELE(ill);
18736 	}
18737 	rw_exit(&ipst->ips_ill_g_lock);
18738 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18739 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18740 	    (int)optp->level, (int)optp->name, (int)optp->len));
18741 	qreply(q, mpctl);
18742 	return (mp2ctl);
18743 }
18744 
18745 /* IPv6 multicast group membership. */
18746 static mblk_t *
18747 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18748 {
18749 	struct opthdr		*optp;
18750 	mblk_t			*mp2ctl;
18751 	ill_t			*ill;
18752 	ilm_t			*ilm;
18753 	ipv6_member_t		ipm6;
18754 	mblk_t			*mp_tail = NULL;
18755 	ill_walk_context_t	ctx;
18756 	zoneid_t		zoneid;
18757 
18758 	/*
18759 	 * make a copy of the original message
18760 	 */
18761 	mp2ctl = copymsg(mpctl);
18762 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18763 
18764 	/* ip6GroupMember table */
18765 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18766 	optp->level = MIB2_IP6;
18767 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18768 
18769 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18770 	ill = ILL_START_WALK_V6(&ctx, ipst);
18771 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18772 		ILM_WALKER_HOLD(ill);
18773 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18774 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18775 			ASSERT(ilm->ilm_ipif == NULL);
18776 			ASSERT(ilm->ilm_ill != NULL);
18777 			if (ilm->ilm_zoneid != zoneid)
18778 				continue;	/* not this zone */
18779 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18780 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18781 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18782 			if (!snmp_append_data2(mpctl->b_cont,
18783 			    &mp_tail,
18784 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18785 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18786 				    "failed to allocate %u bytes\n",
18787 				    (uint_t)sizeof (ipm6)));
18788 			}
18789 		}
18790 		ILM_WALKER_RELE(ill);
18791 	}
18792 	rw_exit(&ipst->ips_ill_g_lock);
18793 
18794 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18795 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18796 	    (int)optp->level, (int)optp->name, (int)optp->len));
18797 	qreply(q, mpctl);
18798 	return (mp2ctl);
18799 }
18800 
18801 /* IP multicast filtered sources */
18802 static mblk_t *
18803 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18804 {
18805 	struct opthdr		*optp;
18806 	mblk_t			*mp2ctl;
18807 	ill_t			*ill;
18808 	ipif_t			*ipif;
18809 	ilm_t			*ilm;
18810 	ip_grpsrc_t		ips;
18811 	mblk_t			*mp_tail = NULL;
18812 	ill_walk_context_t	ctx;
18813 	zoneid_t		zoneid;
18814 	int			i;
18815 	slist_t			*sl;
18816 
18817 	/*
18818 	 * make a copy of the original message
18819 	 */
18820 	mp2ctl = copymsg(mpctl);
18821 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18822 
18823 	/* ipGroupSource table */
18824 	optp = (struct opthdr *)&mpctl->b_rptr[
18825 	    sizeof (struct T_optmgmt_ack)];
18826 	optp->level = MIB2_IP;
18827 	optp->name = EXPER_IP_GROUP_SOURCES;
18828 
18829 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18830 	ill = ILL_START_WALK_V4(&ctx, ipst);
18831 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18832 		ILM_WALKER_HOLD(ill);
18833 		for (ipif = ill->ill_ipif; ipif != NULL;
18834 		    ipif = ipif->ipif_next) {
18835 			if (ipif->ipif_zoneid != zoneid)
18836 				continue;	/* not this zone */
18837 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18838 			    OCTET_LENGTH);
18839 			ips.ipGroupSourceIfIndex.o_length =
18840 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18841 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18842 				ASSERT(ilm->ilm_ipif != NULL);
18843 				ASSERT(ilm->ilm_ill == NULL);
18844 				sl = ilm->ilm_filter;
18845 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18846 					continue;
18847 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18848 				for (i = 0; i < sl->sl_numsrc; i++) {
18849 					if (!IN6_IS_ADDR_V4MAPPED(
18850 					    &sl->sl_addr[i]))
18851 						continue;
18852 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18853 					    ips.ipGroupSourceAddress);
18854 					if (snmp_append_data2(mpctl->b_cont,
18855 					    &mp_tail, (char *)&ips,
18856 					    (int)sizeof (ips)) == 0) {
18857 						ip1dbg(("ip_snmp_get_mib2_"
18858 						    "ip_group_src: failed to "
18859 						    "allocate %u bytes\n",
18860 						    (uint_t)sizeof (ips)));
18861 					}
18862 				}
18863 			}
18864 		}
18865 		ILM_WALKER_RELE(ill);
18866 	}
18867 	rw_exit(&ipst->ips_ill_g_lock);
18868 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18869 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18870 	    (int)optp->level, (int)optp->name, (int)optp->len));
18871 	qreply(q, mpctl);
18872 	return (mp2ctl);
18873 }
18874 
18875 /* IPv6 multicast filtered sources. */
18876 static mblk_t *
18877 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18878 {
18879 	struct opthdr		*optp;
18880 	mblk_t			*mp2ctl;
18881 	ill_t			*ill;
18882 	ilm_t			*ilm;
18883 	ipv6_grpsrc_t		ips6;
18884 	mblk_t			*mp_tail = NULL;
18885 	ill_walk_context_t	ctx;
18886 	zoneid_t		zoneid;
18887 	int			i;
18888 	slist_t			*sl;
18889 
18890 	/*
18891 	 * make a copy of the original message
18892 	 */
18893 	mp2ctl = copymsg(mpctl);
18894 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18895 
18896 	/* ip6GroupMember table */
18897 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18898 	optp->level = MIB2_IP6;
18899 	optp->name = EXPER_IP6_GROUP_SOURCES;
18900 
18901 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18902 	ill = ILL_START_WALK_V6(&ctx, ipst);
18903 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18904 		ILM_WALKER_HOLD(ill);
18905 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18906 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18907 			ASSERT(ilm->ilm_ipif == NULL);
18908 			ASSERT(ilm->ilm_ill != NULL);
18909 			sl = ilm->ilm_filter;
18910 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18911 				continue;
18912 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18913 			for (i = 0; i < sl->sl_numsrc; i++) {
18914 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18915 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18916 				    (char *)&ips6, (int)sizeof (ips6))) {
18917 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18918 					    "group_src: failed to allocate "
18919 					    "%u bytes\n",
18920 					    (uint_t)sizeof (ips6)));
18921 				}
18922 			}
18923 		}
18924 		ILM_WALKER_RELE(ill);
18925 	}
18926 	rw_exit(&ipst->ips_ill_g_lock);
18927 
18928 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18929 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18930 	    (int)optp->level, (int)optp->name, (int)optp->len));
18931 	qreply(q, mpctl);
18932 	return (mp2ctl);
18933 }
18934 
18935 /* Multicast routing virtual interface table. */
18936 static mblk_t *
18937 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18938 {
18939 	struct opthdr		*optp;
18940 	mblk_t			*mp2ctl;
18941 
18942 	/*
18943 	 * make a copy of the original message
18944 	 */
18945 	mp2ctl = copymsg(mpctl);
18946 
18947 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18948 	optp->level = EXPER_DVMRP;
18949 	optp->name = EXPER_DVMRP_VIF;
18950 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18951 		ip0dbg(("ip_mroute_vif: failed\n"));
18952 	}
18953 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18954 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18955 	    (int)optp->level, (int)optp->name, (int)optp->len));
18956 	qreply(q, mpctl);
18957 	return (mp2ctl);
18958 }
18959 
18960 /* Multicast routing table. */
18961 static mblk_t *
18962 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18963 {
18964 	struct opthdr		*optp;
18965 	mblk_t			*mp2ctl;
18966 
18967 	/*
18968 	 * make a copy of the original message
18969 	 */
18970 	mp2ctl = copymsg(mpctl);
18971 
18972 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18973 	optp->level = EXPER_DVMRP;
18974 	optp->name = EXPER_DVMRP_MRT;
18975 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18976 		ip0dbg(("ip_mroute_mrt: failed\n"));
18977 	}
18978 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18979 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18980 	    (int)optp->level, (int)optp->name, (int)optp->len));
18981 	qreply(q, mpctl);
18982 	return (mp2ctl);
18983 }
18984 
18985 /*
18986  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18987  * in one IRE walk.
18988  */
18989 static mblk_t *
18990 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18991 {
18992 	struct opthdr	*optp;
18993 	mblk_t		*mp2ctl;	/* Returned */
18994 	mblk_t		*mp3ctl;	/* nettomedia */
18995 	mblk_t		*mp4ctl;	/* routeattrs */
18996 	iproutedata_t	ird;
18997 	zoneid_t	zoneid;
18998 
18999 	/*
19000 	 * make copies of the original message
19001 	 *	- mp2ctl is returned unchanged to the caller for his use
19002 	 *	- mpctl is sent upstream as ipRouteEntryTable
19003 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
19004 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
19005 	 */
19006 	mp2ctl = copymsg(mpctl);
19007 	mp3ctl = copymsg(mpctl);
19008 	mp4ctl = copymsg(mpctl);
19009 	if (mp3ctl == NULL || mp4ctl == NULL) {
19010 		freemsg(mp4ctl);
19011 		freemsg(mp3ctl);
19012 		freemsg(mp2ctl);
19013 		freemsg(mpctl);
19014 		return (NULL);
19015 	}
19016 
19017 	bzero(&ird, sizeof (ird));
19018 
19019 	ird.ird_route.lp_head = mpctl->b_cont;
19020 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19021 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19022 
19023 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19024 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
19025 
19026 	/* ipRouteEntryTable in mpctl */
19027 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19028 	optp->level = MIB2_IP;
19029 	optp->name = MIB2_IP_ROUTE;
19030 	optp->len = msgdsize(ird.ird_route.lp_head);
19031 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19032 	    (int)optp->level, (int)optp->name, (int)optp->len));
19033 	qreply(q, mpctl);
19034 
19035 	/* ipNetToMediaEntryTable in mp3ctl */
19036 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19037 	optp->level = MIB2_IP;
19038 	optp->name = MIB2_IP_MEDIA;
19039 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19040 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19041 	    (int)optp->level, (int)optp->name, (int)optp->len));
19042 	qreply(q, mp3ctl);
19043 
19044 	/* ipRouteAttributeTable in mp4ctl */
19045 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19046 	optp->level = MIB2_IP;
19047 	optp->name = EXPER_IP_RTATTR;
19048 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19049 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
19050 	    (int)optp->level, (int)optp->name, (int)optp->len));
19051 	if (optp->len == 0)
19052 		freemsg(mp4ctl);
19053 	else
19054 		qreply(q, mp4ctl);
19055 
19056 	return (mp2ctl);
19057 }
19058 
19059 /*
19060  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19061  * ipv6NetToMediaEntryTable in an NDP walk.
19062  */
19063 static mblk_t *
19064 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19065 {
19066 	struct opthdr	*optp;
19067 	mblk_t		*mp2ctl;	/* Returned */
19068 	mblk_t		*mp3ctl;	/* nettomedia */
19069 	mblk_t		*mp4ctl;	/* routeattrs */
19070 	iproutedata_t	ird;
19071 	zoneid_t	zoneid;
19072 
19073 	/*
19074 	 * make copies of the original message
19075 	 *	- mp2ctl is returned unchanged to the caller for his use
19076 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19077 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19078 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19079 	 */
19080 	mp2ctl = copymsg(mpctl);
19081 	mp3ctl = copymsg(mpctl);
19082 	mp4ctl = copymsg(mpctl);
19083 	if (mp3ctl == NULL || mp4ctl == NULL) {
19084 		freemsg(mp4ctl);
19085 		freemsg(mp3ctl);
19086 		freemsg(mp2ctl);
19087 		freemsg(mpctl);
19088 		return (NULL);
19089 	}
19090 
19091 	bzero(&ird, sizeof (ird));
19092 
19093 	ird.ird_route.lp_head = mpctl->b_cont;
19094 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19095 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19096 
19097 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19098 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19099 
19100 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19101 	optp->level = MIB2_IP6;
19102 	optp->name = MIB2_IP6_ROUTE;
19103 	optp->len = msgdsize(ird.ird_route.lp_head);
19104 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19105 	    (int)optp->level, (int)optp->name, (int)optp->len));
19106 	qreply(q, mpctl);
19107 
19108 	/* ipv6NetToMediaEntryTable in mp3ctl */
19109 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19110 
19111 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19112 	optp->level = MIB2_IP6;
19113 	optp->name = MIB2_IP6_MEDIA;
19114 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19115 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19116 	    (int)optp->level, (int)optp->name, (int)optp->len));
19117 	qreply(q, mp3ctl);
19118 
19119 	/* ipv6RouteAttributeTable in mp4ctl */
19120 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19121 	optp->level = MIB2_IP6;
19122 	optp->name = EXPER_IP_RTATTR;
19123 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19124 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19125 	    (int)optp->level, (int)optp->name, (int)optp->len));
19126 	if (optp->len == 0)
19127 		freemsg(mp4ctl);
19128 	else
19129 		qreply(q, mp4ctl);
19130 
19131 	return (mp2ctl);
19132 }
19133 
19134 /*
19135  * IPv6 mib: One per ill
19136  */
19137 static mblk_t *
19138 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19139 {
19140 	struct opthdr		*optp;
19141 	mblk_t			*mp2ctl;
19142 	ill_t			*ill;
19143 	ill_walk_context_t	ctx;
19144 	mblk_t			*mp_tail = NULL;
19145 
19146 	/*
19147 	 * Make a copy of the original message
19148 	 */
19149 	mp2ctl = copymsg(mpctl);
19150 
19151 	/* fixed length IPv6 structure ... */
19152 
19153 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19154 	optp->level = MIB2_IP6;
19155 	optp->name = 0;
19156 	/* Include "unknown interface" ip6_mib */
19157 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19158 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19159 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19160 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19161 	    ipst->ips_ipv6_forward ? 1 : 2);
19162 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19163 	    ipst->ips_ipv6_def_hops);
19164 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19165 	    sizeof (mib2_ipIfStatsEntry_t));
19166 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19167 	    sizeof (mib2_ipv6AddrEntry_t));
19168 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19169 	    sizeof (mib2_ipv6RouteEntry_t));
19170 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19171 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19172 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19173 	    sizeof (ipv6_member_t));
19174 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19175 	    sizeof (ipv6_grpsrc_t));
19176 
19177 	/*
19178 	 * Synchronize 64- and 32-bit counters
19179 	 */
19180 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19181 	    ipIfStatsHCInReceives);
19182 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19183 	    ipIfStatsHCInDelivers);
19184 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19185 	    ipIfStatsHCOutRequests);
19186 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19187 	    ipIfStatsHCOutForwDatagrams);
19188 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19189 	    ipIfStatsHCOutMcastPkts);
19190 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19191 	    ipIfStatsHCInMcastPkts);
19192 
19193 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19194 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19195 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19196 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19197 	}
19198 
19199 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19200 	ill = ILL_START_WALK_V6(&ctx, ipst);
19201 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19202 		ill->ill_ip_mib->ipIfStatsIfIndex =
19203 		    ill->ill_phyint->phyint_ifindex;
19204 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19205 		    ipst->ips_ipv6_forward ? 1 : 2);
19206 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19207 		    ill->ill_max_hops);
19208 
19209 		/*
19210 		 * Synchronize 64- and 32-bit counters
19211 		 */
19212 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19213 		    ipIfStatsHCInReceives);
19214 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19215 		    ipIfStatsHCInDelivers);
19216 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19217 		    ipIfStatsHCOutRequests);
19218 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19219 		    ipIfStatsHCOutForwDatagrams);
19220 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19221 		    ipIfStatsHCOutMcastPkts);
19222 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19223 		    ipIfStatsHCInMcastPkts);
19224 
19225 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19226 		    (char *)ill->ill_ip_mib,
19227 		    (int)sizeof (*ill->ill_ip_mib))) {
19228 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19229 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19230 		}
19231 	}
19232 	rw_exit(&ipst->ips_ill_g_lock);
19233 
19234 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19235 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19236 	    (int)optp->level, (int)optp->name, (int)optp->len));
19237 	qreply(q, mpctl);
19238 	return (mp2ctl);
19239 }
19240 
19241 /*
19242  * ICMPv6 mib: One per ill
19243  */
19244 static mblk_t *
19245 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19246 {
19247 	struct opthdr		*optp;
19248 	mblk_t			*mp2ctl;
19249 	ill_t			*ill;
19250 	ill_walk_context_t	ctx;
19251 	mblk_t			*mp_tail = NULL;
19252 	/*
19253 	 * Make a copy of the original message
19254 	 */
19255 	mp2ctl = copymsg(mpctl);
19256 
19257 	/* fixed length ICMPv6 structure ... */
19258 
19259 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19260 	optp->level = MIB2_ICMP6;
19261 	optp->name = 0;
19262 	/* Include "unknown interface" icmp6_mib */
19263 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19264 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19265 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19266 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19267 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19268 	    (char *)&ipst->ips_icmp6_mib,
19269 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19270 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19271 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19272 	}
19273 
19274 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19275 	ill = ILL_START_WALK_V6(&ctx, ipst);
19276 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19277 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19278 		    ill->ill_phyint->phyint_ifindex;
19279 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19280 		    (char *)ill->ill_icmp6_mib,
19281 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19282 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19283 			    "%u bytes\n",
19284 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19285 		}
19286 	}
19287 	rw_exit(&ipst->ips_ill_g_lock);
19288 
19289 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19290 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19291 	    (int)optp->level, (int)optp->name, (int)optp->len));
19292 	qreply(q, mpctl);
19293 	return (mp2ctl);
19294 }
19295 
19296 /*
19297  * ire_walk routine to create both ipRouteEntryTable and
19298  * ipRouteAttributeTable in one IRE walk
19299  */
19300 static void
19301 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19302 {
19303 	ill_t				*ill;
19304 	ipif_t				*ipif;
19305 	mib2_ipRouteEntry_t		*re;
19306 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19307 	ipaddr_t			gw_addr;
19308 	tsol_ire_gw_secattr_t		*attrp;
19309 	tsol_gc_t			*gc = NULL;
19310 	tsol_gcgrp_t			*gcgrp = NULL;
19311 	uint_t				sacnt = 0;
19312 	int				i;
19313 
19314 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19315 
19316 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19317 		return;
19318 
19319 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19320 		mutex_enter(&attrp->igsa_lock);
19321 		if ((gc = attrp->igsa_gc) != NULL) {
19322 			gcgrp = gc->gc_grp;
19323 			ASSERT(gcgrp != NULL);
19324 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19325 			sacnt = 1;
19326 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19327 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19328 			gc = gcgrp->gcgrp_head;
19329 			sacnt = gcgrp->gcgrp_count;
19330 		}
19331 		mutex_exit(&attrp->igsa_lock);
19332 
19333 		/* do nothing if there's no gc to report */
19334 		if (gc == NULL) {
19335 			ASSERT(sacnt == 0);
19336 			if (gcgrp != NULL) {
19337 				/* we might as well drop the lock now */
19338 				rw_exit(&gcgrp->gcgrp_rwlock);
19339 				gcgrp = NULL;
19340 			}
19341 			attrp = NULL;
19342 		}
19343 
19344 		ASSERT(gc == NULL || (gcgrp != NULL &&
19345 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19346 	}
19347 	ASSERT(sacnt == 0 || gc != NULL);
19348 
19349 	if (sacnt != 0 &&
19350 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19351 		kmem_free(re, sizeof (*re));
19352 		rw_exit(&gcgrp->gcgrp_rwlock);
19353 		return;
19354 	}
19355 
19356 	/*
19357 	 * Return all IRE types for route table... let caller pick and choose
19358 	 */
19359 	re->ipRouteDest = ire->ire_addr;
19360 	ipif = ire->ire_ipif;
19361 	re->ipRouteIfIndex.o_length = 0;
19362 	if (ire->ire_type == IRE_CACHE) {
19363 		ill = (ill_t *)ire->ire_stq->q_ptr;
19364 		re->ipRouteIfIndex.o_length =
19365 		    ill->ill_name_length == 0 ? 0 :
19366 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19367 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19368 		    re->ipRouteIfIndex.o_length);
19369 	} else if (ipif != NULL) {
19370 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19371 		re->ipRouteIfIndex.o_length =
19372 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19373 	}
19374 	re->ipRouteMetric1 = -1;
19375 	re->ipRouteMetric2 = -1;
19376 	re->ipRouteMetric3 = -1;
19377 	re->ipRouteMetric4 = -1;
19378 
19379 	gw_addr = ire->ire_gateway_addr;
19380 
19381 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19382 		re->ipRouteNextHop = ire->ire_src_addr;
19383 	else
19384 		re->ipRouteNextHop = gw_addr;
19385 	/* indirect(4), direct(3), or invalid(2) */
19386 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19387 		re->ipRouteType = 2;
19388 	else
19389 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19390 	re->ipRouteProto = -1;
19391 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19392 	re->ipRouteMask = ire->ire_mask;
19393 	re->ipRouteMetric5 = -1;
19394 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19395 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19396 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19397 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19398 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19399 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19400 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19401 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19402 
19403 	if (ire->ire_flags & RTF_DYNAMIC) {
19404 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19405 	} else {
19406 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19407 	}
19408 
19409 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19410 	    (char *)re, (int)sizeof (*re))) {
19411 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19412 		    (uint_t)sizeof (*re)));
19413 	}
19414 
19415 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19416 		iaeptr->iae_routeidx = ird->ird_idx;
19417 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19418 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19419 	}
19420 
19421 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19422 	    (char *)iae, sacnt * sizeof (*iae))) {
19423 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19424 		    (unsigned)(sacnt * sizeof (*iae))));
19425 	}
19426 
19427 	/* bump route index for next pass */
19428 	ird->ird_idx++;
19429 
19430 	kmem_free(re, sizeof (*re));
19431 	if (sacnt != 0)
19432 		kmem_free(iae, sacnt * sizeof (*iae));
19433 
19434 	if (gcgrp != NULL)
19435 		rw_exit(&gcgrp->gcgrp_rwlock);
19436 }
19437 
19438 /*
19439  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19440  */
19441 static void
19442 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19443 {
19444 	ill_t				*ill;
19445 	ipif_t				*ipif;
19446 	mib2_ipv6RouteEntry_t		*re;
19447 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19448 	in6_addr_t			gw_addr_v6;
19449 	tsol_ire_gw_secattr_t		*attrp;
19450 	tsol_gc_t			*gc = NULL;
19451 	tsol_gcgrp_t			*gcgrp = NULL;
19452 	uint_t				sacnt = 0;
19453 	int				i;
19454 
19455 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19456 
19457 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19458 		return;
19459 
19460 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19461 		mutex_enter(&attrp->igsa_lock);
19462 		if ((gc = attrp->igsa_gc) != NULL) {
19463 			gcgrp = gc->gc_grp;
19464 			ASSERT(gcgrp != NULL);
19465 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19466 			sacnt = 1;
19467 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19468 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19469 			gc = gcgrp->gcgrp_head;
19470 			sacnt = gcgrp->gcgrp_count;
19471 		}
19472 		mutex_exit(&attrp->igsa_lock);
19473 
19474 		/* do nothing if there's no gc to report */
19475 		if (gc == NULL) {
19476 			ASSERT(sacnt == 0);
19477 			if (gcgrp != NULL) {
19478 				/* we might as well drop the lock now */
19479 				rw_exit(&gcgrp->gcgrp_rwlock);
19480 				gcgrp = NULL;
19481 			}
19482 			attrp = NULL;
19483 		}
19484 
19485 		ASSERT(gc == NULL || (gcgrp != NULL &&
19486 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19487 	}
19488 	ASSERT(sacnt == 0 || gc != NULL);
19489 
19490 	if (sacnt != 0 &&
19491 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19492 		kmem_free(re, sizeof (*re));
19493 		rw_exit(&gcgrp->gcgrp_rwlock);
19494 		return;
19495 	}
19496 
19497 	/*
19498 	 * Return all IRE types for route table... let caller pick and choose
19499 	 */
19500 	re->ipv6RouteDest = ire->ire_addr_v6;
19501 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19502 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19503 	re->ipv6RouteIfIndex.o_length = 0;
19504 	ipif = ire->ire_ipif;
19505 	if (ire->ire_type == IRE_CACHE) {
19506 		ill = (ill_t *)ire->ire_stq->q_ptr;
19507 		re->ipv6RouteIfIndex.o_length =
19508 		    ill->ill_name_length == 0 ? 0 :
19509 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19510 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19511 		    re->ipv6RouteIfIndex.o_length);
19512 	} else if (ipif != NULL) {
19513 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19514 		re->ipv6RouteIfIndex.o_length =
19515 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19516 	}
19517 
19518 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19519 
19520 	mutex_enter(&ire->ire_lock);
19521 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19522 	mutex_exit(&ire->ire_lock);
19523 
19524 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19525 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19526 	else
19527 		re->ipv6RouteNextHop = gw_addr_v6;
19528 
19529 	/* remote(4), local(3), or discard(2) */
19530 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19531 		re->ipv6RouteType = 2;
19532 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19533 		re->ipv6RouteType = 3;
19534 	else
19535 		re->ipv6RouteType = 4;
19536 
19537 	re->ipv6RouteProtocol	= -1;
19538 	re->ipv6RoutePolicy	= 0;
19539 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19540 	re->ipv6RouteNextHopRDI	= 0;
19541 	re->ipv6RouteWeight	= 0;
19542 	re->ipv6RouteMetric	= 0;
19543 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19544 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19545 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19546 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19547 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19548 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19549 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19550 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19551 
19552 	if (ire->ire_flags & RTF_DYNAMIC) {
19553 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19554 	} else {
19555 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19556 	}
19557 
19558 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19559 	    (char *)re, (int)sizeof (*re))) {
19560 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19561 		    (uint_t)sizeof (*re)));
19562 	}
19563 
19564 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19565 		iaeptr->iae_routeidx = ird->ird_idx;
19566 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19567 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19568 	}
19569 
19570 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19571 	    (char *)iae, sacnt * sizeof (*iae))) {
19572 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19573 		    (unsigned)(sacnt * sizeof (*iae))));
19574 	}
19575 
19576 	/* bump route index for next pass */
19577 	ird->ird_idx++;
19578 
19579 	kmem_free(re, sizeof (*re));
19580 	if (sacnt != 0)
19581 		kmem_free(iae, sacnt * sizeof (*iae));
19582 
19583 	if (gcgrp != NULL)
19584 		rw_exit(&gcgrp->gcgrp_rwlock);
19585 }
19586 
19587 /*
19588  * ndp_walk routine to create ipv6NetToMediaEntryTable
19589  */
19590 static int
19591 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19592 {
19593 	ill_t				*ill;
19594 	mib2_ipv6NetToMediaEntry_t	ntme;
19595 	dl_unitdata_req_t		*dl;
19596 
19597 	ill = nce->nce_ill;
19598 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19599 		return (0);
19600 
19601 	/*
19602 	 * Neighbor cache entry attached to IRE with on-link
19603 	 * destination.
19604 	 */
19605 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19606 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19607 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19608 	    (nce->nce_res_mp != NULL)) {
19609 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19610 		ntme.ipv6NetToMediaPhysAddress.o_length =
19611 		    dl->dl_dest_addr_length;
19612 	} else {
19613 		ntme.ipv6NetToMediaPhysAddress.o_length =
19614 		    ill->ill_phys_addr_length;
19615 	}
19616 	if (nce->nce_res_mp != NULL) {
19617 		bcopy((char *)nce->nce_res_mp->b_rptr +
19618 		    NCE_LL_ADDR_OFFSET(ill),
19619 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19620 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19621 	} else {
19622 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19623 		    ill->ill_phys_addr_length);
19624 	}
19625 	/*
19626 	 * Note: Returns ND_* states. Should be:
19627 	 * reachable(1), stale(2), delay(3), probe(4),
19628 	 * invalid(5), unknown(6)
19629 	 */
19630 	ntme.ipv6NetToMediaState = nce->nce_state;
19631 	ntme.ipv6NetToMediaLastUpdated = 0;
19632 
19633 	/* other(1), dynamic(2), static(3), local(4) */
19634 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19635 		ntme.ipv6NetToMediaType = 4;
19636 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19637 		ntme.ipv6NetToMediaType = 1;
19638 	} else {
19639 		ntme.ipv6NetToMediaType = 2;
19640 	}
19641 
19642 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19643 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19644 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19645 		    (uint_t)sizeof (ntme)));
19646 	}
19647 	return (0);
19648 }
19649 
19650 /*
19651  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19652  */
19653 /* ARGSUSED */
19654 int
19655 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19656 {
19657 	switch (level) {
19658 	case MIB2_IP:
19659 	case MIB2_ICMP:
19660 		switch (name) {
19661 		default:
19662 			break;
19663 		}
19664 		return (1);
19665 	default:
19666 		return (1);
19667 	}
19668 }
19669 
19670 /*
19671  * When there exists both a 64- and 32-bit counter of a particular type
19672  * (i.e., InReceives), only the 64-bit counters are added.
19673  */
19674 void
19675 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19676 {
19677 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19678 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19679 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19680 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19681 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19682 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19683 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19684 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19685 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19686 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19687 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19688 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19689 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19690 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19691 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19692 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19693 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19694 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19695 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19696 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19697 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19698 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19699 	    o2->ipIfStatsInWrongIPVersion);
19700 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19701 	    o2->ipIfStatsInWrongIPVersion);
19702 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19703 	    o2->ipIfStatsOutSwitchIPVersion);
19704 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19705 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19706 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19707 	    o2->ipIfStatsHCInForwDatagrams);
19708 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19709 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19710 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19711 	    o2->ipIfStatsHCOutForwDatagrams);
19712 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19713 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19714 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19715 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19716 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19717 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19718 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19719 	    o2->ipIfStatsHCOutMcastOctets);
19720 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19721 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19722 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19723 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19724 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19725 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19726 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19727 }
19728 
19729 void
19730 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19731 {
19732 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19733 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19734 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19735 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19736 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19737 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19738 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19739 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19740 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19741 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19742 	    o2->ipv6IfIcmpInRouterSolicits);
19743 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19744 	    o2->ipv6IfIcmpInRouterAdvertisements);
19745 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19746 	    o2->ipv6IfIcmpInNeighborSolicits);
19747 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19748 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19749 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19750 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19751 	    o2->ipv6IfIcmpInGroupMembQueries);
19752 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19753 	    o2->ipv6IfIcmpInGroupMembResponses);
19754 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19755 	    o2->ipv6IfIcmpInGroupMembReductions);
19756 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19757 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19758 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19759 	    o2->ipv6IfIcmpOutDestUnreachs);
19760 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19761 	    o2->ipv6IfIcmpOutAdminProhibs);
19762 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19763 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19764 	    o2->ipv6IfIcmpOutParmProblems);
19765 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19766 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19767 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19768 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19769 	    o2->ipv6IfIcmpOutRouterSolicits);
19770 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19771 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19772 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19773 	    o2->ipv6IfIcmpOutNeighborSolicits);
19774 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19775 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19776 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19777 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19778 	    o2->ipv6IfIcmpOutGroupMembQueries);
19779 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19780 	    o2->ipv6IfIcmpOutGroupMembResponses);
19781 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19782 	    o2->ipv6IfIcmpOutGroupMembReductions);
19783 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19784 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19785 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19786 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19787 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19788 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19789 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19790 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19791 	    o2->ipv6IfIcmpInGroupMembTotal);
19792 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19793 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19794 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19795 	    o2->ipv6IfIcmpInGroupMembBadReports);
19796 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19797 	    o2->ipv6IfIcmpInGroupMembOurReports);
19798 }
19799 
19800 /*
19801  * Called before the options are updated to check if this packet will
19802  * be source routed from here.
19803  * This routine assumes that the options are well formed i.e. that they
19804  * have already been checked.
19805  */
19806 static boolean_t
19807 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19808 {
19809 	ipoptp_t	opts;
19810 	uchar_t		*opt;
19811 	uint8_t		optval;
19812 	uint8_t		optlen;
19813 	ipaddr_t	dst;
19814 	ire_t		*ire;
19815 
19816 	if (IS_SIMPLE_IPH(ipha)) {
19817 		ip2dbg(("not source routed\n"));
19818 		return (B_FALSE);
19819 	}
19820 	dst = ipha->ipha_dst;
19821 	for (optval = ipoptp_first(&opts, ipha);
19822 	    optval != IPOPT_EOL;
19823 	    optval = ipoptp_next(&opts)) {
19824 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19825 		opt = opts.ipoptp_cur;
19826 		optlen = opts.ipoptp_len;
19827 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19828 		    optval, optlen));
19829 		switch (optval) {
19830 			uint32_t off;
19831 		case IPOPT_SSRR:
19832 		case IPOPT_LSRR:
19833 			/*
19834 			 * If dst is one of our addresses and there are some
19835 			 * entries left in the source route return (true).
19836 			 */
19837 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19838 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19839 			if (ire == NULL) {
19840 				ip2dbg(("ip_source_routed: not next"
19841 				    " source route 0x%x\n",
19842 				    ntohl(dst)));
19843 				return (B_FALSE);
19844 			}
19845 			ire_refrele(ire);
19846 			off = opt[IPOPT_OFFSET];
19847 			off--;
19848 			if (optlen < IP_ADDR_LEN ||
19849 			    off > optlen - IP_ADDR_LEN) {
19850 				/* End of source route */
19851 				ip1dbg(("ip_source_routed: end of SR\n"));
19852 				return (B_FALSE);
19853 			}
19854 			return (B_TRUE);
19855 		}
19856 	}
19857 	ip2dbg(("not source routed\n"));
19858 	return (B_FALSE);
19859 }
19860 
19861 /*
19862  * Check if the packet contains any source route.
19863  */
19864 static boolean_t
19865 ip_source_route_included(ipha_t *ipha)
19866 {
19867 	ipoptp_t	opts;
19868 	uint8_t		optval;
19869 
19870 	if (IS_SIMPLE_IPH(ipha))
19871 		return (B_FALSE);
19872 	for (optval = ipoptp_first(&opts, ipha);
19873 	    optval != IPOPT_EOL;
19874 	    optval = ipoptp_next(&opts)) {
19875 		switch (optval) {
19876 		case IPOPT_SSRR:
19877 		case IPOPT_LSRR:
19878 			return (B_TRUE);
19879 		}
19880 	}
19881 	return (B_FALSE);
19882 }
19883 
19884 /*
19885  * Called when the IRE expiration timer fires.
19886  */
19887 void
19888 ip_trash_timer_expire(void *args)
19889 {
19890 	int			flush_flag = 0;
19891 	ire_expire_arg_t	iea;
19892 	ip_stack_t		*ipst = (ip_stack_t *)args;
19893 
19894 	iea.iea_ipst = ipst;	/* No netstack_hold */
19895 
19896 	/*
19897 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19898 	 * This lock makes sure that a new invocation of this function
19899 	 * that occurs due to an almost immediate timer firing will not
19900 	 * progress beyond this point until the current invocation is done
19901 	 */
19902 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19903 	ipst->ips_ip_ire_expire_id = 0;
19904 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19905 
19906 	/* Periodic timer */
19907 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19908 	    ipst->ips_ip_ire_arp_interval) {
19909 		/*
19910 		 * Remove all IRE_CACHE entries since they might
19911 		 * contain arp information.
19912 		 */
19913 		flush_flag |= FLUSH_ARP_TIME;
19914 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19915 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19916 	}
19917 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19918 	    ipst->ips_ip_ire_redir_interval) {
19919 		/* Remove all redirects */
19920 		flush_flag |= FLUSH_REDIRECT_TIME;
19921 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19922 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19923 	}
19924 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19925 	    ipst->ips_ip_ire_pathmtu_interval) {
19926 		/* Increase path mtu */
19927 		flush_flag |= FLUSH_MTU_TIME;
19928 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19929 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19930 	}
19931 
19932 	/*
19933 	 * Optimize for the case when there are no redirects in the
19934 	 * ftable, that is, no need to walk the ftable in that case.
19935 	 */
19936 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19937 		iea.iea_flush_flag = flush_flag;
19938 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19939 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19940 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19941 		    NULL, ALL_ZONES, ipst);
19942 	}
19943 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19944 	    ipst->ips_ip_redirect_cnt > 0) {
19945 		iea.iea_flush_flag = flush_flag;
19946 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19947 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19948 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19949 	}
19950 	if (flush_flag & FLUSH_MTU_TIME) {
19951 		/*
19952 		 * Walk all IPv6 IRE's and update them
19953 		 * Note that ARP and redirect timers are not
19954 		 * needed since NUD handles stale entries.
19955 		 */
19956 		flush_flag = FLUSH_MTU_TIME;
19957 		iea.iea_flush_flag = flush_flag;
19958 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19959 		    ALL_ZONES, ipst);
19960 	}
19961 
19962 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19963 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19964 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19965 
19966 	/*
19967 	 * Hold the lock to serialize timeout calls and prevent
19968 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19969 	 * for the timer to fire and a new invocation of this function
19970 	 * to start before the return value of timeout has been stored
19971 	 * in ip_ire_expire_id by the current invocation.
19972 	 */
19973 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19974 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19975 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19976 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19977 }
19978 
19979 /*
19980  * Called by the memory allocator subsystem directly, when the system
19981  * is running low on memory.
19982  */
19983 /* ARGSUSED */
19984 void
19985 ip_trash_ire_reclaim(void *args)
19986 {
19987 	netstack_handle_t nh;
19988 	netstack_t *ns;
19989 
19990 	netstack_next_init(&nh);
19991 	while ((ns = netstack_next(&nh)) != NULL) {
19992 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19993 		netstack_rele(ns);
19994 	}
19995 	netstack_next_fini(&nh);
19996 }
19997 
19998 static void
19999 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
20000 {
20001 	ire_cache_count_t icc;
20002 	ire_cache_reclaim_t icr;
20003 	ncc_cache_count_t ncc;
20004 	nce_cache_reclaim_t ncr;
20005 	uint_t delete_cnt;
20006 	/*
20007 	 * Memory reclaim call back.
20008 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
20009 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
20010 	 * entries, determine what fraction to free for
20011 	 * each category of IRE_CACHE entries giving absolute priority
20012 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
20013 	 * entry will be freed unless all offlink entries are freed).
20014 	 */
20015 	icc.icc_total = 0;
20016 	icc.icc_unused = 0;
20017 	icc.icc_offlink = 0;
20018 	icc.icc_pmtu = 0;
20019 	icc.icc_onlink = 0;
20020 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20021 
20022 	/*
20023 	 * Free NCEs for IPv6 like the onlink ires.
20024 	 */
20025 	ncc.ncc_total = 0;
20026 	ncc.ncc_host = 0;
20027 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
20028 
20029 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
20030 	    icc.icc_pmtu + icc.icc_onlink);
20031 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
20032 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
20033 	if (delete_cnt == 0)
20034 		return;
20035 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
20036 	/* Always delete all unused offlink entries */
20037 	icr.icr_ipst = ipst;
20038 	icr.icr_unused = 1;
20039 	if (delete_cnt <= icc.icc_unused) {
20040 		/*
20041 		 * Only need to free unused entries.  In other words,
20042 		 * there are enough unused entries to free to meet our
20043 		 * target number of freed ire cache entries.
20044 		 */
20045 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
20046 		ncr.ncr_host = 0;
20047 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
20048 		/*
20049 		 * Only need to free unused entries, plus a fraction of offlink
20050 		 * entries.  It follows from the first if statement that
20051 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
20052 		 */
20053 		delete_cnt -= icc.icc_unused;
20054 		/* Round up # deleted by truncating fraction */
20055 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
20056 		icr.icr_pmtu = icr.icr_onlink = 0;
20057 		ncr.ncr_host = 0;
20058 	} else if (delete_cnt <=
20059 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20060 		/*
20061 		 * Free all unused and offlink entries, plus a fraction of
20062 		 * pmtu entries.  It follows from the previous if statement
20063 		 * that icc_pmtu is non-zero, and that
20064 		 * delete_cnt != icc_unused + icc_offlink.
20065 		 */
20066 		icr.icr_offlink = 1;
20067 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20068 		/* Round up # deleted by truncating fraction */
20069 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20070 		icr.icr_onlink = 0;
20071 		ncr.ncr_host = 0;
20072 	} else {
20073 		/*
20074 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20075 		 * of onlink entries.  If we're here, then we know that
20076 		 * icc_onlink is non-zero, and that
20077 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20078 		 */
20079 		icr.icr_offlink = icr.icr_pmtu = 1;
20080 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20081 		    icc.icc_pmtu;
20082 		/* Round up # deleted by truncating fraction */
20083 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20084 		/* Using the same delete fraction as for onlink IREs */
20085 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20086 	}
20087 #ifdef DEBUG
20088 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20089 	    "fractions %d/%d/%d/%d\n",
20090 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20091 	    icc.icc_unused, icc.icc_offlink,
20092 	    icc.icc_pmtu, icc.icc_onlink,
20093 	    icr.icr_unused, icr.icr_offlink,
20094 	    icr.icr_pmtu, icr.icr_onlink));
20095 #endif
20096 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20097 	if (ncr.ncr_host != 0)
20098 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20099 		    (uchar_t *)&ncr, ipst);
20100 #ifdef DEBUG
20101 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20102 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20103 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20104 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20105 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20106 	    icc.icc_pmtu, icc.icc_onlink));
20107 #endif
20108 }
20109 
20110 /*
20111  * ip_unbind is called when a copy of an unbind request is received from the
20112  * upper level protocol.  We remove this conn from any fanout hash list it is
20113  * on, and zero out the bind information.  No reply is expected up above.
20114  */
20115 mblk_t *
20116 ip_unbind(queue_t *q, mblk_t *mp)
20117 {
20118 	conn_t	*connp = Q_TO_CONN(q);
20119 
20120 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20121 
20122 	if (is_system_labeled() && connp->conn_anon_port) {
20123 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20124 		    connp->conn_mlp_type, connp->conn_ulp,
20125 		    ntohs(connp->conn_lport), B_FALSE);
20126 		connp->conn_anon_port = 0;
20127 	}
20128 	connp->conn_mlp_type = mlptSingle;
20129 
20130 	ipcl_hash_remove(connp);
20131 
20132 	ASSERT(mp->b_cont == NULL);
20133 	/*
20134 	 * Convert mp into a T_OK_ACK
20135 	 */
20136 	mp = mi_tpi_ok_ack_alloc(mp);
20137 
20138 	/*
20139 	 * should not happen in practice... T_OK_ACK is smaller than the
20140 	 * original message.
20141 	 */
20142 	if (mp == NULL)
20143 		return (NULL);
20144 
20145 	return (mp);
20146 }
20147 
20148 /*
20149  * Write side put procedure.  Outbound data, IOCTLs, responses from
20150  * resolvers, etc, come down through here.
20151  *
20152  * arg2 is always a queue_t *.
20153  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20154  * the zoneid.
20155  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20156  */
20157 void
20158 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20159 {
20160 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20161 }
20162 
20163 void
20164 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20165     ip_opt_info_t *infop)
20166 {
20167 	conn_t		*connp = NULL;
20168 	queue_t		*q = (queue_t *)arg2;
20169 	ipha_t		*ipha;
20170 #define	rptr	((uchar_t *)ipha)
20171 	ire_t		*ire = NULL;
20172 	ire_t		*sctp_ire = NULL;
20173 	uint32_t	v_hlen_tos_len;
20174 	ipaddr_t	dst;
20175 	mblk_t		*first_mp = NULL;
20176 	boolean_t	mctl_present;
20177 	ipsec_out_t	*io;
20178 	int		match_flags;
20179 	ill_t		*attach_ill = NULL;
20180 					/* Bind to IPIF_NOFAILOVER ill etc. */
20181 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20182 	ipif_t		*dst_ipif;
20183 	boolean_t	multirt_need_resolve = B_FALSE;
20184 	mblk_t		*copy_mp = NULL;
20185 	int		err;
20186 	zoneid_t	zoneid;
20187 	int	adjust;
20188 	uint16_t iplen;
20189 	boolean_t	need_decref = B_FALSE;
20190 	boolean_t	ignore_dontroute = B_FALSE;
20191 	boolean_t	ignore_nexthop = B_FALSE;
20192 	boolean_t	ip_nexthop = B_FALSE;
20193 	ipaddr_t	nexthop_addr;
20194 	ip_stack_t	*ipst;
20195 
20196 #ifdef	_BIG_ENDIAN
20197 #define	V_HLEN	(v_hlen_tos_len >> 24)
20198 #else
20199 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20200 #endif
20201 
20202 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20203 	    "ip_wput_start: q %p", q);
20204 
20205 	/*
20206 	 * ip_wput fast path
20207 	 */
20208 
20209 	/* is packet from ARP ? */
20210 	if (q->q_next != NULL) {
20211 		zoneid = (zoneid_t)(uintptr_t)arg;
20212 		goto qnext;
20213 	}
20214 
20215 	connp = (conn_t *)arg;
20216 	ASSERT(connp != NULL);
20217 	zoneid = connp->conn_zoneid;
20218 	ipst = connp->conn_netstack->netstack_ip;
20219 
20220 	/* is queue flow controlled? */
20221 	if ((q->q_first != NULL || connp->conn_draining) &&
20222 	    (caller == IP_WPUT)) {
20223 		ASSERT(!need_decref);
20224 		(void) putq(q, mp);
20225 		return;
20226 	}
20227 
20228 	/* Multidata transmit? */
20229 	if (DB_TYPE(mp) == M_MULTIDATA) {
20230 		/*
20231 		 * We should never get here, since all Multidata messages
20232 		 * originating from tcp should have been directed over to
20233 		 * tcp_multisend() in the first place.
20234 		 */
20235 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20236 		freemsg(mp);
20237 		return;
20238 	} else if (DB_TYPE(mp) != M_DATA)
20239 		goto notdata;
20240 
20241 	if (mp->b_flag & MSGHASREF) {
20242 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20243 		mp->b_flag &= ~MSGHASREF;
20244 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20245 		need_decref = B_TRUE;
20246 	}
20247 	ipha = (ipha_t *)mp->b_rptr;
20248 
20249 	/* is IP header non-aligned or mblk smaller than basic IP header */
20250 #ifndef SAFETY_BEFORE_SPEED
20251 	if (!OK_32PTR(rptr) ||
20252 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20253 		goto hdrtoosmall;
20254 #endif
20255 
20256 	ASSERT(OK_32PTR(ipha));
20257 
20258 	/*
20259 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20260 	 * wrong version, we'll catch it again in ip_output_v6.
20261 	 *
20262 	 * Note that this is *only* locally-generated output here, and never
20263 	 * forwarded data, and that we need to deal only with transports that
20264 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20265 	 * label.)
20266 	 */
20267 	if (is_system_labeled() &&
20268 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20269 	    !connp->conn_ulp_labeled) {
20270 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20271 		    connp->conn_mac_exempt, ipst);
20272 		ipha = (ipha_t *)mp->b_rptr;
20273 		if (err != 0) {
20274 			first_mp = mp;
20275 			if (err == EINVAL)
20276 				goto icmp_parameter_problem;
20277 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20278 			goto discard_pkt;
20279 		}
20280 		iplen = ntohs(ipha->ipha_length) + adjust;
20281 		ipha->ipha_length = htons(iplen);
20282 	}
20283 
20284 	ASSERT(infop != NULL);
20285 
20286 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20287 		/*
20288 		 * IP_PKTINFO ancillary option is present.
20289 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20290 		 * allows using address of any zone as the source address.
20291 		 */
20292 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20293 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20294 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20295 		if (ire == NULL)
20296 			goto drop_pkt;
20297 		ire_refrele(ire);
20298 		ire = NULL;
20299 	}
20300 
20301 	/*
20302 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20303 	 * passed in IP_PKTINFO.
20304 	 */
20305 	if (infop->ip_opt_ill_index != 0 &&
20306 	    connp->conn_outgoing_ill == NULL &&
20307 	    connp->conn_nofailover_ill == NULL) {
20308 
20309 		xmit_ill = ill_lookup_on_ifindex(
20310 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20311 		    ipst);
20312 
20313 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20314 			goto drop_pkt;
20315 		/*
20316 		 * check that there is an ipif belonging
20317 		 * to our zone. IPCL_ZONEID is not used because
20318 		 * IP_ALLZONES option is valid only when the ill is
20319 		 * accessible from all zones i.e has a valid ipif in
20320 		 * all zones.
20321 		 */
20322 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20323 			goto drop_pkt;
20324 		}
20325 	}
20326 
20327 	/*
20328 	 * If there is a policy, try to attach an ipsec_out in
20329 	 * the front. At the end, first_mp either points to a
20330 	 * M_DATA message or IPSEC_OUT message linked to a
20331 	 * M_DATA message. We have to do it now as we might
20332 	 * lose the "conn" if we go through ip_newroute.
20333 	 */
20334 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20335 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20336 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20337 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20338 			if (need_decref)
20339 				CONN_DEC_REF(connp);
20340 			return;
20341 		} else {
20342 			ASSERT(mp->b_datap->db_type == M_CTL);
20343 			first_mp = mp;
20344 			mp = mp->b_cont;
20345 			mctl_present = B_TRUE;
20346 		}
20347 	} else {
20348 		first_mp = mp;
20349 		mctl_present = B_FALSE;
20350 	}
20351 
20352 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20353 
20354 	/* is wrong version or IP options present */
20355 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20356 		goto version_hdrlen_check;
20357 	dst = ipha->ipha_dst;
20358 
20359 	if (connp->conn_nofailover_ill != NULL) {
20360 		attach_ill = conn_get_held_ill(connp,
20361 		    &connp->conn_nofailover_ill, &err);
20362 		if (err == ILL_LOOKUP_FAILED) {
20363 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20364 			if (need_decref)
20365 				CONN_DEC_REF(connp);
20366 			freemsg(first_mp);
20367 			return;
20368 		}
20369 	}
20370 
20371 	/* If IP_BOUND_IF has been set, use that ill. */
20372 	if (connp->conn_outgoing_ill != NULL) {
20373 		xmit_ill = conn_get_held_ill(connp,
20374 		    &connp->conn_outgoing_ill, &err);
20375 		if (err == ILL_LOOKUP_FAILED)
20376 			goto drop_pkt;
20377 
20378 		goto send_from_ill;
20379 	}
20380 
20381 	/* is packet multicast? */
20382 	if (CLASSD(dst))
20383 		goto multicast;
20384 
20385 	/*
20386 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20387 	 * takes precedence over conn_dontroute and conn_nexthop_set
20388 	 */
20389 	if (xmit_ill != NULL)
20390 		goto send_from_ill;
20391 
20392 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20393 		/*
20394 		 * If the destination is a broadcast, local, or loopback
20395 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20396 		 * standard path.
20397 		 */
20398 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20399 		if ((ire == NULL) || (ire->ire_type &
20400 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20401 			if (ire != NULL) {
20402 				ire_refrele(ire);
20403 				/* No more access to ire */
20404 				ire = NULL;
20405 			}
20406 			/*
20407 			 * bypass routing checks and go directly to interface.
20408 			 */
20409 			if (connp->conn_dontroute)
20410 				goto dontroute;
20411 
20412 			ASSERT(connp->conn_nexthop_set);
20413 			ip_nexthop = B_TRUE;
20414 			nexthop_addr = connp->conn_nexthop_v4;
20415 			goto send_from_ill;
20416 		}
20417 
20418 		/* Must be a broadcast, a loopback or a local ire */
20419 		ire_refrele(ire);
20420 		/* No more access to ire */
20421 		ire = NULL;
20422 	}
20423 
20424 	if (attach_ill != NULL)
20425 		goto send_from_ill;
20426 
20427 	/*
20428 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20429 	 * this for the tcp global queue and listen end point
20430 	 * as it does not really have a real destination to
20431 	 * talk to.  This is also true for SCTP.
20432 	 */
20433 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20434 	    !connp->conn_fully_bound) {
20435 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20436 		if (ire == NULL)
20437 			goto noirefound;
20438 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20439 		    "ip_wput_end: q %p (%S)", q, "end");
20440 
20441 		/*
20442 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20443 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20444 		 */
20445 		if (ire->ire_flags & RTF_MULTIRT) {
20446 
20447 			/*
20448 			 * Force the TTL of multirouted packets if required.
20449 			 * The TTL of such packets is bounded by the
20450 			 * ip_multirt_ttl ndd variable.
20451 			 */
20452 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20453 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20454 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20455 				    "(was %d), dst 0x%08x\n",
20456 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20457 				    ntohl(ire->ire_addr)));
20458 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20459 			}
20460 			/*
20461 			 * We look at this point if there are pending
20462 			 * unresolved routes. ire_multirt_resolvable()
20463 			 * checks in O(n) that all IRE_OFFSUBNET ire
20464 			 * entries for the packet's destination and
20465 			 * flagged RTF_MULTIRT are currently resolved.
20466 			 * If some remain unresolved, we make a copy
20467 			 * of the current message. It will be used
20468 			 * to initiate additional route resolutions.
20469 			 */
20470 			multirt_need_resolve =
20471 			    ire_multirt_need_resolve(ire->ire_addr,
20472 			    MBLK_GETLABEL(first_mp), ipst);
20473 			ip2dbg(("ip_wput[TCP]: ire %p, "
20474 			    "multirt_need_resolve %d, first_mp %p\n",
20475 			    (void *)ire, multirt_need_resolve,
20476 			    (void *)first_mp));
20477 			if (multirt_need_resolve) {
20478 				copy_mp = copymsg(first_mp);
20479 				if (copy_mp != NULL) {
20480 					MULTIRT_DEBUG_TAG(copy_mp);
20481 				}
20482 			}
20483 		}
20484 
20485 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20486 
20487 		/*
20488 		 * Try to resolve another multiroute if
20489 		 * ire_multirt_need_resolve() deemed it necessary.
20490 		 */
20491 		if (copy_mp != NULL)
20492 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20493 		if (need_decref)
20494 			CONN_DEC_REF(connp);
20495 		return;
20496 	}
20497 
20498 	/*
20499 	 * Access to conn_ire_cache. (protected by conn_lock)
20500 	 *
20501 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20502 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20503 	 * send a packet or two with the IRE_CACHE that is going away.
20504 	 * Access to the ire requires an ire refhold on the ire prior to
20505 	 * its use since an interface unplumb thread may delete the cached
20506 	 * ire and release the refhold at any time.
20507 	 *
20508 	 * Caching an ire in the conn_ire_cache
20509 	 *
20510 	 * o Caching an ire pointer in the conn requires a strict check for
20511 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20512 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20513 	 * in the conn is done after making sure under the bucket lock that the
20514 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20515 	 * caching an ire after the unplumb thread has cleaned up the conn.
20516 	 * If the conn does not send a packet subsequently the unplumb thread
20517 	 * will be hanging waiting for the ire count to drop to zero.
20518 	 *
20519 	 * o We also need to atomically test for a null conn_ire_cache and
20520 	 * set the conn_ire_cache under the the protection of the conn_lock
20521 	 * to avoid races among concurrent threads trying to simultaneously
20522 	 * cache an ire in the conn_ire_cache.
20523 	 */
20524 	mutex_enter(&connp->conn_lock);
20525 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20526 
20527 	if (ire != NULL && ire->ire_addr == dst &&
20528 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20529 
20530 		IRE_REFHOLD(ire);
20531 		mutex_exit(&connp->conn_lock);
20532 
20533 	} else {
20534 		boolean_t cached = B_FALSE;
20535 		connp->conn_ire_cache = NULL;
20536 		mutex_exit(&connp->conn_lock);
20537 		/* Release the old ire */
20538 		if (ire != NULL && sctp_ire == NULL)
20539 			IRE_REFRELE_NOTR(ire);
20540 
20541 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20542 		if (ire == NULL)
20543 			goto noirefound;
20544 		IRE_REFHOLD_NOTR(ire);
20545 
20546 		mutex_enter(&connp->conn_lock);
20547 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20548 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20549 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20550 				if (connp->conn_ulp == IPPROTO_TCP)
20551 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20552 				connp->conn_ire_cache = ire;
20553 				cached = B_TRUE;
20554 			}
20555 			rw_exit(&ire->ire_bucket->irb_lock);
20556 		}
20557 		mutex_exit(&connp->conn_lock);
20558 
20559 		/*
20560 		 * We can continue to use the ire but since it was
20561 		 * not cached, we should drop the extra reference.
20562 		 */
20563 		if (!cached)
20564 			IRE_REFRELE_NOTR(ire);
20565 	}
20566 
20567 
20568 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20569 	    "ip_wput_end: q %p (%S)", q, "end");
20570 
20571 	/*
20572 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20573 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20574 	 */
20575 	if (ire->ire_flags & RTF_MULTIRT) {
20576 
20577 		/*
20578 		 * Force the TTL of multirouted packets if required.
20579 		 * The TTL of such packets is bounded by the
20580 		 * ip_multirt_ttl ndd variable.
20581 		 */
20582 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20583 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20584 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20585 			    "(was %d), dst 0x%08x\n",
20586 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20587 			    ntohl(ire->ire_addr)));
20588 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20589 		}
20590 
20591 		/*
20592 		 * At this point, we check to see if there are any pending
20593 		 * unresolved routes. ire_multirt_resolvable()
20594 		 * checks in O(n) that all IRE_OFFSUBNET ire
20595 		 * entries for the packet's destination and
20596 		 * flagged RTF_MULTIRT are currently resolved.
20597 		 * If some remain unresolved, we make a copy
20598 		 * of the current message. It will be used
20599 		 * to initiate additional route resolutions.
20600 		 */
20601 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20602 		    MBLK_GETLABEL(first_mp), ipst);
20603 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20604 		    "multirt_need_resolve %d, first_mp %p\n",
20605 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20606 		if (multirt_need_resolve) {
20607 			copy_mp = copymsg(first_mp);
20608 			if (copy_mp != NULL) {
20609 				MULTIRT_DEBUG_TAG(copy_mp);
20610 			}
20611 		}
20612 	}
20613 
20614 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20615 
20616 	/*
20617 	 * Try to resolve another multiroute if
20618 	 * ire_multirt_resolvable() deemed it necessary
20619 	 */
20620 	if (copy_mp != NULL)
20621 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20622 	if (need_decref)
20623 		CONN_DEC_REF(connp);
20624 	return;
20625 
20626 qnext:
20627 	/*
20628 	 * Upper Level Protocols pass down complete IP datagrams
20629 	 * as M_DATA messages.	Everything else is a sideshow.
20630 	 *
20631 	 * 1) We could be re-entering ip_wput because of ip_neworute
20632 	 *    in which case we could have a IPSEC_OUT message. We
20633 	 *    need to pass through ip_wput like other datagrams and
20634 	 *    hence cannot branch to ip_wput_nondata.
20635 	 *
20636 	 * 2) ARP, AH, ESP, and other clients who are on the module
20637 	 *    instance of IP stream, give us something to deal with.
20638 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20639 	 *
20640 	 * 3) ICMP replies also could come here.
20641 	 */
20642 	ipst = ILLQ_TO_IPST(q);
20643 
20644 	if (DB_TYPE(mp) != M_DATA) {
20645 notdata:
20646 		if (DB_TYPE(mp) == M_CTL) {
20647 			/*
20648 			 * M_CTL messages are used by ARP, AH and ESP to
20649 			 * communicate with IP. We deal with IPSEC_IN and
20650 			 * IPSEC_OUT here. ip_wput_nondata handles other
20651 			 * cases.
20652 			 */
20653 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20654 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20655 				first_mp = mp->b_cont;
20656 				first_mp->b_flag &= ~MSGHASREF;
20657 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20658 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20659 				CONN_DEC_REF(connp);
20660 				connp = NULL;
20661 			}
20662 			if (ii->ipsec_info_type == IPSEC_IN) {
20663 				/*
20664 				 * Either this message goes back to
20665 				 * IPsec for further processing or to
20666 				 * ULP after policy checks.
20667 				 */
20668 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20669 				return;
20670 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20671 				io = (ipsec_out_t *)ii;
20672 				if (io->ipsec_out_proc_begin) {
20673 					/*
20674 					 * IPsec processing has already started.
20675 					 * Complete it.
20676 					 * IPQoS notes: We don't care what is
20677 					 * in ipsec_out_ill_index since this
20678 					 * won't be processed for IPQoS policies
20679 					 * in ipsec_out_process.
20680 					 */
20681 					ipsec_out_process(q, mp, NULL,
20682 					    io->ipsec_out_ill_index);
20683 					return;
20684 				} else {
20685 					connp = (q->q_next != NULL) ?
20686 					    NULL : Q_TO_CONN(q);
20687 					first_mp = mp;
20688 					mp = mp->b_cont;
20689 					mctl_present = B_TRUE;
20690 				}
20691 				zoneid = io->ipsec_out_zoneid;
20692 				ASSERT(zoneid != ALL_ZONES);
20693 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20694 				/*
20695 				 * It's an IPsec control message requesting
20696 				 * an SADB update to be sent to the IPsec
20697 				 * hardware acceleration capable ills.
20698 				 */
20699 				ipsec_ctl_t *ipsec_ctl =
20700 				    (ipsec_ctl_t *)mp->b_rptr;
20701 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20702 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20703 				mblk_t *cmp = mp->b_cont;
20704 
20705 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20706 				ASSERT(cmp != NULL);
20707 
20708 				freeb(mp);
20709 				ill_ipsec_capab_send_all(satype, cmp, sa,
20710 				    ipst->ips_netstack);
20711 				return;
20712 			} else {
20713 				/*
20714 				 * This must be ARP or special TSOL signaling.
20715 				 */
20716 				ip_wput_nondata(NULL, q, mp, NULL);
20717 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20718 				    "ip_wput_end: q %p (%S)", q, "nondata");
20719 				return;
20720 			}
20721 		} else {
20722 			/*
20723 			 * This must be non-(ARP/AH/ESP) messages.
20724 			 */
20725 			ASSERT(!need_decref);
20726 			ip_wput_nondata(NULL, q, mp, NULL);
20727 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20728 			    "ip_wput_end: q %p (%S)", q, "nondata");
20729 			return;
20730 		}
20731 	} else {
20732 		first_mp = mp;
20733 		mctl_present = B_FALSE;
20734 	}
20735 
20736 	ASSERT(first_mp != NULL);
20737 	/*
20738 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20739 	 * to make sure that this packet goes out on the same interface it
20740 	 * came in. We handle that here.
20741 	 */
20742 	if (mctl_present) {
20743 		uint_t ifindex;
20744 
20745 		io = (ipsec_out_t *)first_mp->b_rptr;
20746 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20747 			/*
20748 			 * We may have lost the conn context if we are
20749 			 * coming here from ip_newroute(). Copy the
20750 			 * nexthop information.
20751 			 */
20752 			if (io->ipsec_out_ip_nexthop) {
20753 				ip_nexthop = B_TRUE;
20754 				nexthop_addr = io->ipsec_out_nexthop_addr;
20755 
20756 				ipha = (ipha_t *)mp->b_rptr;
20757 				dst = ipha->ipha_dst;
20758 				goto send_from_ill;
20759 			} else {
20760 				ASSERT(io->ipsec_out_ill_index != 0);
20761 				ifindex = io->ipsec_out_ill_index;
20762 				attach_ill = ill_lookup_on_ifindex(ifindex,
20763 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20764 				if (attach_ill == NULL) {
20765 					ASSERT(xmit_ill == NULL);
20766 					ip1dbg(("ip_output: bad ifindex for "
20767 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20768 					    ifindex));
20769 					freemsg(first_mp);
20770 					BUMP_MIB(&ipst->ips_ip_mib,
20771 					    ipIfStatsOutDiscards);
20772 					ASSERT(!need_decref);
20773 					return;
20774 				}
20775 			}
20776 		}
20777 	}
20778 
20779 	ASSERT(xmit_ill == NULL);
20780 
20781 	/* We have a complete IP datagram heading outbound. */
20782 	ipha = (ipha_t *)mp->b_rptr;
20783 
20784 #ifndef SPEED_BEFORE_SAFETY
20785 	/*
20786 	 * Make sure we have a full-word aligned message and that at least
20787 	 * a simple IP header is accessible in the first message.  If not,
20788 	 * try a pullup.
20789 	 */
20790 	if (!OK_32PTR(rptr) ||
20791 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20792 hdrtoosmall:
20793 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20794 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20795 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20796 			if (first_mp == NULL)
20797 				first_mp = mp;
20798 			goto discard_pkt;
20799 		}
20800 
20801 		/* This function assumes that mp points to an IPv4 packet. */
20802 		if (is_system_labeled() && q->q_next == NULL &&
20803 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20804 		    !connp->conn_ulp_labeled) {
20805 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20806 			    &adjust, connp->conn_mac_exempt, ipst);
20807 			ipha = (ipha_t *)mp->b_rptr;
20808 			if (first_mp != NULL)
20809 				first_mp->b_cont = mp;
20810 			if (err != 0) {
20811 				if (first_mp == NULL)
20812 					first_mp = mp;
20813 				if (err == EINVAL)
20814 					goto icmp_parameter_problem;
20815 				ip2dbg(("ip_wput: label check failed (%d)\n",
20816 				    err));
20817 				goto discard_pkt;
20818 			}
20819 			iplen = ntohs(ipha->ipha_length) + adjust;
20820 			ipha->ipha_length = htons(iplen);
20821 		}
20822 
20823 		ipha = (ipha_t *)mp->b_rptr;
20824 		if (first_mp == NULL) {
20825 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20826 			/*
20827 			 * If we got here because of "goto hdrtoosmall"
20828 			 * We need to attach a IPSEC_OUT.
20829 			 */
20830 			if (connp->conn_out_enforce_policy) {
20831 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20832 				    NULL, ipha->ipha_protocol,
20833 				    ipst->ips_netstack)) == NULL)) {
20834 					BUMP_MIB(&ipst->ips_ip_mib,
20835 					    ipIfStatsOutDiscards);
20836 					if (need_decref)
20837 						CONN_DEC_REF(connp);
20838 					return;
20839 				} else {
20840 					ASSERT(mp->b_datap->db_type == M_CTL);
20841 					first_mp = mp;
20842 					mp = mp->b_cont;
20843 					mctl_present = B_TRUE;
20844 				}
20845 			} else {
20846 				first_mp = mp;
20847 				mctl_present = B_FALSE;
20848 			}
20849 		}
20850 	}
20851 #endif
20852 
20853 	/* Most of the code below is written for speed, not readability */
20854 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20855 
20856 	/*
20857 	 * If ip_newroute() fails, we're going to need a full
20858 	 * header for the icmp wraparound.
20859 	 */
20860 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20861 		uint_t	v_hlen;
20862 version_hdrlen_check:
20863 		ASSERT(first_mp != NULL);
20864 		v_hlen = V_HLEN;
20865 		/*
20866 		 * siphon off IPv6 packets coming down from transport
20867 		 * layer modules here.
20868 		 * Note: high-order bit carries NUD reachability confirmation
20869 		 */
20870 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20871 			/*
20872 			 * FIXME: assume that callers of ip_output* call
20873 			 * the right version?
20874 			 */
20875 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20876 			ASSERT(xmit_ill == NULL);
20877 			if (attach_ill != NULL)
20878 				ill_refrele(attach_ill);
20879 			if (need_decref)
20880 				mp->b_flag |= MSGHASREF;
20881 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20882 			return;
20883 		}
20884 
20885 		if ((v_hlen >> 4) != IP_VERSION) {
20886 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20887 			    "ip_wput_end: q %p (%S)", q, "badvers");
20888 			goto discard_pkt;
20889 		}
20890 		/*
20891 		 * Is the header length at least 20 bytes?
20892 		 *
20893 		 * Are there enough bytes accessible in the header?  If
20894 		 * not, try a pullup.
20895 		 */
20896 		v_hlen &= 0xF;
20897 		v_hlen <<= 2;
20898 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20899 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20900 			    "ip_wput_end: q %p (%S)", q, "badlen");
20901 			goto discard_pkt;
20902 		}
20903 		if (v_hlen > (mp->b_wptr - rptr)) {
20904 			if (!pullupmsg(mp, v_hlen)) {
20905 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20906 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20907 				goto discard_pkt;
20908 			}
20909 			ipha = (ipha_t *)mp->b_rptr;
20910 		}
20911 		/*
20912 		 * Move first entry from any source route into ipha_dst and
20913 		 * verify the options
20914 		 */
20915 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20916 		    zoneid, ipst)) {
20917 			ASSERT(xmit_ill == NULL);
20918 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20919 			if (attach_ill != NULL)
20920 				ill_refrele(attach_ill);
20921 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20922 			    "ip_wput_end: q %p (%S)", q, "badopts");
20923 			if (need_decref)
20924 				CONN_DEC_REF(connp);
20925 			return;
20926 		}
20927 	}
20928 	dst = ipha->ipha_dst;
20929 
20930 	/*
20931 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20932 	 * we have to run the packet through ip_newroute which will take
20933 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20934 	 * a resolver, or assigning a default gateway, etc.
20935 	 */
20936 	if (CLASSD(dst)) {
20937 		ipif_t	*ipif;
20938 		uint32_t setsrc = 0;
20939 
20940 multicast:
20941 		ASSERT(first_mp != NULL);
20942 		ip2dbg(("ip_wput: CLASSD\n"));
20943 		if (connp == NULL) {
20944 			/*
20945 			 * Use the first good ipif on the ill.
20946 			 * XXX Should this ever happen? (Appears
20947 			 * to show up with just ppp and no ethernet due
20948 			 * to in.rdisc.)
20949 			 * However, ire_send should be able to
20950 			 * call ip_wput_ire directly.
20951 			 *
20952 			 * XXX Also, this can happen for ICMP and other packets
20953 			 * with multicast source addresses.  Perhaps we should
20954 			 * fix things so that we drop the packet in question,
20955 			 * but for now, just run with it.
20956 			 */
20957 			ill_t *ill = (ill_t *)q->q_ptr;
20958 
20959 			/*
20960 			 * Don't honor attach_if for this case. If ill
20961 			 * is part of the group, ipif could belong to
20962 			 * any ill and we cannot maintain attach_ill
20963 			 * and ipif_ill same anymore and the assert
20964 			 * below would fail.
20965 			 */
20966 			if (mctl_present && io->ipsec_out_attach_if) {
20967 				io->ipsec_out_ill_index = 0;
20968 				io->ipsec_out_attach_if = B_FALSE;
20969 				ASSERT(attach_ill != NULL);
20970 				ill_refrele(attach_ill);
20971 				attach_ill = NULL;
20972 			}
20973 
20974 			ASSERT(attach_ill == NULL);
20975 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20976 			if (ipif == NULL) {
20977 				if (need_decref)
20978 					CONN_DEC_REF(connp);
20979 				freemsg(first_mp);
20980 				return;
20981 			}
20982 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20983 			    ntohl(dst), ill->ill_name));
20984 		} else {
20985 			/*
20986 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20987 			 * and IP_MULTICAST_IF.  The block comment above this
20988 			 * function explains the locking mechanism used here.
20989 			 */
20990 			if (xmit_ill == NULL) {
20991 				xmit_ill = conn_get_held_ill(connp,
20992 				    &connp->conn_outgoing_ill, &err);
20993 				if (err == ILL_LOOKUP_FAILED) {
20994 					ip1dbg(("ip_wput: No ill for "
20995 					    "IP_BOUND_IF\n"));
20996 					BUMP_MIB(&ipst->ips_ip_mib,
20997 					    ipIfStatsOutNoRoutes);
20998 					goto drop_pkt;
20999 				}
21000 			}
21001 
21002 			if (xmit_ill == NULL) {
21003 				ipif = conn_get_held_ipif(connp,
21004 				    &connp->conn_multicast_ipif, &err);
21005 				if (err == IPIF_LOOKUP_FAILED) {
21006 					ip1dbg(("ip_wput: No ipif for "
21007 					    "multicast\n"));
21008 					BUMP_MIB(&ipst->ips_ip_mib,
21009 					    ipIfStatsOutNoRoutes);
21010 					goto drop_pkt;
21011 				}
21012 			}
21013 			if (xmit_ill != NULL) {
21014 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
21015 				if (ipif == NULL) {
21016 					ip1dbg(("ip_wput: No ipif for "
21017 					    "xmit_ill\n"));
21018 					BUMP_MIB(&ipst->ips_ip_mib,
21019 					    ipIfStatsOutNoRoutes);
21020 					goto drop_pkt;
21021 				}
21022 			} else if (ipif == NULL || ipif->ipif_isv6) {
21023 				/*
21024 				 * We must do this ipif determination here
21025 				 * else we could pass through ip_newroute
21026 				 * and come back here without the conn context.
21027 				 *
21028 				 * Note: we do late binding i.e. we bind to
21029 				 * the interface when the first packet is sent.
21030 				 * For performance reasons we do not rebind on
21031 				 * each packet but keep the binding until the
21032 				 * next IP_MULTICAST_IF option.
21033 				 *
21034 				 * conn_multicast_{ipif,ill} are shared between
21035 				 * IPv4 and IPv6 and AF_INET6 sockets can
21036 				 * send both IPv4 and IPv6 packets. Hence
21037 				 * we have to check that "isv6" matches above.
21038 				 */
21039 				if (ipif != NULL)
21040 					ipif_refrele(ipif);
21041 				ipif = ipif_lookup_group(dst, zoneid, ipst);
21042 				if (ipif == NULL) {
21043 					ip1dbg(("ip_wput: No ipif for "
21044 					    "multicast\n"));
21045 					BUMP_MIB(&ipst->ips_ip_mib,
21046 					    ipIfStatsOutNoRoutes);
21047 					goto drop_pkt;
21048 				}
21049 				err = conn_set_held_ipif(connp,
21050 				    &connp->conn_multicast_ipif, ipif);
21051 				if (err == IPIF_LOOKUP_FAILED) {
21052 					ipif_refrele(ipif);
21053 					ip1dbg(("ip_wput: No ipif for "
21054 					    "multicast\n"));
21055 					BUMP_MIB(&ipst->ips_ip_mib,
21056 					    ipIfStatsOutNoRoutes);
21057 					goto drop_pkt;
21058 				}
21059 			}
21060 		}
21061 		ASSERT(!ipif->ipif_isv6);
21062 		/*
21063 		 * As we may lose the conn by the time we reach ip_wput_ire,
21064 		 * we copy conn_multicast_loop and conn_dontroute on to an
21065 		 * ipsec_out. In case if this datagram goes out secure,
21066 		 * we need the ill_index also. Copy that also into the
21067 		 * ipsec_out.
21068 		 */
21069 		if (mctl_present) {
21070 			io = (ipsec_out_t *)first_mp->b_rptr;
21071 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21072 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21073 		} else {
21074 			ASSERT(mp == first_mp);
21075 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21076 			    BPRI_HI)) == NULL) {
21077 				ipif_refrele(ipif);
21078 				first_mp = mp;
21079 				goto discard_pkt;
21080 			}
21081 			first_mp->b_datap->db_type = M_CTL;
21082 			first_mp->b_wptr += sizeof (ipsec_info_t);
21083 			/* ipsec_out_secure is B_FALSE now */
21084 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21085 			io = (ipsec_out_t *)first_mp->b_rptr;
21086 			io->ipsec_out_type = IPSEC_OUT;
21087 			io->ipsec_out_len = sizeof (ipsec_out_t);
21088 			io->ipsec_out_use_global_policy = B_TRUE;
21089 			io->ipsec_out_ns = ipst->ips_netstack;
21090 			first_mp->b_cont = mp;
21091 			mctl_present = B_TRUE;
21092 		}
21093 		if (attach_ill != NULL) {
21094 			ASSERT(attach_ill == ipif->ipif_ill);
21095 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21096 
21097 			/*
21098 			 * Check if we need an ire that will not be
21099 			 * looked up by anybody else i.e. HIDDEN.
21100 			 */
21101 			if (ill_is_probeonly(attach_ill)) {
21102 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21103 			}
21104 			io->ipsec_out_ill_index =
21105 			    attach_ill->ill_phyint->phyint_ifindex;
21106 			io->ipsec_out_attach_if = B_TRUE;
21107 		} else {
21108 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21109 			io->ipsec_out_ill_index =
21110 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21111 		}
21112 		if (connp != NULL) {
21113 			io->ipsec_out_multicast_loop =
21114 			    connp->conn_multicast_loop;
21115 			io->ipsec_out_dontroute = connp->conn_dontroute;
21116 			io->ipsec_out_zoneid = connp->conn_zoneid;
21117 		}
21118 		/*
21119 		 * If the application uses IP_MULTICAST_IF with
21120 		 * different logical addresses of the same ILL, we
21121 		 * need to make sure that the soruce address of
21122 		 * the packet matches the logical IP address used
21123 		 * in the option. We do it by initializing ipha_src
21124 		 * here. This should keep IPsec also happy as
21125 		 * when we return from IPsec processing, we don't
21126 		 * have to worry about getting the right address on
21127 		 * the packet. Thus it is sufficient to look for
21128 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21129 		 * MATCH_IRE_IPIF.
21130 		 *
21131 		 * NOTE : We need to do it for non-secure case also as
21132 		 * this might go out secure if there is a global policy
21133 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21134 		 * address, the source should be initialized already and
21135 		 * hence we won't be initializing here.
21136 		 *
21137 		 * As we do not have the ire yet, it is possible that
21138 		 * we set the source address here and then later discover
21139 		 * that the ire implies the source address to be assigned
21140 		 * through the RTF_SETSRC flag.
21141 		 * In that case, the setsrc variable will remind us
21142 		 * that overwritting the source address by the one
21143 		 * of the RTF_SETSRC-flagged ire is allowed.
21144 		 */
21145 		if (ipha->ipha_src == INADDR_ANY &&
21146 		    (connp == NULL || !connp->conn_unspec_src)) {
21147 			ipha->ipha_src = ipif->ipif_src_addr;
21148 			setsrc = RTF_SETSRC;
21149 		}
21150 		/*
21151 		 * Find an IRE which matches the destination and the outgoing
21152 		 * queue (i.e. the outgoing interface.)
21153 		 * For loopback use a unicast IP address for
21154 		 * the ire lookup.
21155 		 */
21156 		if (IS_LOOPBACK(ipif->ipif_ill))
21157 			dst = ipif->ipif_lcl_addr;
21158 
21159 		/*
21160 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21161 		 * We don't need to lookup ire in ctable as the packet
21162 		 * needs to be sent to the destination through the specified
21163 		 * ill irrespective of ires in the cache table.
21164 		 */
21165 		ire = NULL;
21166 		if (xmit_ill == NULL) {
21167 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21168 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21169 		}
21170 
21171 		/*
21172 		 * refrele attach_ill as its not needed anymore.
21173 		 */
21174 		if (attach_ill != NULL) {
21175 			ill_refrele(attach_ill);
21176 			attach_ill = NULL;
21177 		}
21178 
21179 		if (ire == NULL) {
21180 			/*
21181 			 * Multicast loopback and multicast forwarding is
21182 			 * done in ip_wput_ire.
21183 			 *
21184 			 * Mark this packet to make it be delivered to
21185 			 * ip_wput_ire after the new ire has been
21186 			 * created.
21187 			 *
21188 			 * The call to ip_newroute_ipif takes into account
21189 			 * the setsrc reminder. In any case, we take care
21190 			 * of the RTF_MULTIRT flag.
21191 			 */
21192 			mp->b_prev = mp->b_next = NULL;
21193 			if (xmit_ill == NULL ||
21194 			    xmit_ill->ill_ipif_up_count > 0) {
21195 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21196 				    setsrc | RTF_MULTIRT, zoneid, infop);
21197 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21198 				    "ip_wput_end: q %p (%S)", q, "noire");
21199 			} else {
21200 				freemsg(first_mp);
21201 			}
21202 			ipif_refrele(ipif);
21203 			if (xmit_ill != NULL)
21204 				ill_refrele(xmit_ill);
21205 			if (need_decref)
21206 				CONN_DEC_REF(connp);
21207 			return;
21208 		}
21209 
21210 		ipif_refrele(ipif);
21211 		ipif = NULL;
21212 		ASSERT(xmit_ill == NULL);
21213 
21214 		/*
21215 		 * Honor the RTF_SETSRC flag for multicast packets,
21216 		 * if allowed by the setsrc reminder.
21217 		 */
21218 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21219 			ipha->ipha_src = ire->ire_src_addr;
21220 		}
21221 
21222 		/*
21223 		 * Unconditionally force the TTL to 1 for
21224 		 * multirouted multicast packets:
21225 		 * multirouted multicast should not cross
21226 		 * multicast routers.
21227 		 */
21228 		if (ire->ire_flags & RTF_MULTIRT) {
21229 			if (ipha->ipha_ttl > 1) {
21230 				ip2dbg(("ip_wput: forcing multicast "
21231 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21232 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21233 				ipha->ipha_ttl = 1;
21234 			}
21235 		}
21236 	} else {
21237 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21238 		if ((ire != NULL) && (ire->ire_type &
21239 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21240 			ignore_dontroute = B_TRUE;
21241 			ignore_nexthop = B_TRUE;
21242 		}
21243 		if (ire != NULL) {
21244 			ire_refrele(ire);
21245 			ire = NULL;
21246 		}
21247 		/*
21248 		 * Guard against coming in from arp in which case conn is NULL.
21249 		 * Also guard against non M_DATA with dontroute set but
21250 		 * destined to local, loopback or broadcast addresses.
21251 		 */
21252 		if (connp != NULL && connp->conn_dontroute &&
21253 		    !ignore_dontroute) {
21254 dontroute:
21255 			/*
21256 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21257 			 * routing protocols from seeing false direct
21258 			 * connectivity.
21259 			 */
21260 			ipha->ipha_ttl = 1;
21261 
21262 			/* If suitable ipif not found, drop packet */
21263 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21264 			if (dst_ipif == NULL) {
21265 noroute:
21266 				ip1dbg(("ip_wput: no route for dst using"
21267 				    " SO_DONTROUTE\n"));
21268 				BUMP_MIB(&ipst->ips_ip_mib,
21269 				    ipIfStatsOutNoRoutes);
21270 				mp->b_prev = mp->b_next = NULL;
21271 				if (first_mp == NULL)
21272 					first_mp = mp;
21273 				goto drop_pkt;
21274 			} else {
21275 				/*
21276 				 * If suitable ipif has been found, set
21277 				 * xmit_ill to the corresponding
21278 				 * ipif_ill because we'll be using the
21279 				 * send_from_ill logic below.
21280 				 */
21281 				ASSERT(xmit_ill == NULL);
21282 				xmit_ill = dst_ipif->ipif_ill;
21283 				mutex_enter(&xmit_ill->ill_lock);
21284 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21285 					mutex_exit(&xmit_ill->ill_lock);
21286 					xmit_ill = NULL;
21287 					ipif_refrele(dst_ipif);
21288 					goto noroute;
21289 				}
21290 				ill_refhold_locked(xmit_ill);
21291 				mutex_exit(&xmit_ill->ill_lock);
21292 				ipif_refrele(dst_ipif);
21293 			}
21294 		}
21295 		/*
21296 		 * If we are bound to IPIF_NOFAILOVER address, look for
21297 		 * an IRE_CACHE matching the ill.
21298 		 */
21299 send_from_ill:
21300 		if (attach_ill != NULL) {
21301 			ipif_t	*attach_ipif;
21302 
21303 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21304 
21305 			/*
21306 			 * Check if we need an ire that will not be
21307 			 * looked up by anybody else i.e. HIDDEN.
21308 			 */
21309 			if (ill_is_probeonly(attach_ill)) {
21310 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21311 			}
21312 
21313 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21314 			if (attach_ipif == NULL) {
21315 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21316 				goto discard_pkt;
21317 			}
21318 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21319 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21320 			ipif_refrele(attach_ipif);
21321 		} else if (xmit_ill != NULL) {
21322 			ipif_t *ipif;
21323 
21324 			/*
21325 			 * Mark this packet as originated locally
21326 			 */
21327 			mp->b_prev = mp->b_next = NULL;
21328 
21329 			/*
21330 			 * Could be SO_DONTROUTE case also.
21331 			 * Verify that at least one ipif is up on the ill.
21332 			 */
21333 			if (xmit_ill->ill_ipif_up_count == 0) {
21334 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21335 				    xmit_ill->ill_name));
21336 				goto drop_pkt;
21337 			}
21338 
21339 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21340 			if (ipif == NULL) {
21341 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21342 				    xmit_ill->ill_name));
21343 				goto drop_pkt;
21344 			}
21345 
21346 			/*
21347 			 * Look for a ire that is part of the group,
21348 			 * if found use it else call ip_newroute_ipif.
21349 			 * IPCL_ZONEID is not used for matching because
21350 			 * IP_ALLZONES option is valid only when the
21351 			 * ill is accessible from all zones i.e has a
21352 			 * valid ipif in all zones.
21353 			 */
21354 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21355 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21356 			    MBLK_GETLABEL(mp), match_flags, ipst);
21357 			/*
21358 			 * If an ire exists use it or else create
21359 			 * an ire but don't add it to the cache.
21360 			 * Adding an ire may cause issues with
21361 			 * asymmetric routing.
21362 			 * In case of multiroute always act as if
21363 			 * ire does not exist.
21364 			 */
21365 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21366 				if (ire != NULL)
21367 					ire_refrele(ire);
21368 				ip_newroute_ipif(q, first_mp, ipif,
21369 				    dst, connp, 0, zoneid, infop);
21370 				ipif_refrele(ipif);
21371 				ip1dbg(("ip_output: xmit_ill via %s\n",
21372 				    xmit_ill->ill_name));
21373 				ill_refrele(xmit_ill);
21374 				if (need_decref)
21375 					CONN_DEC_REF(connp);
21376 				return;
21377 			}
21378 			ipif_refrele(ipif);
21379 		} else if (ip_nexthop || (connp != NULL &&
21380 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21381 			if (!ip_nexthop) {
21382 				ip_nexthop = B_TRUE;
21383 				nexthop_addr = connp->conn_nexthop_v4;
21384 			}
21385 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21386 			    MATCH_IRE_GW;
21387 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21388 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21389 		} else {
21390 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21391 			    ipst);
21392 		}
21393 		if (!ire) {
21394 			/*
21395 			 * Make sure we don't load spread if this
21396 			 * is IPIF_NOFAILOVER case.
21397 			 */
21398 			if ((attach_ill != NULL) ||
21399 			    (ip_nexthop && !ignore_nexthop)) {
21400 				if (mctl_present) {
21401 					io = (ipsec_out_t *)first_mp->b_rptr;
21402 					ASSERT(first_mp->b_datap->db_type ==
21403 					    M_CTL);
21404 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21405 				} else {
21406 					ASSERT(mp == first_mp);
21407 					first_mp = allocb(
21408 					    sizeof (ipsec_info_t), BPRI_HI);
21409 					if (first_mp == NULL) {
21410 						first_mp = mp;
21411 						goto discard_pkt;
21412 					}
21413 					first_mp->b_datap->db_type = M_CTL;
21414 					first_mp->b_wptr +=
21415 					    sizeof (ipsec_info_t);
21416 					/* ipsec_out_secure is B_FALSE now */
21417 					bzero(first_mp->b_rptr,
21418 					    sizeof (ipsec_info_t));
21419 					io = (ipsec_out_t *)first_mp->b_rptr;
21420 					io->ipsec_out_type = IPSEC_OUT;
21421 					io->ipsec_out_len =
21422 					    sizeof (ipsec_out_t);
21423 					io->ipsec_out_use_global_policy =
21424 					    B_TRUE;
21425 					io->ipsec_out_ns = ipst->ips_netstack;
21426 					first_mp->b_cont = mp;
21427 					mctl_present = B_TRUE;
21428 				}
21429 				if (attach_ill != NULL) {
21430 					io->ipsec_out_ill_index = attach_ill->
21431 					    ill_phyint->phyint_ifindex;
21432 					io->ipsec_out_attach_if = B_TRUE;
21433 				} else {
21434 					io->ipsec_out_ip_nexthop = ip_nexthop;
21435 					io->ipsec_out_nexthop_addr =
21436 					    nexthop_addr;
21437 				}
21438 			}
21439 noirefound:
21440 			/*
21441 			 * Mark this packet as having originated on
21442 			 * this machine.  This will be noted in
21443 			 * ire_add_then_send, which needs to know
21444 			 * whether to run it back through ip_wput or
21445 			 * ip_rput following successful resolution.
21446 			 */
21447 			mp->b_prev = NULL;
21448 			mp->b_next = NULL;
21449 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21450 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21451 			    "ip_wput_end: q %p (%S)", q, "newroute");
21452 			if (attach_ill != NULL)
21453 				ill_refrele(attach_ill);
21454 			if (xmit_ill != NULL)
21455 				ill_refrele(xmit_ill);
21456 			if (need_decref)
21457 				CONN_DEC_REF(connp);
21458 			return;
21459 		}
21460 	}
21461 
21462 	/* We now know where we are going with it. */
21463 
21464 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21465 	    "ip_wput_end: q %p (%S)", q, "end");
21466 
21467 	/*
21468 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21469 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21470 	 */
21471 	if (ire->ire_flags & RTF_MULTIRT) {
21472 		/*
21473 		 * Force the TTL of multirouted packets if required.
21474 		 * The TTL of such packets is bounded by the
21475 		 * ip_multirt_ttl ndd variable.
21476 		 */
21477 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21478 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21479 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21480 			    "(was %d), dst 0x%08x\n",
21481 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21482 			    ntohl(ire->ire_addr)));
21483 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21484 		}
21485 		/*
21486 		 * At this point, we check to see if there are any pending
21487 		 * unresolved routes. ire_multirt_resolvable()
21488 		 * checks in O(n) that all IRE_OFFSUBNET ire
21489 		 * entries for the packet's destination and
21490 		 * flagged RTF_MULTIRT are currently resolved.
21491 		 * If some remain unresolved, we make a copy
21492 		 * of the current message. It will be used
21493 		 * to initiate additional route resolutions.
21494 		 */
21495 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21496 		    MBLK_GETLABEL(first_mp), ipst);
21497 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21498 		    "multirt_need_resolve %d, first_mp %p\n",
21499 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21500 		if (multirt_need_resolve) {
21501 			copy_mp = copymsg(first_mp);
21502 			if (copy_mp != NULL) {
21503 				MULTIRT_DEBUG_TAG(copy_mp);
21504 			}
21505 		}
21506 	}
21507 
21508 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21509 	/*
21510 	 * Try to resolve another multiroute if
21511 	 * ire_multirt_resolvable() deemed it necessary.
21512 	 * At this point, we need to distinguish
21513 	 * multicasts from other packets. For multicasts,
21514 	 * we call ip_newroute_ipif() and request that both
21515 	 * multirouting and setsrc flags are checked.
21516 	 */
21517 	if (copy_mp != NULL) {
21518 		if (CLASSD(dst)) {
21519 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21520 			if (ipif) {
21521 				ASSERT(infop->ip_opt_ill_index == 0);
21522 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21523 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21524 				ipif_refrele(ipif);
21525 			} else {
21526 				MULTIRT_DEBUG_UNTAG(copy_mp);
21527 				freemsg(copy_mp);
21528 				copy_mp = NULL;
21529 			}
21530 		} else {
21531 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21532 		}
21533 	}
21534 	if (attach_ill != NULL)
21535 		ill_refrele(attach_ill);
21536 	if (xmit_ill != NULL)
21537 		ill_refrele(xmit_ill);
21538 	if (need_decref)
21539 		CONN_DEC_REF(connp);
21540 	return;
21541 
21542 icmp_parameter_problem:
21543 	/* could not have originated externally */
21544 	ASSERT(mp->b_prev == NULL);
21545 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21546 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21547 		/* it's the IP header length that's in trouble */
21548 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21549 		first_mp = NULL;
21550 	}
21551 
21552 discard_pkt:
21553 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21554 drop_pkt:
21555 	ip1dbg(("ip_wput: dropped packet\n"));
21556 	if (ire != NULL)
21557 		ire_refrele(ire);
21558 	if (need_decref)
21559 		CONN_DEC_REF(connp);
21560 	freemsg(first_mp);
21561 	if (attach_ill != NULL)
21562 		ill_refrele(attach_ill);
21563 	if (xmit_ill != NULL)
21564 		ill_refrele(xmit_ill);
21565 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21566 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21567 }
21568 
21569 /*
21570  * If this is a conn_t queue, then we pass in the conn. This includes the
21571  * zoneid.
21572  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21573  * in which case we use the global zoneid since those are all part of
21574  * the global zone.
21575  */
21576 void
21577 ip_wput(queue_t *q, mblk_t *mp)
21578 {
21579 	if (CONN_Q(q))
21580 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21581 	else
21582 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21583 }
21584 
21585 /*
21586  *
21587  * The following rules must be observed when accessing any ipif or ill
21588  * that has been cached in the conn. Typically conn_nofailover_ill,
21589  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21590  *
21591  * Access: The ipif or ill pointed to from the conn can be accessed under
21592  * the protection of the conn_lock or after it has been refheld under the
21593  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21594  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21595  * The reason for this is that a concurrent unplumb could actually be
21596  * cleaning up these cached pointers by walking the conns and might have
21597  * finished cleaning up the conn in question. The macros check that an
21598  * unplumb has not yet started on the ipif or ill.
21599  *
21600  * Caching: An ipif or ill pointer may be cached in the conn only after
21601  * making sure that an unplumb has not started. So the caching is done
21602  * while holding both the conn_lock and the ill_lock and after using the
21603  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21604  * flag before starting the cleanup of conns.
21605  *
21606  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21607  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21608  * or a reference to the ipif or a reference to an ire that references the
21609  * ipif. An ipif does not change its ill except for failover/failback. Since
21610  * failover/failback happens only after bringing down the ipif and making sure
21611  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21612  * the above holds.
21613  */
21614 ipif_t *
21615 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21616 {
21617 	ipif_t	*ipif;
21618 	ill_t	*ill;
21619 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21620 
21621 	*err = 0;
21622 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21623 	mutex_enter(&connp->conn_lock);
21624 	ipif = *ipifp;
21625 	if (ipif != NULL) {
21626 		ill = ipif->ipif_ill;
21627 		mutex_enter(&ill->ill_lock);
21628 		if (IPIF_CAN_LOOKUP(ipif)) {
21629 			ipif_refhold_locked(ipif);
21630 			mutex_exit(&ill->ill_lock);
21631 			mutex_exit(&connp->conn_lock);
21632 			rw_exit(&ipst->ips_ill_g_lock);
21633 			return (ipif);
21634 		} else {
21635 			*err = IPIF_LOOKUP_FAILED;
21636 		}
21637 		mutex_exit(&ill->ill_lock);
21638 	}
21639 	mutex_exit(&connp->conn_lock);
21640 	rw_exit(&ipst->ips_ill_g_lock);
21641 	return (NULL);
21642 }
21643 
21644 ill_t *
21645 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21646 {
21647 	ill_t	*ill;
21648 
21649 	*err = 0;
21650 	mutex_enter(&connp->conn_lock);
21651 	ill = *illp;
21652 	if (ill != NULL) {
21653 		mutex_enter(&ill->ill_lock);
21654 		if (ILL_CAN_LOOKUP(ill)) {
21655 			ill_refhold_locked(ill);
21656 			mutex_exit(&ill->ill_lock);
21657 			mutex_exit(&connp->conn_lock);
21658 			return (ill);
21659 		} else {
21660 			*err = ILL_LOOKUP_FAILED;
21661 		}
21662 		mutex_exit(&ill->ill_lock);
21663 	}
21664 	mutex_exit(&connp->conn_lock);
21665 	return (NULL);
21666 }
21667 
21668 static int
21669 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21670 {
21671 	ill_t	*ill;
21672 
21673 	ill = ipif->ipif_ill;
21674 	mutex_enter(&connp->conn_lock);
21675 	mutex_enter(&ill->ill_lock);
21676 	if (IPIF_CAN_LOOKUP(ipif)) {
21677 		*ipifp = ipif;
21678 		mutex_exit(&ill->ill_lock);
21679 		mutex_exit(&connp->conn_lock);
21680 		return (0);
21681 	}
21682 	mutex_exit(&ill->ill_lock);
21683 	mutex_exit(&connp->conn_lock);
21684 	return (IPIF_LOOKUP_FAILED);
21685 }
21686 
21687 /*
21688  * This is called if the outbound datagram needs fragmentation.
21689  *
21690  * NOTE : This function does not ire_refrele the ire argument passed in.
21691  */
21692 static void
21693 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21694     ip_stack_t *ipst)
21695 {
21696 	ipha_t		*ipha;
21697 	mblk_t		*mp;
21698 	uint32_t	v_hlen_tos_len;
21699 	uint32_t	max_frag;
21700 	uint32_t	frag_flag;
21701 	boolean_t	dont_use;
21702 
21703 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21704 		mp = ipsec_mp->b_cont;
21705 	} else {
21706 		mp = ipsec_mp;
21707 	}
21708 
21709 	ipha = (ipha_t *)mp->b_rptr;
21710 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21711 
21712 #ifdef	_BIG_ENDIAN
21713 #define	V_HLEN	(v_hlen_tos_len >> 24)
21714 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21715 #else
21716 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21717 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21718 #endif
21719 
21720 #ifndef SPEED_BEFORE_SAFETY
21721 	/*
21722 	 * Check that ipha_length is consistent with
21723 	 * the mblk length
21724 	 */
21725 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21726 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21727 		    LENGTH, msgdsize(mp)));
21728 		freemsg(ipsec_mp);
21729 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21730 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21731 		    "packet length mismatch");
21732 		return;
21733 	}
21734 #endif
21735 	/*
21736 	 * Don't use frag_flag if pre-built packet or source
21737 	 * routed or if multicast (since multicast packets do not solicit
21738 	 * ICMP "packet too big" messages). Get the values of
21739 	 * max_frag and frag_flag atomically by acquiring the
21740 	 * ire_lock.
21741 	 */
21742 	mutex_enter(&ire->ire_lock);
21743 	max_frag = ire->ire_max_frag;
21744 	frag_flag = ire->ire_frag_flag;
21745 	mutex_exit(&ire->ire_lock);
21746 
21747 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21748 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21749 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21750 
21751 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21752 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21753 }
21754 
21755 /*
21756  * Used for deciding the MSS size for the upper layer. Thus
21757  * we need to check the outbound policy values in the conn.
21758  */
21759 int
21760 conn_ipsec_length(conn_t *connp)
21761 {
21762 	ipsec_latch_t *ipl;
21763 
21764 	ipl = connp->conn_latch;
21765 	if (ipl == NULL)
21766 		return (0);
21767 
21768 	if (ipl->ipl_out_policy == NULL)
21769 		return (0);
21770 
21771 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21772 }
21773 
21774 /*
21775  * Returns an estimate of the IPsec headers size. This is used if
21776  * we don't want to call into IPsec to get the exact size.
21777  */
21778 int
21779 ipsec_out_extra_length(mblk_t *ipsec_mp)
21780 {
21781 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21782 	ipsec_action_t *a;
21783 
21784 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21785 	if (!io->ipsec_out_secure)
21786 		return (0);
21787 
21788 	a = io->ipsec_out_act;
21789 
21790 	if (a == NULL) {
21791 		ASSERT(io->ipsec_out_policy != NULL);
21792 		a = io->ipsec_out_policy->ipsp_act;
21793 	}
21794 	ASSERT(a != NULL);
21795 
21796 	return (a->ipa_ovhd);
21797 }
21798 
21799 /*
21800  * Returns an estimate of the IPsec headers size. This is used if
21801  * we don't want to call into IPsec to get the exact size.
21802  */
21803 int
21804 ipsec_in_extra_length(mblk_t *ipsec_mp)
21805 {
21806 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21807 	ipsec_action_t *a;
21808 
21809 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21810 
21811 	a = ii->ipsec_in_action;
21812 	return (a == NULL ? 0 : a->ipa_ovhd);
21813 }
21814 
21815 /*
21816  * If there are any source route options, return the true final
21817  * destination. Otherwise, return the destination.
21818  */
21819 ipaddr_t
21820 ip_get_dst(ipha_t *ipha)
21821 {
21822 	ipoptp_t	opts;
21823 	uchar_t		*opt;
21824 	uint8_t		optval;
21825 	uint8_t		optlen;
21826 	ipaddr_t	dst;
21827 	uint32_t off;
21828 
21829 	dst = ipha->ipha_dst;
21830 
21831 	if (IS_SIMPLE_IPH(ipha))
21832 		return (dst);
21833 
21834 	for (optval = ipoptp_first(&opts, ipha);
21835 	    optval != IPOPT_EOL;
21836 	    optval = ipoptp_next(&opts)) {
21837 		opt = opts.ipoptp_cur;
21838 		optlen = opts.ipoptp_len;
21839 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21840 		switch (optval) {
21841 		case IPOPT_SSRR:
21842 		case IPOPT_LSRR:
21843 			off = opt[IPOPT_OFFSET];
21844 			/*
21845 			 * If one of the conditions is true, it means
21846 			 * end of options and dst already has the right
21847 			 * value.
21848 			 */
21849 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21850 				off = optlen - IP_ADDR_LEN;
21851 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21852 			}
21853 			return (dst);
21854 		default:
21855 			break;
21856 		}
21857 	}
21858 
21859 	return (dst);
21860 }
21861 
21862 mblk_t *
21863 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21864     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21865 {
21866 	ipsec_out_t	*io;
21867 	mblk_t		*first_mp;
21868 	boolean_t policy_present;
21869 	ip_stack_t	*ipst;
21870 	ipsec_stack_t	*ipss;
21871 
21872 	ASSERT(ire != NULL);
21873 	ipst = ire->ire_ipst;
21874 	ipss = ipst->ips_netstack->netstack_ipsec;
21875 
21876 	first_mp = mp;
21877 	if (mp->b_datap->db_type == M_CTL) {
21878 		io = (ipsec_out_t *)first_mp->b_rptr;
21879 		/*
21880 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21881 		 *
21882 		 * 1) There is per-socket policy (including cached global
21883 		 *    policy) or a policy on the IP-in-IP tunnel.
21884 		 * 2) There is no per-socket policy, but it is
21885 		 *    a multicast packet that needs to go out
21886 		 *    on a specific interface. This is the case
21887 		 *    where (ip_wput and ip_wput_multicast) attaches
21888 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21889 		 *
21890 		 * In case (2) we check with global policy to
21891 		 * see if there is a match and set the ill_index
21892 		 * appropriately so that we can lookup the ire
21893 		 * properly in ip_wput_ipsec_out.
21894 		 */
21895 
21896 		/*
21897 		 * ipsec_out_use_global_policy is set to B_FALSE
21898 		 * in ipsec_in_to_out(). Refer to that function for
21899 		 * details.
21900 		 */
21901 		if ((io->ipsec_out_latch == NULL) &&
21902 		    (io->ipsec_out_use_global_policy)) {
21903 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21904 			    ire, connp, unspec_src, zoneid));
21905 		}
21906 		if (!io->ipsec_out_secure) {
21907 			/*
21908 			 * If this is not a secure packet, drop
21909 			 * the IPSEC_OUT mp and treat it as a clear
21910 			 * packet. This happens when we are sending
21911 			 * a ICMP reply back to a clear packet. See
21912 			 * ipsec_in_to_out() for details.
21913 			 */
21914 			mp = first_mp->b_cont;
21915 			freeb(first_mp);
21916 		}
21917 		return (mp);
21918 	}
21919 	/*
21920 	 * See whether we need to attach a global policy here. We
21921 	 * don't depend on the conn (as it could be null) for deciding
21922 	 * what policy this datagram should go through because it
21923 	 * should have happened in ip_wput if there was some
21924 	 * policy. This normally happens for connections which are not
21925 	 * fully bound preventing us from caching policies in
21926 	 * ip_bind. Packets coming from the TCP listener/global queue
21927 	 * - which are non-hard_bound - could also be affected by
21928 	 * applying policy here.
21929 	 *
21930 	 * If this packet is coming from tcp global queue or listener,
21931 	 * we will be applying policy here.  This may not be *right*
21932 	 * if these packets are coming from the detached connection as
21933 	 * it could have gone in clear before. This happens only if a
21934 	 * TCP connection started when there is no policy and somebody
21935 	 * added policy before it became detached. Thus packets of the
21936 	 * detached connection could go out secure and the other end
21937 	 * would drop it because it will be expecting in clear. The
21938 	 * converse is not true i.e if somebody starts a TCP
21939 	 * connection and deletes the policy, all the packets will
21940 	 * still go out with the policy that existed before deleting
21941 	 * because ip_unbind sends up policy information which is used
21942 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21943 	 * TCP to attach a dummy IPSEC_OUT and set
21944 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21945 	 * affect performance for normal cases, we are not doing it.
21946 	 * Thus, set policy before starting any TCP connections.
21947 	 *
21948 	 * NOTE - We might apply policy even for a hard bound connection
21949 	 * - for which we cached policy in ip_bind - if somebody added
21950 	 * global policy after we inherited the policy in ip_bind.
21951 	 * This means that the packets that were going out in clear
21952 	 * previously would start going secure and hence get dropped
21953 	 * on the other side. To fix this, TCP attaches a dummy
21954 	 * ipsec_out and make sure that we don't apply global policy.
21955 	 */
21956 	if (ipha != NULL)
21957 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21958 	else
21959 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21960 	if (!policy_present)
21961 		return (mp);
21962 
21963 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21964 	    zoneid));
21965 }
21966 
21967 ire_t *
21968 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21969 {
21970 	ipaddr_t addr;
21971 	ire_t *save_ire;
21972 	irb_t *irb;
21973 	ill_group_t *illgrp;
21974 	int	err;
21975 
21976 	save_ire = ire;
21977 	addr = ire->ire_addr;
21978 
21979 	ASSERT(ire->ire_type == IRE_BROADCAST);
21980 
21981 	illgrp = connp->conn_outgoing_ill->ill_group;
21982 	if (illgrp == NULL) {
21983 		*conn_outgoing_ill = conn_get_held_ill(connp,
21984 		    &connp->conn_outgoing_ill, &err);
21985 		if (err == ILL_LOOKUP_FAILED) {
21986 			ire_refrele(save_ire);
21987 			return (NULL);
21988 		}
21989 		return (save_ire);
21990 	}
21991 	/*
21992 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21993 	 * If it is part of the group, we need to send on the ire
21994 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21995 	 * to this group. This is okay as IP_BOUND_IF really means
21996 	 * any ill in the group. We depend on the fact that the
21997 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21998 	 * if such an ire exists. This is possible only if you have
21999 	 * at least one ill in the group that has not failed.
22000 	 *
22001 	 * First get to the ire that matches the address and group.
22002 	 *
22003 	 * We don't look for an ire with a matching zoneid because a given zone
22004 	 * won't always have broadcast ires on all ills in the group.
22005 	 */
22006 	irb = ire->ire_bucket;
22007 	rw_enter(&irb->irb_lock, RW_READER);
22008 	if (ire->ire_marks & IRE_MARK_NORECV) {
22009 		/*
22010 		 * If the current zone only has an ire broadcast for this
22011 		 * address marked NORECV, the ire we want is ahead in the
22012 		 * bucket, so we look it up deliberately ignoring the zoneid.
22013 		 */
22014 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
22015 			if (ire->ire_addr != addr)
22016 				continue;
22017 			/* skip over deleted ires */
22018 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
22019 				continue;
22020 		}
22021 	}
22022 	while (ire != NULL) {
22023 		/*
22024 		 * If a new interface is coming up, we could end up
22025 		 * seeing the loopback ire and the non-loopback ire
22026 		 * may not have been added yet. So check for ire_stq
22027 		 */
22028 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
22029 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
22030 			break;
22031 		}
22032 		ire = ire->ire_next;
22033 	}
22034 	if (ire != NULL && ire->ire_addr == addr &&
22035 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
22036 		IRE_REFHOLD(ire);
22037 		rw_exit(&irb->irb_lock);
22038 		ire_refrele(save_ire);
22039 		*conn_outgoing_ill = ire_to_ill(ire);
22040 		/*
22041 		 * Refhold the ill to make the conn_outgoing_ill
22042 		 * independent of the ire. ip_wput_ire goes in a loop
22043 		 * and may refrele the ire. Since we have an ire at this
22044 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
22045 		 */
22046 		ill_refhold(*conn_outgoing_ill);
22047 		return (ire);
22048 	}
22049 	rw_exit(&irb->irb_lock);
22050 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
22051 	/*
22052 	 * If we can't find a suitable ire, return the original ire.
22053 	 */
22054 	return (save_ire);
22055 }
22056 
22057 /*
22058  * This function does the ire_refrele of the ire passed in as the
22059  * argument. As this function looks up more ires i.e broadcast ires,
22060  * it needs to REFRELE them. Currently, for simplicity we don't
22061  * differentiate the one passed in and looked up here. We always
22062  * REFRELE.
22063  * IPQoS Notes:
22064  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22065  * IPsec packets are done in ipsec_out_process.
22066  *
22067  */
22068 void
22069 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22070     zoneid_t zoneid)
22071 {
22072 	ipha_t		*ipha;
22073 #define	rptr	((uchar_t *)ipha)
22074 	queue_t		*stq;
22075 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22076 	uint32_t	v_hlen_tos_len;
22077 	uint32_t	ttl_protocol;
22078 	ipaddr_t	src;
22079 	ipaddr_t	dst;
22080 	uint32_t	cksum;
22081 	ipaddr_t	orig_src;
22082 	ire_t		*ire1;
22083 	mblk_t		*next_mp;
22084 	uint_t		hlen;
22085 	uint16_t	*up;
22086 	uint32_t	max_frag = ire->ire_max_frag;
22087 	ill_t		*ill = ire_to_ill(ire);
22088 	int		clusterwide;
22089 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22090 	int		ipsec_len;
22091 	mblk_t		*first_mp;
22092 	ipsec_out_t	*io;
22093 	boolean_t	conn_dontroute;		/* conn value for multicast */
22094 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22095 	boolean_t	multicast_forward;	/* Should we forward ? */
22096 	boolean_t	unspec_src;
22097 	ill_t		*conn_outgoing_ill = NULL;
22098 	ill_t		*ire_ill;
22099 	ill_t		*ire1_ill;
22100 	ill_t		*out_ill;
22101 	uint32_t 	ill_index = 0;
22102 	boolean_t	multirt_send = B_FALSE;
22103 	int		err;
22104 	ipxmit_state_t	pktxmit_state;
22105 	ip_stack_t	*ipst = ire->ire_ipst;
22106 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22107 
22108 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22109 	    "ip_wput_ire_start: q %p", q);
22110 
22111 	multicast_forward = B_FALSE;
22112 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22113 
22114 	if (ire->ire_flags & RTF_MULTIRT) {
22115 		/*
22116 		 * Multirouting case. The bucket where ire is stored
22117 		 * probably holds other RTF_MULTIRT flagged ire
22118 		 * to the destination. In this call to ip_wput_ire,
22119 		 * we attempt to send the packet through all
22120 		 * those ires. Thus, we first ensure that ire is the
22121 		 * first RTF_MULTIRT ire in the bucket,
22122 		 * before walking the ire list.
22123 		 */
22124 		ire_t *first_ire;
22125 		irb_t *irb = ire->ire_bucket;
22126 		ASSERT(irb != NULL);
22127 
22128 		/* Make sure we do not omit any multiroute ire. */
22129 		IRB_REFHOLD(irb);
22130 		for (first_ire = irb->irb_ire;
22131 		    first_ire != NULL;
22132 		    first_ire = first_ire->ire_next) {
22133 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22134 			    (first_ire->ire_addr == ire->ire_addr) &&
22135 			    !(first_ire->ire_marks &
22136 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22137 				break;
22138 			}
22139 		}
22140 
22141 		if ((first_ire != NULL) && (first_ire != ire)) {
22142 			IRE_REFHOLD(first_ire);
22143 			ire_refrele(ire);
22144 			ire = first_ire;
22145 			ill = ire_to_ill(ire);
22146 		}
22147 		IRB_REFRELE(irb);
22148 	}
22149 
22150 	/*
22151 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22152 	 * for performance we don't grab the mutexs in the fastpath
22153 	 */
22154 	if ((connp != NULL) &&
22155 	    (ire->ire_type == IRE_BROADCAST) &&
22156 	    ((connp->conn_nofailover_ill != NULL) ||
22157 	    (connp->conn_outgoing_ill != NULL))) {
22158 		/*
22159 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22160 		 * option. So, see if this endpoint is bound to a
22161 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22162 		 * that if the interface is failed, we will still send
22163 		 * the packet on the same ill which is what we want.
22164 		 */
22165 		conn_outgoing_ill = conn_get_held_ill(connp,
22166 		    &connp->conn_nofailover_ill, &err);
22167 		if (err == ILL_LOOKUP_FAILED) {
22168 			ire_refrele(ire);
22169 			freemsg(mp);
22170 			return;
22171 		}
22172 		if (conn_outgoing_ill == NULL) {
22173 			/*
22174 			 * Choose a good ill in the group to send the
22175 			 * packets on.
22176 			 */
22177 			ire = conn_set_outgoing_ill(connp, ire,
22178 			    &conn_outgoing_ill);
22179 			if (ire == NULL) {
22180 				freemsg(mp);
22181 				return;
22182 			}
22183 		}
22184 	}
22185 
22186 	if (mp->b_datap->db_type != M_CTL) {
22187 		ipha = (ipha_t *)mp->b_rptr;
22188 	} else {
22189 		io = (ipsec_out_t *)mp->b_rptr;
22190 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22191 		ASSERT(zoneid == io->ipsec_out_zoneid);
22192 		ASSERT(zoneid != ALL_ZONES);
22193 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22194 		dst = ipha->ipha_dst;
22195 		/*
22196 		 * For the multicast case, ipsec_out carries conn_dontroute and
22197 		 * conn_multicast_loop as conn may not be available here. We
22198 		 * need this for multicast loopback and forwarding which is done
22199 		 * later in the code.
22200 		 */
22201 		if (CLASSD(dst)) {
22202 			conn_dontroute = io->ipsec_out_dontroute;
22203 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22204 			/*
22205 			 * If conn_dontroute is not set or conn_multicast_loop
22206 			 * is set, we need to do forwarding/loopback. For
22207 			 * datagrams from ip_wput_multicast, conn_dontroute is
22208 			 * set to B_TRUE and conn_multicast_loop is set to
22209 			 * B_FALSE so that we neither do forwarding nor
22210 			 * loopback.
22211 			 */
22212 			if (!conn_dontroute || conn_multicast_loop)
22213 				multicast_forward = B_TRUE;
22214 		}
22215 	}
22216 
22217 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22218 	    ire->ire_zoneid != ALL_ZONES) {
22219 		/*
22220 		 * When a zone sends a packet to another zone, we try to deliver
22221 		 * the packet under the same conditions as if the destination
22222 		 * was a real node on the network. To do so, we look for a
22223 		 * matching route in the forwarding table.
22224 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22225 		 * ip_newroute() does.
22226 		 * Note that IRE_LOCAL are special, since they are used
22227 		 * when the zoneid doesn't match in some cases. This means that
22228 		 * we need to handle ipha_src differently since ire_src_addr
22229 		 * belongs to the receiving zone instead of the sending zone.
22230 		 * When ip_restrict_interzone_loopback is set, then
22231 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22232 		 * for loopback between zones when the logical "Ethernet" would
22233 		 * have looped them back.
22234 		 */
22235 		ire_t *src_ire;
22236 
22237 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22238 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22239 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22240 		if (src_ire != NULL &&
22241 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22242 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22243 		    ire_local_same_ill_group(ire, src_ire))) {
22244 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22245 				ipha->ipha_src = src_ire->ire_src_addr;
22246 			ire_refrele(src_ire);
22247 		} else {
22248 			ire_refrele(ire);
22249 			if (conn_outgoing_ill != NULL)
22250 				ill_refrele(conn_outgoing_ill);
22251 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22252 			if (src_ire != NULL) {
22253 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22254 					ire_refrele(src_ire);
22255 					freemsg(mp);
22256 					return;
22257 				}
22258 				ire_refrele(src_ire);
22259 			}
22260 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22261 				/* Failed */
22262 				freemsg(mp);
22263 				return;
22264 			}
22265 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22266 			    ipst);
22267 			return;
22268 		}
22269 	}
22270 
22271 	if (mp->b_datap->db_type == M_CTL ||
22272 	    ipss->ipsec_outbound_v4_policy_present) {
22273 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22274 		    unspec_src, zoneid);
22275 		if (mp == NULL) {
22276 			ire_refrele(ire);
22277 			if (conn_outgoing_ill != NULL)
22278 				ill_refrele(conn_outgoing_ill);
22279 			return;
22280 		}
22281 	}
22282 
22283 	first_mp = mp;
22284 	ipsec_len = 0;
22285 
22286 	if (first_mp->b_datap->db_type == M_CTL) {
22287 		io = (ipsec_out_t *)first_mp->b_rptr;
22288 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22289 		mp = first_mp->b_cont;
22290 		ipsec_len = ipsec_out_extra_length(first_mp);
22291 		ASSERT(ipsec_len >= 0);
22292 		/* We already picked up the zoneid from the M_CTL above */
22293 		ASSERT(zoneid == io->ipsec_out_zoneid);
22294 		ASSERT(zoneid != ALL_ZONES);
22295 
22296 		/*
22297 		 * Drop M_CTL here if IPsec processing is not needed.
22298 		 * (Non-IPsec use of M_CTL extracted any information it
22299 		 * needed above).
22300 		 */
22301 		if (ipsec_len == 0) {
22302 			freeb(first_mp);
22303 			first_mp = mp;
22304 		}
22305 	}
22306 
22307 	/*
22308 	 * Fast path for ip_wput_ire
22309 	 */
22310 
22311 	ipha = (ipha_t *)mp->b_rptr;
22312 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22313 	dst = ipha->ipha_dst;
22314 
22315 	/*
22316 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22317 	 * if the socket is a SOCK_RAW type. The transport checksum should
22318 	 * be provided in the pre-built packet, so we don't need to compute it.
22319 	 * Also, other application set flags, like DF, should not be altered.
22320 	 * Other transport MUST pass down zero.
22321 	 */
22322 	ip_hdr_included = ipha->ipha_ident;
22323 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22324 
22325 	if (CLASSD(dst)) {
22326 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22327 		    ntohl(dst),
22328 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22329 		    ntohl(ire->ire_addr)));
22330 	}
22331 
22332 /* Macros to extract header fields from data already in registers */
22333 #ifdef	_BIG_ENDIAN
22334 #define	V_HLEN	(v_hlen_tos_len >> 24)
22335 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22336 #define	PROTO	(ttl_protocol & 0xFF)
22337 #else
22338 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22339 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22340 #define	PROTO	(ttl_protocol >> 8)
22341 #endif
22342 
22343 
22344 	orig_src = src = ipha->ipha_src;
22345 	/* (The loop back to "another" is explained down below.) */
22346 another:;
22347 	/*
22348 	 * Assign an ident value for this packet.  We assign idents on
22349 	 * a per destination basis out of the IRE.  There could be
22350 	 * other threads targeting the same destination, so we have to
22351 	 * arrange for a atomic increment.  Note that we use a 32-bit
22352 	 * atomic add because it has better performance than its
22353 	 * 16-bit sibling.
22354 	 *
22355 	 * If running in cluster mode and if the source address
22356 	 * belongs to a replicated service then vector through
22357 	 * cl_inet_ipident vector to allocate ip identifier
22358 	 * NOTE: This is a contract private interface with the
22359 	 * clustering group.
22360 	 */
22361 	clusterwide = 0;
22362 	if (cl_inet_ipident) {
22363 		ASSERT(cl_inet_isclusterwide);
22364 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22365 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22366 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22367 			    AF_INET, (uint8_t *)(uintptr_t)src,
22368 			    (uint8_t *)(uintptr_t)dst);
22369 			clusterwide = 1;
22370 		}
22371 	}
22372 	if (!clusterwide) {
22373 		ipha->ipha_ident =
22374 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22375 	}
22376 
22377 #ifndef _BIG_ENDIAN
22378 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22379 #endif
22380 
22381 	/*
22382 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22383 	 * This is needed to obey conn_unspec_src when packets go through
22384 	 * ip_newroute + arp.
22385 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22386 	 */
22387 	if (src == INADDR_ANY && !unspec_src) {
22388 		/*
22389 		 * Assign the appropriate source address from the IRE if none
22390 		 * was specified.
22391 		 */
22392 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22393 
22394 		/*
22395 		 * With IP multipathing, broadcast packets are sent on the ire
22396 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22397 		 * the group. However, this ire might not be in the same zone so
22398 		 * we can't always use its source address. We look for a
22399 		 * broadcast ire in the same group and in the right zone.
22400 		 */
22401 		if (ire->ire_type == IRE_BROADCAST &&
22402 		    ire->ire_zoneid != zoneid) {
22403 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22404 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22405 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22406 			if (src_ire != NULL) {
22407 				src = src_ire->ire_src_addr;
22408 				ire_refrele(src_ire);
22409 			} else {
22410 				ire_refrele(ire);
22411 				if (conn_outgoing_ill != NULL)
22412 					ill_refrele(conn_outgoing_ill);
22413 				freemsg(first_mp);
22414 				if (ill != NULL) {
22415 					BUMP_MIB(ill->ill_ip_mib,
22416 					    ipIfStatsOutDiscards);
22417 				} else {
22418 					BUMP_MIB(&ipst->ips_ip_mib,
22419 					    ipIfStatsOutDiscards);
22420 				}
22421 				return;
22422 			}
22423 		} else {
22424 			src = ire->ire_src_addr;
22425 		}
22426 
22427 		if (connp == NULL) {
22428 			ip1dbg(("ip_wput_ire: no connp and no src "
22429 			    "address for dst 0x%x, using src 0x%x\n",
22430 			    ntohl(dst),
22431 			    ntohl(src)));
22432 		}
22433 		ipha->ipha_src = src;
22434 	}
22435 	stq = ire->ire_stq;
22436 
22437 	/*
22438 	 * We only allow ire chains for broadcasts since there will
22439 	 * be multiple IRE_CACHE entries for the same multicast
22440 	 * address (one per ipif).
22441 	 */
22442 	next_mp = NULL;
22443 
22444 	/* broadcast packet */
22445 	if (ire->ire_type == IRE_BROADCAST)
22446 		goto broadcast;
22447 
22448 	/* loopback ? */
22449 	if (stq == NULL)
22450 		goto nullstq;
22451 
22452 	/* The ill_index for outbound ILL */
22453 	ill_index = Q_TO_INDEX(stq);
22454 
22455 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22456 	ttl_protocol = ((uint16_t *)ipha)[4];
22457 
22458 	/* pseudo checksum (do it in parts for IP header checksum) */
22459 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22460 
22461 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22462 		queue_t *dev_q = stq->q_next;
22463 
22464 		/* flow controlled */
22465 		if ((dev_q->q_next || dev_q->q_first) &&
22466 		    !canput(dev_q))
22467 			goto blocked;
22468 		if ((PROTO == IPPROTO_UDP) &&
22469 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22470 			hlen = (V_HLEN & 0xF) << 2;
22471 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22472 			if (*up != 0) {
22473 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22474 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22475 				/* Software checksum? */
22476 				if (DB_CKSUMFLAGS(mp) == 0) {
22477 					IP_STAT(ipst, ip_out_sw_cksum);
22478 					IP_STAT_UPDATE(ipst,
22479 					    ip_udp_out_sw_cksum_bytes,
22480 					    LENGTH - hlen);
22481 				}
22482 			}
22483 		}
22484 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22485 		hlen = (V_HLEN & 0xF) << 2;
22486 		if (PROTO == IPPROTO_TCP) {
22487 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22488 			/*
22489 			 * The packet header is processed once and for all, even
22490 			 * in the multirouting case. We disable hardware
22491 			 * checksum if the packet is multirouted, as it will be
22492 			 * replicated via several interfaces, and not all of
22493 			 * them may have this capability.
22494 			 */
22495 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22496 			    LENGTH, max_frag, ipsec_len, cksum);
22497 			/* Software checksum? */
22498 			if (DB_CKSUMFLAGS(mp) == 0) {
22499 				IP_STAT(ipst, ip_out_sw_cksum);
22500 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22501 				    LENGTH - hlen);
22502 			}
22503 		} else {
22504 			sctp_hdr_t	*sctph;
22505 
22506 			ASSERT(PROTO == IPPROTO_SCTP);
22507 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22508 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22509 			/*
22510 			 * Zero out the checksum field to ensure proper
22511 			 * checksum calculation.
22512 			 */
22513 			sctph->sh_chksum = 0;
22514 #ifdef	DEBUG
22515 			if (!skip_sctp_cksum)
22516 #endif
22517 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22518 		}
22519 	}
22520 
22521 	/*
22522 	 * If this is a multicast packet and originated from ip_wput
22523 	 * we need to do loopback and forwarding checks. If it comes
22524 	 * from ip_wput_multicast, we SHOULD not do this.
22525 	 */
22526 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22527 
22528 	/* checksum */
22529 	cksum += ttl_protocol;
22530 
22531 	/* fragment the packet */
22532 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22533 		goto fragmentit;
22534 	/*
22535 	 * Don't use frag_flag if packet is pre-built or source
22536 	 * routed or if multicast (since multicast packets do
22537 	 * not solicit ICMP "packet too big" messages).
22538 	 */
22539 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22540 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22541 	    !ip_source_route_included(ipha)) &&
22542 	    !CLASSD(ipha->ipha_dst))
22543 		ipha->ipha_fragment_offset_and_flags |=
22544 		    htons(ire->ire_frag_flag);
22545 
22546 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22547 		/* calculate IP header checksum */
22548 		cksum += ipha->ipha_ident;
22549 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22550 		cksum += ipha->ipha_fragment_offset_and_flags;
22551 
22552 		/* IP options present */
22553 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22554 		if (hlen)
22555 			goto checksumoptions;
22556 
22557 		/* calculate hdr checksum */
22558 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22559 		cksum = ~(cksum + (cksum >> 16));
22560 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22561 	}
22562 	if (ipsec_len != 0) {
22563 		/*
22564 		 * We will do the rest of the processing after
22565 		 * we come back from IPsec in ip_wput_ipsec_out().
22566 		 */
22567 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22568 
22569 		io = (ipsec_out_t *)first_mp->b_rptr;
22570 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22571 		    ill_phyint->phyint_ifindex;
22572 
22573 		ipsec_out_process(q, first_mp, ire, ill_index);
22574 		ire_refrele(ire);
22575 		if (conn_outgoing_ill != NULL)
22576 			ill_refrele(conn_outgoing_ill);
22577 		return;
22578 	}
22579 
22580 	/*
22581 	 * In most cases, the emission loop below is entered only
22582 	 * once. Only in the case where the ire holds the
22583 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22584 	 * flagged ires in the bucket, and send the packet
22585 	 * through all crossed RTF_MULTIRT routes.
22586 	 */
22587 	if (ire->ire_flags & RTF_MULTIRT) {
22588 		multirt_send = B_TRUE;
22589 	}
22590 	do {
22591 		if (multirt_send) {
22592 			irb_t *irb;
22593 			/*
22594 			 * We are in a multiple send case, need to get
22595 			 * the next ire and make a duplicate of the packet.
22596 			 * ire1 holds here the next ire to process in the
22597 			 * bucket. If multirouting is expected,
22598 			 * any non-RTF_MULTIRT ire that has the
22599 			 * right destination address is ignored.
22600 			 */
22601 			irb = ire->ire_bucket;
22602 			ASSERT(irb != NULL);
22603 
22604 			IRB_REFHOLD(irb);
22605 			for (ire1 = ire->ire_next;
22606 			    ire1 != NULL;
22607 			    ire1 = ire1->ire_next) {
22608 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22609 					continue;
22610 				if (ire1->ire_addr != ire->ire_addr)
22611 					continue;
22612 				if (ire1->ire_marks &
22613 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22614 					continue;
22615 
22616 				/* Got one */
22617 				IRE_REFHOLD(ire1);
22618 				break;
22619 			}
22620 			IRB_REFRELE(irb);
22621 
22622 			if (ire1 != NULL) {
22623 				next_mp = copyb(mp);
22624 				if ((next_mp == NULL) ||
22625 				    ((mp->b_cont != NULL) &&
22626 				    ((next_mp->b_cont =
22627 				    dupmsg(mp->b_cont)) == NULL))) {
22628 					freemsg(next_mp);
22629 					next_mp = NULL;
22630 					ire_refrele(ire1);
22631 					ire1 = NULL;
22632 				}
22633 			}
22634 
22635 			/* Last multiroute ire; don't loop anymore. */
22636 			if (ire1 == NULL) {
22637 				multirt_send = B_FALSE;
22638 			}
22639 		}
22640 
22641 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22642 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22643 		    mblk_t *, mp);
22644 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22645 		    ipst->ips_ipv4firewall_physical_out,
22646 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22647 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22648 		if (mp == NULL)
22649 			goto release_ire_and_ill;
22650 
22651 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22652 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22653 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22654 		if ((pktxmit_state == SEND_FAILED) ||
22655 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22656 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22657 			    "- packet dropped\n"));
22658 release_ire_and_ill:
22659 			ire_refrele(ire);
22660 			if (next_mp != NULL) {
22661 				freemsg(next_mp);
22662 				ire_refrele(ire1);
22663 			}
22664 			if (conn_outgoing_ill != NULL)
22665 				ill_refrele(conn_outgoing_ill);
22666 			return;
22667 		}
22668 
22669 		if (CLASSD(dst)) {
22670 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22671 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22672 			    LENGTH);
22673 		}
22674 
22675 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22676 		    "ip_wput_ire_end: q %p (%S)",
22677 		    q, "last copy out");
22678 		IRE_REFRELE(ire);
22679 
22680 		if (multirt_send) {
22681 			ASSERT(ire1);
22682 			/*
22683 			 * Proceed with the next RTF_MULTIRT ire,
22684 			 * Also set up the send-to queue accordingly.
22685 			 */
22686 			ire = ire1;
22687 			ire1 = NULL;
22688 			stq = ire->ire_stq;
22689 			mp = next_mp;
22690 			next_mp = NULL;
22691 			ipha = (ipha_t *)mp->b_rptr;
22692 			ill_index = Q_TO_INDEX(stq);
22693 			ill = (ill_t *)stq->q_ptr;
22694 		}
22695 	} while (multirt_send);
22696 	if (conn_outgoing_ill != NULL)
22697 		ill_refrele(conn_outgoing_ill);
22698 	return;
22699 
22700 	/*
22701 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22702 	 */
22703 broadcast:
22704 	{
22705 		/*
22706 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22707 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22708 		 * can be overridden stack-wide through the ip_broadcast_ttl
22709 		 * ndd tunable, or on a per-connection basis through the
22710 		 * IP_BROADCAST_TTL socket option.
22711 		 *
22712 		 * In the event that we are replying to incoming ICMP packets,
22713 		 * connp could be NULL.
22714 		 */
22715 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22716 		if (connp != NULL) {
22717 			if (connp->conn_dontroute)
22718 				ipha->ipha_ttl = 1;
22719 			else if (connp->conn_broadcast_ttl != 0)
22720 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22721 		}
22722 
22723 		/*
22724 		 * Note that we are not doing a IRB_REFHOLD here.
22725 		 * Actually we don't care if the list changes i.e
22726 		 * if somebody deletes an IRE from the list while
22727 		 * we drop the lock, the next time we come around
22728 		 * ire_next will be NULL and hence we won't send
22729 		 * out multiple copies which is fine.
22730 		 */
22731 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22732 		ire1 = ire->ire_next;
22733 		if (conn_outgoing_ill != NULL) {
22734 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22735 				ASSERT(ire1 == ire->ire_next);
22736 				if (ire1 != NULL && ire1->ire_addr == dst) {
22737 					ire_refrele(ire);
22738 					ire = ire1;
22739 					IRE_REFHOLD(ire);
22740 					ire1 = ire->ire_next;
22741 					continue;
22742 				}
22743 				rw_exit(&ire->ire_bucket->irb_lock);
22744 				/* Did not find a matching ill */
22745 				ip1dbg(("ip_wput_ire: broadcast with no "
22746 				    "matching IP_BOUND_IF ill %s dst %x\n",
22747 				    conn_outgoing_ill->ill_name, dst));
22748 				freemsg(first_mp);
22749 				if (ire != NULL)
22750 					ire_refrele(ire);
22751 				ill_refrele(conn_outgoing_ill);
22752 				return;
22753 			}
22754 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22755 			/*
22756 			 * If the next IRE has the same address and is not one
22757 			 * of the two copies that we need to send, try to see
22758 			 * whether this copy should be sent at all. This
22759 			 * assumes that we insert loopbacks first and then
22760 			 * non-loopbacks. This is acheived by inserting the
22761 			 * loopback always before non-loopback.
22762 			 * This is used to send a single copy of a broadcast
22763 			 * packet out all physical interfaces that have an
22764 			 * matching IRE_BROADCAST while also looping
22765 			 * back one copy (to ip_wput_local) for each
22766 			 * matching physical interface. However, we avoid
22767 			 * sending packets out different logical that match by
22768 			 * having ipif_up/ipif_down supress duplicate
22769 			 * IRE_BROADCASTS.
22770 			 *
22771 			 * This feature is currently used to get broadcasts
22772 			 * sent to multiple interfaces, when the broadcast
22773 			 * address being used applies to multiple interfaces.
22774 			 * For example, a whole net broadcast will be
22775 			 * replicated on every connected subnet of
22776 			 * the target net.
22777 			 *
22778 			 * Each zone has its own set of IRE_BROADCASTs, so that
22779 			 * we're able to distribute inbound packets to multiple
22780 			 * zones who share a broadcast address. We avoid looping
22781 			 * back outbound packets in different zones but on the
22782 			 * same ill, as the application would see duplicates.
22783 			 *
22784 			 * If the interfaces are part of the same group,
22785 			 * we would want to send only one copy out for
22786 			 * whole group.
22787 			 *
22788 			 * This logic assumes that ire_add_v4() groups the
22789 			 * IRE_BROADCAST entries so that those with the same
22790 			 * ire_addr and ill_group are kept together.
22791 			 */
22792 			ire_ill = ire->ire_ipif->ipif_ill;
22793 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22794 				if (ire_ill->ill_group != NULL &&
22795 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22796 					/*
22797 					 * If the current zone only has an ire
22798 					 * broadcast for this address marked
22799 					 * NORECV, the ire we want is ahead in
22800 					 * the bucket, so we look it up
22801 					 * deliberately ignoring the zoneid.
22802 					 */
22803 					for (ire1 = ire->ire_bucket->irb_ire;
22804 					    ire1 != NULL;
22805 					    ire1 = ire1->ire_next) {
22806 						ire1_ill =
22807 						    ire1->ire_ipif->ipif_ill;
22808 						if (ire1->ire_addr != dst)
22809 							continue;
22810 						/* skip over the current ire */
22811 						if (ire1 == ire)
22812 							continue;
22813 						/* skip over deleted ires */
22814 						if (ire1->ire_marks &
22815 						    IRE_MARK_CONDEMNED)
22816 							continue;
22817 						/*
22818 						 * non-loopback ire in our
22819 						 * group: use it for the next
22820 						 * pass in the loop
22821 						 */
22822 						if (ire1->ire_stq != NULL &&
22823 						    ire1_ill->ill_group ==
22824 						    ire_ill->ill_group)
22825 							break;
22826 					}
22827 				}
22828 			} else {
22829 				while (ire1 != NULL && ire1->ire_addr == dst) {
22830 					ire1_ill = ire1->ire_ipif->ipif_ill;
22831 					/*
22832 					 * We can have two broadcast ires on the
22833 					 * same ill in different zones; here
22834 					 * we'll send a copy of the packet on
22835 					 * each ill and the fanout code will
22836 					 * call conn_wantpacket() to check that
22837 					 * the zone has the broadcast address
22838 					 * configured on the ill. If the two
22839 					 * ires are in the same group we only
22840 					 * send one copy up.
22841 					 */
22842 					if (ire1_ill != ire_ill &&
22843 					    (ire1_ill->ill_group == NULL ||
22844 					    ire_ill->ill_group == NULL ||
22845 					    ire1_ill->ill_group !=
22846 					    ire_ill->ill_group)) {
22847 						break;
22848 					}
22849 					ire1 = ire1->ire_next;
22850 				}
22851 			}
22852 		}
22853 		ASSERT(multirt_send == B_FALSE);
22854 		if (ire1 != NULL && ire1->ire_addr == dst) {
22855 			if ((ire->ire_flags & RTF_MULTIRT) &&
22856 			    (ire1->ire_flags & RTF_MULTIRT)) {
22857 				/*
22858 				 * We are in the multirouting case.
22859 				 * The message must be sent at least
22860 				 * on both ires. These ires have been
22861 				 * inserted AFTER the standard ones
22862 				 * in ip_rt_add(). There are thus no
22863 				 * other ire entries for the destination
22864 				 * address in the rest of the bucket
22865 				 * that do not have the RTF_MULTIRT
22866 				 * flag. We don't process a copy
22867 				 * of the message here. This will be
22868 				 * done in the final sending loop.
22869 				 */
22870 				multirt_send = B_TRUE;
22871 			} else {
22872 				next_mp = ip_copymsg(first_mp);
22873 				if (next_mp != NULL)
22874 					IRE_REFHOLD(ire1);
22875 			}
22876 		}
22877 		rw_exit(&ire->ire_bucket->irb_lock);
22878 	}
22879 
22880 	if (stq) {
22881 		/*
22882 		 * A non-NULL send-to queue means this packet is going
22883 		 * out of this machine.
22884 		 */
22885 		out_ill = (ill_t *)stq->q_ptr;
22886 
22887 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22888 		ttl_protocol = ((uint16_t *)ipha)[4];
22889 		/*
22890 		 * We accumulate the pseudo header checksum in cksum.
22891 		 * This is pretty hairy code, so watch close.  One
22892 		 * thing to keep in mind is that UDP and TCP have
22893 		 * stored their respective datagram lengths in their
22894 		 * checksum fields.  This lines things up real nice.
22895 		 */
22896 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22897 		    (src >> 16) + (src & 0xFFFF);
22898 		/*
22899 		 * We assume the udp checksum field contains the
22900 		 * length, so to compute the pseudo header checksum,
22901 		 * all we need is the protocol number and src/dst.
22902 		 */
22903 		/* Provide the checksums for UDP and TCP. */
22904 		if ((PROTO == IPPROTO_TCP) &&
22905 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22906 			/* hlen gets the number of uchar_ts in the IP header */
22907 			hlen = (V_HLEN & 0xF) << 2;
22908 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22909 			IP_STAT(ipst, ip_out_sw_cksum);
22910 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22911 			    LENGTH - hlen);
22912 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22913 		} else if (PROTO == IPPROTO_SCTP &&
22914 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22915 			sctp_hdr_t	*sctph;
22916 
22917 			hlen = (V_HLEN & 0xF) << 2;
22918 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22919 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22920 			sctph->sh_chksum = 0;
22921 #ifdef	DEBUG
22922 			if (!skip_sctp_cksum)
22923 #endif
22924 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22925 		} else {
22926 			queue_t *dev_q = stq->q_next;
22927 
22928 			if ((dev_q->q_next || dev_q->q_first) &&
22929 			    !canput(dev_q)) {
22930 blocked:
22931 				ipha->ipha_ident = ip_hdr_included;
22932 				/*
22933 				 * If we don't have a conn to apply
22934 				 * backpressure, free the message.
22935 				 * In the ire_send path, we don't know
22936 				 * the position to requeue the packet. Rather
22937 				 * than reorder packets, we just drop this
22938 				 * packet.
22939 				 */
22940 				if (ipst->ips_ip_output_queue &&
22941 				    connp != NULL &&
22942 				    caller != IRE_SEND) {
22943 					if (caller == IP_WSRV) {
22944 						connp->conn_did_putbq = 1;
22945 						(void) putbq(connp->conn_wq,
22946 						    first_mp);
22947 						conn_drain_insert(connp);
22948 						/*
22949 						 * This is the service thread,
22950 						 * and the queue is already
22951 						 * noenabled. The check for
22952 						 * canput and the putbq is not
22953 						 * atomic. So we need to check
22954 						 * again.
22955 						 */
22956 						if (canput(stq->q_next))
22957 							connp->conn_did_putbq
22958 							    = 0;
22959 						IP_STAT(ipst, ip_conn_flputbq);
22960 					} else {
22961 						/*
22962 						 * We are not the service proc.
22963 						 * ip_wsrv will be scheduled or
22964 						 * is already running.
22965 						 */
22966 						(void) putq(connp->conn_wq,
22967 						    first_mp);
22968 					}
22969 				} else {
22970 					out_ill = (ill_t *)stq->q_ptr;
22971 					BUMP_MIB(out_ill->ill_ip_mib,
22972 					    ipIfStatsOutDiscards);
22973 					freemsg(first_mp);
22974 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22975 					    "ip_wput_ire_end: q %p (%S)",
22976 					    q, "discard");
22977 				}
22978 				ire_refrele(ire);
22979 				if (next_mp) {
22980 					ire_refrele(ire1);
22981 					freemsg(next_mp);
22982 				}
22983 				if (conn_outgoing_ill != NULL)
22984 					ill_refrele(conn_outgoing_ill);
22985 				return;
22986 			}
22987 			if ((PROTO == IPPROTO_UDP) &&
22988 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22989 				/*
22990 				 * hlen gets the number of uchar_ts in the
22991 				 * IP header
22992 				 */
22993 				hlen = (V_HLEN & 0xF) << 2;
22994 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22995 				max_frag = ire->ire_max_frag;
22996 				if (*up != 0) {
22997 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22998 					    up, PROTO, hlen, LENGTH, max_frag,
22999 					    ipsec_len, cksum);
23000 					/* Software checksum? */
23001 					if (DB_CKSUMFLAGS(mp) == 0) {
23002 						IP_STAT(ipst, ip_out_sw_cksum);
23003 						IP_STAT_UPDATE(ipst,
23004 						    ip_udp_out_sw_cksum_bytes,
23005 						    LENGTH - hlen);
23006 					}
23007 				}
23008 			}
23009 		}
23010 		/*
23011 		 * Need to do this even when fragmenting. The local
23012 		 * loopback can be done without computing checksums
23013 		 * but forwarding out other interface must be done
23014 		 * after the IP checksum (and ULP checksums) have been
23015 		 * computed.
23016 		 *
23017 		 * NOTE : multicast_forward is set only if this packet
23018 		 * originated from ip_wput. For packets originating from
23019 		 * ip_wput_multicast, it is not set.
23020 		 */
23021 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
23022 multi_loopback:
23023 			ip2dbg(("ip_wput: multicast, loop %d\n",
23024 			    conn_multicast_loop));
23025 
23026 			/*  Forget header checksum offload */
23027 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
23028 
23029 			/*
23030 			 * Local loopback of multicasts?  Check the
23031 			 * ill.
23032 			 *
23033 			 * Note that the loopback function will not come
23034 			 * in through ip_rput - it will only do the
23035 			 * client fanout thus we need to do an mforward
23036 			 * as well.  The is different from the BSD
23037 			 * logic.
23038 			 */
23039 			if (ill != NULL) {
23040 				ilm_t	*ilm;
23041 
23042 				ILM_WALKER_HOLD(ill);
23043 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
23044 				    ALL_ZONES);
23045 				ILM_WALKER_RELE(ill);
23046 				if (ilm != NULL) {
23047 					/*
23048 					 * Pass along the virtual output q.
23049 					 * ip_wput_local() will distribute the
23050 					 * packet to all the matching zones,
23051 					 * except the sending zone when
23052 					 * IP_MULTICAST_LOOP is false.
23053 					 */
23054 					ip_multicast_loopback(q, ill, first_mp,
23055 					    conn_multicast_loop ? 0 :
23056 					    IP_FF_NO_MCAST_LOOP, zoneid);
23057 				}
23058 			}
23059 			if (ipha->ipha_ttl == 0) {
23060 				/*
23061 				 * 0 => only to this host i.e. we are
23062 				 * done. We are also done if this was the
23063 				 * loopback interface since it is sufficient
23064 				 * to loopback one copy of a multicast packet.
23065 				 */
23066 				freemsg(first_mp);
23067 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23068 				    "ip_wput_ire_end: q %p (%S)",
23069 				    q, "loopback");
23070 				ire_refrele(ire);
23071 				if (conn_outgoing_ill != NULL)
23072 					ill_refrele(conn_outgoing_ill);
23073 				return;
23074 			}
23075 			/*
23076 			 * ILLF_MULTICAST is checked in ip_newroute
23077 			 * i.e. we don't need to check it here since
23078 			 * all IRE_CACHEs come from ip_newroute.
23079 			 * For multicast traffic, SO_DONTROUTE is interpreted
23080 			 * to mean only send the packet out the interface
23081 			 * (optionally specified with IP_MULTICAST_IF)
23082 			 * and do not forward it out additional interfaces.
23083 			 * RSVP and the rsvp daemon is an example of a
23084 			 * protocol and user level process that
23085 			 * handles it's own routing. Hence, it uses the
23086 			 * SO_DONTROUTE option to accomplish this.
23087 			 */
23088 
23089 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23090 			    ill != NULL) {
23091 				/* Unconditionally redo the checksum */
23092 				ipha->ipha_hdr_checksum = 0;
23093 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23094 
23095 				/*
23096 				 * If this needs to go out secure, we need
23097 				 * to wait till we finish the IPsec
23098 				 * processing.
23099 				 */
23100 				if (ipsec_len == 0 &&
23101 				    ip_mforward(ill, ipha, mp)) {
23102 					freemsg(first_mp);
23103 					ip1dbg(("ip_wput: mforward failed\n"));
23104 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23105 					    "ip_wput_ire_end: q %p (%S)",
23106 					    q, "mforward failed");
23107 					ire_refrele(ire);
23108 					if (conn_outgoing_ill != NULL)
23109 						ill_refrele(conn_outgoing_ill);
23110 					return;
23111 				}
23112 			}
23113 		}
23114 		max_frag = ire->ire_max_frag;
23115 		cksum += ttl_protocol;
23116 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23117 			/* No fragmentation required for this one. */
23118 			/*
23119 			 * Don't use frag_flag if packet is pre-built or source
23120 			 * routed or if multicast (since multicast packets do
23121 			 * not solicit ICMP "packet too big" messages).
23122 			 */
23123 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23124 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23125 			    !ip_source_route_included(ipha)) &&
23126 			    !CLASSD(ipha->ipha_dst))
23127 				ipha->ipha_fragment_offset_and_flags |=
23128 				    htons(ire->ire_frag_flag);
23129 
23130 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23131 				/* Complete the IP header checksum. */
23132 				cksum += ipha->ipha_ident;
23133 				cksum += (v_hlen_tos_len >> 16)+
23134 				    (v_hlen_tos_len & 0xFFFF);
23135 				cksum += ipha->ipha_fragment_offset_and_flags;
23136 				hlen = (V_HLEN & 0xF) -
23137 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23138 				if (hlen) {
23139 checksumoptions:
23140 					/*
23141 					 * Account for the IP Options in the IP
23142 					 * header checksum.
23143 					 */
23144 					up = (uint16_t *)(rptr+
23145 					    IP_SIMPLE_HDR_LENGTH);
23146 					do {
23147 						cksum += up[0];
23148 						cksum += up[1];
23149 						up += 2;
23150 					} while (--hlen);
23151 				}
23152 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23153 				cksum = ~(cksum + (cksum >> 16));
23154 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23155 			}
23156 			if (ipsec_len != 0) {
23157 				ipsec_out_process(q, first_mp, ire, ill_index);
23158 				if (!next_mp) {
23159 					ire_refrele(ire);
23160 					if (conn_outgoing_ill != NULL)
23161 						ill_refrele(conn_outgoing_ill);
23162 					return;
23163 				}
23164 				goto next;
23165 			}
23166 
23167 			/*
23168 			 * multirt_send has already been handled
23169 			 * for broadcast, but not yet for multicast
23170 			 * or IP options.
23171 			 */
23172 			if (next_mp == NULL) {
23173 				if (ire->ire_flags & RTF_MULTIRT) {
23174 					multirt_send = B_TRUE;
23175 				}
23176 			}
23177 
23178 			/*
23179 			 * In most cases, the emission loop below is
23180 			 * entered only once. Only in the case where
23181 			 * the ire holds the RTF_MULTIRT flag, do we loop
23182 			 * to process all RTF_MULTIRT ires in the bucket,
23183 			 * and send the packet through all crossed
23184 			 * RTF_MULTIRT routes.
23185 			 */
23186 			do {
23187 				if (multirt_send) {
23188 					irb_t *irb;
23189 
23190 					irb = ire->ire_bucket;
23191 					ASSERT(irb != NULL);
23192 					/*
23193 					 * We are in a multiple send case,
23194 					 * need to get the next IRE and make
23195 					 * a duplicate of the packet.
23196 					 */
23197 					IRB_REFHOLD(irb);
23198 					for (ire1 = ire->ire_next;
23199 					    ire1 != NULL;
23200 					    ire1 = ire1->ire_next) {
23201 						if (!(ire1->ire_flags &
23202 						    RTF_MULTIRT)) {
23203 							continue;
23204 						}
23205 						if (ire1->ire_addr !=
23206 						    ire->ire_addr) {
23207 							continue;
23208 						}
23209 						if (ire1->ire_marks &
23210 						    (IRE_MARK_CONDEMNED|
23211 						    IRE_MARK_HIDDEN)) {
23212 							continue;
23213 						}
23214 
23215 						/* Got one */
23216 						IRE_REFHOLD(ire1);
23217 						break;
23218 					}
23219 					IRB_REFRELE(irb);
23220 
23221 					if (ire1 != NULL) {
23222 						next_mp = copyb(mp);
23223 						if ((next_mp == NULL) ||
23224 						    ((mp->b_cont != NULL) &&
23225 						    ((next_mp->b_cont =
23226 						    dupmsg(mp->b_cont))
23227 						    == NULL))) {
23228 							freemsg(next_mp);
23229 							next_mp = NULL;
23230 							ire_refrele(ire1);
23231 							ire1 = NULL;
23232 						}
23233 					}
23234 
23235 					/*
23236 					 * Last multiroute ire; don't loop
23237 					 * anymore. The emission is over
23238 					 * and next_mp is NULL.
23239 					 */
23240 					if (ire1 == NULL) {
23241 						multirt_send = B_FALSE;
23242 					}
23243 				}
23244 
23245 				out_ill = ire_to_ill(ire);
23246 				DTRACE_PROBE4(ip4__physical__out__start,
23247 				    ill_t *, NULL,
23248 				    ill_t *, out_ill,
23249 				    ipha_t *, ipha, mblk_t *, mp);
23250 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23251 				    ipst->ips_ipv4firewall_physical_out,
23252 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23253 				DTRACE_PROBE1(ip4__physical__out__end,
23254 				    mblk_t *, mp);
23255 				if (mp == NULL)
23256 					goto release_ire_and_ill_2;
23257 
23258 				ASSERT(ipsec_len == 0);
23259 				mp->b_prev =
23260 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23261 				DTRACE_PROBE2(ip__xmit__2,
23262 				    mblk_t *, mp, ire_t *, ire);
23263 				pktxmit_state = ip_xmit_v4(mp, ire,
23264 				    NULL, B_TRUE);
23265 				if ((pktxmit_state == SEND_FAILED) ||
23266 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23267 release_ire_and_ill_2:
23268 					if (next_mp) {
23269 						freemsg(next_mp);
23270 						ire_refrele(ire1);
23271 					}
23272 					ire_refrele(ire);
23273 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23274 					    "ip_wput_ire_end: q %p (%S)",
23275 					    q, "discard MDATA");
23276 					if (conn_outgoing_ill != NULL)
23277 						ill_refrele(conn_outgoing_ill);
23278 					return;
23279 				}
23280 
23281 				if (CLASSD(dst)) {
23282 					BUMP_MIB(out_ill->ill_ip_mib,
23283 					    ipIfStatsHCOutMcastPkts);
23284 					UPDATE_MIB(out_ill->ill_ip_mib,
23285 					    ipIfStatsHCOutMcastOctets,
23286 					    LENGTH);
23287 				} else if (ire->ire_type == IRE_BROADCAST) {
23288 					BUMP_MIB(out_ill->ill_ip_mib,
23289 					    ipIfStatsHCOutBcastPkts);
23290 				}
23291 
23292 				if (multirt_send) {
23293 					/*
23294 					 * We are in a multiple send case,
23295 					 * need to re-enter the sending loop
23296 					 * using the next ire.
23297 					 */
23298 					ire_refrele(ire);
23299 					ire = ire1;
23300 					stq = ire->ire_stq;
23301 					mp = next_mp;
23302 					next_mp = NULL;
23303 					ipha = (ipha_t *)mp->b_rptr;
23304 					ill_index = Q_TO_INDEX(stq);
23305 				}
23306 			} while (multirt_send);
23307 
23308 			if (!next_mp) {
23309 				/*
23310 				 * Last copy going out (the ultra-common
23311 				 * case).  Note that we intentionally replicate
23312 				 * the putnext rather than calling it before
23313 				 * the next_mp check in hopes of a little
23314 				 * tail-call action out of the compiler.
23315 				 */
23316 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23317 				    "ip_wput_ire_end: q %p (%S)",
23318 				    q, "last copy out(1)");
23319 				ire_refrele(ire);
23320 				if (conn_outgoing_ill != NULL)
23321 					ill_refrele(conn_outgoing_ill);
23322 				return;
23323 			}
23324 			/* More copies going out below. */
23325 		} else {
23326 			int offset;
23327 fragmentit:
23328 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23329 			/*
23330 			 * If this would generate a icmp_frag_needed message,
23331 			 * we need to handle it before we do the IPsec
23332 			 * processing. Otherwise, we need to strip the IPsec
23333 			 * headers before we send up the message to the ULPs
23334 			 * which becomes messy and difficult.
23335 			 */
23336 			if (ipsec_len != 0) {
23337 				if ((max_frag < (unsigned int)(LENGTH +
23338 				    ipsec_len)) && (offset & IPH_DF)) {
23339 					out_ill = (ill_t *)stq->q_ptr;
23340 					BUMP_MIB(out_ill->ill_ip_mib,
23341 					    ipIfStatsOutFragFails);
23342 					BUMP_MIB(out_ill->ill_ip_mib,
23343 					    ipIfStatsOutFragReqds);
23344 					ipha->ipha_hdr_checksum = 0;
23345 					ipha->ipha_hdr_checksum =
23346 					    (uint16_t)ip_csum_hdr(ipha);
23347 					icmp_frag_needed(ire->ire_stq, first_mp,
23348 					    max_frag, zoneid, ipst);
23349 					if (!next_mp) {
23350 						ire_refrele(ire);
23351 						if (conn_outgoing_ill != NULL) {
23352 							ill_refrele(
23353 							    conn_outgoing_ill);
23354 						}
23355 						return;
23356 					}
23357 				} else {
23358 					/*
23359 					 * This won't cause a icmp_frag_needed
23360 					 * message. to be generated. Send it on
23361 					 * the wire. Note that this could still
23362 					 * cause fragmentation and all we
23363 					 * do is the generation of the message
23364 					 * to the ULP if needed before IPsec.
23365 					 */
23366 					if (!next_mp) {
23367 						ipsec_out_process(q, first_mp,
23368 						    ire, ill_index);
23369 						TRACE_2(TR_FAC_IP,
23370 						    TR_IP_WPUT_IRE_END,
23371 						    "ip_wput_ire_end: q %p "
23372 						    "(%S)", q,
23373 						    "last ipsec_out_process");
23374 						ire_refrele(ire);
23375 						if (conn_outgoing_ill != NULL) {
23376 							ill_refrele(
23377 							    conn_outgoing_ill);
23378 						}
23379 						return;
23380 					}
23381 					ipsec_out_process(q, first_mp,
23382 					    ire, ill_index);
23383 				}
23384 			} else {
23385 				/*
23386 				 * Initiate IPPF processing. For
23387 				 * fragmentable packets we finish
23388 				 * all QOS packet processing before
23389 				 * calling:
23390 				 * ip_wput_ire_fragmentit->ip_wput_frag
23391 				 */
23392 
23393 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23394 					ip_process(IPP_LOCAL_OUT, &mp,
23395 					    ill_index);
23396 					if (mp == NULL) {
23397 						out_ill = (ill_t *)stq->q_ptr;
23398 						BUMP_MIB(out_ill->ill_ip_mib,
23399 						    ipIfStatsOutDiscards);
23400 						if (next_mp != NULL) {
23401 							freemsg(next_mp);
23402 							ire_refrele(ire1);
23403 						}
23404 						ire_refrele(ire);
23405 						TRACE_2(TR_FAC_IP,
23406 						    TR_IP_WPUT_IRE_END,
23407 						    "ip_wput_ire: q %p (%S)",
23408 						    q, "discard MDATA");
23409 						if (conn_outgoing_ill != NULL) {
23410 							ill_refrele(
23411 							    conn_outgoing_ill);
23412 						}
23413 						return;
23414 					}
23415 				}
23416 				if (!next_mp) {
23417 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23418 					    "ip_wput_ire_end: q %p (%S)",
23419 					    q, "last fragmentation");
23420 					ip_wput_ire_fragmentit(mp, ire,
23421 					    zoneid, ipst);
23422 					ire_refrele(ire);
23423 					if (conn_outgoing_ill != NULL)
23424 						ill_refrele(conn_outgoing_ill);
23425 					return;
23426 				}
23427 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23428 			}
23429 		}
23430 	} else {
23431 nullstq:
23432 		/* A NULL stq means the destination address is local. */
23433 		UPDATE_OB_PKT_COUNT(ire);
23434 		ire->ire_last_used_time = lbolt;
23435 		ASSERT(ire->ire_ipif != NULL);
23436 		if (!next_mp) {
23437 			/*
23438 			 * Is there an "in" and "out" for traffic local
23439 			 * to a host (loopback)?  The code in Solaris doesn't
23440 			 * explicitly draw a line in its code for in vs out,
23441 			 * so we've had to draw a line in the sand: ip_wput_ire
23442 			 * is considered to be the "output" side and
23443 			 * ip_wput_local to be the "input" side.
23444 			 */
23445 			out_ill = ire_to_ill(ire);
23446 
23447 			DTRACE_PROBE4(ip4__loopback__out__start,
23448 			    ill_t *, NULL, ill_t *, out_ill,
23449 			    ipha_t *, ipha, mblk_t *, first_mp);
23450 
23451 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23452 			    ipst->ips_ipv4firewall_loopback_out,
23453 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23454 
23455 			DTRACE_PROBE1(ip4__loopback__out_end,
23456 			    mblk_t *, first_mp);
23457 
23458 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23459 			    "ip_wput_ire_end: q %p (%S)",
23460 			    q, "local address");
23461 
23462 			if (first_mp != NULL)
23463 				ip_wput_local(q, out_ill, ipha,
23464 				    first_mp, ire, 0, ire->ire_zoneid);
23465 			ire_refrele(ire);
23466 			if (conn_outgoing_ill != NULL)
23467 				ill_refrele(conn_outgoing_ill);
23468 			return;
23469 		}
23470 
23471 		out_ill = ire_to_ill(ire);
23472 
23473 		DTRACE_PROBE4(ip4__loopback__out__start,
23474 		    ill_t *, NULL, ill_t *, out_ill,
23475 		    ipha_t *, ipha, mblk_t *, first_mp);
23476 
23477 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23478 		    ipst->ips_ipv4firewall_loopback_out,
23479 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23480 
23481 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23482 
23483 		if (first_mp != NULL)
23484 			ip_wput_local(q, out_ill, ipha,
23485 			    first_mp, ire, 0, ire->ire_zoneid);
23486 	}
23487 next:
23488 	/*
23489 	 * More copies going out to additional interfaces.
23490 	 * ire1 has already been held. We don't need the
23491 	 * "ire" anymore.
23492 	 */
23493 	ire_refrele(ire);
23494 	ire = ire1;
23495 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23496 	mp = next_mp;
23497 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23498 	ill = ire_to_ill(ire);
23499 	first_mp = mp;
23500 	if (ipsec_len != 0) {
23501 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23502 		mp = mp->b_cont;
23503 	}
23504 	dst = ire->ire_addr;
23505 	ipha = (ipha_t *)mp->b_rptr;
23506 	/*
23507 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23508 	 * Restore ipha_ident "no checksum" flag.
23509 	 */
23510 	src = orig_src;
23511 	ipha->ipha_ident = ip_hdr_included;
23512 	goto another;
23513 
23514 #undef	rptr
23515 #undef	Q_TO_INDEX
23516 }
23517 
23518 /*
23519  * Routine to allocate a message that is used to notify the ULP about MDT.
23520  * The caller may provide a pointer to the link-layer MDT capabilities,
23521  * or NULL if MDT is to be disabled on the stream.
23522  */
23523 mblk_t *
23524 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23525 {
23526 	mblk_t *mp;
23527 	ip_mdt_info_t *mdti;
23528 	ill_mdt_capab_t *idst;
23529 
23530 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23531 		DB_TYPE(mp) = M_CTL;
23532 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23533 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23534 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23535 		idst = &(mdti->mdt_capab);
23536 
23537 		/*
23538 		 * If the caller provides us with the capability, copy
23539 		 * it over into our notification message; otherwise
23540 		 * we zero out the capability portion.
23541 		 */
23542 		if (isrc != NULL)
23543 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23544 		else
23545 			bzero((caddr_t)idst, sizeof (*idst));
23546 	}
23547 	return (mp);
23548 }
23549 
23550 /*
23551  * Routine which determines whether MDT can be enabled on the destination
23552  * IRE and IPC combination, and if so, allocates and returns the MDT
23553  * notification mblk that may be used by ULP.  We also check if we need to
23554  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23555  * MDT usage in the past have been lifted.  This gets called during IP
23556  * and ULP binding.
23557  */
23558 mblk_t *
23559 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23560     ill_mdt_capab_t *mdt_cap)
23561 {
23562 	mblk_t *mp;
23563 	boolean_t rc = B_FALSE;
23564 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23565 
23566 	ASSERT(dst_ire != NULL);
23567 	ASSERT(connp != NULL);
23568 	ASSERT(mdt_cap != NULL);
23569 
23570 	/*
23571 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23572 	 * Multidata, which is handled in tcp_multisend().  This
23573 	 * is the reason why we do all these checks here, to ensure
23574 	 * that we don't enable Multidata for the cases which we
23575 	 * can't handle at the moment.
23576 	 */
23577 	do {
23578 		/* Only do TCP at the moment */
23579 		if (connp->conn_ulp != IPPROTO_TCP)
23580 			break;
23581 
23582 		/*
23583 		 * IPsec outbound policy present?  Note that we get here
23584 		 * after calling ipsec_conn_cache_policy() where the global
23585 		 * policy checking is performed.  conn_latch will be
23586 		 * non-NULL as long as there's a policy defined,
23587 		 * i.e. conn_out_enforce_policy may be NULL in such case
23588 		 * when the connection is non-secure, and hence we check
23589 		 * further if the latch refers to an outbound policy.
23590 		 */
23591 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23592 			break;
23593 
23594 		/* CGTP (multiroute) is enabled? */
23595 		if (dst_ire->ire_flags & RTF_MULTIRT)
23596 			break;
23597 
23598 		/* Outbound IPQoS enabled? */
23599 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23600 			/*
23601 			 * In this case, we disable MDT for this and all
23602 			 * future connections going over the interface.
23603 			 */
23604 			mdt_cap->ill_mdt_on = 0;
23605 			break;
23606 		}
23607 
23608 		/* socket option(s) present? */
23609 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23610 			break;
23611 
23612 		rc = B_TRUE;
23613 	/* CONSTCOND */
23614 	} while (0);
23615 
23616 	/* Remember the result */
23617 	connp->conn_mdt_ok = rc;
23618 
23619 	if (!rc)
23620 		return (NULL);
23621 	else if (!mdt_cap->ill_mdt_on) {
23622 		/*
23623 		 * If MDT has been previously turned off in the past, and we
23624 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23625 		 * then enable it for this interface.
23626 		 */
23627 		mdt_cap->ill_mdt_on = 1;
23628 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23629 		    "interface %s\n", ill_name));
23630 	}
23631 
23632 	/* Allocate the MDT info mblk */
23633 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23634 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23635 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23636 		return (NULL);
23637 	}
23638 	return (mp);
23639 }
23640 
23641 /*
23642  * Routine to allocate a message that is used to notify the ULP about LSO.
23643  * The caller may provide a pointer to the link-layer LSO capabilities,
23644  * or NULL if LSO is to be disabled on the stream.
23645  */
23646 mblk_t *
23647 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23648 {
23649 	mblk_t *mp;
23650 	ip_lso_info_t *lsoi;
23651 	ill_lso_capab_t *idst;
23652 
23653 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23654 		DB_TYPE(mp) = M_CTL;
23655 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23656 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23657 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23658 		idst = &(lsoi->lso_capab);
23659 
23660 		/*
23661 		 * If the caller provides us with the capability, copy
23662 		 * it over into our notification message; otherwise
23663 		 * we zero out the capability portion.
23664 		 */
23665 		if (isrc != NULL)
23666 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23667 		else
23668 			bzero((caddr_t)idst, sizeof (*idst));
23669 	}
23670 	return (mp);
23671 }
23672 
23673 /*
23674  * Routine which determines whether LSO can be enabled on the destination
23675  * IRE and IPC combination, and if so, allocates and returns the LSO
23676  * notification mblk that may be used by ULP.  We also check if we need to
23677  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23678  * LSO usage in the past have been lifted.  This gets called during IP
23679  * and ULP binding.
23680  */
23681 mblk_t *
23682 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23683     ill_lso_capab_t *lso_cap)
23684 {
23685 	mblk_t *mp;
23686 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23687 
23688 	ASSERT(dst_ire != NULL);
23689 	ASSERT(connp != NULL);
23690 	ASSERT(lso_cap != NULL);
23691 
23692 	connp->conn_lso_ok = B_TRUE;
23693 
23694 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23695 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23696 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23697 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23698 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23699 		connp->conn_lso_ok = B_FALSE;
23700 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23701 			/*
23702 			 * Disable LSO for this and all future connections going
23703 			 * over the interface.
23704 			 */
23705 			lso_cap->ill_lso_on = 0;
23706 		}
23707 	}
23708 
23709 	if (!connp->conn_lso_ok)
23710 		return (NULL);
23711 	else if (!lso_cap->ill_lso_on) {
23712 		/*
23713 		 * If LSO has been previously turned off in the past, and we
23714 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23715 		 * then enable it for this interface.
23716 		 */
23717 		lso_cap->ill_lso_on = 1;
23718 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23719 		    ill_name));
23720 	}
23721 
23722 	/* Allocate the LSO info mblk */
23723 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23724 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23725 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23726 
23727 	return (mp);
23728 }
23729 
23730 /*
23731  * Create destination address attribute, and fill it with the physical
23732  * destination address and SAP taken from the template DL_UNITDATA_REQ
23733  * message block.
23734  */
23735 boolean_t
23736 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23737 {
23738 	dl_unitdata_req_t *dlurp;
23739 	pattr_t *pa;
23740 	pattrinfo_t pa_info;
23741 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23742 	uint_t das_len, das_off;
23743 
23744 	ASSERT(dlmp != NULL);
23745 
23746 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23747 	das_len = dlurp->dl_dest_addr_length;
23748 	das_off = dlurp->dl_dest_addr_offset;
23749 
23750 	pa_info.type = PATTR_DSTADDRSAP;
23751 	pa_info.len = sizeof (**das) + das_len - 1;
23752 
23753 	/* create and associate the attribute */
23754 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23755 	if (pa != NULL) {
23756 		ASSERT(*das != NULL);
23757 		(*das)->addr_is_group = 0;
23758 		(*das)->addr_len = (uint8_t)das_len;
23759 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23760 	}
23761 
23762 	return (pa != NULL);
23763 }
23764 
23765 /*
23766  * Create hardware checksum attribute and fill it with the values passed.
23767  */
23768 boolean_t
23769 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23770     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23771 {
23772 	pattr_t *pa;
23773 	pattrinfo_t pa_info;
23774 
23775 	ASSERT(mmd != NULL);
23776 
23777 	pa_info.type = PATTR_HCKSUM;
23778 	pa_info.len = sizeof (pattr_hcksum_t);
23779 
23780 	/* create and associate the attribute */
23781 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23782 	if (pa != NULL) {
23783 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23784 
23785 		hck->hcksum_start_offset = start_offset;
23786 		hck->hcksum_stuff_offset = stuff_offset;
23787 		hck->hcksum_end_offset = end_offset;
23788 		hck->hcksum_flags = flags;
23789 	}
23790 	return (pa != NULL);
23791 }
23792 
23793 /*
23794  * Create zerocopy attribute and fill it with the specified flags
23795  */
23796 boolean_t
23797 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23798 {
23799 	pattr_t *pa;
23800 	pattrinfo_t pa_info;
23801 
23802 	ASSERT(mmd != NULL);
23803 	pa_info.type = PATTR_ZCOPY;
23804 	pa_info.len = sizeof (pattr_zcopy_t);
23805 
23806 	/* create and associate the attribute */
23807 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23808 	if (pa != NULL) {
23809 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23810 
23811 		zcopy->zcopy_flags = flags;
23812 	}
23813 	return (pa != NULL);
23814 }
23815 
23816 /*
23817  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23818  * block chain. We could rewrite to handle arbitrary message block chains but
23819  * that would make the code complicated and slow. Right now there three
23820  * restrictions:
23821  *
23822  *   1. The first message block must contain the complete IP header and
23823  *	at least 1 byte of payload data.
23824  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23825  *	so that we can use a single Multidata message.
23826  *   3. No frag must be distributed over two or more message blocks so
23827  *	that we don't need more than two packet descriptors per frag.
23828  *
23829  * The above restrictions allow us to support userland applications (which
23830  * will send down a single message block) and NFS over UDP (which will
23831  * send down a chain of at most three message blocks).
23832  *
23833  * We also don't use MDT for payloads with less than or equal to
23834  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23835  */
23836 boolean_t
23837 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23838 {
23839 	int	blocks;
23840 	ssize_t	total, missing, size;
23841 
23842 	ASSERT(mp != NULL);
23843 	ASSERT(hdr_len > 0);
23844 
23845 	size = MBLKL(mp) - hdr_len;
23846 	if (size <= 0)
23847 		return (B_FALSE);
23848 
23849 	/* The first mblk contains the header and some payload. */
23850 	blocks = 1;
23851 	total = size;
23852 	size %= len;
23853 	missing = (size == 0) ? 0 : (len - size);
23854 	mp = mp->b_cont;
23855 
23856 	while (mp != NULL) {
23857 		/*
23858 		 * Give up if we encounter a zero length message block.
23859 		 * In practice, this should rarely happen and therefore
23860 		 * not worth the trouble of freeing and re-linking the
23861 		 * mblk from the chain to handle such case.
23862 		 */
23863 		if ((size = MBLKL(mp)) == 0)
23864 			return (B_FALSE);
23865 
23866 		/* Too many payload buffers for a single Multidata message? */
23867 		if (++blocks > MULTIDATA_MAX_PBUFS)
23868 			return (B_FALSE);
23869 
23870 		total += size;
23871 		/* Is a frag distributed over two or more message blocks? */
23872 		if (missing > size)
23873 			return (B_FALSE);
23874 		size -= missing;
23875 
23876 		size %= len;
23877 		missing = (size == 0) ? 0 : (len - size);
23878 
23879 		mp = mp->b_cont;
23880 	}
23881 
23882 	return (total > ip_wput_frag_mdt_min);
23883 }
23884 
23885 /*
23886  * Outbound IPv4 fragmentation routine using MDT.
23887  */
23888 static void
23889 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23890     uint32_t frag_flag, int offset)
23891 {
23892 	ipha_t		*ipha_orig;
23893 	int		i1, ip_data_end;
23894 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23895 	mblk_t		*hdr_mp, *md_mp = NULL;
23896 	unsigned char	*hdr_ptr, *pld_ptr;
23897 	multidata_t	*mmd;
23898 	ip_pdescinfo_t	pdi;
23899 	ill_t		*ill;
23900 	ip_stack_t	*ipst = ire->ire_ipst;
23901 
23902 	ASSERT(DB_TYPE(mp) == M_DATA);
23903 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23904 
23905 	ill = ire_to_ill(ire);
23906 	ASSERT(ill != NULL);
23907 
23908 	ipha_orig = (ipha_t *)mp->b_rptr;
23909 	mp->b_rptr += sizeof (ipha_t);
23910 
23911 	/* Calculate how many packets we will send out */
23912 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23913 	pkts = (i1 + len - 1) / len;
23914 	ASSERT(pkts > 1);
23915 
23916 	/* Allocate a message block which will hold all the IP Headers. */
23917 	wroff = ipst->ips_ip_wroff_extra;
23918 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23919 
23920 	i1 = pkts * hdr_chunk_len;
23921 	/*
23922 	 * Create the header buffer, Multidata and destination address
23923 	 * and SAP attribute that should be associated with it.
23924 	 */
23925 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23926 	    ((hdr_mp->b_wptr += i1),
23927 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23928 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23929 		freemsg(mp);
23930 		if (md_mp == NULL) {
23931 			freemsg(hdr_mp);
23932 		} else {
23933 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23934 			freemsg(md_mp);
23935 		}
23936 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23937 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23938 		return;
23939 	}
23940 	IP_STAT(ipst, ip_frag_mdt_allocd);
23941 
23942 	/*
23943 	 * Add a payload buffer to the Multidata; this operation must not
23944 	 * fail, or otherwise our logic in this routine is broken.  There
23945 	 * is no memory allocation done by the routine, so any returned
23946 	 * failure simply tells us that we've done something wrong.
23947 	 *
23948 	 * A failure tells us that either we're adding the same payload
23949 	 * buffer more than once, or we're trying to add more buffers than
23950 	 * allowed.  None of the above cases should happen, and we panic
23951 	 * because either there's horrible heap corruption, and/or
23952 	 * programming mistake.
23953 	 */
23954 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23955 		goto pbuf_panic;
23956 
23957 	hdr_ptr = hdr_mp->b_rptr;
23958 	pld_ptr = mp->b_rptr;
23959 
23960 	/* Establish the ending byte offset, based on the starting offset. */
23961 	offset <<= 3;
23962 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23963 	    IP_SIMPLE_HDR_LENGTH;
23964 
23965 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23966 
23967 	while (pld_ptr < mp->b_wptr) {
23968 		ipha_t		*ipha;
23969 		uint16_t	offset_and_flags;
23970 		uint16_t	ip_len;
23971 		int		error;
23972 
23973 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23974 		ipha = (ipha_t *)(hdr_ptr + wroff);
23975 		ASSERT(OK_32PTR(ipha));
23976 		*ipha = *ipha_orig;
23977 
23978 		if (ip_data_end - offset > len) {
23979 			offset_and_flags = IPH_MF;
23980 		} else {
23981 			/*
23982 			 * Last frag. Set len to the length of this last piece.
23983 			 */
23984 			len = ip_data_end - offset;
23985 			/* A frag of a frag might have IPH_MF non-zero */
23986 			offset_and_flags =
23987 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23988 			    IPH_MF;
23989 		}
23990 		offset_and_flags |= (uint16_t)(offset >> 3);
23991 		offset_and_flags |= (uint16_t)frag_flag;
23992 		/* Store the offset and flags in the IP header. */
23993 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23994 
23995 		/* Store the length in the IP header. */
23996 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23997 		ipha->ipha_length = htons(ip_len);
23998 
23999 		/*
24000 		 * Set the IP header checksum.  Note that mp is just
24001 		 * the header, so this is easy to pass to ip_csum.
24002 		 */
24003 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24004 
24005 		/*
24006 		 * Record offset and size of header and data of the next packet
24007 		 * in the multidata message.
24008 		 */
24009 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
24010 		PDESC_PLD_INIT(&pdi);
24011 		i1 = MIN(mp->b_wptr - pld_ptr, len);
24012 		ASSERT(i1 > 0);
24013 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
24014 		if (i1 == len) {
24015 			pld_ptr += len;
24016 		} else {
24017 			i1 = len - i1;
24018 			mp = mp->b_cont;
24019 			ASSERT(mp != NULL);
24020 			ASSERT(MBLKL(mp) >= i1);
24021 			/*
24022 			 * Attach the next payload message block to the
24023 			 * multidata message.
24024 			 */
24025 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24026 				goto pbuf_panic;
24027 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
24028 			pld_ptr = mp->b_rptr + i1;
24029 		}
24030 
24031 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
24032 		    KM_NOSLEEP)) == NULL) {
24033 			/*
24034 			 * Any failure other than ENOMEM indicates that we
24035 			 * have passed in invalid pdesc info or parameters
24036 			 * to mmd_addpdesc, which must not happen.
24037 			 *
24038 			 * EINVAL is a result of failure on boundary checks
24039 			 * against the pdesc info contents.  It should not
24040 			 * happen, and we panic because either there's
24041 			 * horrible heap corruption, and/or programming
24042 			 * mistake.
24043 			 */
24044 			if (error != ENOMEM) {
24045 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
24046 				    "pdesc logic error detected for "
24047 				    "mmd %p pinfo %p (%d)\n",
24048 				    (void *)mmd, (void *)&pdi, error);
24049 				/* NOTREACHED */
24050 			}
24051 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
24052 			/* Free unattached payload message blocks as well */
24053 			md_mp->b_cont = mp->b_cont;
24054 			goto free_mmd;
24055 		}
24056 
24057 		/* Advance fragment offset. */
24058 		offset += len;
24059 
24060 		/* Advance to location for next header in the buffer. */
24061 		hdr_ptr += hdr_chunk_len;
24062 
24063 		/* Did we reach the next payload message block? */
24064 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24065 			mp = mp->b_cont;
24066 			/*
24067 			 * Attach the next message block with payload
24068 			 * data to the multidata message.
24069 			 */
24070 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24071 				goto pbuf_panic;
24072 			pld_ptr = mp->b_rptr;
24073 		}
24074 	}
24075 
24076 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24077 	ASSERT(mp->b_wptr == pld_ptr);
24078 
24079 	/* Update IP statistics */
24080 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24081 
24082 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24083 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24084 
24085 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24086 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24087 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24088 
24089 	if (pkt_type == OB_PKT) {
24090 		ire->ire_ob_pkt_count += pkts;
24091 		if (ire->ire_ipif != NULL)
24092 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24093 	} else {
24094 		/* The type is IB_PKT in the forwarding path. */
24095 		ire->ire_ib_pkt_count += pkts;
24096 		ASSERT(!IRE_IS_LOCAL(ire));
24097 		if (ire->ire_type & IRE_BROADCAST) {
24098 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24099 		} else {
24100 			UPDATE_MIB(ill->ill_ip_mib,
24101 			    ipIfStatsHCOutForwDatagrams, pkts);
24102 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24103 		}
24104 	}
24105 	ire->ire_last_used_time = lbolt;
24106 	/* Send it down */
24107 	putnext(ire->ire_stq, md_mp);
24108 	return;
24109 
24110 pbuf_panic:
24111 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24112 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24113 	    pbuf_idx);
24114 	/* NOTREACHED */
24115 }
24116 
24117 /*
24118  * Outbound IP fragmentation routine.
24119  *
24120  * NOTE : This routine does not ire_refrele the ire that is passed in
24121  * as the argument.
24122  */
24123 static void
24124 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24125     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24126 {
24127 	int		i1;
24128 	mblk_t		*ll_hdr_mp;
24129 	int 		ll_hdr_len;
24130 	int		hdr_len;
24131 	mblk_t		*hdr_mp;
24132 	ipha_t		*ipha;
24133 	int		ip_data_end;
24134 	int		len;
24135 	mblk_t		*mp = mp_orig, *mp1;
24136 	int		offset;
24137 	queue_t		*q;
24138 	uint32_t	v_hlen_tos_len;
24139 	mblk_t		*first_mp;
24140 	boolean_t	mctl_present;
24141 	ill_t		*ill;
24142 	ill_t		*out_ill;
24143 	mblk_t		*xmit_mp;
24144 	mblk_t		*carve_mp;
24145 	ire_t		*ire1 = NULL;
24146 	ire_t		*save_ire = NULL;
24147 	mblk_t  	*next_mp = NULL;
24148 	boolean_t	last_frag = B_FALSE;
24149 	boolean_t	multirt_send = B_FALSE;
24150 	ire_t		*first_ire = NULL;
24151 	irb_t		*irb = NULL;
24152 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24153 
24154 	ill = ire_to_ill(ire);
24155 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24156 
24157 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24158 
24159 	if (max_frag == 0) {
24160 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24161 		    " -  dropping packet\n"));
24162 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24163 		freemsg(mp);
24164 		return;
24165 	}
24166 
24167 	/*
24168 	 * IPsec does not allow hw accelerated packets to be fragmented
24169 	 * This check is made in ip_wput_ipsec_out prior to coming here
24170 	 * via ip_wput_ire_fragmentit.
24171 	 *
24172 	 * If at this point we have an ire whose ARP request has not
24173 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24174 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24175 	 * This packet and all fragmentable packets for this ire will
24176 	 * continue to get dropped while ire_nce->nce_state remains in
24177 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24178 	 * ND_REACHABLE, all subsquent large packets for this ire will
24179 	 * get fragemented and sent out by this function.
24180 	 */
24181 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24182 		/* If nce_state is ND_INITIAL, trigger ARP query */
24183 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24184 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24185 		    " -  dropping packet\n"));
24186 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24187 		freemsg(mp);
24188 		return;
24189 	}
24190 
24191 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24192 	    "ip_wput_frag_start:");
24193 
24194 	if (mp->b_datap->db_type == M_CTL) {
24195 		first_mp = mp;
24196 		mp_orig = mp = mp->b_cont;
24197 		mctl_present = B_TRUE;
24198 	} else {
24199 		first_mp = mp;
24200 		mctl_present = B_FALSE;
24201 	}
24202 
24203 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24204 	ipha = (ipha_t *)mp->b_rptr;
24205 
24206 	/*
24207 	 * If the Don't Fragment flag is on, generate an ICMP destination
24208 	 * unreachable, fragmentation needed.
24209 	 */
24210 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24211 	if (offset & IPH_DF) {
24212 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24213 		if (is_system_labeled()) {
24214 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24215 			    ire->ire_max_frag - max_frag, AF_INET);
24216 		}
24217 		/*
24218 		 * Need to compute hdr checksum if called from ip_wput_ire.
24219 		 * Note that ip_rput_forward verifies the checksum before
24220 		 * calling this routine so in that case this is a noop.
24221 		 */
24222 		ipha->ipha_hdr_checksum = 0;
24223 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24224 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24225 		    ipst);
24226 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24227 		    "ip_wput_frag_end:(%S)",
24228 		    "don't fragment");
24229 		return;
24230 	}
24231 	/*
24232 	 * Labeled systems adjust max_frag if they add a label
24233 	 * to send the correct path mtu.  We need the real mtu since we
24234 	 * are fragmenting the packet after label adjustment.
24235 	 */
24236 	if (is_system_labeled())
24237 		max_frag = ire->ire_max_frag;
24238 	if (mctl_present)
24239 		freeb(first_mp);
24240 	/*
24241 	 * Establish the starting offset.  May not be zero if we are fragging
24242 	 * a fragment that is being forwarded.
24243 	 */
24244 	offset = offset & IPH_OFFSET;
24245 
24246 	/* TODO why is this test needed? */
24247 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24248 	if (((max_frag - LENGTH) & ~7) < 8) {
24249 		/* TODO: notify ulp somehow */
24250 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24251 		freemsg(mp);
24252 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24253 		    "ip_wput_frag_end:(%S)",
24254 		    "len < 8");
24255 		return;
24256 	}
24257 
24258 	hdr_len = (V_HLEN & 0xF) << 2;
24259 
24260 	ipha->ipha_hdr_checksum = 0;
24261 
24262 	/*
24263 	 * Establish the number of bytes maximum per frag, after putting
24264 	 * in the header.
24265 	 */
24266 	len = (max_frag - hdr_len) & ~7;
24267 
24268 	/* Check if we can use MDT to send out the frags. */
24269 	ASSERT(!IRE_IS_LOCAL(ire));
24270 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24271 	    ipst->ips_ip_multidata_outbound &&
24272 	    !(ire->ire_flags & RTF_MULTIRT) &&
24273 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24274 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24275 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24276 		ASSERT(ill->ill_mdt_capab != NULL);
24277 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24278 			/*
24279 			 * If MDT has been previously turned off in the past,
24280 			 * and we currently can do MDT (due to IPQoS policy
24281 			 * removal, etc.) then enable it for this interface.
24282 			 */
24283 			ill->ill_mdt_capab->ill_mdt_on = 1;
24284 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24285 			    ill->ill_name));
24286 		}
24287 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24288 		    offset);
24289 		return;
24290 	}
24291 
24292 	/* Get a copy of the header for the trailing frags */
24293 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24294 	if (!hdr_mp) {
24295 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24296 		freemsg(mp);
24297 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24298 		    "ip_wput_frag_end:(%S)",
24299 		    "couldn't copy hdr");
24300 		return;
24301 	}
24302 	if (DB_CRED(mp) != NULL)
24303 		mblk_setcred(hdr_mp, DB_CRED(mp));
24304 
24305 	/* Store the starting offset, with the MoreFrags flag. */
24306 	i1 = offset | IPH_MF | frag_flag;
24307 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24308 
24309 	/* Establish the ending byte offset, based on the starting offset. */
24310 	offset <<= 3;
24311 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24312 
24313 	/* Store the length of the first fragment in the IP header. */
24314 	i1 = len + hdr_len;
24315 	ASSERT(i1 <= IP_MAXPACKET);
24316 	ipha->ipha_length = htons((uint16_t)i1);
24317 
24318 	/*
24319 	 * Compute the IP header checksum for the first frag.  We have to
24320 	 * watch out that we stop at the end of the header.
24321 	 */
24322 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24323 
24324 	/*
24325 	 * Now carve off the first frag.  Note that this will include the
24326 	 * original IP header.
24327 	 */
24328 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24329 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24330 		freeb(hdr_mp);
24331 		freemsg(mp_orig);
24332 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24333 		    "ip_wput_frag_end:(%S)",
24334 		    "couldn't carve first");
24335 		return;
24336 	}
24337 
24338 	/*
24339 	 * Multirouting case. Each fragment is replicated
24340 	 * via all non-condemned RTF_MULTIRT routes
24341 	 * currently resolved.
24342 	 * We ensure that first_ire is the first RTF_MULTIRT
24343 	 * ire in the bucket.
24344 	 */
24345 	if (ire->ire_flags & RTF_MULTIRT) {
24346 		irb = ire->ire_bucket;
24347 		ASSERT(irb != NULL);
24348 
24349 		multirt_send = B_TRUE;
24350 
24351 		/* Make sure we do not omit any multiroute ire. */
24352 		IRB_REFHOLD(irb);
24353 		for (first_ire = irb->irb_ire;
24354 		    first_ire != NULL;
24355 		    first_ire = first_ire->ire_next) {
24356 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24357 			    (first_ire->ire_addr == ire->ire_addr) &&
24358 			    !(first_ire->ire_marks &
24359 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24360 				break;
24361 			}
24362 		}
24363 
24364 		if (first_ire != NULL) {
24365 			if (first_ire != ire) {
24366 				IRE_REFHOLD(first_ire);
24367 				/*
24368 				 * Do not release the ire passed in
24369 				 * as the argument.
24370 				 */
24371 				ire = first_ire;
24372 			} else {
24373 				first_ire = NULL;
24374 			}
24375 		}
24376 		IRB_REFRELE(irb);
24377 
24378 		/*
24379 		 * Save the first ire; we will need to restore it
24380 		 * for the trailing frags.
24381 		 * We REFHOLD save_ire, as each iterated ire will be
24382 		 * REFRELEd.
24383 		 */
24384 		save_ire = ire;
24385 		IRE_REFHOLD(save_ire);
24386 	}
24387 
24388 	/*
24389 	 * First fragment emission loop.
24390 	 * In most cases, the emission loop below is entered only
24391 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24392 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24393 	 * bucket, and send the fragment through all crossed
24394 	 * RTF_MULTIRT routes.
24395 	 */
24396 	do {
24397 		if (ire->ire_flags & RTF_MULTIRT) {
24398 			/*
24399 			 * We are in a multiple send case, need to get
24400 			 * the next ire and make a copy of the packet.
24401 			 * ire1 holds here the next ire to process in the
24402 			 * bucket. If multirouting is expected,
24403 			 * any non-RTF_MULTIRT ire that has the
24404 			 * right destination address is ignored.
24405 			 *
24406 			 * We have to take into account the MTU of
24407 			 * each walked ire. max_frag is set by the
24408 			 * the caller and generally refers to
24409 			 * the primary ire entry. Here we ensure that
24410 			 * no route with a lower MTU will be used, as
24411 			 * fragments are carved once for all ires,
24412 			 * then replicated.
24413 			 */
24414 			ASSERT(irb != NULL);
24415 			IRB_REFHOLD(irb);
24416 			for (ire1 = ire->ire_next;
24417 			    ire1 != NULL;
24418 			    ire1 = ire1->ire_next) {
24419 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24420 					continue;
24421 				if (ire1->ire_addr != ire->ire_addr)
24422 					continue;
24423 				if (ire1->ire_marks &
24424 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24425 					continue;
24426 				/*
24427 				 * Ensure we do not exceed the MTU
24428 				 * of the next route.
24429 				 */
24430 				if (ire1->ire_max_frag < max_frag) {
24431 					ip_multirt_bad_mtu(ire1, max_frag);
24432 					continue;
24433 				}
24434 
24435 				/* Got one. */
24436 				IRE_REFHOLD(ire1);
24437 				break;
24438 			}
24439 			IRB_REFRELE(irb);
24440 
24441 			if (ire1 != NULL) {
24442 				next_mp = copyb(mp);
24443 				if ((next_mp == NULL) ||
24444 				    ((mp->b_cont != NULL) &&
24445 				    ((next_mp->b_cont =
24446 				    dupmsg(mp->b_cont)) == NULL))) {
24447 					freemsg(next_mp);
24448 					next_mp = NULL;
24449 					ire_refrele(ire1);
24450 					ire1 = NULL;
24451 				}
24452 			}
24453 
24454 			/* Last multiroute ire; don't loop anymore. */
24455 			if (ire1 == NULL) {
24456 				multirt_send = B_FALSE;
24457 			}
24458 		}
24459 
24460 		ll_hdr_len = 0;
24461 		LOCK_IRE_FP_MP(ire);
24462 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24463 		if (ll_hdr_mp != NULL) {
24464 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24465 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24466 		} else {
24467 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24468 		}
24469 
24470 		/* If there is a transmit header, get a copy for this frag. */
24471 		/*
24472 		 * TODO: should check db_ref before calling ip_carve_mp since
24473 		 * it might give us a dup.
24474 		 */
24475 		if (!ll_hdr_mp) {
24476 			/* No xmit header. */
24477 			xmit_mp = mp;
24478 
24479 		/* We have a link-layer header that can fit in our mblk. */
24480 		} else if (mp->b_datap->db_ref == 1 &&
24481 		    ll_hdr_len != 0 &&
24482 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24483 			/* M_DATA fastpath */
24484 			mp->b_rptr -= ll_hdr_len;
24485 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24486 			xmit_mp = mp;
24487 
24488 		/* Corner case if copyb has failed */
24489 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24490 			UNLOCK_IRE_FP_MP(ire);
24491 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24492 			freeb(hdr_mp);
24493 			freemsg(mp);
24494 			freemsg(mp_orig);
24495 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24496 			    "ip_wput_frag_end:(%S)",
24497 			    "discard");
24498 
24499 			if (multirt_send) {
24500 				ASSERT(ire1);
24501 				ASSERT(next_mp);
24502 
24503 				freemsg(next_mp);
24504 				ire_refrele(ire1);
24505 			}
24506 			if (save_ire != NULL)
24507 				IRE_REFRELE(save_ire);
24508 
24509 			if (first_ire != NULL)
24510 				ire_refrele(first_ire);
24511 			return;
24512 
24513 		/*
24514 		 * Case of res_mp OR the fastpath mp can't fit
24515 		 * in the mblk
24516 		 */
24517 		} else {
24518 			xmit_mp->b_cont = mp;
24519 			if (DB_CRED(mp) != NULL)
24520 				mblk_setcred(xmit_mp, DB_CRED(mp));
24521 			/*
24522 			 * Get priority marking, if any.
24523 			 * We propagate the CoS marking from the
24524 			 * original packet that went to QoS processing
24525 			 * in ip_wput_ire to the newly carved mp.
24526 			 */
24527 			if (DB_TYPE(xmit_mp) == M_DATA)
24528 				xmit_mp->b_band = mp->b_band;
24529 		}
24530 		UNLOCK_IRE_FP_MP(ire);
24531 
24532 		q = ire->ire_stq;
24533 		out_ill = (ill_t *)q->q_ptr;
24534 
24535 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24536 
24537 		DTRACE_PROBE4(ip4__physical__out__start,
24538 		    ill_t *, NULL, ill_t *, out_ill,
24539 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24540 
24541 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24542 		    ipst->ips_ipv4firewall_physical_out,
24543 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24544 
24545 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24546 
24547 		if (xmit_mp != NULL) {
24548 			putnext(q, xmit_mp);
24549 
24550 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24551 			UPDATE_MIB(out_ill->ill_ip_mib,
24552 			    ipIfStatsHCOutOctets, i1);
24553 
24554 			if (pkt_type != OB_PKT) {
24555 				/*
24556 				 * Update the packet count and MIB stats
24557 				 * of trailing RTF_MULTIRT ires.
24558 				 */
24559 				UPDATE_OB_PKT_COUNT(ire);
24560 				BUMP_MIB(out_ill->ill_ip_mib,
24561 				    ipIfStatsOutFragReqds);
24562 			}
24563 		}
24564 
24565 		if (multirt_send) {
24566 			/*
24567 			 * We are in a multiple send case; look for
24568 			 * the next ire and re-enter the loop.
24569 			 */
24570 			ASSERT(ire1);
24571 			ASSERT(next_mp);
24572 			/* REFRELE the current ire before looping */
24573 			ire_refrele(ire);
24574 			ire = ire1;
24575 			ire1 = NULL;
24576 			mp = next_mp;
24577 			next_mp = NULL;
24578 		}
24579 	} while (multirt_send);
24580 
24581 	ASSERT(ire1 == NULL);
24582 
24583 	/* Restore the original ire; we need it for the trailing frags */
24584 	if (save_ire != NULL) {
24585 		/* REFRELE the last iterated ire */
24586 		ire_refrele(ire);
24587 		/* save_ire has been REFHOLDed */
24588 		ire = save_ire;
24589 		save_ire = NULL;
24590 		q = ire->ire_stq;
24591 	}
24592 
24593 	if (pkt_type == OB_PKT) {
24594 		UPDATE_OB_PKT_COUNT(ire);
24595 	} else {
24596 		out_ill = (ill_t *)q->q_ptr;
24597 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24598 		UPDATE_IB_PKT_COUNT(ire);
24599 	}
24600 
24601 	/* Advance the offset to the second frag starting point. */
24602 	offset += len;
24603 	/*
24604 	 * Update hdr_len from the copied header - there might be less options
24605 	 * in the later fragments.
24606 	 */
24607 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24608 	/* Loop until done. */
24609 	for (;;) {
24610 		uint16_t	offset_and_flags;
24611 		uint16_t	ip_len;
24612 
24613 		if (ip_data_end - offset > len) {
24614 			/*
24615 			 * Carve off the appropriate amount from the original
24616 			 * datagram.
24617 			 */
24618 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24619 				mp = NULL;
24620 				break;
24621 			}
24622 			/*
24623 			 * More frags after this one.  Get another copy
24624 			 * of the header.
24625 			 */
24626 			if (carve_mp->b_datap->db_ref == 1 &&
24627 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24628 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24629 				/* Inline IP header */
24630 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24631 				    hdr_mp->b_rptr;
24632 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24633 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24634 				mp = carve_mp;
24635 			} else {
24636 				if (!(mp = copyb(hdr_mp))) {
24637 					freemsg(carve_mp);
24638 					break;
24639 				}
24640 				/* Get priority marking, if any. */
24641 				mp->b_band = carve_mp->b_band;
24642 				mp->b_cont = carve_mp;
24643 			}
24644 			ipha = (ipha_t *)mp->b_rptr;
24645 			offset_and_flags = IPH_MF;
24646 		} else {
24647 			/*
24648 			 * Last frag.  Consume the header. Set len to
24649 			 * the length of this last piece.
24650 			 */
24651 			len = ip_data_end - offset;
24652 
24653 			/*
24654 			 * Carve off the appropriate amount from the original
24655 			 * datagram.
24656 			 */
24657 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24658 				mp = NULL;
24659 				break;
24660 			}
24661 			if (carve_mp->b_datap->db_ref == 1 &&
24662 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24663 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24664 				/* Inline IP header */
24665 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24666 				    hdr_mp->b_rptr;
24667 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24668 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24669 				mp = carve_mp;
24670 				freeb(hdr_mp);
24671 				hdr_mp = mp;
24672 			} else {
24673 				mp = hdr_mp;
24674 				/* Get priority marking, if any. */
24675 				mp->b_band = carve_mp->b_band;
24676 				mp->b_cont = carve_mp;
24677 			}
24678 			ipha = (ipha_t *)mp->b_rptr;
24679 			/* A frag of a frag might have IPH_MF non-zero */
24680 			offset_and_flags =
24681 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24682 			    IPH_MF;
24683 		}
24684 		offset_and_flags |= (uint16_t)(offset >> 3);
24685 		offset_and_flags |= (uint16_t)frag_flag;
24686 		/* Store the offset and flags in the IP header. */
24687 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24688 
24689 		/* Store the length in the IP header. */
24690 		ip_len = (uint16_t)(len + hdr_len);
24691 		ipha->ipha_length = htons(ip_len);
24692 
24693 		/*
24694 		 * Set the IP header checksum.	Note that mp is just
24695 		 * the header, so this is easy to pass to ip_csum.
24696 		 */
24697 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24698 
24699 		/* Attach a transmit header, if any, and ship it. */
24700 		if (pkt_type == OB_PKT) {
24701 			UPDATE_OB_PKT_COUNT(ire);
24702 		} else {
24703 			out_ill = (ill_t *)q->q_ptr;
24704 			BUMP_MIB(out_ill->ill_ip_mib,
24705 			    ipIfStatsHCOutForwDatagrams);
24706 			UPDATE_IB_PKT_COUNT(ire);
24707 		}
24708 
24709 		if (ire->ire_flags & RTF_MULTIRT) {
24710 			irb = ire->ire_bucket;
24711 			ASSERT(irb != NULL);
24712 
24713 			multirt_send = B_TRUE;
24714 
24715 			/*
24716 			 * Save the original ire; we will need to restore it
24717 			 * for the tailing frags.
24718 			 */
24719 			save_ire = ire;
24720 			IRE_REFHOLD(save_ire);
24721 		}
24722 		/*
24723 		 * Emission loop for this fragment, similar
24724 		 * to what is done for the first fragment.
24725 		 */
24726 		do {
24727 			if (multirt_send) {
24728 				/*
24729 				 * We are in a multiple send case, need to get
24730 				 * the next ire and make a copy of the packet.
24731 				 */
24732 				ASSERT(irb != NULL);
24733 				IRB_REFHOLD(irb);
24734 				for (ire1 = ire->ire_next;
24735 				    ire1 != NULL;
24736 				    ire1 = ire1->ire_next) {
24737 					if (!(ire1->ire_flags & RTF_MULTIRT))
24738 						continue;
24739 					if (ire1->ire_addr != ire->ire_addr)
24740 						continue;
24741 					if (ire1->ire_marks &
24742 					    (IRE_MARK_CONDEMNED|
24743 					    IRE_MARK_HIDDEN)) {
24744 						continue;
24745 					}
24746 					/*
24747 					 * Ensure we do not exceed the MTU
24748 					 * of the next route.
24749 					 */
24750 					if (ire1->ire_max_frag < max_frag) {
24751 						ip_multirt_bad_mtu(ire1,
24752 						    max_frag);
24753 						continue;
24754 					}
24755 
24756 					/* Got one. */
24757 					IRE_REFHOLD(ire1);
24758 					break;
24759 				}
24760 				IRB_REFRELE(irb);
24761 
24762 				if (ire1 != NULL) {
24763 					next_mp = copyb(mp);
24764 					if ((next_mp == NULL) ||
24765 					    ((mp->b_cont != NULL) &&
24766 					    ((next_mp->b_cont =
24767 					    dupmsg(mp->b_cont)) == NULL))) {
24768 						freemsg(next_mp);
24769 						next_mp = NULL;
24770 						ire_refrele(ire1);
24771 						ire1 = NULL;
24772 					}
24773 				}
24774 
24775 				/* Last multiroute ire; don't loop anymore. */
24776 				if (ire1 == NULL) {
24777 					multirt_send = B_FALSE;
24778 				}
24779 			}
24780 
24781 			/* Update transmit header */
24782 			ll_hdr_len = 0;
24783 			LOCK_IRE_FP_MP(ire);
24784 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24785 			if (ll_hdr_mp != NULL) {
24786 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24787 				ll_hdr_len = MBLKL(ll_hdr_mp);
24788 			} else {
24789 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24790 			}
24791 
24792 			if (!ll_hdr_mp) {
24793 				xmit_mp = mp;
24794 
24795 			/*
24796 			 * We have link-layer header that can fit in
24797 			 * our mblk.
24798 			 */
24799 			} else if (mp->b_datap->db_ref == 1 &&
24800 			    ll_hdr_len != 0 &&
24801 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24802 				/* M_DATA fastpath */
24803 				mp->b_rptr -= ll_hdr_len;
24804 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24805 				    ll_hdr_len);
24806 				xmit_mp = mp;
24807 
24808 			/*
24809 			 * Case of res_mp OR the fastpath mp can't fit
24810 			 * in the mblk
24811 			 */
24812 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24813 				xmit_mp->b_cont = mp;
24814 				if (DB_CRED(mp) != NULL)
24815 					mblk_setcred(xmit_mp, DB_CRED(mp));
24816 				/* Get priority marking, if any. */
24817 				if (DB_TYPE(xmit_mp) == M_DATA)
24818 					xmit_mp->b_band = mp->b_band;
24819 
24820 			/* Corner case if copyb failed */
24821 			} else {
24822 				/*
24823 				 * Exit both the replication and
24824 				 * fragmentation loops.
24825 				 */
24826 				UNLOCK_IRE_FP_MP(ire);
24827 				goto drop_pkt;
24828 			}
24829 			UNLOCK_IRE_FP_MP(ire);
24830 
24831 			mp1 = mp;
24832 			out_ill = (ill_t *)q->q_ptr;
24833 
24834 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24835 
24836 			DTRACE_PROBE4(ip4__physical__out__start,
24837 			    ill_t *, NULL, ill_t *, out_ill,
24838 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24839 
24840 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24841 			    ipst->ips_ipv4firewall_physical_out,
24842 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24843 
24844 			DTRACE_PROBE1(ip4__physical__out__end,
24845 			    mblk_t *, xmit_mp);
24846 
24847 			if (mp != mp1 && hdr_mp == mp1)
24848 				hdr_mp = mp;
24849 			if (mp != mp1 && mp_orig == mp1)
24850 				mp_orig = mp;
24851 
24852 			if (xmit_mp != NULL) {
24853 				putnext(q, xmit_mp);
24854 
24855 				BUMP_MIB(out_ill->ill_ip_mib,
24856 				    ipIfStatsHCOutTransmits);
24857 				UPDATE_MIB(out_ill->ill_ip_mib,
24858 				    ipIfStatsHCOutOctets, ip_len);
24859 
24860 				if (pkt_type != OB_PKT) {
24861 					/*
24862 					 * Update the packet count of trailing
24863 					 * RTF_MULTIRT ires.
24864 					 */
24865 					UPDATE_OB_PKT_COUNT(ire);
24866 				}
24867 			}
24868 
24869 			/* All done if we just consumed the hdr_mp. */
24870 			if (mp == hdr_mp) {
24871 				last_frag = B_TRUE;
24872 				BUMP_MIB(out_ill->ill_ip_mib,
24873 				    ipIfStatsOutFragOKs);
24874 			}
24875 
24876 			if (multirt_send) {
24877 				/*
24878 				 * We are in a multiple send case; look for
24879 				 * the next ire and re-enter the loop.
24880 				 */
24881 				ASSERT(ire1);
24882 				ASSERT(next_mp);
24883 				/* REFRELE the current ire before looping */
24884 				ire_refrele(ire);
24885 				ire = ire1;
24886 				ire1 = NULL;
24887 				q = ire->ire_stq;
24888 				mp = next_mp;
24889 				next_mp = NULL;
24890 			}
24891 		} while (multirt_send);
24892 		/*
24893 		 * Restore the original ire; we need it for the
24894 		 * trailing frags
24895 		 */
24896 		if (save_ire != NULL) {
24897 			ASSERT(ire1 == NULL);
24898 			/* REFRELE the last iterated ire */
24899 			ire_refrele(ire);
24900 			/* save_ire has been REFHOLDed */
24901 			ire = save_ire;
24902 			q = ire->ire_stq;
24903 			save_ire = NULL;
24904 		}
24905 
24906 		if (last_frag) {
24907 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24908 			    "ip_wput_frag_end:(%S)",
24909 			    "consumed hdr_mp");
24910 
24911 			if (first_ire != NULL)
24912 				ire_refrele(first_ire);
24913 			return;
24914 		}
24915 		/* Otherwise, advance and loop. */
24916 		offset += len;
24917 	}
24918 
24919 drop_pkt:
24920 	/* Clean up following allocation failure. */
24921 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24922 	freemsg(mp);
24923 	if (mp != hdr_mp)
24924 		freeb(hdr_mp);
24925 	if (mp != mp_orig)
24926 		freemsg(mp_orig);
24927 
24928 	if (save_ire != NULL)
24929 		IRE_REFRELE(save_ire);
24930 	if (first_ire != NULL)
24931 		ire_refrele(first_ire);
24932 
24933 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24934 	    "ip_wput_frag_end:(%S)",
24935 	    "end--alloc failure");
24936 }
24937 
24938 /*
24939  * Copy the header plus those options which have the copy bit set
24940  */
24941 static mblk_t *
24942 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24943 {
24944 	mblk_t	*mp;
24945 	uchar_t	*up;
24946 
24947 	/*
24948 	 * Quick check if we need to look for options without the copy bit
24949 	 * set
24950 	 */
24951 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24952 	if (!mp)
24953 		return (mp);
24954 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24955 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24956 		bcopy(rptr, mp->b_rptr, hdr_len);
24957 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24958 		return (mp);
24959 	}
24960 	up  = mp->b_rptr;
24961 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24962 	up += IP_SIMPLE_HDR_LENGTH;
24963 	rptr += IP_SIMPLE_HDR_LENGTH;
24964 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24965 	while (hdr_len > 0) {
24966 		uint32_t optval;
24967 		uint32_t optlen;
24968 
24969 		optval = *rptr;
24970 		if (optval == IPOPT_EOL)
24971 			break;
24972 		if (optval == IPOPT_NOP)
24973 			optlen = 1;
24974 		else
24975 			optlen = rptr[1];
24976 		if (optval & IPOPT_COPY) {
24977 			bcopy(rptr, up, optlen);
24978 			up += optlen;
24979 		}
24980 		rptr += optlen;
24981 		hdr_len -= optlen;
24982 	}
24983 	/*
24984 	 * Make sure that we drop an even number of words by filling
24985 	 * with EOL to the next word boundary.
24986 	 */
24987 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24988 	    hdr_len & 0x3; hdr_len++)
24989 		*up++ = IPOPT_EOL;
24990 	mp->b_wptr = up;
24991 	/* Update header length */
24992 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24993 	return (mp);
24994 }
24995 
24996 /*
24997  * Delivery to local recipients including fanout to multiple recipients.
24998  * Does not do checksumming of UDP/TCP.
24999  * Note: q should be the read side queue for either the ill or conn.
25000  * Note: rq should be the read side q for the lower (ill) stream.
25001  * We don't send packets to IPPF processing, thus the last argument
25002  * to all the fanout calls are B_FALSE.
25003  */
25004 void
25005 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
25006     int fanout_flags, zoneid_t zoneid)
25007 {
25008 	uint32_t	protocol;
25009 	mblk_t		*first_mp;
25010 	boolean_t	mctl_present;
25011 	int		ire_type;
25012 #define	rptr	((uchar_t *)ipha)
25013 	ip_stack_t	*ipst = ill->ill_ipst;
25014 
25015 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
25016 	    "ip_wput_local_start: q %p", q);
25017 
25018 	if (ire != NULL) {
25019 		ire_type = ire->ire_type;
25020 	} else {
25021 		/*
25022 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
25023 		 * packet is not multicast, we can't tell the ire type.
25024 		 */
25025 		ASSERT(CLASSD(ipha->ipha_dst));
25026 		ire_type = IRE_BROADCAST;
25027 	}
25028 
25029 	first_mp = mp;
25030 	if (first_mp->b_datap->db_type == M_CTL) {
25031 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
25032 		if (!io->ipsec_out_secure) {
25033 			/*
25034 			 * This ipsec_out_t was allocated in ip_wput
25035 			 * for multicast packets to store the ill_index.
25036 			 * As this is being delivered locally, we don't
25037 			 * need this anymore.
25038 			 */
25039 			mp = first_mp->b_cont;
25040 			freeb(first_mp);
25041 			first_mp = mp;
25042 			mctl_present = B_FALSE;
25043 		} else {
25044 			/*
25045 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
25046 			 * security properties for the looped-back packet.
25047 			 */
25048 			mctl_present = B_TRUE;
25049 			mp = first_mp->b_cont;
25050 			ASSERT(mp != NULL);
25051 			ipsec_out_to_in(first_mp);
25052 		}
25053 	} else {
25054 		mctl_present = B_FALSE;
25055 	}
25056 
25057 	DTRACE_PROBE4(ip4__loopback__in__start,
25058 	    ill_t *, ill, ill_t *, NULL,
25059 	    ipha_t *, ipha, mblk_t *, first_mp);
25060 
25061 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25062 	    ipst->ips_ipv4firewall_loopback_in,
25063 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25064 
25065 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25066 
25067 	if (first_mp == NULL)
25068 		return;
25069 
25070 	ipst->ips_loopback_packets++;
25071 
25072 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25073 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25074 	if (!IS_SIMPLE_IPH(ipha)) {
25075 		ip_wput_local_options(ipha, ipst);
25076 	}
25077 
25078 	protocol = ipha->ipha_protocol;
25079 	switch (protocol) {
25080 	case IPPROTO_ICMP: {
25081 		ire_t		*ire_zone;
25082 		ilm_t		*ilm;
25083 		mblk_t		*mp1;
25084 		zoneid_t	last_zoneid;
25085 
25086 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25087 			ASSERT(ire_type == IRE_BROADCAST);
25088 			/*
25089 			 * In the multicast case, applications may have joined
25090 			 * the group from different zones, so we need to deliver
25091 			 * the packet to each of them. Loop through the
25092 			 * multicast memberships structures (ilm) on the receive
25093 			 * ill and send a copy of the packet up each matching
25094 			 * one. However, we don't do this for multicasts sent on
25095 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25096 			 * they must stay in the sender's zone.
25097 			 *
25098 			 * ilm_add_v6() ensures that ilms in the same zone are
25099 			 * contiguous in the ill_ilm list. We use this property
25100 			 * to avoid sending duplicates needed when two
25101 			 * applications in the same zone join the same group on
25102 			 * different logical interfaces: we ignore the ilm if
25103 			 * it's zoneid is the same as the last matching one.
25104 			 * In addition, the sending of the packet for
25105 			 * ire_zoneid is delayed until all of the other ilms
25106 			 * have been exhausted.
25107 			 */
25108 			last_zoneid = -1;
25109 			ILM_WALKER_HOLD(ill);
25110 			for (ilm = ill->ill_ilm; ilm != NULL;
25111 			    ilm = ilm->ilm_next) {
25112 				if ((ilm->ilm_flags & ILM_DELETED) ||
25113 				    ipha->ipha_dst != ilm->ilm_addr ||
25114 				    ilm->ilm_zoneid == last_zoneid ||
25115 				    ilm->ilm_zoneid == zoneid ||
25116 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25117 					continue;
25118 				mp1 = ip_copymsg(first_mp);
25119 				if (mp1 == NULL)
25120 					continue;
25121 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25122 				    mctl_present, B_FALSE, ill,
25123 				    ilm->ilm_zoneid);
25124 				last_zoneid = ilm->ilm_zoneid;
25125 			}
25126 			ILM_WALKER_RELE(ill);
25127 			/*
25128 			 * Loopback case: the sending endpoint has
25129 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25130 			 * dispatch the multicast packet to the sending zone.
25131 			 */
25132 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25133 				freemsg(first_mp);
25134 				return;
25135 			}
25136 		} else if (ire_type == IRE_BROADCAST) {
25137 			/*
25138 			 * In the broadcast case, there may be many zones
25139 			 * which need a copy of the packet delivered to them.
25140 			 * There is one IRE_BROADCAST per broadcast address
25141 			 * and per zone; we walk those using a helper function.
25142 			 * In addition, the sending of the packet for zoneid is
25143 			 * delayed until all of the other ires have been
25144 			 * processed.
25145 			 */
25146 			IRB_REFHOLD(ire->ire_bucket);
25147 			ire_zone = NULL;
25148 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25149 			    ire)) != NULL) {
25150 				mp1 = ip_copymsg(first_mp);
25151 				if (mp1 == NULL)
25152 					continue;
25153 
25154 				UPDATE_IB_PKT_COUNT(ire_zone);
25155 				ire_zone->ire_last_used_time = lbolt;
25156 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25157 				    mctl_present, B_FALSE, ill,
25158 				    ire_zone->ire_zoneid);
25159 			}
25160 			IRB_REFRELE(ire->ire_bucket);
25161 		}
25162 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25163 		    0, mctl_present, B_FALSE, ill, zoneid);
25164 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25165 		    "ip_wput_local_end: q %p (%S)",
25166 		    q, "icmp");
25167 		return;
25168 	}
25169 	case IPPROTO_IGMP:
25170 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25171 			/* Bad packet - discarded by igmp_input */
25172 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25173 			    "ip_wput_local_end: q %p (%S)",
25174 			    q, "igmp_input--bad packet");
25175 			if (mctl_present)
25176 				freeb(first_mp);
25177 			return;
25178 		}
25179 		/*
25180 		 * igmp_input() may have returned the pulled up message.
25181 		 * So first_mp and ipha need to be reinitialized.
25182 		 */
25183 		ipha = (ipha_t *)mp->b_rptr;
25184 		if (mctl_present)
25185 			first_mp->b_cont = mp;
25186 		else
25187 			first_mp = mp;
25188 		/* deliver to local raw users */
25189 		break;
25190 	case IPPROTO_ENCAP:
25191 		/*
25192 		 * This case is covered by either ip_fanout_proto, or by
25193 		 * the above security processing for self-tunneled packets.
25194 		 */
25195 		break;
25196 	case IPPROTO_UDP: {
25197 		uint16_t	*up;
25198 		uint32_t	ports;
25199 
25200 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25201 		    UDP_PORTS_OFFSET);
25202 		/* Force a 'valid' checksum. */
25203 		up[3] = 0;
25204 
25205 		ports = *(uint32_t *)up;
25206 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25207 		    (ire_type == IRE_BROADCAST),
25208 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25209 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25210 		    ill, zoneid);
25211 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25212 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25213 		return;
25214 	}
25215 	case IPPROTO_TCP: {
25216 
25217 		/*
25218 		 * For TCP, discard broadcast packets.
25219 		 */
25220 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25221 			freemsg(first_mp);
25222 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25223 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25224 			return;
25225 		}
25226 
25227 		if (mp->b_datap->db_type == M_DATA) {
25228 			/*
25229 			 * M_DATA mblk, so init mblk (chain) for no struio().
25230 			 */
25231 			mblk_t	*mp1 = mp;
25232 
25233 			do {
25234 				mp1->b_datap->db_struioflag = 0;
25235 			} while ((mp1 = mp1->b_cont) != NULL);
25236 		}
25237 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25238 		    <= mp->b_wptr);
25239 		ip_fanout_tcp(q, first_mp, ill, ipha,
25240 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25241 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25242 		    mctl_present, B_FALSE, zoneid);
25243 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25244 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25245 		return;
25246 	}
25247 	case IPPROTO_SCTP:
25248 	{
25249 		uint32_t	ports;
25250 
25251 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25252 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25253 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25254 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25255 		return;
25256 	}
25257 
25258 	default:
25259 		break;
25260 	}
25261 	/*
25262 	 * Find a client for some other protocol.  We give
25263 	 * copies to multiple clients, if more than one is
25264 	 * bound.
25265 	 */
25266 	ip_fanout_proto(q, first_mp, ill, ipha,
25267 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25268 	    mctl_present, B_FALSE, ill, zoneid);
25269 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25270 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25271 #undef	rptr
25272 }
25273 
25274 /*
25275  * Update any source route, record route, or timestamp options.
25276  * Check that we are at end of strict source route.
25277  * The options have been sanity checked by ip_wput_options().
25278  */
25279 static void
25280 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25281 {
25282 	ipoptp_t	opts;
25283 	uchar_t		*opt;
25284 	uint8_t		optval;
25285 	uint8_t		optlen;
25286 	ipaddr_t	dst;
25287 	uint32_t	ts;
25288 	ire_t		*ire;
25289 	timestruc_t	now;
25290 
25291 	ip2dbg(("ip_wput_local_options\n"));
25292 	for (optval = ipoptp_first(&opts, ipha);
25293 	    optval != IPOPT_EOL;
25294 	    optval = ipoptp_next(&opts)) {
25295 		opt = opts.ipoptp_cur;
25296 		optlen = opts.ipoptp_len;
25297 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25298 		switch (optval) {
25299 			uint32_t off;
25300 		case IPOPT_SSRR:
25301 		case IPOPT_LSRR:
25302 			off = opt[IPOPT_OFFSET];
25303 			off--;
25304 			if (optlen < IP_ADDR_LEN ||
25305 			    off > optlen - IP_ADDR_LEN) {
25306 				/* End of source route */
25307 				break;
25308 			}
25309 			/*
25310 			 * This will only happen if two consecutive entries
25311 			 * in the source route contains our address or if
25312 			 * it is a packet with a loose source route which
25313 			 * reaches us before consuming the whole source route
25314 			 */
25315 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25316 			if (optval == IPOPT_SSRR) {
25317 				return;
25318 			}
25319 			/*
25320 			 * Hack: instead of dropping the packet truncate the
25321 			 * source route to what has been used by filling the
25322 			 * rest with IPOPT_NOP.
25323 			 */
25324 			opt[IPOPT_OLEN] = (uint8_t)off;
25325 			while (off < optlen) {
25326 				opt[off++] = IPOPT_NOP;
25327 			}
25328 			break;
25329 		case IPOPT_RR:
25330 			off = opt[IPOPT_OFFSET];
25331 			off--;
25332 			if (optlen < IP_ADDR_LEN ||
25333 			    off > optlen - IP_ADDR_LEN) {
25334 				/* No more room - ignore */
25335 				ip1dbg((
25336 				    "ip_wput_forward_options: end of RR\n"));
25337 				break;
25338 			}
25339 			dst = htonl(INADDR_LOOPBACK);
25340 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25341 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25342 			break;
25343 		case IPOPT_TS:
25344 			/* Insert timestamp if there is romm */
25345 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25346 			case IPOPT_TS_TSONLY:
25347 				off = IPOPT_TS_TIMELEN;
25348 				break;
25349 			case IPOPT_TS_PRESPEC:
25350 			case IPOPT_TS_PRESPEC_RFC791:
25351 				/* Verify that the address matched */
25352 				off = opt[IPOPT_OFFSET] - 1;
25353 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25354 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25355 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25356 				    ipst);
25357 				if (ire == NULL) {
25358 					/* Not for us */
25359 					break;
25360 				}
25361 				ire_refrele(ire);
25362 				/* FALLTHRU */
25363 			case IPOPT_TS_TSANDADDR:
25364 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25365 				break;
25366 			default:
25367 				/*
25368 				 * ip_*put_options should have already
25369 				 * dropped this packet.
25370 				 */
25371 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25372 				    "unknown IT - bug in ip_wput_options?\n");
25373 				return;	/* Keep "lint" happy */
25374 			}
25375 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25376 				/* Increase overflow counter */
25377 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25378 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25379 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25380 				    (off << 4);
25381 				break;
25382 			}
25383 			off = opt[IPOPT_OFFSET] - 1;
25384 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25385 			case IPOPT_TS_PRESPEC:
25386 			case IPOPT_TS_PRESPEC_RFC791:
25387 			case IPOPT_TS_TSANDADDR:
25388 				dst = htonl(INADDR_LOOPBACK);
25389 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25390 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25391 				/* FALLTHRU */
25392 			case IPOPT_TS_TSONLY:
25393 				off = opt[IPOPT_OFFSET] - 1;
25394 				/* Compute # of milliseconds since midnight */
25395 				gethrestime(&now);
25396 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25397 				    now.tv_nsec / (NANOSEC / MILLISEC);
25398 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25399 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25400 				break;
25401 			}
25402 			break;
25403 		}
25404 	}
25405 }
25406 
25407 /*
25408  * Send out a multicast packet on interface ipif.
25409  * The sender does not have an conn.
25410  * Caller verifies that this isn't a PHYI_LOOPBACK.
25411  */
25412 void
25413 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25414 {
25415 	ipha_t	*ipha;
25416 	ire_t	*ire;
25417 	ipaddr_t	dst;
25418 	mblk_t		*first_mp;
25419 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25420 
25421 	/* igmp_sendpkt always allocates a ipsec_out_t */
25422 	ASSERT(mp->b_datap->db_type == M_CTL);
25423 	ASSERT(!ipif->ipif_isv6);
25424 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25425 
25426 	first_mp = mp;
25427 	mp = first_mp->b_cont;
25428 	ASSERT(mp->b_datap->db_type == M_DATA);
25429 	ipha = (ipha_t *)mp->b_rptr;
25430 
25431 	/*
25432 	 * Find an IRE which matches the destination and the outgoing
25433 	 * queue (i.e. the outgoing interface.)
25434 	 */
25435 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25436 		dst = ipif->ipif_pp_dst_addr;
25437 	else
25438 		dst = ipha->ipha_dst;
25439 	/*
25440 	 * The source address has already been initialized by the
25441 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25442 	 * be sufficient rather than MATCH_IRE_IPIF.
25443 	 *
25444 	 * This function is used for sending IGMP packets. We need
25445 	 * to make sure that we send the packet out of the interface
25446 	 * (ipif->ipif_ill) where we joined the group. This is to
25447 	 * prevent from switches doing IGMP snooping to send us multicast
25448 	 * packets for a given group on the interface we have joined.
25449 	 * If we can't find an ire, igmp_sendpkt has already initialized
25450 	 * ipsec_out_attach_if so that this will not be load spread in
25451 	 * ip_newroute_ipif.
25452 	 */
25453 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25454 	    MATCH_IRE_ILL, ipst);
25455 	if (!ire) {
25456 		/*
25457 		 * Mark this packet to make it be delivered to
25458 		 * ip_wput_ire after the new ire has been
25459 		 * created.
25460 		 */
25461 		mp->b_prev = NULL;
25462 		mp->b_next = NULL;
25463 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25464 		    zoneid, &zero_info);
25465 		return;
25466 	}
25467 
25468 	/*
25469 	 * Honor the RTF_SETSRC flag; this is the only case
25470 	 * where we force this addr whatever the current src addr is,
25471 	 * because this address is set by igmp_sendpkt(), and
25472 	 * cannot be specified by any user.
25473 	 */
25474 	if (ire->ire_flags & RTF_SETSRC) {
25475 		ipha->ipha_src = ire->ire_src_addr;
25476 	}
25477 
25478 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25479 }
25480 
25481 /*
25482  * NOTE : This function does not ire_refrele the ire argument passed in.
25483  *
25484  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25485  * failure. The nce_fp_mp can vanish any time in the case of
25486  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25487  * the ire_lock to access the nce_fp_mp in this case.
25488  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25489  * prepending a fastpath message IPQoS processing must precede it, we also set
25490  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25491  * (IPQoS might have set the b_band for CoS marking).
25492  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25493  * must follow it so that IPQoS can mark the dl_priority field for CoS
25494  * marking, if needed.
25495  */
25496 static mblk_t *
25497 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25498 {
25499 	uint_t	hlen;
25500 	ipha_t *ipha;
25501 	mblk_t *mp1;
25502 	boolean_t qos_done = B_FALSE;
25503 	uchar_t	*ll_hdr;
25504 	ip_stack_t	*ipst = ire->ire_ipst;
25505 
25506 #define	rptr	((uchar_t *)ipha)
25507 
25508 	ipha = (ipha_t *)mp->b_rptr;
25509 	hlen = 0;
25510 	LOCK_IRE_FP_MP(ire);
25511 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25512 		ASSERT(DB_TYPE(mp1) == M_DATA);
25513 		/* Initiate IPPF processing */
25514 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25515 			UNLOCK_IRE_FP_MP(ire);
25516 			ip_process(proc, &mp, ill_index);
25517 			if (mp == NULL)
25518 				return (NULL);
25519 
25520 			ipha = (ipha_t *)mp->b_rptr;
25521 			LOCK_IRE_FP_MP(ire);
25522 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25523 				qos_done = B_TRUE;
25524 				goto no_fp_mp;
25525 			}
25526 			ASSERT(DB_TYPE(mp1) == M_DATA);
25527 		}
25528 		hlen = MBLKL(mp1);
25529 		/*
25530 		 * Check if we have enough room to prepend fastpath
25531 		 * header
25532 		 */
25533 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25534 			ll_hdr = rptr - hlen;
25535 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25536 			/*
25537 			 * Set the b_rptr to the start of the link layer
25538 			 * header
25539 			 */
25540 			mp->b_rptr = ll_hdr;
25541 			mp1 = mp;
25542 		} else {
25543 			mp1 = copyb(mp1);
25544 			if (mp1 == NULL)
25545 				goto unlock_err;
25546 			mp1->b_band = mp->b_band;
25547 			mp1->b_cont = mp;
25548 			/*
25549 			 * certain system generated traffic may not
25550 			 * have cred/label in ip header block. This
25551 			 * is true even for a labeled system. But for
25552 			 * labeled traffic, inherit the label in the
25553 			 * new header.
25554 			 */
25555 			if (DB_CRED(mp) != NULL)
25556 				mblk_setcred(mp1, DB_CRED(mp));
25557 			/*
25558 			 * XXX disable ICK_VALID and compute checksum
25559 			 * here; can happen if nce_fp_mp changes and
25560 			 * it can't be copied now due to insufficient
25561 			 * space. (unlikely, fp mp can change, but it
25562 			 * does not increase in length)
25563 			 */
25564 		}
25565 		UNLOCK_IRE_FP_MP(ire);
25566 	} else {
25567 no_fp_mp:
25568 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25569 		if (mp1 == NULL) {
25570 unlock_err:
25571 			UNLOCK_IRE_FP_MP(ire);
25572 			freemsg(mp);
25573 			return (NULL);
25574 		}
25575 		UNLOCK_IRE_FP_MP(ire);
25576 		mp1->b_cont = mp;
25577 		/*
25578 		 * certain system generated traffic may not
25579 		 * have cred/label in ip header block. This
25580 		 * is true even for a labeled system. But for
25581 		 * labeled traffic, inherit the label in the
25582 		 * new header.
25583 		 */
25584 		if (DB_CRED(mp) != NULL)
25585 			mblk_setcred(mp1, DB_CRED(mp));
25586 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25587 			ip_process(proc, &mp1, ill_index);
25588 			if (mp1 == NULL)
25589 				return (NULL);
25590 		}
25591 	}
25592 	return (mp1);
25593 #undef rptr
25594 }
25595 
25596 /*
25597  * Finish the outbound IPsec processing for an IPv6 packet. This function
25598  * is called from ipsec_out_process() if the IPsec packet was processed
25599  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25600  * asynchronously.
25601  */
25602 void
25603 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25604     ire_t *ire_arg)
25605 {
25606 	in6_addr_t *v6dstp;
25607 	ire_t *ire;
25608 	mblk_t *mp;
25609 	ip6_t *ip6h1;
25610 	uint_t	ill_index;
25611 	ipsec_out_t *io;
25612 	boolean_t attach_if, hwaccel;
25613 	uint32_t flags = IP6_NO_IPPOLICY;
25614 	int match_flags;
25615 	zoneid_t zoneid;
25616 	boolean_t ill_need_rele = B_FALSE;
25617 	boolean_t ire_need_rele = B_FALSE;
25618 	ip_stack_t	*ipst;
25619 
25620 	mp = ipsec_mp->b_cont;
25621 	ip6h1 = (ip6_t *)mp->b_rptr;
25622 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25623 	ASSERT(io->ipsec_out_ns != NULL);
25624 	ipst = io->ipsec_out_ns->netstack_ip;
25625 	ill_index = io->ipsec_out_ill_index;
25626 	if (io->ipsec_out_reachable) {
25627 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25628 	}
25629 	attach_if = io->ipsec_out_attach_if;
25630 	hwaccel = io->ipsec_out_accelerated;
25631 	zoneid = io->ipsec_out_zoneid;
25632 	ASSERT(zoneid != ALL_ZONES);
25633 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25634 	/* Multicast addresses should have non-zero ill_index. */
25635 	v6dstp = &ip6h->ip6_dst;
25636 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25637 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25638 	ASSERT(!attach_if || ill_index != 0);
25639 	if (ill_index != 0) {
25640 		if (ill == NULL) {
25641 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25642 			    B_TRUE, ipst);
25643 
25644 			/* Failure case frees things for us. */
25645 			if (ill == NULL)
25646 				return;
25647 
25648 			ill_need_rele = B_TRUE;
25649 		}
25650 		/*
25651 		 * If this packet needs to go out on a particular interface
25652 		 * honor it.
25653 		 */
25654 		if (attach_if) {
25655 			match_flags = MATCH_IRE_ILL;
25656 
25657 			/*
25658 			 * Check if we need an ire that will not be
25659 			 * looked up by anybody else i.e. HIDDEN.
25660 			 */
25661 			if (ill_is_probeonly(ill)) {
25662 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25663 			}
25664 		}
25665 	}
25666 	ASSERT(mp != NULL);
25667 
25668 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25669 		boolean_t unspec_src;
25670 		ipif_t	*ipif;
25671 
25672 		/*
25673 		 * Use the ill_index to get the right ill.
25674 		 */
25675 		unspec_src = io->ipsec_out_unspec_src;
25676 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25677 		if (ipif == NULL) {
25678 			if (ill_need_rele)
25679 				ill_refrele(ill);
25680 			freemsg(ipsec_mp);
25681 			return;
25682 		}
25683 
25684 		if (ire_arg != NULL) {
25685 			ire = ire_arg;
25686 		} else {
25687 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25688 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25689 			ire_need_rele = B_TRUE;
25690 		}
25691 		if (ire != NULL) {
25692 			ipif_refrele(ipif);
25693 			/*
25694 			 * XXX Do the multicast forwarding now, as the IPsec
25695 			 * processing has been done.
25696 			 */
25697 			goto send;
25698 		}
25699 
25700 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25701 		mp->b_prev = NULL;
25702 		mp->b_next = NULL;
25703 
25704 		/*
25705 		 * If the IPsec packet was processed asynchronously,
25706 		 * drop it now.
25707 		 */
25708 		if (q == NULL) {
25709 			if (ill_need_rele)
25710 				ill_refrele(ill);
25711 			freemsg(ipsec_mp);
25712 			return;
25713 		}
25714 
25715 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25716 		    unspec_src, zoneid);
25717 		ipif_refrele(ipif);
25718 	} else {
25719 		if (attach_if) {
25720 			ipif_t	*ipif;
25721 
25722 			ipif = ipif_get_next_ipif(NULL, ill);
25723 			if (ipif == NULL) {
25724 				if (ill_need_rele)
25725 					ill_refrele(ill);
25726 				freemsg(ipsec_mp);
25727 				return;
25728 			}
25729 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25730 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25731 			ire_need_rele = B_TRUE;
25732 			ipif_refrele(ipif);
25733 		} else {
25734 			if (ire_arg != NULL) {
25735 				ire = ire_arg;
25736 			} else {
25737 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25738 				    ipst);
25739 				ire_need_rele = B_TRUE;
25740 			}
25741 		}
25742 		if (ire != NULL)
25743 			goto send;
25744 		/*
25745 		 * ire disappeared underneath.
25746 		 *
25747 		 * What we need to do here is the ip_newroute
25748 		 * logic to get the ire without doing the IPsec
25749 		 * processing. Follow the same old path. But this
25750 		 * time, ip_wput or ire_add_then_send will call us
25751 		 * directly as all the IPsec operations are done.
25752 		 */
25753 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25754 		mp->b_prev = NULL;
25755 		mp->b_next = NULL;
25756 
25757 		/*
25758 		 * If the IPsec packet was processed asynchronously,
25759 		 * drop it now.
25760 		 */
25761 		if (q == NULL) {
25762 			if (ill_need_rele)
25763 				ill_refrele(ill);
25764 			freemsg(ipsec_mp);
25765 			return;
25766 		}
25767 
25768 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25769 		    zoneid, ipst);
25770 	}
25771 	if (ill != NULL && ill_need_rele)
25772 		ill_refrele(ill);
25773 	return;
25774 send:
25775 	if (ill != NULL && ill_need_rele)
25776 		ill_refrele(ill);
25777 
25778 	/* Local delivery */
25779 	if (ire->ire_stq == NULL) {
25780 		ill_t	*out_ill;
25781 		ASSERT(q != NULL);
25782 
25783 		/* PFHooks: LOOPBACK_OUT */
25784 		out_ill = ire_to_ill(ire);
25785 
25786 		DTRACE_PROBE4(ip6__loopback__out__start,
25787 		    ill_t *, NULL, ill_t *, out_ill,
25788 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25789 
25790 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25791 		    ipst->ips_ipv6firewall_loopback_out,
25792 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25793 
25794 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25795 
25796 		if (ipsec_mp != NULL)
25797 			ip_wput_local_v6(RD(q), out_ill,
25798 			    ip6h, ipsec_mp, ire, 0);
25799 		if (ire_need_rele)
25800 			ire_refrele(ire);
25801 		return;
25802 	}
25803 	/*
25804 	 * Everything is done. Send it out on the wire.
25805 	 * We force the insertion of a fragment header using the
25806 	 * IPH_FRAG_HDR flag in two cases:
25807 	 * - after reception of an ICMPv6 "packet too big" message
25808 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25809 	 * - for multirouted IPv6 packets, so that the receiver can
25810 	 *   discard duplicates according to their fragment identifier
25811 	 */
25812 	/* XXX fix flow control problems. */
25813 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25814 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25815 		if (hwaccel) {
25816 			/*
25817 			 * hardware acceleration does not handle these
25818 			 * "slow path" cases.
25819 			 */
25820 			/* IPsec KSTATS: should bump bean counter here. */
25821 			if (ire_need_rele)
25822 				ire_refrele(ire);
25823 			freemsg(ipsec_mp);
25824 			return;
25825 		}
25826 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25827 		    (mp->b_cont ? msgdsize(mp) :
25828 		    mp->b_wptr - (uchar_t *)ip6h)) {
25829 			/* IPsec KSTATS: should bump bean counter here. */
25830 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25831 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25832 			    msgdsize(mp)));
25833 			if (ire_need_rele)
25834 				ire_refrele(ire);
25835 			freemsg(ipsec_mp);
25836 			return;
25837 		}
25838 		ASSERT(mp->b_prev == NULL);
25839 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25840 		    ntohs(ip6h->ip6_plen) +
25841 		    IPV6_HDR_LEN, ire->ire_max_frag));
25842 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25843 		    ire->ire_max_frag);
25844 	} else {
25845 		UPDATE_OB_PKT_COUNT(ire);
25846 		ire->ire_last_used_time = lbolt;
25847 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25848 	}
25849 	if (ire_need_rele)
25850 		ire_refrele(ire);
25851 	freeb(ipsec_mp);
25852 }
25853 
25854 void
25855 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25856 {
25857 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25858 	da_ipsec_t *hada;	/* data attributes */
25859 	ill_t *ill = (ill_t *)q->q_ptr;
25860 
25861 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25862 
25863 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25864 		/* IPsec KSTATS: Bump lose counter here! */
25865 		freemsg(mp);
25866 		return;
25867 	}
25868 
25869 	/*
25870 	 * It's an IPsec packet that must be
25871 	 * accelerated by the Provider, and the
25872 	 * outbound ill is IPsec acceleration capable.
25873 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25874 	 * to the ill.
25875 	 * IPsec KSTATS: should bump packet counter here.
25876 	 */
25877 
25878 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25879 	if (hada_mp == NULL) {
25880 		/* IPsec KSTATS: should bump packet counter here. */
25881 		freemsg(mp);
25882 		return;
25883 	}
25884 
25885 	hada_mp->b_datap->db_type = M_CTL;
25886 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25887 	hada_mp->b_cont = mp;
25888 
25889 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25890 	bzero(hada, sizeof (da_ipsec_t));
25891 	hada->da_type = IPHADA_M_CTL;
25892 
25893 	putnext(q, hada_mp);
25894 }
25895 
25896 /*
25897  * Finish the outbound IPsec processing. This function is called from
25898  * ipsec_out_process() if the IPsec packet was processed
25899  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25900  * asynchronously.
25901  */
25902 void
25903 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25904     ire_t *ire_arg)
25905 {
25906 	uint32_t v_hlen_tos_len;
25907 	ipaddr_t	dst;
25908 	ipif_t	*ipif = NULL;
25909 	ire_t *ire;
25910 	ire_t *ire1 = NULL;
25911 	mblk_t *next_mp = NULL;
25912 	uint32_t max_frag;
25913 	boolean_t multirt_send = B_FALSE;
25914 	mblk_t *mp;
25915 	ipha_t *ipha1;
25916 	uint_t	ill_index;
25917 	ipsec_out_t *io;
25918 	boolean_t attach_if;
25919 	int match_flags;
25920 	irb_t *irb = NULL;
25921 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25922 	zoneid_t zoneid;
25923 	ipxmit_state_t	pktxmit_state;
25924 	ip_stack_t	*ipst;
25925 
25926 #ifdef	_BIG_ENDIAN
25927 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25928 #else
25929 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25930 #endif
25931 
25932 	mp = ipsec_mp->b_cont;
25933 	ipha1 = (ipha_t *)mp->b_rptr;
25934 	ASSERT(mp != NULL);
25935 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25936 	dst = ipha->ipha_dst;
25937 
25938 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25939 	ill_index = io->ipsec_out_ill_index;
25940 	attach_if = io->ipsec_out_attach_if;
25941 	zoneid = io->ipsec_out_zoneid;
25942 	ASSERT(zoneid != ALL_ZONES);
25943 	ipst = io->ipsec_out_ns->netstack_ip;
25944 	ASSERT(io->ipsec_out_ns != NULL);
25945 
25946 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25947 	if (ill_index != 0) {
25948 		if (ill == NULL) {
25949 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25950 			    ill_index, B_FALSE, ipst);
25951 
25952 			/* Failure case frees things for us. */
25953 			if (ill == NULL)
25954 				return;
25955 
25956 			ill_need_rele = B_TRUE;
25957 		}
25958 		/*
25959 		 * If this packet needs to go out on a particular interface
25960 		 * honor it.
25961 		 */
25962 		if (attach_if) {
25963 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25964 
25965 			/*
25966 			 * Check if we need an ire that will not be
25967 			 * looked up by anybody else i.e. HIDDEN.
25968 			 */
25969 			if (ill_is_probeonly(ill)) {
25970 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25971 			}
25972 		}
25973 	}
25974 
25975 	if (CLASSD(dst)) {
25976 		boolean_t conn_dontroute;
25977 		/*
25978 		 * Use the ill_index to get the right ipif.
25979 		 */
25980 		conn_dontroute = io->ipsec_out_dontroute;
25981 		if (ill_index == 0)
25982 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25983 		else
25984 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25985 		if (ipif == NULL) {
25986 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25987 			    " multicast\n"));
25988 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25989 			freemsg(ipsec_mp);
25990 			goto done;
25991 		}
25992 		/*
25993 		 * ipha_src has already been intialized with the
25994 		 * value of the ipif in ip_wput. All we need now is
25995 		 * an ire to send this downstream.
25996 		 */
25997 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25998 		    MBLK_GETLABEL(mp), match_flags, ipst);
25999 		if (ire != NULL) {
26000 			ill_t *ill1;
26001 			/*
26002 			 * Do the multicast forwarding now, as the IPsec
26003 			 * processing has been done.
26004 			 */
26005 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
26006 			    (ill1 = ire_to_ill(ire))) {
26007 				if (ip_mforward(ill1, ipha, mp)) {
26008 					freemsg(ipsec_mp);
26009 					ip1dbg(("ip_wput_ipsec_out: mforward "
26010 					    "failed\n"));
26011 					ire_refrele(ire);
26012 					goto done;
26013 				}
26014 			}
26015 			goto send;
26016 		}
26017 
26018 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
26019 		mp->b_prev = NULL;
26020 		mp->b_next = NULL;
26021 
26022 		/*
26023 		 * If the IPsec packet was processed asynchronously,
26024 		 * drop it now.
26025 		 */
26026 		if (q == NULL) {
26027 			freemsg(ipsec_mp);
26028 			goto done;
26029 		}
26030 
26031 		/*
26032 		 * We may be using a wrong ipif to create the ire.
26033 		 * But it is okay as the source address is assigned
26034 		 * for the packet already. Next outbound packet would
26035 		 * create the IRE with the right IPIF in ip_wput.
26036 		 *
26037 		 * Also handle RTF_MULTIRT routes.
26038 		 */
26039 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
26040 		    zoneid, &zero_info);
26041 	} else {
26042 		if (attach_if) {
26043 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
26044 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
26045 		} else {
26046 			if (ire_arg != NULL) {
26047 				ire = ire_arg;
26048 				ire_need_rele = B_FALSE;
26049 			} else {
26050 				ire = ire_cache_lookup(dst, zoneid,
26051 				    MBLK_GETLABEL(mp), ipst);
26052 			}
26053 		}
26054 		if (ire != NULL) {
26055 			goto send;
26056 		}
26057 
26058 		/*
26059 		 * ire disappeared underneath.
26060 		 *
26061 		 * What we need to do here is the ip_newroute
26062 		 * logic to get the ire without doing the IPsec
26063 		 * processing. Follow the same old path. But this
26064 		 * time, ip_wput or ire_add_then_put will call us
26065 		 * directly as all the IPsec operations are done.
26066 		 */
26067 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26068 		mp->b_prev = NULL;
26069 		mp->b_next = NULL;
26070 
26071 		/*
26072 		 * If the IPsec packet was processed asynchronously,
26073 		 * drop it now.
26074 		 */
26075 		if (q == NULL) {
26076 			freemsg(ipsec_mp);
26077 			goto done;
26078 		}
26079 
26080 		/*
26081 		 * Since we're going through ip_newroute() again, we
26082 		 * need to make sure we don't:
26083 		 *
26084 		 *	1.) Trigger the ASSERT() with the ipha_ident
26085 		 *	    overloading.
26086 		 *	2.) Redo transport-layer checksumming, since we've
26087 		 *	    already done all that to get this far.
26088 		 *
26089 		 * The easiest way not do either of the above is to set
26090 		 * the ipha_ident field to IP_HDR_INCLUDED.
26091 		 */
26092 		ipha->ipha_ident = IP_HDR_INCLUDED;
26093 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26094 		    zoneid, ipst);
26095 	}
26096 	goto done;
26097 send:
26098 	if (ire->ire_stq == NULL) {
26099 		ill_t	*out_ill;
26100 		/*
26101 		 * Loopbacks go through ip_wput_local except for one case.
26102 		 * We come here if we generate a icmp_frag_needed message
26103 		 * after IPsec processing is over. When this function calls
26104 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26105 		 * icmp_frag_needed. The message generated comes back here
26106 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26107 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26108 		 * source address as it is usually set in ip_wput_ire. As
26109 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26110 		 * and we end up here. We can't enter ip_wput_ire once the
26111 		 * IPsec processing is over and hence we need to do it here.
26112 		 */
26113 		ASSERT(q != NULL);
26114 		UPDATE_OB_PKT_COUNT(ire);
26115 		ire->ire_last_used_time = lbolt;
26116 		if (ipha->ipha_src == 0)
26117 			ipha->ipha_src = ire->ire_src_addr;
26118 
26119 		/* PFHooks: LOOPBACK_OUT */
26120 		out_ill = ire_to_ill(ire);
26121 
26122 		DTRACE_PROBE4(ip4__loopback__out__start,
26123 		    ill_t *, NULL, ill_t *, out_ill,
26124 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26125 
26126 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26127 		    ipst->ips_ipv4firewall_loopback_out,
26128 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26129 
26130 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26131 
26132 		if (ipsec_mp != NULL)
26133 			ip_wput_local(RD(q), out_ill,
26134 			    ipha, ipsec_mp, ire, 0, zoneid);
26135 		if (ire_need_rele)
26136 			ire_refrele(ire);
26137 		goto done;
26138 	}
26139 
26140 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26141 		/*
26142 		 * We are through with IPsec processing.
26143 		 * Fragment this and send it on the wire.
26144 		 */
26145 		if (io->ipsec_out_accelerated) {
26146 			/*
26147 			 * The packet has been accelerated but must
26148 			 * be fragmented. This should not happen
26149 			 * since AH and ESP must not accelerate
26150 			 * packets that need fragmentation, however
26151 			 * the configuration could have changed
26152 			 * since the AH or ESP processing.
26153 			 * Drop packet.
26154 			 * IPsec KSTATS: bump bean counter here.
26155 			 */
26156 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26157 			    "fragmented accelerated packet!\n"));
26158 			freemsg(ipsec_mp);
26159 		} else {
26160 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26161 		}
26162 		if (ire_need_rele)
26163 			ire_refrele(ire);
26164 		goto done;
26165 	}
26166 
26167 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26168 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26169 	    (void *)ire->ire_ipif, (void *)ipif));
26170 
26171 	/*
26172 	 * Multiroute the secured packet, unless IPsec really
26173 	 * requires the packet to go out only through a particular
26174 	 * interface.
26175 	 */
26176 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26177 		ire_t *first_ire;
26178 		irb = ire->ire_bucket;
26179 		ASSERT(irb != NULL);
26180 		/*
26181 		 * This ire has been looked up as the one that
26182 		 * goes through the given ipif;
26183 		 * make sure we do not omit any other multiroute ire
26184 		 * that may be present in the bucket before this one.
26185 		 */
26186 		IRB_REFHOLD(irb);
26187 		for (first_ire = irb->irb_ire;
26188 		    first_ire != NULL;
26189 		    first_ire = first_ire->ire_next) {
26190 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26191 			    (first_ire->ire_addr == ire->ire_addr) &&
26192 			    !(first_ire->ire_marks &
26193 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26194 				break;
26195 			}
26196 		}
26197 
26198 		if ((first_ire != NULL) && (first_ire != ire)) {
26199 			/*
26200 			 * Don't change the ire if the packet must
26201 			 * be fragmented if sent via this new one.
26202 			 */
26203 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26204 				IRE_REFHOLD(first_ire);
26205 				if (ire_need_rele)
26206 					ire_refrele(ire);
26207 				else
26208 					ire_need_rele = B_TRUE;
26209 				ire = first_ire;
26210 			}
26211 		}
26212 		IRB_REFRELE(irb);
26213 
26214 		multirt_send = B_TRUE;
26215 		max_frag = ire->ire_max_frag;
26216 	} else {
26217 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26218 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26219 			    "flag, attach_if %d\n", attach_if));
26220 		}
26221 	}
26222 
26223 	/*
26224 	 * In most cases, the emission loop below is entered only once.
26225 	 * Only in the case where the ire holds the RTF_MULTIRT
26226 	 * flag, we loop to process all RTF_MULTIRT ires in the
26227 	 * bucket, and send the packet through all crossed
26228 	 * RTF_MULTIRT routes.
26229 	 */
26230 	do {
26231 		if (multirt_send) {
26232 			/*
26233 			 * ire1 holds here the next ire to process in the
26234 			 * bucket. If multirouting is expected,
26235 			 * any non-RTF_MULTIRT ire that has the
26236 			 * right destination address is ignored.
26237 			 */
26238 			ASSERT(irb != NULL);
26239 			IRB_REFHOLD(irb);
26240 			for (ire1 = ire->ire_next;
26241 			    ire1 != NULL;
26242 			    ire1 = ire1->ire_next) {
26243 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26244 					continue;
26245 				if (ire1->ire_addr != ire->ire_addr)
26246 					continue;
26247 				if (ire1->ire_marks &
26248 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26249 					continue;
26250 				/* No loopback here */
26251 				if (ire1->ire_stq == NULL)
26252 					continue;
26253 				/*
26254 				 * Ensure we do not exceed the MTU
26255 				 * of the next route.
26256 				 */
26257 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26258 					ip_multirt_bad_mtu(ire1, max_frag);
26259 					continue;
26260 				}
26261 
26262 				IRE_REFHOLD(ire1);
26263 				break;
26264 			}
26265 			IRB_REFRELE(irb);
26266 			if (ire1 != NULL) {
26267 				/*
26268 				 * We are in a multiple send case, need to
26269 				 * make a copy of the packet.
26270 				 */
26271 				next_mp = copymsg(ipsec_mp);
26272 				if (next_mp == NULL) {
26273 					ire_refrele(ire1);
26274 					ire1 = NULL;
26275 				}
26276 			}
26277 		}
26278 		/*
26279 		 * Everything is done. Send it out on the wire
26280 		 *
26281 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26282 		 * either send it on the wire or, in the case of
26283 		 * HW acceleration, call ipsec_hw_putnext.
26284 		 */
26285 		if (ire->ire_nce &&
26286 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26287 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26288 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26289 			/*
26290 			 * If ire's link-layer is unresolved (this
26291 			 * would only happen if the incomplete ire
26292 			 * was added to cachetable via forwarding path)
26293 			 * don't bother going to ip_xmit_v4. Just drop the
26294 			 * packet.
26295 			 * There is a slight risk here, in that, if we
26296 			 * have the forwarding path create an incomplete
26297 			 * IRE, then until the IRE is completed, any
26298 			 * transmitted IPsec packets will be dropped
26299 			 * instead of being queued waiting for resolution.
26300 			 *
26301 			 * But the likelihood of a forwarding packet and a wput
26302 			 * packet sending to the same dst at the same time
26303 			 * and there not yet be an ARP entry for it is small.
26304 			 * Furthermore, if this actually happens, it might
26305 			 * be likely that wput would generate multiple
26306 			 * packets (and forwarding would also have a train
26307 			 * of packets) for that destination. If this is
26308 			 * the case, some of them would have been dropped
26309 			 * anyway, since ARP only queues a few packets while
26310 			 * waiting for resolution
26311 			 *
26312 			 * NOTE: We should really call ip_xmit_v4,
26313 			 * and let it queue the packet and send the
26314 			 * ARP query and have ARP come back thus:
26315 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26316 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26317 			 * hw accel work. But it's too complex to get
26318 			 * the IPsec hw  acceleration approach to fit
26319 			 * well with ip_xmit_v4 doing ARP without
26320 			 * doing IPsec simplification. For now, we just
26321 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26322 			 * that we can continue with the send on the next
26323 			 * attempt.
26324 			 *
26325 			 * XXX THis should be revisited, when
26326 			 * the IPsec/IP interaction is cleaned up
26327 			 */
26328 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26329 			    " - dropping packet\n"));
26330 			freemsg(ipsec_mp);
26331 			/*
26332 			 * Call ip_xmit_v4() to trigger ARP query
26333 			 * in case the nce_state is ND_INITIAL
26334 			 */
26335 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26336 			goto drop_pkt;
26337 		}
26338 
26339 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26340 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26341 		    mblk_t *, ipsec_mp);
26342 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26343 		    ipst->ips_ipv4firewall_physical_out, NULL,
26344 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26345 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26346 		if (ipsec_mp == NULL)
26347 			goto drop_pkt;
26348 
26349 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26350 		pktxmit_state = ip_xmit_v4(mp, ire,
26351 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26352 
26353 		if ((pktxmit_state ==  SEND_FAILED) ||
26354 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26355 
26356 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26357 drop_pkt:
26358 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26359 			    ipIfStatsOutDiscards);
26360 			if (ire_need_rele)
26361 				ire_refrele(ire);
26362 			if (ire1 != NULL) {
26363 				ire_refrele(ire1);
26364 				freemsg(next_mp);
26365 			}
26366 			goto done;
26367 		}
26368 
26369 		freeb(ipsec_mp);
26370 		if (ire_need_rele)
26371 			ire_refrele(ire);
26372 
26373 		if (ire1 != NULL) {
26374 			ire = ire1;
26375 			ire_need_rele = B_TRUE;
26376 			ASSERT(next_mp);
26377 			ipsec_mp = next_mp;
26378 			mp = ipsec_mp->b_cont;
26379 			ire1 = NULL;
26380 			next_mp = NULL;
26381 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26382 		} else {
26383 			multirt_send = B_FALSE;
26384 		}
26385 	} while (multirt_send);
26386 done:
26387 	if (ill != NULL && ill_need_rele)
26388 		ill_refrele(ill);
26389 	if (ipif != NULL)
26390 		ipif_refrele(ipif);
26391 }
26392 
26393 /*
26394  * Get the ill corresponding to the specified ire, and compare its
26395  * capabilities with the protocol and algorithms specified by the
26396  * the SA obtained from ipsec_out. If they match, annotate the
26397  * ipsec_out structure to indicate that the packet needs acceleration.
26398  *
26399  *
26400  * A packet is eligible for outbound hardware acceleration if the
26401  * following conditions are satisfied:
26402  *
26403  * 1. the packet will not be fragmented
26404  * 2. the provider supports the algorithm
26405  * 3. there is no pending control message being exchanged
26406  * 4. snoop is not attached
26407  * 5. the destination address is not a broadcast or multicast address.
26408  *
26409  * Rationale:
26410  *	- Hardware drivers do not support fragmentation with
26411  *	  the current interface.
26412  *	- snoop, multicast, and broadcast may result in exposure of
26413  *	  a cleartext datagram.
26414  * We check all five of these conditions here.
26415  *
26416  * XXX would like to nuke "ire_t *" parameter here; problem is that
26417  * IRE is only way to figure out if a v4 address is a broadcast and
26418  * thus ineligible for acceleration...
26419  */
26420 static void
26421 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26422 {
26423 	ipsec_out_t *io;
26424 	mblk_t *data_mp;
26425 	uint_t plen, overhead;
26426 	ip_stack_t	*ipst;
26427 
26428 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26429 		return;
26430 
26431 	if (ill == NULL)
26432 		return;
26433 	ipst = ill->ill_ipst;
26434 	/*
26435 	 * Destination address is a broadcast or multicast.  Punt.
26436 	 */
26437 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26438 	    IRE_LOCAL)))
26439 		return;
26440 
26441 	data_mp = ipsec_mp->b_cont;
26442 
26443 	if (ill->ill_isv6) {
26444 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26445 
26446 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26447 			return;
26448 
26449 		plen = ip6h->ip6_plen;
26450 	} else {
26451 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26452 
26453 		if (CLASSD(ipha->ipha_dst))
26454 			return;
26455 
26456 		plen = ipha->ipha_length;
26457 	}
26458 	/*
26459 	 * Is there a pending DLPI control message being exchanged
26460 	 * between IP/IPsec and the DLS Provider? If there is, it
26461 	 * could be a SADB update, and the state of the DLS Provider
26462 	 * SADB might not be in sync with the SADB maintained by
26463 	 * IPsec. To avoid dropping packets or using the wrong keying
26464 	 * material, we do not accelerate this packet.
26465 	 */
26466 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26467 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26468 		    "ill_dlpi_pending! don't accelerate packet\n"));
26469 		return;
26470 	}
26471 
26472 	/*
26473 	 * Is the Provider in promiscous mode? If it does, we don't
26474 	 * accelerate the packet since it will bounce back up to the
26475 	 * listeners in the clear.
26476 	 */
26477 	if (ill->ill_promisc_on_phys) {
26478 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26479 		    "ill in promiscous mode, don't accelerate packet\n"));
26480 		return;
26481 	}
26482 
26483 	/*
26484 	 * Will the packet require fragmentation?
26485 	 */
26486 
26487 	/*
26488 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26489 	 * as is used elsewhere.
26490 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26491 	 *	+ 2-byte trailer
26492 	 */
26493 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26494 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26495 
26496 	if ((plen + overhead) > ill->ill_max_mtu)
26497 		return;
26498 
26499 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26500 
26501 	/*
26502 	 * Can the ill accelerate this IPsec protocol and algorithm
26503 	 * specified by the SA?
26504 	 */
26505 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26506 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26507 		return;
26508 	}
26509 
26510 	/*
26511 	 * Tell AH or ESP that the outbound ill is capable of
26512 	 * accelerating this packet.
26513 	 */
26514 	io->ipsec_out_is_capab_ill = B_TRUE;
26515 }
26516 
26517 /*
26518  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26519  *
26520  * If this function returns B_TRUE, the requested SA's have been filled
26521  * into the ipsec_out_*_sa pointers.
26522  *
26523  * If the function returns B_FALSE, the packet has been "consumed", most
26524  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26525  *
26526  * The SA references created by the protocol-specific "select"
26527  * function will be released when the ipsec_mp is freed, thanks to the
26528  * ipsec_out_free destructor -- see spd.c.
26529  */
26530 static boolean_t
26531 ipsec_out_select_sa(mblk_t *ipsec_mp)
26532 {
26533 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26534 	ipsec_out_t *io;
26535 	ipsec_policy_t *pp;
26536 	ipsec_action_t *ap;
26537 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26538 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26539 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26540 
26541 	if (!io->ipsec_out_secure) {
26542 		/*
26543 		 * We came here by mistake.
26544 		 * Don't bother with ipsec processing
26545 		 * We should "discourage" this path in the future.
26546 		 */
26547 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26548 		return (B_FALSE);
26549 	}
26550 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26551 	ASSERT((io->ipsec_out_policy != NULL) ||
26552 	    (io->ipsec_out_act != NULL));
26553 
26554 	ASSERT(io->ipsec_out_failed == B_FALSE);
26555 
26556 	/*
26557 	 * IPsec processing has started.
26558 	 */
26559 	io->ipsec_out_proc_begin = B_TRUE;
26560 	ap = io->ipsec_out_act;
26561 	if (ap == NULL) {
26562 		pp = io->ipsec_out_policy;
26563 		ASSERT(pp != NULL);
26564 		ap = pp->ipsp_act;
26565 		ASSERT(ap != NULL);
26566 	}
26567 
26568 	/*
26569 	 * We have an action.  now, let's select SA's.
26570 	 * (In the future, we can cache this in the conn_t..)
26571 	 */
26572 	if (ap->ipa_want_esp) {
26573 		if (io->ipsec_out_esp_sa == NULL) {
26574 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26575 			    IPPROTO_ESP);
26576 		}
26577 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26578 	}
26579 
26580 	if (ap->ipa_want_ah) {
26581 		if (io->ipsec_out_ah_sa == NULL) {
26582 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26583 			    IPPROTO_AH);
26584 		}
26585 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26586 		/*
26587 		 * The ESP and AH processing order needs to be preserved
26588 		 * when both protocols are required (ESP should be applied
26589 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26590 		 * when both ESP and AH are required, and an AH ACQUIRE
26591 		 * is needed.
26592 		 */
26593 		if (ap->ipa_want_esp && need_ah_acquire)
26594 			need_esp_acquire = B_TRUE;
26595 	}
26596 
26597 	/*
26598 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26599 	 * Release SAs that got referenced, but will not be used until we
26600 	 * acquire _all_ of the SAs we need.
26601 	 */
26602 	if (need_ah_acquire || need_esp_acquire) {
26603 		if (io->ipsec_out_ah_sa != NULL) {
26604 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26605 			io->ipsec_out_ah_sa = NULL;
26606 		}
26607 		if (io->ipsec_out_esp_sa != NULL) {
26608 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26609 			io->ipsec_out_esp_sa = NULL;
26610 		}
26611 
26612 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26613 		return (B_FALSE);
26614 	}
26615 
26616 	return (B_TRUE);
26617 }
26618 
26619 /*
26620  * Process an IPSEC_OUT message and see what you can
26621  * do with it.
26622  * IPQoS Notes:
26623  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26624  * IPsec.
26625  * XXX would like to nuke ire_t.
26626  * XXX ill_index better be "real"
26627  */
26628 void
26629 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26630 {
26631 	ipsec_out_t *io;
26632 	ipsec_policy_t *pp;
26633 	ipsec_action_t *ap;
26634 	ipha_t *ipha;
26635 	ip6_t *ip6h;
26636 	mblk_t *mp;
26637 	ill_t *ill;
26638 	zoneid_t zoneid;
26639 	ipsec_status_t ipsec_rc;
26640 	boolean_t ill_need_rele = B_FALSE;
26641 	ip_stack_t	*ipst;
26642 	ipsec_stack_t	*ipss;
26643 
26644 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26645 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26646 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26647 	ipst = io->ipsec_out_ns->netstack_ip;
26648 	mp = ipsec_mp->b_cont;
26649 
26650 	/*
26651 	 * Initiate IPPF processing. We do it here to account for packets
26652 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26653 	 * We can check for ipsec_out_proc_begin even for such packets, as
26654 	 * they will always be false (asserted below).
26655 	 */
26656 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26657 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26658 		    io->ipsec_out_ill_index : ill_index);
26659 		if (mp == NULL) {
26660 			ip2dbg(("ipsec_out_process: packet dropped "\
26661 			    "during IPPF processing\n"));
26662 			freeb(ipsec_mp);
26663 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26664 			return;
26665 		}
26666 	}
26667 
26668 	if (!io->ipsec_out_secure) {
26669 		/*
26670 		 * We came here by mistake.
26671 		 * Don't bother with ipsec processing
26672 		 * Should "discourage" this path in the future.
26673 		 */
26674 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26675 		goto done;
26676 	}
26677 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26678 	ASSERT((io->ipsec_out_policy != NULL) ||
26679 	    (io->ipsec_out_act != NULL));
26680 	ASSERT(io->ipsec_out_failed == B_FALSE);
26681 
26682 	ipss = ipst->ips_netstack->netstack_ipsec;
26683 	if (!ipsec_loaded(ipss)) {
26684 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26685 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26686 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26687 		} else {
26688 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26689 		}
26690 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26691 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26692 		    &ipss->ipsec_dropper);
26693 		return;
26694 	}
26695 
26696 	/*
26697 	 * IPsec processing has started.
26698 	 */
26699 	io->ipsec_out_proc_begin = B_TRUE;
26700 	ap = io->ipsec_out_act;
26701 	if (ap == NULL) {
26702 		pp = io->ipsec_out_policy;
26703 		ASSERT(pp != NULL);
26704 		ap = pp->ipsp_act;
26705 		ASSERT(ap != NULL);
26706 	}
26707 
26708 	/*
26709 	 * Save the outbound ill index. When the packet comes back
26710 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26711 	 * before sending it the accelerated packet.
26712 	 */
26713 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26714 		int ifindex;
26715 		ill = ire_to_ill(ire);
26716 		ifindex = ill->ill_phyint->phyint_ifindex;
26717 		io->ipsec_out_capab_ill_index = ifindex;
26718 	}
26719 
26720 	/*
26721 	 * The order of processing is first insert a IP header if needed.
26722 	 * Then insert the ESP header and then the AH header.
26723 	 */
26724 	if ((io->ipsec_out_se_done == B_FALSE) &&
26725 	    (ap->ipa_want_se)) {
26726 		/*
26727 		 * First get the outer IP header before sending
26728 		 * it to ESP.
26729 		 */
26730 		ipha_t *oipha, *iipha;
26731 		mblk_t *outer_mp, *inner_mp;
26732 
26733 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26734 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26735 			    "ipsec_out_process: "
26736 			    "Self-Encapsulation failed: Out of memory\n");
26737 			freemsg(ipsec_mp);
26738 			if (ill != NULL) {
26739 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26740 			} else {
26741 				BUMP_MIB(&ipst->ips_ip_mib,
26742 				    ipIfStatsOutDiscards);
26743 			}
26744 			return;
26745 		}
26746 		inner_mp = ipsec_mp->b_cont;
26747 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26748 		oipha = (ipha_t *)outer_mp->b_rptr;
26749 		iipha = (ipha_t *)inner_mp->b_rptr;
26750 		*oipha = *iipha;
26751 		outer_mp->b_wptr += sizeof (ipha_t);
26752 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26753 		    sizeof (ipha_t));
26754 		oipha->ipha_protocol = IPPROTO_ENCAP;
26755 		oipha->ipha_version_and_hdr_length =
26756 		    IP_SIMPLE_HDR_VERSION;
26757 		oipha->ipha_hdr_checksum = 0;
26758 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26759 		outer_mp->b_cont = inner_mp;
26760 		ipsec_mp->b_cont = outer_mp;
26761 
26762 		io->ipsec_out_se_done = B_TRUE;
26763 		io->ipsec_out_tunnel = B_TRUE;
26764 	}
26765 
26766 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26767 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26768 	    !ipsec_out_select_sa(ipsec_mp))
26769 		return;
26770 
26771 	/*
26772 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26773 	 * to do the heavy lifting.
26774 	 */
26775 	zoneid = io->ipsec_out_zoneid;
26776 	ASSERT(zoneid != ALL_ZONES);
26777 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26778 		ASSERT(io->ipsec_out_esp_sa != NULL);
26779 		io->ipsec_out_esp_done = B_TRUE;
26780 		/*
26781 		 * Note that since hw accel can only apply one transform,
26782 		 * not two, we skip hw accel for ESP if we also have AH
26783 		 * This is an design limitation of the interface
26784 		 * which should be revisited.
26785 		 */
26786 		ASSERT(ire != NULL);
26787 		if (io->ipsec_out_ah_sa == NULL) {
26788 			ill = (ill_t *)ire->ire_stq->q_ptr;
26789 			ipsec_out_is_accelerated(ipsec_mp,
26790 			    io->ipsec_out_esp_sa, ill, ire);
26791 		}
26792 
26793 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26794 		switch (ipsec_rc) {
26795 		case IPSEC_STATUS_SUCCESS:
26796 			break;
26797 		case IPSEC_STATUS_FAILED:
26798 			if (ill != NULL) {
26799 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26800 			} else {
26801 				BUMP_MIB(&ipst->ips_ip_mib,
26802 				    ipIfStatsOutDiscards);
26803 			}
26804 			/* FALLTHRU */
26805 		case IPSEC_STATUS_PENDING:
26806 			return;
26807 		}
26808 	}
26809 
26810 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26811 		ASSERT(io->ipsec_out_ah_sa != NULL);
26812 		io->ipsec_out_ah_done = B_TRUE;
26813 		if (ire == NULL) {
26814 			int idx = io->ipsec_out_capab_ill_index;
26815 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26816 			    NULL, NULL, NULL, NULL, ipst);
26817 			ill_need_rele = B_TRUE;
26818 		} else {
26819 			ill = (ill_t *)ire->ire_stq->q_ptr;
26820 		}
26821 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26822 		    ire);
26823 
26824 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26825 		switch (ipsec_rc) {
26826 		case IPSEC_STATUS_SUCCESS:
26827 			break;
26828 		case IPSEC_STATUS_FAILED:
26829 			if (ill != NULL) {
26830 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26831 			} else {
26832 				BUMP_MIB(&ipst->ips_ip_mib,
26833 				    ipIfStatsOutDiscards);
26834 			}
26835 			/* FALLTHRU */
26836 		case IPSEC_STATUS_PENDING:
26837 			if (ill != NULL && ill_need_rele)
26838 				ill_refrele(ill);
26839 			return;
26840 		}
26841 	}
26842 	/*
26843 	 * We are done with IPsec processing. Send it over
26844 	 * the wire.
26845 	 */
26846 done:
26847 	mp = ipsec_mp->b_cont;
26848 	ipha = (ipha_t *)mp->b_rptr;
26849 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26850 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26851 	} else {
26852 		ip6h = (ip6_t *)ipha;
26853 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26854 	}
26855 	if (ill != NULL && ill_need_rele)
26856 		ill_refrele(ill);
26857 }
26858 
26859 /* ARGSUSED */
26860 void
26861 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26862 {
26863 	opt_restart_t	*or;
26864 	int	err;
26865 	conn_t	*connp;
26866 
26867 	ASSERT(CONN_Q(q));
26868 	connp = Q_TO_CONN(q);
26869 
26870 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26871 	or = (opt_restart_t *)first_mp->b_rptr;
26872 	/*
26873 	 * We don't need to pass any credentials here since this is just
26874 	 * a restart. The credentials are passed in when svr4_optcom_req
26875 	 * is called the first time (from ip_wput_nondata).
26876 	 */
26877 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26878 		err = svr4_optcom_req(q, first_mp, NULL,
26879 		    &ip_opt_obj, B_FALSE);
26880 	} else {
26881 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26882 		err = tpi_optcom_req(q, first_mp, NULL,
26883 		    &ip_opt_obj, B_FALSE);
26884 	}
26885 	if (err != EINPROGRESS) {
26886 		/* operation is done */
26887 		CONN_OPER_PENDING_DONE(connp);
26888 	}
26889 }
26890 
26891 /*
26892  * ioctls that go through a down/up sequence may need to wait for the down
26893  * to complete. This involves waiting for the ire and ipif refcnts to go down
26894  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26895  */
26896 /* ARGSUSED */
26897 void
26898 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26899 {
26900 	struct iocblk *iocp;
26901 	mblk_t *mp1;
26902 	ip_ioctl_cmd_t *ipip;
26903 	int err;
26904 	sin_t	*sin;
26905 	struct lifreq *lifr;
26906 	struct ifreq *ifr;
26907 
26908 	iocp = (struct iocblk *)mp->b_rptr;
26909 	ASSERT(ipsq != NULL);
26910 	/* Existence of mp1 verified in ip_wput_nondata */
26911 	mp1 = mp->b_cont->b_cont;
26912 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26913 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26914 		/*
26915 		 * Special case where ipsq_current_ipif is not set:
26916 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26917 		 * ill could also have become part of a ipmp group in the
26918 		 * process, we are here as were not able to complete the
26919 		 * operation in ipif_set_values because we could not become
26920 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26921 		 * will not be set so we need to set it.
26922 		 */
26923 		ill_t *ill = q->q_ptr;
26924 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26925 	}
26926 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26927 
26928 	if (ipip->ipi_cmd_type == IF_CMD) {
26929 		/* This a old style SIOC[GS]IF* command */
26930 		ifr = (struct ifreq *)mp1->b_rptr;
26931 		sin = (sin_t *)&ifr->ifr_addr;
26932 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26933 		/* This a new style SIOC[GS]LIF* command */
26934 		lifr = (struct lifreq *)mp1->b_rptr;
26935 		sin = (sin_t *)&lifr->lifr_addr;
26936 	} else {
26937 		sin = NULL;
26938 	}
26939 
26940 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26941 	    ipip, mp1->b_rptr);
26942 
26943 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26944 }
26945 
26946 /*
26947  * ioctl processing
26948  *
26949  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26950  * the ioctl command in the ioctl tables, determines the copyin data size
26951  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26952  *
26953  * ioctl processing then continues when the M_IOCDATA makes its way down to
26954  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26955  * associated 'conn' is refheld till the end of the ioctl and the general
26956  * ioctl processing function ip_process_ioctl() is called to extract the
26957  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26958  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26959  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26960  * is used to extract the ioctl's arguments.
26961  *
26962  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26963  * so goes thru the serialization primitive ipsq_try_enter. Then the
26964  * appropriate function to handle the ioctl is called based on the entry in
26965  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26966  * which also refreleases the 'conn' that was refheld at the start of the
26967  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26968  *
26969  * Many exclusive ioctls go thru an internal down up sequence as part of
26970  * the operation. For example an attempt to change the IP address of an
26971  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26972  * does all the cleanup such as deleting all ires that use this address.
26973  * Then we need to wait till all references to the interface go away.
26974  */
26975 void
26976 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26977 {
26978 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26979 	ip_ioctl_cmd_t *ipip = arg;
26980 	ip_extract_func_t *extract_funcp;
26981 	cmd_info_t ci;
26982 	int err;
26983 	boolean_t entered_ipsq = B_FALSE;
26984 
26985 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26986 
26987 	if (ipip == NULL)
26988 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26989 
26990 	/*
26991 	 * SIOCLIFADDIF needs to go thru a special path since the
26992 	 * ill may not exist yet. This happens in the case of lo0
26993 	 * which is created using this ioctl.
26994 	 */
26995 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26996 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26997 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26998 		return;
26999 	}
27000 
27001 	ci.ci_ipif = NULL;
27002 	if (ipip->ipi_cmd_type == MISC_CMD) {
27003 		/*
27004 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
27005 		 */
27006 		if (ipip->ipi_cmd == IF_UNITSEL) {
27007 			/* ioctl comes down the ill */
27008 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
27009 			ipif_refhold(ci.ci_ipif);
27010 		}
27011 		err = 0;
27012 		ci.ci_sin = NULL;
27013 		ci.ci_sin6 = NULL;
27014 		ci.ci_lifr = NULL;
27015 	} else {
27016 		switch (ipip->ipi_cmd_type) {
27017 		case IF_CMD:
27018 		case LIF_CMD:
27019 			extract_funcp = ip_extract_lifreq;
27020 			break;
27021 
27022 		case ARP_CMD:
27023 		case XARP_CMD:
27024 			extract_funcp = ip_extract_arpreq;
27025 			break;
27026 
27027 		case TUN_CMD:
27028 			extract_funcp = ip_extract_tunreq;
27029 			break;
27030 
27031 		case MSFILT_CMD:
27032 			extract_funcp = ip_extract_msfilter;
27033 			break;
27034 
27035 		default:
27036 			ASSERT(0);
27037 		}
27038 
27039 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
27040 		if (err != 0) {
27041 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27042 			return;
27043 		}
27044 
27045 		/*
27046 		 * All of the extraction functions return a refheld ipif.
27047 		 */
27048 		ASSERT(ci.ci_ipif != NULL);
27049 	}
27050 
27051 	/*
27052 	 * If ipsq is non-null, we are already being called exclusively
27053 	 */
27054 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
27055 	if (!(ipip->ipi_flags & IPI_WR)) {
27056 		/*
27057 		 * A return value of EINPROGRESS means the ioctl is
27058 		 * either queued and waiting for some reason or has
27059 		 * already completed.
27060 		 */
27061 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27062 		    ci.ci_lifr);
27063 		if (ci.ci_ipif != NULL)
27064 			ipif_refrele(ci.ci_ipif);
27065 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27066 		return;
27067 	}
27068 
27069 	ASSERT(ci.ci_ipif != NULL);
27070 
27071 	if (ipsq == NULL) {
27072 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27073 		    ip_process_ioctl, NEW_OP, B_TRUE);
27074 		entered_ipsq = B_TRUE;
27075 	}
27076 	/*
27077 	 * Release the ipif so that ipif_down and friends that wait for
27078 	 * references to go away are not misled about the current ipif_refcnt
27079 	 * values. We are writer so we can access the ipif even after releasing
27080 	 * the ipif.
27081 	 */
27082 	ipif_refrele(ci.ci_ipif);
27083 	if (ipsq == NULL)
27084 		return;
27085 
27086 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27087 
27088 	/*
27089 	 * For most set ioctls that come here, this serves as a single point
27090 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27091 	 * be any new references to the ipif. This helps functions that go
27092 	 * through this path and end up trying to wait for the refcnts
27093 	 * associated with the ipif to go down to zero. Some exceptions are
27094 	 * Failover, Failback, and Groupname commands that operate on more than
27095 	 * just the ci.ci_ipif. These commands internally determine the
27096 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27097 	 * flags on that set. Another exception is the Removeif command that
27098 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27099 	 * ipif to operate on.
27100 	 */
27101 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27102 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27103 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27104 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27105 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27106 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27107 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27108 
27109 	/*
27110 	 * A return value of EINPROGRESS means the ioctl is
27111 	 * either queued and waiting for some reason or has
27112 	 * already completed.
27113 	 */
27114 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27115 
27116 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27117 
27118 	if (entered_ipsq)
27119 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27120 }
27121 
27122 /*
27123  * Complete the ioctl. Typically ioctls use the mi package and need to
27124  * do mi_copyout/mi_copy_done.
27125  */
27126 void
27127 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27128 {
27129 	conn_t	*connp = NULL;
27130 
27131 	if (err == EINPROGRESS)
27132 		return;
27133 
27134 	if (CONN_Q(q)) {
27135 		connp = Q_TO_CONN(q);
27136 		ASSERT(connp->conn_ref >= 2);
27137 	}
27138 
27139 	switch (mode) {
27140 	case COPYOUT:
27141 		if (err == 0)
27142 			mi_copyout(q, mp);
27143 		else
27144 			mi_copy_done(q, mp, err);
27145 		break;
27146 
27147 	case NO_COPYOUT:
27148 		mi_copy_done(q, mp, err);
27149 		break;
27150 
27151 	default:
27152 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27153 		break;
27154 	}
27155 
27156 	/*
27157 	 * The refhold placed at the start of the ioctl is released here.
27158 	 */
27159 	if (connp != NULL)
27160 		CONN_OPER_PENDING_DONE(connp);
27161 
27162 	if (ipsq != NULL)
27163 		ipsq_current_finish(ipsq);
27164 }
27165 
27166 /*
27167  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27168  */
27169 /* ARGSUSED */
27170 void
27171 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27172 {
27173 	conn_t *connp = arg;
27174 	tcp_t	*tcp;
27175 
27176 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27177 	tcp = connp->conn_tcp;
27178 
27179 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27180 		freemsg(mp);
27181 	else
27182 		tcp_rput_other(tcp, mp);
27183 	CONN_OPER_PENDING_DONE(connp);
27184 }
27185 
27186 /* Called from ip_wput for all non data messages */
27187 /* ARGSUSED */
27188 void
27189 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27190 {
27191 	mblk_t		*mp1;
27192 	ire_t		*ire, *fake_ire;
27193 	ill_t		*ill;
27194 	struct iocblk	*iocp;
27195 	ip_ioctl_cmd_t	*ipip;
27196 	cred_t		*cr;
27197 	conn_t		*connp;
27198 	int		err;
27199 	nce_t		*nce;
27200 	ipif_t		*ipif;
27201 	ip_stack_t	*ipst;
27202 	char		*proto_str;
27203 
27204 	if (CONN_Q(q)) {
27205 		connp = Q_TO_CONN(q);
27206 		ipst = connp->conn_netstack->netstack_ip;
27207 	} else {
27208 		connp = NULL;
27209 		ipst = ILLQ_TO_IPST(q);
27210 	}
27211 
27212 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27213 
27214 	switch (DB_TYPE(mp)) {
27215 	case M_IOCTL:
27216 		/*
27217 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27218 		 * will arrange to copy in associated control structures.
27219 		 */
27220 		ip_sioctl_copyin_setup(q, mp);
27221 		return;
27222 	case M_IOCDATA:
27223 		/*
27224 		 * Ensure that this is associated with one of our trans-
27225 		 * parent ioctls.  If it's not ours, discard it if we're
27226 		 * running as a driver, or pass it on if we're a module.
27227 		 */
27228 		iocp = (struct iocblk *)mp->b_rptr;
27229 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27230 		if (ipip == NULL) {
27231 			if (q->q_next == NULL) {
27232 				goto nak;
27233 			} else {
27234 				putnext(q, mp);
27235 			}
27236 			return;
27237 		}
27238 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27239 			/*
27240 			 * the ioctl is one we recognise, but is not
27241 			 * consumed by IP as a module, pass M_IOCDATA
27242 			 * for processing downstream, but only for
27243 			 * common Streams ioctls.
27244 			 */
27245 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27246 				putnext(q, mp);
27247 				return;
27248 			} else {
27249 				goto nak;
27250 			}
27251 		}
27252 
27253 		/* IOCTL continuation following copyin or copyout. */
27254 		if (mi_copy_state(q, mp, NULL) == -1) {
27255 			/*
27256 			 * The copy operation failed.  mi_copy_state already
27257 			 * cleaned up, so we're out of here.
27258 			 */
27259 			return;
27260 		}
27261 		/*
27262 		 * If we just completed a copy in, we become writer and
27263 		 * continue processing in ip_sioctl_copyin_done.  If it
27264 		 * was a copy out, we call mi_copyout again.  If there is
27265 		 * nothing more to copy out, it will complete the IOCTL.
27266 		 */
27267 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27268 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27269 				mi_copy_done(q, mp, EPROTO);
27270 				return;
27271 			}
27272 			/*
27273 			 * Check for cases that need more copying.  A return
27274 			 * value of 0 means a second copyin has been started,
27275 			 * so we return; a return value of 1 means no more
27276 			 * copying is needed, so we continue.
27277 			 */
27278 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27279 			    MI_COPY_COUNT(mp) == 1) {
27280 				if (ip_copyin_msfilter(q, mp) == 0)
27281 					return;
27282 			}
27283 			/*
27284 			 * Refhold the conn, till the ioctl completes. This is
27285 			 * needed in case the ioctl ends up in the pending mp
27286 			 * list. Every mp in the ill_pending_mp list and
27287 			 * the ipsq_pending_mp must have a refhold on the conn
27288 			 * to resume processing. The refhold is released when
27289 			 * the ioctl completes. (normally or abnormally)
27290 			 * In all cases ip_ioctl_finish is called to finish
27291 			 * the ioctl.
27292 			 */
27293 			if (connp != NULL) {
27294 				/* This is not a reentry */
27295 				ASSERT(ipsq == NULL);
27296 				CONN_INC_REF(connp);
27297 			} else {
27298 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27299 					mi_copy_done(q, mp, EINVAL);
27300 					return;
27301 				}
27302 			}
27303 
27304 			ip_process_ioctl(ipsq, q, mp, ipip);
27305 
27306 		} else {
27307 			mi_copyout(q, mp);
27308 		}
27309 		return;
27310 nak:
27311 		iocp->ioc_error = EINVAL;
27312 		mp->b_datap->db_type = M_IOCNAK;
27313 		iocp->ioc_count = 0;
27314 		qreply(q, mp);
27315 		return;
27316 
27317 	case M_IOCNAK:
27318 		/*
27319 		 * The only way we could get here is if a resolver didn't like
27320 		 * an IOCTL we sent it.	 This shouldn't happen.
27321 		 */
27322 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27323 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27324 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27325 		freemsg(mp);
27326 		return;
27327 	case M_IOCACK:
27328 		/* /dev/ip shouldn't see this */
27329 		if (CONN_Q(q))
27330 			goto nak;
27331 
27332 		/* Finish socket ioctls passed through to ARP. */
27333 		ip_sioctl_iocack(q, mp);
27334 		return;
27335 	case M_FLUSH:
27336 		if (*mp->b_rptr & FLUSHW)
27337 			flushq(q, FLUSHALL);
27338 		if (q->q_next) {
27339 			putnext(q, mp);
27340 			return;
27341 		}
27342 		if (*mp->b_rptr & FLUSHR) {
27343 			*mp->b_rptr &= ~FLUSHW;
27344 			qreply(q, mp);
27345 			return;
27346 		}
27347 		freemsg(mp);
27348 		return;
27349 	case IRE_DB_REQ_TYPE:
27350 		if (connp == NULL) {
27351 			proto_str = "IRE_DB_REQ_TYPE";
27352 			goto protonak;
27353 		}
27354 		/* An Upper Level Protocol wants a copy of an IRE. */
27355 		ip_ire_req(q, mp);
27356 		return;
27357 	case M_CTL:
27358 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27359 			break;
27360 
27361 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27362 		    TUN_HELLO) {
27363 			ASSERT(connp != NULL);
27364 			connp->conn_flags |= IPCL_IPTUN;
27365 			freeb(mp);
27366 			return;
27367 		}
27368 
27369 		/* M_CTL messages are used by ARP to tell us things. */
27370 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27371 			break;
27372 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27373 		case AR_ENTRY_SQUERY:
27374 			ip_wput_ctl(q, mp);
27375 			return;
27376 		case AR_CLIENT_NOTIFY:
27377 			ip_arp_news(q, mp);
27378 			return;
27379 		case AR_DLPIOP_DONE:
27380 			ASSERT(q->q_next != NULL);
27381 			ill = (ill_t *)q->q_ptr;
27382 			/* qwriter_ip releases the refhold */
27383 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27384 			ill_refhold(ill);
27385 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27386 			return;
27387 		case AR_ARP_CLOSING:
27388 			/*
27389 			 * ARP (above us) is closing. If no ARP bringup is
27390 			 * currently pending, ack the message so that ARP
27391 			 * can complete its close. Also mark ill_arp_closing
27392 			 * so that new ARP bringups will fail. If any
27393 			 * ARP bringup is currently in progress, we will
27394 			 * ack this when the current ARP bringup completes.
27395 			 */
27396 			ASSERT(q->q_next != NULL);
27397 			ill = (ill_t *)q->q_ptr;
27398 			mutex_enter(&ill->ill_lock);
27399 			ill->ill_arp_closing = 1;
27400 			if (!ill->ill_arp_bringup_pending) {
27401 				mutex_exit(&ill->ill_lock);
27402 				qreply(q, mp);
27403 			} else {
27404 				mutex_exit(&ill->ill_lock);
27405 				freemsg(mp);
27406 			}
27407 			return;
27408 		case AR_ARP_EXTEND:
27409 			/*
27410 			 * The ARP module above us is capable of duplicate
27411 			 * address detection.  Old ATM drivers will not send
27412 			 * this message.
27413 			 */
27414 			ASSERT(q->q_next != NULL);
27415 			ill = (ill_t *)q->q_ptr;
27416 			ill->ill_arp_extend = B_TRUE;
27417 			freemsg(mp);
27418 			return;
27419 		default:
27420 			break;
27421 		}
27422 		break;
27423 	case M_PROTO:
27424 	case M_PCPROTO:
27425 		/*
27426 		 * The only PROTO messages we expect are ULP binds and
27427 		 * copies of option negotiation acknowledgements.
27428 		 */
27429 		switch (((union T_primitives *)mp->b_rptr)->type) {
27430 		case O_T_BIND_REQ:
27431 		case T_BIND_REQ: {
27432 			/* Request can get queued in bind */
27433 			if (connp == NULL) {
27434 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27435 				goto protonak;
27436 			}
27437 			/*
27438 			 * The transports except SCTP call ip_bind_{v4,v6}()
27439 			 * directly instead of a a putnext. SCTP doesn't
27440 			 * generate any T_BIND_REQ since it has its own
27441 			 * fanout data structures. However, ESP and AH
27442 			 * come in for regular binds; all other cases are
27443 			 * bind retries.
27444 			 */
27445 			ASSERT(!IPCL_IS_SCTP(connp));
27446 
27447 			/* Don't increment refcnt if this is a re-entry */
27448 			if (ipsq == NULL)
27449 				CONN_INC_REF(connp);
27450 
27451 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27452 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27453 			if (mp == NULL)
27454 				return;
27455 			if (IPCL_IS_TCP(connp)) {
27456 				/*
27457 				 * In the case of TCP endpoint we
27458 				 * come here only for bind retries
27459 				 */
27460 				ASSERT(ipsq != NULL);
27461 				CONN_INC_REF(connp);
27462 				squeue_fill(connp->conn_sqp, mp,
27463 				    ip_resume_tcp_bind, connp,
27464 				    SQTAG_BIND_RETRY);
27465 			} else if (IPCL_IS_UDP(connp)) {
27466 				/*
27467 				 * In the case of UDP endpoint we
27468 				 * come here only for bind retries
27469 				 */
27470 				ASSERT(ipsq != NULL);
27471 				udp_resume_bind(connp, mp);
27472 			} else if (IPCL_IS_RAWIP(connp)) {
27473 				/*
27474 				 * In the case of RAWIP endpoint we
27475 				 * come here only for bind retries
27476 				 */
27477 				ASSERT(ipsq != NULL);
27478 				rawip_resume_bind(connp, mp);
27479 			} else {
27480 				/* The case of AH and ESP */
27481 				qreply(q, mp);
27482 				CONN_OPER_PENDING_DONE(connp);
27483 			}
27484 			return;
27485 		}
27486 		case T_SVR4_OPTMGMT_REQ:
27487 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27488 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27489 
27490 			if (connp == NULL) {
27491 				proto_str = "T_SVR4_OPTMGMT_REQ";
27492 				goto protonak;
27493 			}
27494 
27495 			if (!snmpcom_req(q, mp, ip_snmp_set,
27496 			    ip_snmp_get, cr)) {
27497 				/*
27498 				 * Call svr4_optcom_req so that it can
27499 				 * generate the ack. We don't come here
27500 				 * if this operation is being restarted.
27501 				 * ip_restart_optmgmt will drop the conn ref.
27502 				 * In the case of ipsec option after the ipsec
27503 				 * load is complete conn_restart_ipsec_waiter
27504 				 * drops the conn ref.
27505 				 */
27506 				ASSERT(ipsq == NULL);
27507 				CONN_INC_REF(connp);
27508 				if (ip_check_for_ipsec_opt(q, mp))
27509 					return;
27510 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27511 				    B_FALSE);
27512 				if (err != EINPROGRESS) {
27513 					/* Operation is done */
27514 					CONN_OPER_PENDING_DONE(connp);
27515 				}
27516 			}
27517 			return;
27518 		case T_OPTMGMT_REQ:
27519 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27520 			/*
27521 			 * Note: No snmpcom_req support through new
27522 			 * T_OPTMGMT_REQ.
27523 			 * Call tpi_optcom_req so that it can
27524 			 * generate the ack.
27525 			 */
27526 			if (connp == NULL) {
27527 				proto_str = "T_OPTMGMT_REQ";
27528 				goto protonak;
27529 			}
27530 
27531 			ASSERT(ipsq == NULL);
27532 			/*
27533 			 * We don't come here for restart. ip_restart_optmgmt
27534 			 * will drop the conn ref. In the case of ipsec option
27535 			 * after the ipsec load is complete
27536 			 * conn_restart_ipsec_waiter drops the conn ref.
27537 			 */
27538 			CONN_INC_REF(connp);
27539 			if (ip_check_for_ipsec_opt(q, mp))
27540 				return;
27541 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27542 			if (err != EINPROGRESS) {
27543 				/* Operation is done */
27544 				CONN_OPER_PENDING_DONE(connp);
27545 			}
27546 			return;
27547 		case T_UNBIND_REQ:
27548 			if (connp == NULL) {
27549 				proto_str = "T_UNBIND_REQ";
27550 				goto protonak;
27551 			}
27552 			mp = ip_unbind(q, mp);
27553 			qreply(q, mp);
27554 			return;
27555 		default:
27556 			/*
27557 			 * Have to drop any DLPI messages coming down from
27558 			 * arp (such as an info_req which would cause ip
27559 			 * to receive an extra info_ack if it was passed
27560 			 * through.
27561 			 */
27562 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27563 			    (int)*(uint_t *)mp->b_rptr));
27564 			freemsg(mp);
27565 			return;
27566 		}
27567 		/* NOTREACHED */
27568 	case IRE_DB_TYPE: {
27569 		nce_t		*nce;
27570 		ill_t		*ill;
27571 		in6_addr_t	gw_addr_v6;
27572 
27573 
27574 		/*
27575 		 * This is a response back from a resolver.  It
27576 		 * consists of a message chain containing:
27577 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27578 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27579 		 * The LL_HDR_MBLK is the DLPI header to use to get
27580 		 * the attached packet, and subsequent ones for the
27581 		 * same destination, transmitted.
27582 		 */
27583 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27584 			break;
27585 		/*
27586 		 * First, check to make sure the resolution succeeded.
27587 		 * If it failed, the second mblk will be empty.
27588 		 * If it is, free the chain, dropping the packet.
27589 		 * (We must ire_delete the ire; that frees the ire mblk)
27590 		 * We're doing this now to support PVCs for ATM; it's
27591 		 * a partial xresolv implementation. When we fully implement
27592 		 * xresolv interfaces, instead of freeing everything here
27593 		 * we'll initiate neighbor discovery.
27594 		 *
27595 		 * For v4 (ARP and other external resolvers) the resolver
27596 		 * frees the message, so no check is needed. This check
27597 		 * is required, though, for a full xresolve implementation.
27598 		 * Including this code here now both shows how external
27599 		 * resolvers can NACK a resolution request using an
27600 		 * existing design that has no specific provisions for NACKs,
27601 		 * and also takes into account that the current non-ARP
27602 		 * external resolver has been coded to use this method of
27603 		 * NACKing for all IPv6 (xresolv) cases,
27604 		 * whether our xresolv implementation is complete or not.
27605 		 *
27606 		 */
27607 		ire = (ire_t *)mp->b_rptr;
27608 		ill = ire_to_ill(ire);
27609 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27610 		if (mp1->b_rptr == mp1->b_wptr) {
27611 			if (ire->ire_ipversion == IPV6_VERSION) {
27612 				/*
27613 				 * XRESOLV interface.
27614 				 */
27615 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27616 				mutex_enter(&ire->ire_lock);
27617 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27618 				mutex_exit(&ire->ire_lock);
27619 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27620 					nce = ndp_lookup_v6(ill,
27621 					    &ire->ire_addr_v6, B_FALSE);
27622 				} else {
27623 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27624 					    B_FALSE);
27625 				}
27626 				if (nce != NULL) {
27627 					nce_resolv_failed(nce);
27628 					ndp_delete(nce);
27629 					NCE_REFRELE(nce);
27630 				}
27631 			}
27632 			mp->b_cont = NULL;
27633 			freemsg(mp1);		/* frees the pkt as well */
27634 			ASSERT(ire->ire_nce == NULL);
27635 			ire_delete((ire_t *)mp->b_rptr);
27636 			return;
27637 		}
27638 
27639 		/*
27640 		 * Split them into IRE_MBLK and pkt and feed it into
27641 		 * ire_add_then_send. Then in ire_add_then_send
27642 		 * the IRE will be added, and then the packet will be
27643 		 * run back through ip_wput. This time it will make
27644 		 * it to the wire.
27645 		 */
27646 		mp->b_cont = NULL;
27647 		mp = mp1->b_cont;		/* now, mp points to pkt */
27648 		mp1->b_cont = NULL;
27649 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27650 		if (ire->ire_ipversion == IPV6_VERSION) {
27651 			/*
27652 			 * XRESOLV interface. Find the nce and put a copy
27653 			 * of the dl_unitdata_req in nce_res_mp
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, &ire->ire_addr_v6,
27661 				    B_FALSE);
27662 			} else {
27663 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27664 			}
27665 			if (nce != NULL) {
27666 				/*
27667 				 * We have to protect nce_res_mp here
27668 				 * from being accessed by other threads
27669 				 * while we change the mblk pointer.
27670 				 * Other functions will also lock the nce when
27671 				 * accessing nce_res_mp.
27672 				 *
27673 				 * The reason we change the mblk pointer
27674 				 * here rather than copying the resolved address
27675 				 * into the template is that, unlike with
27676 				 * ethernet, we have no guarantee that the
27677 				 * resolved address length will be
27678 				 * smaller than or equal to the lla length
27679 				 * with which the template was allocated,
27680 				 * (for ethernet, they're equal)
27681 				 * so we have to use the actual resolved
27682 				 * address mblk - which holds the real
27683 				 * dl_unitdata_req with the resolved address.
27684 				 *
27685 				 * Doing this is the same behavior as was
27686 				 * previously used in the v4 ARP case.
27687 				 */
27688 				mutex_enter(&nce->nce_lock);
27689 				if (nce->nce_res_mp != NULL)
27690 					freemsg(nce->nce_res_mp);
27691 				nce->nce_res_mp = mp1;
27692 				mutex_exit(&nce->nce_lock);
27693 				/*
27694 				 * We do a fastpath probe here because
27695 				 * we have resolved the address without
27696 				 * using Neighbor Discovery.
27697 				 * In the non-XRESOLV v6 case, the fastpath
27698 				 * probe is done right after neighbor
27699 				 * discovery completes.
27700 				 */
27701 				if (nce->nce_res_mp != NULL) {
27702 					int res;
27703 					nce_fastpath_list_add(nce);
27704 					res = ill_fastpath_probe(ill,
27705 					    nce->nce_res_mp);
27706 					if (res != 0 && res != EAGAIN)
27707 						nce_fastpath_list_delete(nce);
27708 				}
27709 
27710 				ire_add_then_send(q, ire, mp);
27711 				/*
27712 				 * Now we have to clean out any packets
27713 				 * that may have been queued on the nce
27714 				 * while it was waiting for address resolution
27715 				 * to complete.
27716 				 */
27717 				mutex_enter(&nce->nce_lock);
27718 				mp1 = nce->nce_qd_mp;
27719 				nce->nce_qd_mp = NULL;
27720 				mutex_exit(&nce->nce_lock);
27721 				while (mp1 != NULL) {
27722 					mblk_t *nxt_mp;
27723 					queue_t *fwdq = NULL;
27724 					ill_t   *inbound_ill;
27725 					uint_t ifindex;
27726 
27727 					nxt_mp = mp1->b_next;
27728 					mp1->b_next = NULL;
27729 					/*
27730 					 * Retrieve ifindex stored in
27731 					 * ip_rput_data_v6()
27732 					 */
27733 					ifindex =
27734 					    (uint_t)(uintptr_t)mp1->b_prev;
27735 					inbound_ill =
27736 					    ill_lookup_on_ifindex(ifindex,
27737 					    B_TRUE, NULL, NULL, NULL,
27738 					    NULL, ipst);
27739 					mp1->b_prev = NULL;
27740 					if (inbound_ill != NULL)
27741 						fwdq = inbound_ill->ill_rq;
27742 
27743 					if (fwdq != NULL) {
27744 						put(fwdq, mp1);
27745 						ill_refrele(inbound_ill);
27746 					} else
27747 						put(WR(ill->ill_rq), mp1);
27748 					mp1 = nxt_mp;
27749 				}
27750 				NCE_REFRELE(nce);
27751 			} else {	/* nce is NULL; clean up */
27752 				ire_delete(ire);
27753 				freemsg(mp);
27754 				freemsg(mp1);
27755 				return;
27756 			}
27757 		} else {
27758 			nce_t *arpce;
27759 			/*
27760 			 * Link layer resolution succeeded. Recompute the
27761 			 * ire_nce.
27762 			 */
27763 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27764 			if ((arpce = ndp_lookup_v4(ill,
27765 			    (ire->ire_gateway_addr != INADDR_ANY ?
27766 			    &ire->ire_gateway_addr : &ire->ire_addr),
27767 			    B_FALSE)) == NULL) {
27768 				freeb(ire->ire_mp);
27769 				freeb(mp1);
27770 				freemsg(mp);
27771 				return;
27772 			}
27773 			mutex_enter(&arpce->nce_lock);
27774 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27775 			if (arpce->nce_state == ND_REACHABLE) {
27776 				/*
27777 				 * Someone resolved this before us;
27778 				 * cleanup the res_mp. Since ire has
27779 				 * not been added yet, the call to ire_add_v4
27780 				 * from ire_add_then_send (when a dup is
27781 				 * detected) will clean up the ire.
27782 				 */
27783 				freeb(mp1);
27784 			} else {
27785 				ASSERT(arpce->nce_res_mp == NULL);
27786 				arpce->nce_res_mp = mp1;
27787 				arpce->nce_state = ND_REACHABLE;
27788 			}
27789 			mutex_exit(&arpce->nce_lock);
27790 			if (ire->ire_marks & IRE_MARK_NOADD) {
27791 				/*
27792 				 * this ire will not be added to the ire
27793 				 * cache table, so we can set the ire_nce
27794 				 * here, as there are no atomicity constraints.
27795 				 */
27796 				ire->ire_nce = arpce;
27797 				/*
27798 				 * We are associating this nce with the ire
27799 				 * so change the nce ref taken in
27800 				 * ndp_lookup_v4() from
27801 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27802 				 */
27803 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27804 			} else {
27805 				NCE_REFRELE(arpce);
27806 			}
27807 			ire_add_then_send(q, ire, mp);
27808 		}
27809 		return;	/* All is well, the packet has been sent. */
27810 	}
27811 	case IRE_ARPRESOLVE_TYPE: {
27812 
27813 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27814 			break;
27815 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27816 		mp->b_cont = NULL;
27817 		/*
27818 		 * First, check to make sure the resolution succeeded.
27819 		 * If it failed, the second mblk will be empty.
27820 		 */
27821 		if (mp1->b_rptr == mp1->b_wptr) {
27822 			/* cleanup  the incomplete ire, free queued packets */
27823 			freemsg(mp); /* fake ire */
27824 			freeb(mp1);  /* dl_unitdata response */
27825 			return;
27826 		}
27827 
27828 		/*
27829 		 * update any incomplete nce_t found. we lookup the ctable
27830 		 * and find the nce from the ire->ire_nce because we need
27831 		 * to pass the ire to ip_xmit_v4 later, and can find both
27832 		 * ire and nce in one lookup from the ctable.
27833 		 */
27834 		fake_ire = (ire_t *)mp->b_rptr;
27835 		/*
27836 		 * By the time we come back here from ARP
27837 		 * the logical outgoing interface  of the incomplete ire
27838 		 * we added in ire_forward could have disappeared,
27839 		 * causing the incomplete ire to also have
27840 		 * dissapeared. So we need to retreive the
27841 		 * proper ipif for the ire  before looking
27842 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27843 		 */
27844 		ill = q->q_ptr;
27845 
27846 		/* Get the outgoing ipif */
27847 		mutex_enter(&ill->ill_lock);
27848 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27849 			mutex_exit(&ill->ill_lock);
27850 			freemsg(mp); /* fake ire */
27851 			freeb(mp1);  /* dl_unitdata response */
27852 			return;
27853 		}
27854 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27855 
27856 		if (ipif == NULL) {
27857 			mutex_exit(&ill->ill_lock);
27858 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27859 			freemsg(mp);
27860 			freeb(mp1);
27861 			return;
27862 		}
27863 		ipif_refhold_locked(ipif);
27864 		mutex_exit(&ill->ill_lock);
27865 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27866 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27867 		    ipif, fake_ire->ire_zoneid, NULL,
27868 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27869 		ipif_refrele(ipif);
27870 		if (ire == NULL) {
27871 			/*
27872 			 * no ire was found; check if there is an nce
27873 			 * for this lookup; if it has no ire's pointing at it
27874 			 * cleanup.
27875 			 */
27876 			if ((nce = ndp_lookup_v4(ill,
27877 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27878 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27879 			    B_FALSE)) != NULL) {
27880 				/*
27881 				 * cleanup:
27882 				 * We check for refcnt 2 (one for the nce
27883 				 * hash list + 1 for the ref taken by
27884 				 * ndp_lookup_v4) to check that there are
27885 				 * no ire's pointing at the nce.
27886 				 */
27887 				if (nce->nce_refcnt == 2)
27888 					ndp_delete(nce);
27889 				NCE_REFRELE(nce);
27890 			}
27891 			freeb(mp1);  /* dl_unitdata response */
27892 			freemsg(mp); /* fake ire */
27893 			return;
27894 		}
27895 		nce = ire->ire_nce;
27896 		DTRACE_PROBE2(ire__arpresolve__type,
27897 		    ire_t *, ire, nce_t *, nce);
27898 		ASSERT(nce->nce_state != ND_INITIAL);
27899 		mutex_enter(&nce->nce_lock);
27900 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27901 		if (nce->nce_state == ND_REACHABLE) {
27902 			/*
27903 			 * Someone resolved this before us;
27904 			 * our response is not needed any more.
27905 			 */
27906 			mutex_exit(&nce->nce_lock);
27907 			freeb(mp1);  /* dl_unitdata response */
27908 		} else {
27909 			ASSERT(nce->nce_res_mp == NULL);
27910 			nce->nce_res_mp = mp1;
27911 			nce->nce_state = ND_REACHABLE;
27912 			mutex_exit(&nce->nce_lock);
27913 			nce_fastpath(nce);
27914 		}
27915 		/*
27916 		 * The cached nce_t has been updated to be reachable;
27917 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27918 		 */
27919 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27920 		freemsg(mp);
27921 		/*
27922 		 * send out queued packets.
27923 		 */
27924 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27925 
27926 		IRE_REFRELE(ire);
27927 		return;
27928 	}
27929 	default:
27930 		break;
27931 	}
27932 	if (q->q_next) {
27933 		putnext(q, mp);
27934 	} else
27935 		freemsg(mp);
27936 	return;
27937 
27938 protonak:
27939 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27940 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27941 		qreply(q, mp);
27942 }
27943 
27944 /*
27945  * Process IP options in an outbound packet.  Modify the destination if there
27946  * is a source route option.
27947  * Returns non-zero if something fails in which case an ICMP error has been
27948  * sent and mp freed.
27949  */
27950 static int
27951 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27952     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27953 {
27954 	ipoptp_t	opts;
27955 	uchar_t		*opt;
27956 	uint8_t		optval;
27957 	uint8_t		optlen;
27958 	ipaddr_t	dst;
27959 	intptr_t	code = 0;
27960 	mblk_t		*mp;
27961 	ire_t		*ire = NULL;
27962 
27963 	ip2dbg(("ip_wput_options\n"));
27964 	mp = ipsec_mp;
27965 	if (mctl_present) {
27966 		mp = ipsec_mp->b_cont;
27967 	}
27968 
27969 	dst = ipha->ipha_dst;
27970 	for (optval = ipoptp_first(&opts, ipha);
27971 	    optval != IPOPT_EOL;
27972 	    optval = ipoptp_next(&opts)) {
27973 		opt = opts.ipoptp_cur;
27974 		optlen = opts.ipoptp_len;
27975 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27976 		    optval, optlen));
27977 		switch (optval) {
27978 			uint32_t off;
27979 		case IPOPT_SSRR:
27980 		case IPOPT_LSRR:
27981 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27982 				ip1dbg((
27983 				    "ip_wput_options: bad option offset\n"));
27984 				code = (char *)&opt[IPOPT_OLEN] -
27985 				    (char *)ipha;
27986 				goto param_prob;
27987 			}
27988 			off = opt[IPOPT_OFFSET];
27989 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27990 			    ntohl(dst)));
27991 			/*
27992 			 * For strict: verify that dst is directly
27993 			 * reachable.
27994 			 */
27995 			if (optval == IPOPT_SSRR) {
27996 				ire = ire_ftable_lookup(dst, 0, 0,
27997 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27998 				    MBLK_GETLABEL(mp),
27999 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
28000 				if (ire == NULL) {
28001 					ip1dbg(("ip_wput_options: SSRR not"
28002 					    " directly reachable: 0x%x\n",
28003 					    ntohl(dst)));
28004 					goto bad_src_route;
28005 				}
28006 				ire_refrele(ire);
28007 			}
28008 			break;
28009 		case IPOPT_RR:
28010 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28011 				ip1dbg((
28012 				    "ip_wput_options: bad option offset\n"));
28013 				code = (char *)&opt[IPOPT_OLEN] -
28014 				    (char *)ipha;
28015 				goto param_prob;
28016 			}
28017 			break;
28018 		case IPOPT_TS:
28019 			/*
28020 			 * Verify that length >=5 and that there is either
28021 			 * room for another timestamp or that the overflow
28022 			 * counter is not maxed out.
28023 			 */
28024 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
28025 			if (optlen < IPOPT_MINLEN_IT) {
28026 				goto param_prob;
28027 			}
28028 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
28029 				ip1dbg((
28030 				    "ip_wput_options: bad option offset\n"));
28031 				code = (char *)&opt[IPOPT_OFFSET] -
28032 				    (char *)ipha;
28033 				goto param_prob;
28034 			}
28035 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
28036 			case IPOPT_TS_TSONLY:
28037 				off = IPOPT_TS_TIMELEN;
28038 				break;
28039 			case IPOPT_TS_TSANDADDR:
28040 			case IPOPT_TS_PRESPEC:
28041 			case IPOPT_TS_PRESPEC_RFC791:
28042 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
28043 				break;
28044 			default:
28045 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
28046 				    (char *)ipha;
28047 				goto param_prob;
28048 			}
28049 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
28050 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
28051 				/*
28052 				 * No room and the overflow counter is 15
28053 				 * already.
28054 				 */
28055 				goto param_prob;
28056 			}
28057 			break;
28058 		}
28059 	}
28060 
28061 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28062 		return (0);
28063 
28064 	ip1dbg(("ip_wput_options: error processing IP options."));
28065 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28066 
28067 param_prob:
28068 	/*
28069 	 * Since ip_wput() isn't close to finished, we fill
28070 	 * in enough of the header for credible error reporting.
28071 	 */
28072 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28073 		/* Failed */
28074 		freemsg(ipsec_mp);
28075 		return (-1);
28076 	}
28077 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28078 	return (-1);
28079 
28080 bad_src_route:
28081 	/*
28082 	 * Since ip_wput() isn't close to finished, we fill
28083 	 * in enough of the header for credible error reporting.
28084 	 */
28085 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28086 		/* Failed */
28087 		freemsg(ipsec_mp);
28088 		return (-1);
28089 	}
28090 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28091 	return (-1);
28092 }
28093 
28094 /*
28095  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28096  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28097  * thru /etc/system.
28098  */
28099 #define	CONN_MAXDRAINCNT	64
28100 
28101 static void
28102 conn_drain_init(ip_stack_t *ipst)
28103 {
28104 	int i;
28105 
28106 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28107 
28108 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28109 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28110 		/*
28111 		 * Default value of the number of drainers is the
28112 		 * number of cpus, subject to maximum of 8 drainers.
28113 		 */
28114 		if (boot_max_ncpus != -1)
28115 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28116 		else
28117 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28118 	}
28119 
28120 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28121 	    sizeof (idl_t), KM_SLEEP);
28122 
28123 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28124 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28125 		    MUTEX_DEFAULT, NULL);
28126 	}
28127 }
28128 
28129 static void
28130 conn_drain_fini(ip_stack_t *ipst)
28131 {
28132 	int i;
28133 
28134 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28135 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28136 	kmem_free(ipst->ips_conn_drain_list,
28137 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28138 	ipst->ips_conn_drain_list = NULL;
28139 }
28140 
28141 /*
28142  * Note: For an overview of how flowcontrol is handled in IP please see the
28143  * IP Flowcontrol notes at the top of this file.
28144  *
28145  * Flow control has blocked us from proceeding. Insert the given conn in one
28146  * of the conn drain lists. These conn wq's will be qenabled later on when
28147  * STREAMS flow control does a backenable. conn_walk_drain will enable
28148  * the first conn in each of these drain lists. Each of these qenabled conns
28149  * in turn enables the next in the list, after it runs, or when it closes,
28150  * thus sustaining the drain process.
28151  *
28152  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28153  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28154  * running at any time, on a given conn, since there can be only 1 service proc
28155  * running on a queue at any time.
28156  */
28157 void
28158 conn_drain_insert(conn_t *connp)
28159 {
28160 	idl_t	*idl;
28161 	uint_t	index;
28162 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28163 
28164 	mutex_enter(&connp->conn_lock);
28165 	if (connp->conn_state_flags & CONN_CLOSING) {
28166 		/*
28167 		 * The conn is closing as a result of which CONN_CLOSING
28168 		 * is set. Return.
28169 		 */
28170 		mutex_exit(&connp->conn_lock);
28171 		return;
28172 	} else if (connp->conn_idl == NULL) {
28173 		/*
28174 		 * Assign the next drain list round robin. We dont' use
28175 		 * a lock, and thus it may not be strictly round robin.
28176 		 * Atomicity of load/stores is enough to make sure that
28177 		 * conn_drain_list_index is always within bounds.
28178 		 */
28179 		index = ipst->ips_conn_drain_list_index;
28180 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28181 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28182 		index++;
28183 		if (index == ipst->ips_conn_drain_list_cnt)
28184 			index = 0;
28185 		ipst->ips_conn_drain_list_index = index;
28186 	}
28187 	mutex_exit(&connp->conn_lock);
28188 
28189 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28190 	if ((connp->conn_drain_prev != NULL) ||
28191 	    (connp->conn_state_flags & CONN_CLOSING)) {
28192 		/*
28193 		 * The conn is already in the drain list, OR
28194 		 * the conn is closing. We need to check again for
28195 		 * the closing case again since close can happen
28196 		 * after we drop the conn_lock, and before we
28197 		 * acquire the CONN_DRAIN_LIST_LOCK.
28198 		 */
28199 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28200 		return;
28201 	} else {
28202 		idl = connp->conn_idl;
28203 	}
28204 
28205 	/*
28206 	 * The conn is not in the drain list. Insert it at the
28207 	 * tail of the drain list. The drain list is circular
28208 	 * and doubly linked. idl_conn points to the 1st element
28209 	 * in the list.
28210 	 */
28211 	if (idl->idl_conn == NULL) {
28212 		idl->idl_conn = connp;
28213 		connp->conn_drain_next = connp;
28214 		connp->conn_drain_prev = connp;
28215 	} else {
28216 		conn_t *head = idl->idl_conn;
28217 
28218 		connp->conn_drain_next = head;
28219 		connp->conn_drain_prev = head->conn_drain_prev;
28220 		head->conn_drain_prev->conn_drain_next = connp;
28221 		head->conn_drain_prev = connp;
28222 	}
28223 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28224 }
28225 
28226 /*
28227  * This conn is closing, and we are called from ip_close. OR
28228  * This conn has been serviced by ip_wsrv, and we need to do the tail
28229  * processing.
28230  * If this conn is part of the drain list, we may need to sustain the drain
28231  * process by qenabling the next conn in the drain list. We may also need to
28232  * remove this conn from the list, if it is done.
28233  */
28234 static void
28235 conn_drain_tail(conn_t *connp, boolean_t closing)
28236 {
28237 	idl_t *idl;
28238 
28239 	/*
28240 	 * connp->conn_idl is stable at this point, and no lock is needed
28241 	 * to check it. If we are called from ip_close, close has already
28242 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28243 	 * called us only because conn_idl is non-null. If we are called thru
28244 	 * service, conn_idl could be null, but it cannot change because
28245 	 * service is single-threaded per queue, and there cannot be another
28246 	 * instance of service trying to call conn_drain_insert on this conn
28247 	 * now.
28248 	 */
28249 	ASSERT(!closing || (connp->conn_idl != NULL));
28250 
28251 	/*
28252 	 * If connp->conn_idl is null, the conn has not been inserted into any
28253 	 * drain list even once since creation of the conn. Just return.
28254 	 */
28255 	if (connp->conn_idl == NULL)
28256 		return;
28257 
28258 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28259 
28260 	if (connp->conn_drain_prev == NULL) {
28261 		/* This conn is currently not in the drain list.  */
28262 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28263 		return;
28264 	}
28265 	idl = connp->conn_idl;
28266 	if (idl->idl_conn_draining == connp) {
28267 		/*
28268 		 * This conn is the current drainer. If this is the last conn
28269 		 * in the drain list, we need to do more checks, in the 'if'
28270 		 * below. Otherwwise we need to just qenable the next conn,
28271 		 * to sustain the draining, and is handled in the 'else'
28272 		 * below.
28273 		 */
28274 		if (connp->conn_drain_next == idl->idl_conn) {
28275 			/*
28276 			 * This conn is the last in this list. This round
28277 			 * of draining is complete. If idl_repeat is set,
28278 			 * it means another flow enabling has happened from
28279 			 * the driver/streams and we need to another round
28280 			 * of draining.
28281 			 * If there are more than 2 conns in the drain list,
28282 			 * do a left rotate by 1, so that all conns except the
28283 			 * conn at the head move towards the head by 1, and the
28284 			 * the conn at the head goes to the tail. This attempts
28285 			 * a more even share for all queues that are being
28286 			 * drained.
28287 			 */
28288 			if ((connp->conn_drain_next != connp) &&
28289 			    (idl->idl_conn->conn_drain_next != connp)) {
28290 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28291 			}
28292 			if (idl->idl_repeat) {
28293 				qenable(idl->idl_conn->conn_wq);
28294 				idl->idl_conn_draining = idl->idl_conn;
28295 				idl->idl_repeat = 0;
28296 			} else {
28297 				idl->idl_conn_draining = NULL;
28298 			}
28299 		} else {
28300 			/*
28301 			 * If the next queue that we are now qenable'ing,
28302 			 * is closing, it will remove itself from this list
28303 			 * and qenable the subsequent queue in ip_close().
28304 			 * Serialization is acheived thru idl_lock.
28305 			 */
28306 			qenable(connp->conn_drain_next->conn_wq);
28307 			idl->idl_conn_draining = connp->conn_drain_next;
28308 		}
28309 	}
28310 	if (!connp->conn_did_putbq || closing) {
28311 		/*
28312 		 * Remove ourself from the drain list, if we did not do
28313 		 * a putbq, or if the conn is closing.
28314 		 * Note: It is possible that q->q_first is non-null. It means
28315 		 * that these messages landed after we did a enableok() in
28316 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28317 		 * service them.
28318 		 */
28319 		if (connp->conn_drain_next == connp) {
28320 			/* Singleton in the list */
28321 			ASSERT(connp->conn_drain_prev == connp);
28322 			idl->idl_conn = NULL;
28323 			idl->idl_conn_draining = NULL;
28324 		} else {
28325 			connp->conn_drain_prev->conn_drain_next =
28326 			    connp->conn_drain_next;
28327 			connp->conn_drain_next->conn_drain_prev =
28328 			    connp->conn_drain_prev;
28329 			if (idl->idl_conn == connp)
28330 				idl->idl_conn = connp->conn_drain_next;
28331 			ASSERT(idl->idl_conn_draining != connp);
28332 
28333 		}
28334 		connp->conn_drain_next = NULL;
28335 		connp->conn_drain_prev = NULL;
28336 	}
28337 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28338 }
28339 
28340 /*
28341  * Write service routine. Shared perimeter entry point.
28342  * ip_wsrv can be called in any of the following ways.
28343  * 1. The device queue's messages has fallen below the low water mark
28344  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28345  *    the drain lists and backenable the first conn in each list.
28346  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28347  *    qenabled non-tcp upper layers. We start dequeing messages and call
28348  *    ip_wput for each message.
28349  */
28350 
28351 void
28352 ip_wsrv(queue_t *q)
28353 {
28354 	conn_t	*connp;
28355 	ill_t	*ill;
28356 	mblk_t	*mp;
28357 
28358 	if (q->q_next) {
28359 		ill = (ill_t *)q->q_ptr;
28360 		if (ill->ill_state_flags == 0) {
28361 			/*
28362 			 * The device flow control has opened up.
28363 			 * Walk through conn drain lists and qenable the
28364 			 * first conn in each list. This makes sense only
28365 			 * if the stream is fully plumbed and setup.
28366 			 * Hence the if check above.
28367 			 */
28368 			ip1dbg(("ip_wsrv: walking\n"));
28369 			conn_walk_drain(ill->ill_ipst);
28370 		}
28371 		return;
28372 	}
28373 
28374 	connp = Q_TO_CONN(q);
28375 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28376 
28377 	/*
28378 	 * 1. Set conn_draining flag to signal that service is active.
28379 	 *
28380 	 * 2. ip_output determines whether it has been called from service,
28381 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28382 	 *    has been called from service.
28383 	 *
28384 	 * 3. Message ordering is preserved by the following logic.
28385 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28386 	 *    the message at the tail, if conn_draining is set (i.e. service
28387 	 *    is running) or if q->q_first is non-null.
28388 	 *
28389 	 *    ii. If ip_output is called from service, and if ip_output cannot
28390 	 *    putnext due to flow control, it does a putbq.
28391 	 *
28392 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28393 	 *    (causing an infinite loop).
28394 	 */
28395 	ASSERT(!connp->conn_did_putbq);
28396 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28397 		connp->conn_draining = 1;
28398 		noenable(q);
28399 		while ((mp = getq(q)) != NULL) {
28400 			ASSERT(CONN_Q(q));
28401 
28402 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28403 			if (connp->conn_did_putbq) {
28404 				/* ip_wput did a putbq */
28405 				break;
28406 			}
28407 		}
28408 		/*
28409 		 * At this point, a thread coming down from top, calling
28410 		 * ip_wput, may end up queueing the message. We have not yet
28411 		 * enabled the queue, so ip_wsrv won't be called again.
28412 		 * To avoid this race, check q->q_first again (in the loop)
28413 		 * If the other thread queued the message before we call
28414 		 * enableok(), we will catch it in the q->q_first check.
28415 		 * If the other thread queues the message after we call
28416 		 * enableok(), ip_wsrv will be called again by STREAMS.
28417 		 */
28418 		connp->conn_draining = 0;
28419 		enableok(q);
28420 	}
28421 
28422 	/* Enable the next conn for draining */
28423 	conn_drain_tail(connp, B_FALSE);
28424 
28425 	connp->conn_did_putbq = 0;
28426 }
28427 
28428 /*
28429  * Walk the list of all conn's calling the function provided with the
28430  * specified argument for each.	 Note that this only walks conn's that
28431  * have been bound.
28432  * Applies to both IPv4 and IPv6.
28433  */
28434 static void
28435 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28436 {
28437 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28438 	    ipst->ips_ipcl_udp_fanout_size,
28439 	    func, arg, zoneid);
28440 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28441 	    ipst->ips_ipcl_conn_fanout_size,
28442 	    func, arg, zoneid);
28443 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28444 	    ipst->ips_ipcl_bind_fanout_size,
28445 	    func, arg, zoneid);
28446 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28447 	    IPPROTO_MAX, func, arg, zoneid);
28448 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28449 	    IPPROTO_MAX, func, arg, zoneid);
28450 }
28451 
28452 /*
28453  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28454  * of conns that need to be drained, check if drain is already in progress.
28455  * If so set the idl_repeat bit, indicating that the last conn in the list
28456  * needs to reinitiate the drain once again, for the list. If drain is not
28457  * in progress for the list, initiate the draining, by qenabling the 1st
28458  * conn in the list. The drain is self-sustaining, each qenabled conn will
28459  * in turn qenable the next conn, when it is done/blocked/closing.
28460  */
28461 static void
28462 conn_walk_drain(ip_stack_t *ipst)
28463 {
28464 	int i;
28465 	idl_t *idl;
28466 
28467 	IP_STAT(ipst, ip_conn_walk_drain);
28468 
28469 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28470 		idl = &ipst->ips_conn_drain_list[i];
28471 		mutex_enter(&idl->idl_lock);
28472 		if (idl->idl_conn == NULL) {
28473 			mutex_exit(&idl->idl_lock);
28474 			continue;
28475 		}
28476 		/*
28477 		 * If this list is not being drained currently by
28478 		 * an ip_wsrv thread, start the process.
28479 		 */
28480 		if (idl->idl_conn_draining == NULL) {
28481 			ASSERT(idl->idl_repeat == 0);
28482 			qenable(idl->idl_conn->conn_wq);
28483 			idl->idl_conn_draining = idl->idl_conn;
28484 		} else {
28485 			idl->idl_repeat = 1;
28486 		}
28487 		mutex_exit(&idl->idl_lock);
28488 	}
28489 }
28490 
28491 /*
28492  * Walk an conn hash table of `count' buckets, calling func for each entry.
28493  */
28494 static void
28495 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28496     zoneid_t zoneid)
28497 {
28498 	conn_t	*connp;
28499 
28500 	while (count-- > 0) {
28501 		mutex_enter(&connfp->connf_lock);
28502 		for (connp = connfp->connf_head; connp != NULL;
28503 		    connp = connp->conn_next) {
28504 			if (zoneid == GLOBAL_ZONEID ||
28505 			    zoneid == connp->conn_zoneid) {
28506 				CONN_INC_REF(connp);
28507 				mutex_exit(&connfp->connf_lock);
28508 				(*func)(connp, arg);
28509 				mutex_enter(&connfp->connf_lock);
28510 				CONN_DEC_REF(connp);
28511 			}
28512 		}
28513 		mutex_exit(&connfp->connf_lock);
28514 		connfp++;
28515 	}
28516 }
28517 
28518 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28519 static void
28520 conn_report1(conn_t *connp, void *mp)
28521 {
28522 	char	buf1[INET6_ADDRSTRLEN];
28523 	char	buf2[INET6_ADDRSTRLEN];
28524 	uint_t	print_len, buf_len;
28525 
28526 	ASSERT(connp != NULL);
28527 
28528 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28529 	if (buf_len <= 0)
28530 		return;
28531 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28532 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28533 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28534 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28535 	    "%5d %s/%05d %s/%05d\n",
28536 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28537 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28538 	    buf1, connp->conn_lport,
28539 	    buf2, connp->conn_fport);
28540 	if (print_len < buf_len) {
28541 		((mblk_t *)mp)->b_wptr += print_len;
28542 	} else {
28543 		((mblk_t *)mp)->b_wptr += buf_len;
28544 	}
28545 }
28546 
28547 /*
28548  * Named Dispatch routine to produce a formatted report on all conns
28549  * that are listed in one of the fanout tables.
28550  * This report is accessed by using the ndd utility to "get" ND variable
28551  * "ip_conn_status".
28552  */
28553 /* ARGSUSED */
28554 static int
28555 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28556 {
28557 	conn_t *connp = Q_TO_CONN(q);
28558 
28559 	(void) mi_mpprintf(mp,
28560 	    "CONN      " MI_COL_HDRPAD_STR
28561 	    "rfq      " MI_COL_HDRPAD_STR
28562 	    "stq      " MI_COL_HDRPAD_STR
28563 	    " zone local                 remote");
28564 
28565 	/*
28566 	 * Because of the ndd constraint, at most we can have 64K buffer
28567 	 * to put in all conn info.  So to be more efficient, just
28568 	 * allocate a 64K buffer here, assuming we need that large buffer.
28569 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28570 	 */
28571 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28572 		/* The following may work even if we cannot get a large buf. */
28573 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28574 		return (0);
28575 	}
28576 
28577 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28578 	    connp->conn_netstack->netstack_ip);
28579 	return (0);
28580 }
28581 
28582 /*
28583  * Determine if the ill and multicast aspects of that packets
28584  * "matches" the conn.
28585  */
28586 boolean_t
28587 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28588     zoneid_t zoneid)
28589 {
28590 	ill_t *in_ill;
28591 	boolean_t found;
28592 	ipif_t *ipif;
28593 	ire_t *ire;
28594 	ipaddr_t dst, src;
28595 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28596 
28597 	dst = ipha->ipha_dst;
28598 	src = ipha->ipha_src;
28599 
28600 	/*
28601 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28602 	 * unicast, broadcast and multicast reception to
28603 	 * conn_incoming_ill. conn_wantpacket itself is called
28604 	 * only for BROADCAST and multicast.
28605 	 *
28606 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28607 	 *    is part of a group. Hence, we should be receiving
28608 	 *    just one copy of broadcast for the whole group.
28609 	 *    Thus, if it is part of the group the packet could
28610 	 *    come on any ill of the group and hence we need a
28611 	 *    match on the group. Otherwise, match on ill should
28612 	 *    be sufficient.
28613 	 *
28614 	 * 2) ip_rput does not suppress duplicate multicast packets.
28615 	 *    If there are two interfaces in a ill group and we have
28616 	 *    2 applications (conns) joined a multicast group G on
28617 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28618 	 *    will give us two packets because we join G on both the
28619 	 *    interfaces rather than nominating just one interface
28620 	 *    for receiving multicast like broadcast above. So,
28621 	 *    we have to call ilg_lookup_ill to filter out duplicate
28622 	 *    copies, if ill is part of a group.
28623 	 */
28624 	in_ill = connp->conn_incoming_ill;
28625 	if (in_ill != NULL) {
28626 		if (in_ill->ill_group == NULL) {
28627 			if (in_ill != ill)
28628 				return (B_FALSE);
28629 		} else if (in_ill->ill_group != ill->ill_group) {
28630 			return (B_FALSE);
28631 		}
28632 	}
28633 
28634 	if (!CLASSD(dst)) {
28635 		if (IPCL_ZONE_MATCH(connp, zoneid))
28636 			return (B_TRUE);
28637 		/*
28638 		 * The conn is in a different zone; we need to check that this
28639 		 * broadcast address is configured in the application's zone and
28640 		 * on one ill in the group.
28641 		 */
28642 		ipif = ipif_get_next_ipif(NULL, ill);
28643 		if (ipif == NULL)
28644 			return (B_FALSE);
28645 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28646 		    connp->conn_zoneid, NULL,
28647 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28648 		ipif_refrele(ipif);
28649 		if (ire != NULL) {
28650 			ire_refrele(ire);
28651 			return (B_TRUE);
28652 		} else {
28653 			return (B_FALSE);
28654 		}
28655 	}
28656 
28657 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28658 	    connp->conn_zoneid == zoneid) {
28659 		/*
28660 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28661 		 * disabled, therefore we don't dispatch the multicast packet to
28662 		 * the sending zone.
28663 		 */
28664 		return (B_FALSE);
28665 	}
28666 
28667 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28668 		/*
28669 		 * Multicast packet on the loopback interface: we only match
28670 		 * conns who joined the group in the specified zone.
28671 		 */
28672 		return (B_FALSE);
28673 	}
28674 
28675 	if (connp->conn_multi_router) {
28676 		/* multicast packet and multicast router socket: send up */
28677 		return (B_TRUE);
28678 	}
28679 
28680 	mutex_enter(&connp->conn_lock);
28681 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28682 	mutex_exit(&connp->conn_lock);
28683 	return (found);
28684 }
28685 
28686 /*
28687  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28688  */
28689 /* ARGSUSED */
28690 static void
28691 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28692 {
28693 	ill_t *ill = (ill_t *)q->q_ptr;
28694 	mblk_t	*mp1, *mp2;
28695 	ipif_t  *ipif;
28696 	int err = 0;
28697 	conn_t *connp = NULL;
28698 	ipsq_t	*ipsq;
28699 	arc_t	*arc;
28700 
28701 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28702 
28703 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28704 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28705 
28706 	ASSERT(IAM_WRITER_ILL(ill));
28707 	mp2 = mp->b_cont;
28708 	mp->b_cont = NULL;
28709 
28710 	/*
28711 	 * We have now received the arp bringup completion message
28712 	 * from ARP. Mark the arp bringup as done. Also if the arp
28713 	 * stream has already started closing, send up the AR_ARP_CLOSING
28714 	 * ack now since ARP is waiting in close for this ack.
28715 	 */
28716 	mutex_enter(&ill->ill_lock);
28717 	ill->ill_arp_bringup_pending = 0;
28718 	if (ill->ill_arp_closing) {
28719 		mutex_exit(&ill->ill_lock);
28720 		/* Let's reuse the mp for sending the ack */
28721 		arc = (arc_t *)mp->b_rptr;
28722 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28723 		arc->arc_cmd = AR_ARP_CLOSING;
28724 		qreply(q, mp);
28725 	} else {
28726 		mutex_exit(&ill->ill_lock);
28727 		freeb(mp);
28728 	}
28729 
28730 	ipsq = ill->ill_phyint->phyint_ipsq;
28731 	ipif = ipsq->ipsq_pending_ipif;
28732 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28733 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28734 	if (mp1 == NULL) {
28735 		/* bringup was aborted by the user */
28736 		freemsg(mp2);
28737 		return;
28738 	}
28739 
28740 	/*
28741 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28742 	 * must have an associated conn_t.  Otherwise, we're bringing this
28743 	 * interface back up as part of handling an asynchronous event (e.g.,
28744 	 * physical address change).
28745 	 */
28746 	if (ipsq->ipsq_current_ioctl != 0) {
28747 		ASSERT(connp != NULL);
28748 		q = CONNP_TO_WQ(connp);
28749 	} else {
28750 		ASSERT(connp == NULL);
28751 		q = ill->ill_rq;
28752 	}
28753 
28754 	/*
28755 	 * If the DL_BIND_REQ fails, it is noted
28756 	 * in arc_name_offset.
28757 	 */
28758 	err = *((int *)mp2->b_rptr);
28759 	if (err == 0) {
28760 		if (ipif->ipif_isv6) {
28761 			if ((err = ipif_up_done_v6(ipif)) != 0)
28762 				ip0dbg(("ip_arp_done: init failed\n"));
28763 		} else {
28764 			if ((err = ipif_up_done(ipif)) != 0)
28765 				ip0dbg(("ip_arp_done: init failed\n"));
28766 		}
28767 	} else {
28768 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28769 	}
28770 
28771 	freemsg(mp2);
28772 
28773 	if ((err == 0) && (ill->ill_up_ipifs)) {
28774 		err = ill_up_ipifs(ill, q, mp1);
28775 		if (err == EINPROGRESS)
28776 			return;
28777 	}
28778 
28779 	if (ill->ill_up_ipifs)
28780 		ill_group_cleanup(ill);
28781 
28782 	/*
28783 	 * The operation must complete without EINPROGRESS since
28784 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28785 	 * Otherwise, the operation will be stuck forever in the ipsq.
28786 	 */
28787 	ASSERT(err != EINPROGRESS);
28788 	if (ipsq->ipsq_current_ioctl != 0)
28789 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28790 	else
28791 		ipsq_current_finish(ipsq);
28792 }
28793 
28794 /* Allocate the private structure */
28795 static int
28796 ip_priv_alloc(void **bufp)
28797 {
28798 	void	*buf;
28799 
28800 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28801 		return (ENOMEM);
28802 
28803 	*bufp = buf;
28804 	return (0);
28805 }
28806 
28807 /* Function to delete the private structure */
28808 void
28809 ip_priv_free(void *buf)
28810 {
28811 	ASSERT(buf != NULL);
28812 	kmem_free(buf, sizeof (ip_priv_t));
28813 }
28814 
28815 /*
28816  * The entry point for IPPF processing.
28817  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28818  * routine just returns.
28819  *
28820  * When called, ip_process generates an ipp_packet_t structure
28821  * which holds the state information for this packet and invokes the
28822  * the classifier (via ipp_packet_process). The classification, depending on
28823  * configured filters, results in a list of actions for this packet. Invoking
28824  * an action may cause the packet to be dropped, in which case the resulting
28825  * mblk (*mpp) is NULL. proc indicates the callout position for
28826  * this packet and ill_index is the interface this packet on or will leave
28827  * on (inbound and outbound resp.).
28828  */
28829 void
28830 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28831 {
28832 	mblk_t		*mp;
28833 	ip_priv_t	*priv;
28834 	ipp_action_id_t	aid;
28835 	int		rc = 0;
28836 	ipp_packet_t	*pp;
28837 #define	IP_CLASS	"ip"
28838 
28839 	/* If the classifier is not loaded, return  */
28840 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28841 		return;
28842 	}
28843 
28844 	mp = *mpp;
28845 	ASSERT(mp != NULL);
28846 
28847 	/* Allocate the packet structure */
28848 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28849 	if (rc != 0) {
28850 		*mpp = NULL;
28851 		freemsg(mp);
28852 		return;
28853 	}
28854 
28855 	/* Allocate the private structure */
28856 	rc = ip_priv_alloc((void **)&priv);
28857 	if (rc != 0) {
28858 		*mpp = NULL;
28859 		freemsg(mp);
28860 		ipp_packet_free(pp);
28861 		return;
28862 	}
28863 	priv->proc = proc;
28864 	priv->ill_index = ill_index;
28865 	ipp_packet_set_private(pp, priv, ip_priv_free);
28866 	ipp_packet_set_data(pp, mp);
28867 
28868 	/* Invoke the classifier */
28869 	rc = ipp_packet_process(&pp);
28870 	if (pp != NULL) {
28871 		mp = ipp_packet_get_data(pp);
28872 		ipp_packet_free(pp);
28873 		if (rc != 0) {
28874 			freemsg(mp);
28875 			*mpp = NULL;
28876 		}
28877 	} else {
28878 		*mpp = NULL;
28879 	}
28880 #undef	IP_CLASS
28881 }
28882 
28883 /*
28884  * Propagate a multicast group membership operation (add/drop) on
28885  * all the interfaces crossed by the related multirt routes.
28886  * The call is considered successful if the operation succeeds
28887  * on at least one interface.
28888  */
28889 static int
28890 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28891     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28892     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28893     mblk_t *first_mp)
28894 {
28895 	ire_t		*ire_gw;
28896 	irb_t		*irb;
28897 	int		error = 0;
28898 	opt_restart_t	*or;
28899 	ip_stack_t	*ipst = ire->ire_ipst;
28900 
28901 	irb = ire->ire_bucket;
28902 	ASSERT(irb != NULL);
28903 
28904 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28905 
28906 	or = (opt_restart_t *)first_mp->b_rptr;
28907 	IRB_REFHOLD(irb);
28908 	for (; ire != NULL; ire = ire->ire_next) {
28909 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28910 			continue;
28911 		if (ire->ire_addr != group)
28912 			continue;
28913 
28914 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28915 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28916 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28917 		/* No resolver exists for the gateway; skip this ire. */
28918 		if (ire_gw == NULL)
28919 			continue;
28920 
28921 		/*
28922 		 * This function can return EINPROGRESS. If so the operation
28923 		 * will be restarted from ip_restart_optmgmt which will
28924 		 * call ip_opt_set and option processing will restart for
28925 		 * this option. So we may end up calling 'fn' more than once.
28926 		 * This requires that 'fn' is idempotent except for the
28927 		 * return value. The operation is considered a success if
28928 		 * it succeeds at least once on any one interface.
28929 		 */
28930 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28931 		    NULL, fmode, src, first_mp);
28932 		if (error == 0)
28933 			or->or_private = CGTP_MCAST_SUCCESS;
28934 
28935 		if (ip_debug > 0) {
28936 			ulong_t	off;
28937 			char	*ksym;
28938 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28939 			ip2dbg(("ip_multirt_apply_membership: "
28940 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28941 			    "error %d [success %u]\n",
28942 			    ksym ? ksym : "?",
28943 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28944 			    error, or->or_private));
28945 		}
28946 
28947 		ire_refrele(ire_gw);
28948 		if (error == EINPROGRESS) {
28949 			IRB_REFRELE(irb);
28950 			return (error);
28951 		}
28952 	}
28953 	IRB_REFRELE(irb);
28954 	/*
28955 	 * Consider the call as successful if we succeeded on at least
28956 	 * one interface. Otherwise, return the last encountered error.
28957 	 */
28958 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28959 }
28960 
28961 
28962 /*
28963  * Issue a warning regarding a route crossing an interface with an
28964  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28965  * amount of time is logged.
28966  */
28967 static void
28968 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28969 {
28970 	hrtime_t	current = gethrtime();
28971 	char		buf[INET_ADDRSTRLEN];
28972 	ip_stack_t	*ipst = ire->ire_ipst;
28973 
28974 	/* Convert interval in ms to hrtime in ns */
28975 	if (ipst->ips_multirt_bad_mtu_last_time +
28976 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28977 	    current) {
28978 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28979 		    "to %s, incorrect MTU %u (expected %u)\n",
28980 		    ip_dot_addr(ire->ire_addr, buf),
28981 		    ire->ire_max_frag, max_frag);
28982 
28983 		ipst->ips_multirt_bad_mtu_last_time = current;
28984 	}
28985 }
28986 
28987 
28988 /*
28989  * Get the CGTP (multirouting) filtering status.
28990  * If 0, the CGTP hooks are transparent.
28991  */
28992 /* ARGSUSED */
28993 static int
28994 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28995 {
28996 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28997 
28998 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28999 	return (0);
29000 }
29001 
29002 
29003 /*
29004  * Set the CGTP (multirouting) filtering status.
29005  * If the status is changed from active to transparent
29006  * or from transparent to active, forward the new status
29007  * to the filtering module (if loaded).
29008  */
29009 /* ARGSUSED */
29010 static int
29011 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
29012     cred_t *ioc_cr)
29013 {
29014 	long		new_value;
29015 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
29016 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29017 
29018 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
29019 		return (EPERM);
29020 
29021 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
29022 	    new_value < 0 || new_value > 1) {
29023 		return (EINVAL);
29024 	}
29025 
29026 	if ((!*ip_cgtp_filter_value) && new_value) {
29027 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
29028 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29029 		    " (module not loaded)" : "");
29030 	}
29031 	if (*ip_cgtp_filter_value && (!new_value)) {
29032 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
29033 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
29034 		    " (module not loaded)" : "");
29035 	}
29036 
29037 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29038 		int	res;
29039 		netstackid_t stackid;
29040 
29041 		stackid = ipst->ips_netstack->netstack_stackid;
29042 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
29043 		    new_value);
29044 		if (res)
29045 			return (res);
29046 	}
29047 
29048 	*ip_cgtp_filter_value = (boolean_t)new_value;
29049 
29050 	return (0);
29051 }
29052 
29053 
29054 /*
29055  * Return the expected CGTP hooks version number.
29056  */
29057 int
29058 ip_cgtp_filter_supported(void)
29059 {
29060 	return (ip_cgtp_filter_rev);
29061 }
29062 
29063 
29064 /*
29065  * CGTP hooks can be registered by invoking this function.
29066  * Checks that the version number matches.
29067  */
29068 int
29069 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29070 {
29071 	netstack_t *ns;
29072 	ip_stack_t *ipst;
29073 
29074 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29075 		return (ENOTSUP);
29076 
29077 	ns = netstack_find_by_stackid(stackid);
29078 	if (ns == NULL)
29079 		return (EINVAL);
29080 	ipst = ns->netstack_ip;
29081 	ASSERT(ipst != NULL);
29082 
29083 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29084 		netstack_rele(ns);
29085 		return (EALREADY);
29086 	}
29087 
29088 	ipst->ips_ip_cgtp_filter_ops = ops;
29089 	netstack_rele(ns);
29090 	return (0);
29091 }
29092 
29093 /*
29094  * CGTP hooks can be unregistered by invoking this function.
29095  * Returns ENXIO if there was no registration.
29096  * Returns EBUSY if the ndd variable has not been turned off.
29097  */
29098 int
29099 ip_cgtp_filter_unregister(netstackid_t stackid)
29100 {
29101 	netstack_t *ns;
29102 	ip_stack_t *ipst;
29103 
29104 	ns = netstack_find_by_stackid(stackid);
29105 	if (ns == NULL)
29106 		return (EINVAL);
29107 	ipst = ns->netstack_ip;
29108 	ASSERT(ipst != NULL);
29109 
29110 	if (ipst->ips_ip_cgtp_filter) {
29111 		netstack_rele(ns);
29112 		return (EBUSY);
29113 	}
29114 
29115 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29116 		netstack_rele(ns);
29117 		return (ENXIO);
29118 	}
29119 	ipst->ips_ip_cgtp_filter_ops = NULL;
29120 	netstack_rele(ns);
29121 	return (0);
29122 }
29123 
29124 /*
29125  * Check whether there is a CGTP filter registration.
29126  * Returns non-zero if there is a registration, otherwise returns zero.
29127  * Note: returns zero if bad stackid.
29128  */
29129 int
29130 ip_cgtp_filter_is_registered(netstackid_t stackid)
29131 {
29132 	netstack_t *ns;
29133 	ip_stack_t *ipst;
29134 	int ret;
29135 
29136 	ns = netstack_find_by_stackid(stackid);
29137 	if (ns == NULL)
29138 		return (0);
29139 	ipst = ns->netstack_ip;
29140 	ASSERT(ipst != NULL);
29141 
29142 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29143 		ret = 1;
29144 	else
29145 		ret = 0;
29146 
29147 	netstack_rele(ns);
29148 	return (ret);
29149 }
29150 
29151 static squeue_func_t
29152 ip_squeue_switch(int val)
29153 {
29154 	squeue_func_t rval = squeue_fill;
29155 
29156 	switch (val) {
29157 	case IP_SQUEUE_ENTER_NODRAIN:
29158 		rval = squeue_enter_nodrain;
29159 		break;
29160 	case IP_SQUEUE_ENTER:
29161 		rval = squeue_enter;
29162 		break;
29163 	default:
29164 		break;
29165 	}
29166 	return (rval);
29167 }
29168 
29169 /* ARGSUSED */
29170 static int
29171 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29172     caddr_t addr, cred_t *cr)
29173 {
29174 	int *v = (int *)addr;
29175 	long new_value;
29176 
29177 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29178 		return (EPERM);
29179 
29180 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29181 		return (EINVAL);
29182 
29183 	ip_input_proc = ip_squeue_switch(new_value);
29184 	*v = new_value;
29185 	return (0);
29186 }
29187 
29188 /*
29189  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29190  * ip_debug.
29191  */
29192 /* ARGSUSED */
29193 static int
29194 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29195     caddr_t addr, cred_t *cr)
29196 {
29197 	int *v = (int *)addr;
29198 	long new_value;
29199 
29200 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29201 		return (EPERM);
29202 
29203 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29204 		return (EINVAL);
29205 
29206 	*v = new_value;
29207 	return (0);
29208 }
29209 
29210 /*
29211  * Handle changes to ipmp_hook_emulation ndd variable.
29212  * Need to update phyint_hook_ifindex.
29213  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29214  */
29215 static void
29216 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29217 {
29218 	phyint_t *phyi;
29219 	phyint_t *phyi_tmp;
29220 	char *groupname;
29221 	int namelen;
29222 	ill_t	*ill;
29223 	boolean_t new_group;
29224 
29225 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29226 	/*
29227 	 * Group indicies are stored in the phyint - a common structure
29228 	 * to both IPv4 and IPv6.
29229 	 */
29230 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29231 	for (; phyi != NULL;
29232 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29233 	    phyi, AVL_AFTER)) {
29234 		/* Ignore the ones that do not have a group */
29235 		if (phyi->phyint_groupname_len == 0)
29236 			continue;
29237 
29238 		/*
29239 		 * Look for other phyint in group.
29240 		 * Clear name/namelen so the lookup doesn't find ourselves.
29241 		 */
29242 		namelen = phyi->phyint_groupname_len;
29243 		groupname = phyi->phyint_groupname;
29244 		phyi->phyint_groupname_len = 0;
29245 		phyi->phyint_groupname = NULL;
29246 
29247 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29248 		/* Restore */
29249 		phyi->phyint_groupname_len = namelen;
29250 		phyi->phyint_groupname = groupname;
29251 
29252 		new_group = B_FALSE;
29253 		if (ipst->ips_ipmp_hook_emulation) {
29254 			/*
29255 			 * If the group already exists and has already
29256 			 * been assigned a group ifindex, we use the existing
29257 			 * group_ifindex, otherwise we pick a new group_ifindex
29258 			 * here.
29259 			 */
29260 			if (phyi_tmp != NULL &&
29261 			    phyi_tmp->phyint_group_ifindex != 0) {
29262 				phyi->phyint_group_ifindex =
29263 				    phyi_tmp->phyint_group_ifindex;
29264 			} else {
29265 				/* XXX We need a recovery strategy here. */
29266 				if (!ip_assign_ifindex(
29267 				    &phyi->phyint_group_ifindex, ipst))
29268 					cmn_err(CE_PANIC,
29269 					    "ip_assign_ifindex() failed");
29270 				new_group = B_TRUE;
29271 			}
29272 		} else {
29273 			phyi->phyint_group_ifindex = 0;
29274 		}
29275 		if (ipst->ips_ipmp_hook_emulation)
29276 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29277 		else
29278 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29279 
29280 		/*
29281 		 * For IP Filter to find out the relationship between
29282 		 * names and interface indicies, we need to generate
29283 		 * a NE_PLUMB event when a new group can appear.
29284 		 * We always generate events when a new interface appears
29285 		 * (even when ipmp_hook_emulation is set) so there
29286 		 * is no need to generate NE_PLUMB events when
29287 		 * ipmp_hook_emulation is turned off.
29288 		 * And since it isn't critical for IP Filter to get
29289 		 * the NE_UNPLUMB events we skip those here.
29290 		 */
29291 		if (new_group) {
29292 			/*
29293 			 * First phyint in group - generate group PLUMB event.
29294 			 * Since we are not running inside the ipsq we do
29295 			 * the dispatch immediately.
29296 			 */
29297 			if (phyi->phyint_illv4 != NULL)
29298 				ill = phyi->phyint_illv4;
29299 			else
29300 				ill = phyi->phyint_illv6;
29301 
29302 			if (ill != NULL) {
29303 				mutex_enter(&ill->ill_lock);
29304 				ill_nic_info_plumb(ill, B_TRUE);
29305 				ill_nic_info_dispatch(ill);
29306 				mutex_exit(&ill->ill_lock);
29307 			}
29308 		}
29309 	}
29310 	rw_exit(&ipst->ips_ill_g_lock);
29311 }
29312 
29313 /* ARGSUSED */
29314 static int
29315 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29316     caddr_t addr, cred_t *cr)
29317 {
29318 	int *v = (int *)addr;
29319 	long new_value;
29320 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29321 
29322 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29323 		return (EINVAL);
29324 
29325 	if (*v != new_value) {
29326 		*v = new_value;
29327 		ipmp_hook_emulation_changed(ipst);
29328 	}
29329 	return (0);
29330 }
29331 
29332 static void *
29333 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29334 {
29335 	kstat_t *ksp;
29336 
29337 	ip_stat_t template = {
29338 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29339 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29340 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29341 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29342 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29343 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29344 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29345 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29346 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29347 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29348 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29349 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29350 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29351 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29352 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29353 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29354 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29355 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29356 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29357 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29358 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29359 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29360 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29361 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29362 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29363 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29364 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29365 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29366 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29367 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29368 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29369 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29370 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29371 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29372 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29373 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29374 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29375 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29376 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29377 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29378 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29379 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29380 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29381 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29382 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29383 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29384 	};
29385 
29386 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29387 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29388 	    KSTAT_FLAG_VIRTUAL, stackid);
29389 
29390 	if (ksp == NULL)
29391 		return (NULL);
29392 
29393 	bcopy(&template, ip_statisticsp, sizeof (template));
29394 	ksp->ks_data = (void *)ip_statisticsp;
29395 	ksp->ks_private = (void *)(uintptr_t)stackid;
29396 
29397 	kstat_install(ksp);
29398 	return (ksp);
29399 }
29400 
29401 static void
29402 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29403 {
29404 	if (ksp != NULL) {
29405 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29406 		kstat_delete_netstack(ksp, stackid);
29407 	}
29408 }
29409 
29410 static void *
29411 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29412 {
29413 	kstat_t	*ksp;
29414 
29415 	ip_named_kstat_t template = {
29416 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29417 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29418 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29419 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29420 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29421 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29422 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29423 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29424 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29425 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29426 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29427 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29428 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29429 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29430 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29431 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29432 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29433 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29434 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29435 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29436 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29437 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29438 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29439 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29440 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29441 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29442 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29443 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29444 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29445 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29446 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29447 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29448 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29449 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29450 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29451 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29452 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29453 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29454 	};
29455 
29456 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29457 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29458 	if (ksp == NULL || ksp->ks_data == NULL)
29459 		return (NULL);
29460 
29461 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29462 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29463 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29464 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29465 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29466 
29467 	template.netToMediaEntrySize.value.i32 =
29468 	    sizeof (mib2_ipNetToMediaEntry_t);
29469 
29470 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29471 
29472 	bcopy(&template, ksp->ks_data, sizeof (template));
29473 	ksp->ks_update = ip_kstat_update;
29474 	ksp->ks_private = (void *)(uintptr_t)stackid;
29475 
29476 	kstat_install(ksp);
29477 	return (ksp);
29478 }
29479 
29480 static void
29481 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29482 {
29483 	if (ksp != NULL) {
29484 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29485 		kstat_delete_netstack(ksp, stackid);
29486 	}
29487 }
29488 
29489 static int
29490 ip_kstat_update(kstat_t *kp, int rw)
29491 {
29492 	ip_named_kstat_t *ipkp;
29493 	mib2_ipIfStatsEntry_t ipmib;
29494 	ill_walk_context_t ctx;
29495 	ill_t *ill;
29496 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29497 	netstack_t	*ns;
29498 	ip_stack_t	*ipst;
29499 
29500 	if (kp == NULL || kp->ks_data == NULL)
29501 		return (EIO);
29502 
29503 	if (rw == KSTAT_WRITE)
29504 		return (EACCES);
29505 
29506 	ns = netstack_find_by_stackid(stackid);
29507 	if (ns == NULL)
29508 		return (-1);
29509 	ipst = ns->netstack_ip;
29510 	if (ipst == NULL) {
29511 		netstack_rele(ns);
29512 		return (-1);
29513 	}
29514 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29515 
29516 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29517 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29518 	ill = ILL_START_WALK_V4(&ctx, ipst);
29519 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29520 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29521 	rw_exit(&ipst->ips_ill_g_lock);
29522 
29523 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29524 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29525 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29526 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29527 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29528 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29529 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29530 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29531 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29532 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29533 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29534 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29535 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29536 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29537 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29538 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29539 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29540 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29541 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29542 
29543 	ipkp->routingDiscards.value.ui32 =	0;
29544 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29545 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29546 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29547 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29548 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29549 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29550 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29551 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29552 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29553 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29554 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29555 
29556 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29557 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29558 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29559 
29560 	netstack_rele(ns);
29561 
29562 	return (0);
29563 }
29564 
29565 static void *
29566 icmp_kstat_init(netstackid_t stackid)
29567 {
29568 	kstat_t	*ksp;
29569 
29570 	icmp_named_kstat_t template = {
29571 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29572 		{ "inErrors",		KSTAT_DATA_UINT32 },
29573 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29574 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29575 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29576 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29577 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29578 		{ "inEchos",		KSTAT_DATA_UINT32 },
29579 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29580 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29581 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29582 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29583 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29584 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29585 		{ "outErrors",		KSTAT_DATA_UINT32 },
29586 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29587 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29588 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29589 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29590 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29591 		{ "outEchos",		KSTAT_DATA_UINT32 },
29592 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29593 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29594 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29595 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29596 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29597 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29598 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29599 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29600 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29601 		{ "outDrops",		KSTAT_DATA_UINT32 },
29602 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29603 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29604 	};
29605 
29606 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29607 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29608 	if (ksp == NULL || ksp->ks_data == NULL)
29609 		return (NULL);
29610 
29611 	bcopy(&template, ksp->ks_data, sizeof (template));
29612 
29613 	ksp->ks_update = icmp_kstat_update;
29614 	ksp->ks_private = (void *)(uintptr_t)stackid;
29615 
29616 	kstat_install(ksp);
29617 	return (ksp);
29618 }
29619 
29620 static void
29621 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29622 {
29623 	if (ksp != NULL) {
29624 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29625 		kstat_delete_netstack(ksp, stackid);
29626 	}
29627 }
29628 
29629 static int
29630 icmp_kstat_update(kstat_t *kp, int rw)
29631 {
29632 	icmp_named_kstat_t *icmpkp;
29633 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29634 	netstack_t	*ns;
29635 	ip_stack_t	*ipst;
29636 
29637 	if ((kp == NULL) || (kp->ks_data == NULL))
29638 		return (EIO);
29639 
29640 	if (rw == KSTAT_WRITE)
29641 		return (EACCES);
29642 
29643 	ns = netstack_find_by_stackid(stackid);
29644 	if (ns == NULL)
29645 		return (-1);
29646 	ipst = ns->netstack_ip;
29647 	if (ipst == NULL) {
29648 		netstack_rele(ns);
29649 		return (-1);
29650 	}
29651 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29652 
29653 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29654 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29655 	icmpkp->inDestUnreachs.value.ui32 =
29656 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29657 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29658 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29659 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29660 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29661 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29662 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29663 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29664 	icmpkp->inTimestampReps.value.ui32 =
29665 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29666 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29667 	icmpkp->inAddrMaskReps.value.ui32 =
29668 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29669 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29670 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29671 	icmpkp->outDestUnreachs.value.ui32 =
29672 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29673 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29674 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29675 	icmpkp->outSrcQuenchs.value.ui32 =
29676 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29677 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29678 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29679 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29680 	icmpkp->outTimestamps.value.ui32 =
29681 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29682 	icmpkp->outTimestampReps.value.ui32 =
29683 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29684 	icmpkp->outAddrMasks.value.ui32 =
29685 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29686 	icmpkp->outAddrMaskReps.value.ui32 =
29687 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29688 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29689 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29690 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29691 	icmpkp->outFragNeeded.value.ui32 =
29692 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29693 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29694 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29695 	icmpkp->inBadRedirects.value.ui32 =
29696 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29697 
29698 	netstack_rele(ns);
29699 	return (0);
29700 }
29701 
29702 /*
29703  * This is the fanout function for raw socket opened for SCTP.  Note
29704  * that it is called after SCTP checks that there is no socket which
29705  * wants a packet.  Then before SCTP handles this out of the blue packet,
29706  * this function is called to see if there is any raw socket for SCTP.
29707  * If there is and it is bound to the correct address, the packet will
29708  * be sent to that socket.  Note that only one raw socket can be bound to
29709  * a port.  This is assured in ipcl_sctp_hash_insert();
29710  */
29711 void
29712 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29713     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29714     zoneid_t zoneid)
29715 {
29716 	conn_t		*connp;
29717 	queue_t		*rq;
29718 	mblk_t		*first_mp;
29719 	boolean_t	secure;
29720 	ip6_t		*ip6h;
29721 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29722 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29723 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29724 	boolean_t	sctp_csum_err = B_FALSE;
29725 
29726 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29727 		sctp_csum_err = B_TRUE;
29728 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29729 	}
29730 
29731 	first_mp = mp;
29732 	if (mctl_present) {
29733 		mp = first_mp->b_cont;
29734 		secure = ipsec_in_is_secure(first_mp);
29735 		ASSERT(mp != NULL);
29736 	} else {
29737 		secure = B_FALSE;
29738 	}
29739 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29740 
29741 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29742 	if (connp == NULL) {
29743 		/*
29744 		 * Although raw sctp is not summed, OOB chunks must be.
29745 		 * Drop the packet here if the sctp checksum failed.
29746 		 */
29747 		if (sctp_csum_err) {
29748 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29749 			freemsg(first_mp);
29750 			return;
29751 		}
29752 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29753 		return;
29754 	}
29755 	rq = connp->conn_rq;
29756 	if (!canputnext(rq)) {
29757 		CONN_DEC_REF(connp);
29758 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29759 		freemsg(first_mp);
29760 		return;
29761 	}
29762 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29763 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29764 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29765 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29766 		if (first_mp == NULL) {
29767 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29768 			CONN_DEC_REF(connp);
29769 			return;
29770 		}
29771 	}
29772 	/*
29773 	 * We probably should not send M_CTL message up to
29774 	 * raw socket.
29775 	 */
29776 	if (mctl_present)
29777 		freeb(first_mp);
29778 
29779 	/* Initiate IPPF processing here if needed. */
29780 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29781 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29782 		ip_process(IPP_LOCAL_IN, &mp,
29783 		    recv_ill->ill_phyint->phyint_ifindex);
29784 		if (mp == NULL) {
29785 			CONN_DEC_REF(connp);
29786 			return;
29787 		}
29788 	}
29789 
29790 	if (connp->conn_recvif || connp->conn_recvslla ||
29791 	    ((connp->conn_ip_recvpktinfo ||
29792 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29793 	    (flags & IP_FF_IPINFO))) {
29794 		int in_flags = 0;
29795 
29796 		/*
29797 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29798 		 * IPF_RECVIF.
29799 		 */
29800 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29801 			in_flags = IPF_RECVIF;
29802 		}
29803 		if (connp->conn_recvslla) {
29804 			in_flags |= IPF_RECVSLLA;
29805 		}
29806 		if (isv4) {
29807 			mp = ip_add_info(mp, recv_ill, in_flags,
29808 			    IPCL_ZONEID(connp), ipst);
29809 		} else {
29810 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29811 			if (mp == NULL) {
29812 				BUMP_MIB(recv_ill->ill_ip_mib,
29813 				    ipIfStatsInDiscards);
29814 				CONN_DEC_REF(connp);
29815 				return;
29816 			}
29817 		}
29818 	}
29819 
29820 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29821 	/*
29822 	 * We are sending the IPSEC_IN message also up. Refer
29823 	 * to comments above this function.
29824 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29825 	 */
29826 	(connp->conn_recv)(connp, mp, NULL);
29827 	CONN_DEC_REF(connp);
29828 }
29829 
29830 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29831 {									\
29832 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29833 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29834 }
29835 /*
29836  * This function should be called only if all packet processing
29837  * including fragmentation is complete. Callers of this function
29838  * must set mp->b_prev to one of these values:
29839  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29840  * prior to handing over the mp as first argument to this function.
29841  *
29842  * If the ire passed by caller is incomplete, this function
29843  * queues the packet and if necessary, sends ARP request and bails.
29844  * If the ire passed is fully resolved, we simply prepend
29845  * the link-layer header to the packet, do ipsec hw acceleration
29846  * work if necessary, and send the packet out on the wire.
29847  *
29848  * NOTE: IPsec will only call this function with fully resolved
29849  * ires if hw acceleration is involved.
29850  * TODO list :
29851  * 	a Handle M_MULTIDATA so that
29852  *	  tcp_multisend->tcp_multisend_data can
29853  *	  call ip_xmit_v4 directly
29854  *	b Handle post-ARP work for fragments so that
29855  *	  ip_wput_frag can call this function.
29856  */
29857 ipxmit_state_t
29858 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29859 {
29860 	nce_t		*arpce;
29861 	queue_t		*q;
29862 	int		ill_index;
29863 	mblk_t		*nxt_mp, *first_mp;
29864 	boolean_t	xmit_drop = B_FALSE;
29865 	ip_proc_t	proc;
29866 	ill_t		*out_ill;
29867 	int		pkt_len;
29868 
29869 	arpce = ire->ire_nce;
29870 	ASSERT(arpce != NULL);
29871 
29872 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29873 
29874 	mutex_enter(&arpce->nce_lock);
29875 	switch (arpce->nce_state) {
29876 	case ND_REACHABLE:
29877 		/* If there are other queued packets, queue this packet */
29878 		if (arpce->nce_qd_mp != NULL) {
29879 			if (mp != NULL)
29880 				nce_queue_mp_common(arpce, mp, B_FALSE);
29881 			mp = arpce->nce_qd_mp;
29882 		}
29883 		arpce->nce_qd_mp = NULL;
29884 		mutex_exit(&arpce->nce_lock);
29885 
29886 		/*
29887 		 * Flush the queue.  In the common case, where the
29888 		 * ARP is already resolved,  it will go through the
29889 		 * while loop only once.
29890 		 */
29891 		while (mp != NULL) {
29892 
29893 			nxt_mp = mp->b_next;
29894 			mp->b_next = NULL;
29895 			ASSERT(mp->b_datap->db_type != M_CTL);
29896 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29897 			/*
29898 			 * This info is needed for IPQOS to do COS marking
29899 			 * in ip_wput_attach_llhdr->ip_process.
29900 			 */
29901 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29902 			mp->b_prev = NULL;
29903 
29904 			/* set up ill index for outbound qos processing */
29905 			out_ill = ire_to_ill(ire);
29906 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29907 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29908 			    ill_index);
29909 			if (first_mp == NULL) {
29910 				xmit_drop = B_TRUE;
29911 				BUMP_MIB(out_ill->ill_ip_mib,
29912 				    ipIfStatsOutDiscards);
29913 				goto next_mp;
29914 			}
29915 			/* non-ipsec hw accel case */
29916 			if (io == NULL || !io->ipsec_out_accelerated) {
29917 				/* send it */
29918 				q = ire->ire_stq;
29919 				if (proc == IPP_FWD_OUT) {
29920 					UPDATE_IB_PKT_COUNT(ire);
29921 				} else {
29922 					UPDATE_OB_PKT_COUNT(ire);
29923 				}
29924 				ire->ire_last_used_time = lbolt;
29925 
29926 				if (flow_ctl_enabled || canputnext(q)) {
29927 					if (proc == IPP_FWD_OUT) {
29928 
29929 					BUMP_MIB(out_ill->ill_ip_mib,
29930 					    ipIfStatsHCOutForwDatagrams);
29931 
29932 					}
29933 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29934 					    pkt_len);
29935 
29936 					putnext(q, first_mp);
29937 				} else {
29938 					BUMP_MIB(out_ill->ill_ip_mib,
29939 					    ipIfStatsOutDiscards);
29940 					xmit_drop = B_TRUE;
29941 					freemsg(first_mp);
29942 				}
29943 			} else {
29944 				/*
29945 				 * Safety Pup says: make sure this
29946 				 *  is going to the right interface!
29947 				 */
29948 				ill_t *ill1 =
29949 				    (ill_t *)ire->ire_stq->q_ptr;
29950 				int ifindex =
29951 				    ill1->ill_phyint->phyint_ifindex;
29952 				if (ifindex !=
29953 				    io->ipsec_out_capab_ill_index) {
29954 					xmit_drop = B_TRUE;
29955 					freemsg(mp);
29956 				} else {
29957 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29958 					    pkt_len);
29959 					ipsec_hw_putnext(ire->ire_stq, mp);
29960 				}
29961 			}
29962 next_mp:
29963 			mp = nxt_mp;
29964 		} /* while (mp != NULL) */
29965 		if (xmit_drop)
29966 			return (SEND_FAILED);
29967 		else
29968 			return (SEND_PASSED);
29969 
29970 	case ND_INITIAL:
29971 	case ND_INCOMPLETE:
29972 
29973 		/*
29974 		 * While we do send off packets to dests that
29975 		 * use fully-resolved CGTP routes, we do not
29976 		 * handle unresolved CGTP routes.
29977 		 */
29978 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29979 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29980 
29981 		if (mp != NULL) {
29982 			/* queue the packet */
29983 			nce_queue_mp_common(arpce, mp, B_FALSE);
29984 		}
29985 
29986 		if (arpce->nce_state == ND_INCOMPLETE) {
29987 			mutex_exit(&arpce->nce_lock);
29988 			DTRACE_PROBE3(ip__xmit__incomplete,
29989 			    (ire_t *), ire, (mblk_t *), mp,
29990 			    (ipsec_out_t *), io);
29991 			return (LOOKUP_IN_PROGRESS);
29992 		}
29993 
29994 		arpce->nce_state = ND_INCOMPLETE;
29995 		mutex_exit(&arpce->nce_lock);
29996 		/*
29997 		 * Note that ire_add() (called from ire_forward())
29998 		 * holds a ref on the ire until ARP is completed.
29999 		 */
30000 
30001 		ire_arpresolve(ire, ire_to_ill(ire));
30002 		return (LOOKUP_IN_PROGRESS);
30003 	default:
30004 		ASSERT(0);
30005 		mutex_exit(&arpce->nce_lock);
30006 		return (LLHDR_RESLV_FAILED);
30007 	}
30008 }
30009 
30010 #undef	UPDATE_IP_MIB_OB_COUNTERS
30011 
30012 /*
30013  * Return B_TRUE if the buffers differ in length or content.
30014  * This is used for comparing extension header buffers.
30015  * Note that an extension header would be declared different
30016  * even if all that changed was the next header value in that header i.e.
30017  * what really changed is the next extension header.
30018  */
30019 boolean_t
30020 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
30021     uint_t blen)
30022 {
30023 	if (!b_valid)
30024 		blen = 0;
30025 
30026 	if (alen != blen)
30027 		return (B_TRUE);
30028 	if (alen == 0)
30029 		return (B_FALSE);	/* Both zero length */
30030 	return (bcmp(abuf, bbuf, alen));
30031 }
30032 
30033 /*
30034  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
30035  * Return B_FALSE if memory allocation fails - don't change any state!
30036  */
30037 boolean_t
30038 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30039     const void *src, uint_t srclen)
30040 {
30041 	void *dst;
30042 
30043 	if (!src_valid)
30044 		srclen = 0;
30045 
30046 	ASSERT(*dstlenp == 0);
30047 	if (src != NULL && srclen != 0) {
30048 		dst = mi_alloc(srclen, BPRI_MED);
30049 		if (dst == NULL)
30050 			return (B_FALSE);
30051 	} else {
30052 		dst = NULL;
30053 	}
30054 	if (*dstp != NULL)
30055 		mi_free(*dstp);
30056 	*dstp = dst;
30057 	*dstlenp = dst == NULL ? 0 : srclen;
30058 	return (B_TRUE);
30059 }
30060 
30061 /*
30062  * Replace what is in *dst, *dstlen with the source.
30063  * Assumes ip_allocbuf has already been called.
30064  */
30065 void
30066 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30067     const void *src, uint_t srclen)
30068 {
30069 	if (!src_valid)
30070 		srclen = 0;
30071 
30072 	ASSERT(*dstlenp == srclen);
30073 	if (src != NULL && srclen != 0)
30074 		bcopy(src, *dstp, srclen);
30075 }
30076 
30077 /*
30078  * Free the storage pointed to by the members of an ip6_pkt_t.
30079  */
30080 void
30081 ip6_pkt_free(ip6_pkt_t *ipp)
30082 {
30083 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30084 
30085 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30086 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30087 		ipp->ipp_hopopts = NULL;
30088 		ipp->ipp_hopoptslen = 0;
30089 	}
30090 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30091 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30092 		ipp->ipp_rtdstopts = NULL;
30093 		ipp->ipp_rtdstoptslen = 0;
30094 	}
30095 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30096 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30097 		ipp->ipp_dstopts = NULL;
30098 		ipp->ipp_dstoptslen = 0;
30099 	}
30100 	if (ipp->ipp_fields & IPPF_RTHDR) {
30101 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30102 		ipp->ipp_rthdr = NULL;
30103 		ipp->ipp_rthdrlen = 0;
30104 	}
30105 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30106 	    IPPF_RTHDR);
30107 }
30108