xref: /titanic_52/usr/src/uts/common/inet/ip/ip.c (revision c6f08383a2dc4e4b97e3bd267c9e7e4c49c9536e)
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 /*
6057  * Debug formatting routine.  Returns a character string representation of the
6058  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6059  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6060  *
6061  * Once the ndd table-printing interfaces are removed, this can be changed to
6062  * standard dotted-decimal form.
6063  */
6064 char *
6065 ip_dot_addr(ipaddr_t addr, char *buf)
6066 {
6067 	uint8_t *ap = (uint8_t *)&addr;
6068 
6069 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6070 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6071 	return (buf);
6072 }
6073 
6074 /*
6075  * Write the given MAC address as a printable string in the usual colon-
6076  * separated format.
6077  */
6078 const char *
6079 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6080 {
6081 	char *bp;
6082 
6083 	if (alen == 0 || buflen < 4)
6084 		return ("?");
6085 	bp = buf;
6086 	for (;;) {
6087 		/*
6088 		 * If there are more MAC address bytes available, but we won't
6089 		 * have any room to print them, then add "..." to the string
6090 		 * instead.  See below for the 'magic number' explanation.
6091 		 */
6092 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6093 			(void) strcpy(bp, "...");
6094 			break;
6095 		}
6096 		(void) sprintf(bp, "%02x", *addr++);
6097 		bp += 2;
6098 		if (--alen == 0)
6099 			break;
6100 		*bp++ = ':';
6101 		buflen -= 3;
6102 		/*
6103 		 * At this point, based on the first 'if' statement above,
6104 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6105 		 * buflen >= 4.  The first case leaves room for the final "xx"
6106 		 * number and trailing NUL byte.  The second leaves room for at
6107 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6108 		 * that statement.
6109 		 */
6110 	}
6111 	return (buf);
6112 }
6113 
6114 /*
6115  * Send an ICMP error after patching up the packet appropriately.  Returns
6116  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6117  */
6118 static boolean_t
6119 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6120     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6121     zoneid_t zoneid, ip_stack_t *ipst)
6122 {
6123 	ipha_t *ipha;
6124 	mblk_t *first_mp;
6125 	boolean_t secure;
6126 	unsigned char db_type;
6127 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6128 
6129 	first_mp = mp;
6130 	if (mctl_present) {
6131 		mp = mp->b_cont;
6132 		secure = ipsec_in_is_secure(first_mp);
6133 		ASSERT(mp != NULL);
6134 	} else {
6135 		/*
6136 		 * If this is an ICMP error being reported - which goes
6137 		 * up as M_CTLs, we need to convert them to M_DATA till
6138 		 * we finish checking with global policy because
6139 		 * ipsec_check_global_policy() assumes M_DATA as clear
6140 		 * and M_CTL as secure.
6141 		 */
6142 		db_type = DB_TYPE(mp);
6143 		DB_TYPE(mp) = M_DATA;
6144 		secure = B_FALSE;
6145 	}
6146 	/*
6147 	 * We are generating an icmp error for some inbound packet.
6148 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6149 	 * Before we generate an error, check with global policy
6150 	 * to see whether this is allowed to enter the system. As
6151 	 * there is no "conn", we are checking with global policy.
6152 	 */
6153 	ipha = (ipha_t *)mp->b_rptr;
6154 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6155 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6156 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6157 		if (first_mp == NULL)
6158 			return (B_FALSE);
6159 	}
6160 
6161 	if (!mctl_present)
6162 		DB_TYPE(mp) = db_type;
6163 
6164 	if (flags & IP_FF_SEND_ICMP) {
6165 		if (flags & IP_FF_HDR_COMPLETE) {
6166 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6167 				freemsg(first_mp);
6168 				return (B_TRUE);
6169 			}
6170 		}
6171 		if (flags & IP_FF_CKSUM) {
6172 			/*
6173 			 * Have to correct checksum since
6174 			 * the packet might have been
6175 			 * fragmented and the reassembly code in ip_rput
6176 			 * does not restore the IP checksum.
6177 			 */
6178 			ipha->ipha_hdr_checksum = 0;
6179 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6180 		}
6181 		switch (icmp_type) {
6182 		case ICMP_DEST_UNREACHABLE:
6183 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6184 			    ipst);
6185 			break;
6186 		default:
6187 			freemsg(first_mp);
6188 			break;
6189 		}
6190 	} else {
6191 		freemsg(first_mp);
6192 		return (B_FALSE);
6193 	}
6194 
6195 	return (B_TRUE);
6196 }
6197 
6198 /*
6199  * Used to send an ICMP error message when a packet is received for
6200  * a protocol that is not supported. The mblk passed as argument
6201  * is consumed by this function.
6202  */
6203 void
6204 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6205     ip_stack_t *ipst)
6206 {
6207 	mblk_t *mp;
6208 	ipha_t *ipha;
6209 	ill_t *ill;
6210 	ipsec_in_t *ii;
6211 
6212 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6213 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6214 
6215 	mp = ipsec_mp->b_cont;
6216 	ipsec_mp->b_cont = NULL;
6217 	ipha = (ipha_t *)mp->b_rptr;
6218 	/* Get ill from index in ipsec_in_t. */
6219 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6220 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6221 	    ipst);
6222 	if (ill != NULL) {
6223 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6224 			if (ip_fanout_send_icmp(q, mp, flags,
6225 			    ICMP_DEST_UNREACHABLE,
6226 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6227 				BUMP_MIB(ill->ill_ip_mib,
6228 				    ipIfStatsInUnknownProtos);
6229 			}
6230 		} else {
6231 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6232 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6233 			    0, B_FALSE, zoneid, ipst)) {
6234 				BUMP_MIB(ill->ill_ip_mib,
6235 				    ipIfStatsInUnknownProtos);
6236 			}
6237 		}
6238 		ill_refrele(ill);
6239 	} else { /* re-link for the freemsg() below. */
6240 		ipsec_mp->b_cont = mp;
6241 	}
6242 
6243 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6244 	freemsg(ipsec_mp);
6245 }
6246 
6247 /*
6248  * See if the inbound datagram has had IPsec processing applied to it.
6249  */
6250 boolean_t
6251 ipsec_in_is_secure(mblk_t *ipsec_mp)
6252 {
6253 	ipsec_in_t *ii;
6254 
6255 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6256 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6257 
6258 	if (ii->ipsec_in_loopback) {
6259 		return (ii->ipsec_in_secure);
6260 	} else {
6261 		return (ii->ipsec_in_ah_sa != NULL ||
6262 		    ii->ipsec_in_esp_sa != NULL ||
6263 		    ii->ipsec_in_decaps);
6264 	}
6265 }
6266 
6267 /*
6268  * Handle protocols with which IP is less intimate.  There
6269  * can be more than one stream bound to a particular
6270  * protocol.  When this is the case, normally each one gets a copy
6271  * of any incoming packets.
6272  *
6273  * IPsec NOTE :
6274  *
6275  * Don't allow a secure packet going up a non-secure connection.
6276  * We don't allow this because
6277  *
6278  * 1) Reply might go out in clear which will be dropped at
6279  *    the sending side.
6280  * 2) If the reply goes out in clear it will give the
6281  *    adversary enough information for getting the key in
6282  *    most of the cases.
6283  *
6284  * Moreover getting a secure packet when we expect clear
6285  * implies that SA's were added without checking for
6286  * policy on both ends. This should not happen once ISAKMP
6287  * is used to negotiate SAs as SAs will be added only after
6288  * verifying the policy.
6289  *
6290  * NOTE : If the packet was tunneled and not multicast we only send
6291  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6292  * back to delivering packets to AF_INET6 raw sockets.
6293  *
6294  * IPQoS Notes:
6295  * Once we have determined the client, invoke IPPF processing.
6296  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6297  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6298  * ip_policy will be false.
6299  *
6300  * Zones notes:
6301  * Currently only applications in the global zone can create raw sockets for
6302  * protocols other than ICMP. So unlike the broadcast / multicast case of
6303  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6304  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6305  */
6306 static void
6307 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6308     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6309     zoneid_t zoneid)
6310 {
6311 	queue_t	*rq;
6312 	mblk_t	*mp1, *first_mp1;
6313 	uint_t	protocol = ipha->ipha_protocol;
6314 	ipaddr_t dst;
6315 	boolean_t one_only;
6316 	mblk_t *first_mp = mp;
6317 	boolean_t secure;
6318 	uint32_t ill_index;
6319 	conn_t	*connp, *first_connp, *next_connp;
6320 	connf_t	*connfp;
6321 	boolean_t shared_addr;
6322 	mib2_ipIfStatsEntry_t *mibptr;
6323 	ip_stack_t *ipst = recv_ill->ill_ipst;
6324 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6325 
6326 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6327 	if (mctl_present) {
6328 		mp = first_mp->b_cont;
6329 		secure = ipsec_in_is_secure(first_mp);
6330 		ASSERT(mp != NULL);
6331 	} else {
6332 		secure = B_FALSE;
6333 	}
6334 	dst = ipha->ipha_dst;
6335 	/*
6336 	 * If the packet was tunneled and not multicast we only send to it
6337 	 * the first match.
6338 	 */
6339 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6340 	    !CLASSD(dst));
6341 
6342 	shared_addr = (zoneid == ALL_ZONES);
6343 	if (shared_addr) {
6344 		/*
6345 		 * We don't allow multilevel ports for raw IP, so no need to
6346 		 * check for that here.
6347 		 */
6348 		zoneid = tsol_packet_to_zoneid(mp);
6349 	}
6350 
6351 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6352 	mutex_enter(&connfp->connf_lock);
6353 	connp = connfp->connf_head;
6354 	for (connp = connfp->connf_head; connp != NULL;
6355 	    connp = connp->conn_next) {
6356 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6357 		    zoneid) &&
6358 		    (!is_system_labeled() ||
6359 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6360 		    connp))) {
6361 			break;
6362 		}
6363 	}
6364 
6365 	if (connp == NULL || connp->conn_upq == NULL) {
6366 		/*
6367 		 * No one bound to these addresses.  Is
6368 		 * there a client that wants all
6369 		 * unclaimed datagrams?
6370 		 */
6371 		mutex_exit(&connfp->connf_lock);
6372 		/*
6373 		 * Check for IPPROTO_ENCAP...
6374 		 */
6375 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6376 			/*
6377 			 * If an IPsec mblk is here on a multicast
6378 			 * tunnel (using ip_mroute stuff), check policy here,
6379 			 * THEN ship off to ip_mroute_decap().
6380 			 *
6381 			 * BTW,  If I match a configured IP-in-IP
6382 			 * tunnel, this path will not be reached, and
6383 			 * ip_mroute_decap will never be called.
6384 			 */
6385 			first_mp = ipsec_check_global_policy(first_mp, connp,
6386 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6387 			if (first_mp != NULL) {
6388 				if (mctl_present)
6389 					freeb(first_mp);
6390 				ip_mroute_decap(q, mp, ill);
6391 			} /* Else we already freed everything! */
6392 		} else {
6393 			/*
6394 			 * Otherwise send an ICMP protocol unreachable.
6395 			 */
6396 			if (ip_fanout_send_icmp(q, first_mp, flags,
6397 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6398 			    mctl_present, zoneid, ipst)) {
6399 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6400 			}
6401 		}
6402 		return;
6403 	}
6404 	CONN_INC_REF(connp);
6405 	first_connp = connp;
6406 
6407 	/*
6408 	 * Only send message to one tunnel driver by immediately
6409 	 * terminating the loop.
6410 	 */
6411 	connp = one_only ? NULL : connp->conn_next;
6412 
6413 	for (;;) {
6414 		while (connp != NULL) {
6415 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6416 			    flags, zoneid) &&
6417 			    (!is_system_labeled() ||
6418 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6419 			    shared_addr, connp)))
6420 				break;
6421 			connp = connp->conn_next;
6422 		}
6423 
6424 		/*
6425 		 * Copy the packet.
6426 		 */
6427 		if (connp == NULL || connp->conn_upq == NULL ||
6428 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6429 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6430 			/*
6431 			 * No more interested clients or memory
6432 			 * allocation failed
6433 			 */
6434 			connp = first_connp;
6435 			break;
6436 		}
6437 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6438 		CONN_INC_REF(connp);
6439 		mutex_exit(&connfp->connf_lock);
6440 		rq = connp->conn_rq;
6441 		if (!canputnext(rq)) {
6442 			if (flags & IP_FF_RAWIP) {
6443 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6444 			} else {
6445 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6446 			}
6447 
6448 			freemsg(first_mp1);
6449 		} else {
6450 			/*
6451 			 * Don't enforce here if we're an actual tunnel -
6452 			 * let "tun" do it instead.
6453 			 */
6454 			if (!IPCL_IS_IPTUN(connp) &&
6455 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6456 			    secure)) {
6457 				first_mp1 = ipsec_check_inbound_policy
6458 				    (first_mp1, connp, ipha, NULL,
6459 				    mctl_present);
6460 			}
6461 			if (first_mp1 != NULL) {
6462 				int in_flags = 0;
6463 				/*
6464 				 * ip_fanout_proto also gets called from
6465 				 * icmp_inbound_error_fanout, in which case
6466 				 * the msg type is M_CTL.  Don't add info
6467 				 * in this case for the time being. In future
6468 				 * when there is a need for knowing the
6469 				 * inbound iface index for ICMP error msgs,
6470 				 * then this can be changed.
6471 				 */
6472 				if (connp->conn_recvif)
6473 					in_flags = IPF_RECVIF;
6474 				/*
6475 				 * The ULP may support IP_RECVPKTINFO for both
6476 				 * IP v4 and v6 so pass the appropriate argument
6477 				 * based on conn IP version.
6478 				 */
6479 				if (connp->conn_ip_recvpktinfo) {
6480 					if (connp->conn_af_isv6) {
6481 						/*
6482 						 * V6 only needs index
6483 						 */
6484 						in_flags |= IPF_RECVIF;
6485 					} else {
6486 						/*
6487 						 * V4 needs index +
6488 						 * matching address.
6489 						 */
6490 						in_flags |= IPF_RECVADDR;
6491 					}
6492 				}
6493 				if ((in_flags != 0) &&
6494 				    (mp->b_datap->db_type != M_CTL)) {
6495 					/*
6496 					 * the actual data will be
6497 					 * contained in b_cont upon
6498 					 * successful return of the
6499 					 * following call else
6500 					 * original mblk is returned
6501 					 */
6502 					ASSERT(recv_ill != NULL);
6503 					mp1 = ip_add_info(mp1, recv_ill,
6504 					    in_flags, IPCL_ZONEID(connp), ipst);
6505 				}
6506 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6507 				if (mctl_present)
6508 					freeb(first_mp1);
6509 				(connp->conn_recv)(connp, mp1, NULL);
6510 			}
6511 		}
6512 		mutex_enter(&connfp->connf_lock);
6513 		/* Follow the next pointer before releasing the conn. */
6514 		next_connp = connp->conn_next;
6515 		CONN_DEC_REF(connp);
6516 		connp = next_connp;
6517 	}
6518 
6519 	/* Last one.  Send it upstream. */
6520 	mutex_exit(&connfp->connf_lock);
6521 
6522 	/*
6523 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6524 	 * will be set to false.
6525 	 */
6526 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6527 		ill_index = ill->ill_phyint->phyint_ifindex;
6528 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6529 		if (mp == NULL) {
6530 			CONN_DEC_REF(connp);
6531 			if (mctl_present) {
6532 				freeb(first_mp);
6533 			}
6534 			return;
6535 		}
6536 	}
6537 
6538 	rq = connp->conn_rq;
6539 	if (!canputnext(rq)) {
6540 		if (flags & IP_FF_RAWIP) {
6541 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6542 		} else {
6543 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6544 		}
6545 
6546 		freemsg(first_mp);
6547 	} else {
6548 		if (IPCL_IS_IPTUN(connp)) {
6549 			/*
6550 			 * Tunneled packet.  We enforce policy in the tunnel
6551 			 * module itself.
6552 			 *
6553 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6554 			 * a policy check.
6555 			 * FIXME to use conn_recv for tun later.
6556 			 */
6557 			putnext(rq, first_mp);
6558 			CONN_DEC_REF(connp);
6559 			return;
6560 		}
6561 
6562 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6563 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6564 			    ipha, NULL, mctl_present);
6565 		}
6566 
6567 		if (first_mp != NULL) {
6568 			int in_flags = 0;
6569 
6570 			/*
6571 			 * ip_fanout_proto also gets called
6572 			 * from icmp_inbound_error_fanout, in
6573 			 * which case the msg type is M_CTL.
6574 			 * Don't add info in this case for time
6575 			 * being. In future when there is a
6576 			 * need for knowing the inbound iface
6577 			 * index for ICMP error msgs, then this
6578 			 * can be changed
6579 			 */
6580 			if (connp->conn_recvif)
6581 				in_flags = IPF_RECVIF;
6582 			if (connp->conn_ip_recvpktinfo) {
6583 				if (connp->conn_af_isv6) {
6584 					/*
6585 					 * V6 only needs index
6586 					 */
6587 					in_flags |= IPF_RECVIF;
6588 				} else {
6589 					/*
6590 					 * V4 needs index +
6591 					 * matching address.
6592 					 */
6593 					in_flags |= IPF_RECVADDR;
6594 				}
6595 			}
6596 			if ((in_flags != 0) &&
6597 			    (mp->b_datap->db_type != M_CTL)) {
6598 
6599 				/*
6600 				 * the actual data will be contained in
6601 				 * b_cont upon successful return
6602 				 * of the following call else original
6603 				 * mblk is returned
6604 				 */
6605 				ASSERT(recv_ill != NULL);
6606 				mp = ip_add_info(mp, recv_ill,
6607 				    in_flags, IPCL_ZONEID(connp), ipst);
6608 			}
6609 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6610 			(connp->conn_recv)(connp, mp, NULL);
6611 			if (mctl_present)
6612 				freeb(first_mp);
6613 		}
6614 	}
6615 	CONN_DEC_REF(connp);
6616 }
6617 
6618 /*
6619  * Fanout for TCP packets
6620  * The caller puts <fport, lport> in the ports parameter.
6621  *
6622  * IPQoS Notes
6623  * Before sending it to the client, invoke IPPF processing.
6624  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6625  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6626  * ip_policy is false.
6627  */
6628 static void
6629 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6630     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6631 {
6632 	mblk_t  *first_mp;
6633 	boolean_t secure;
6634 	uint32_t ill_index;
6635 	int	ip_hdr_len;
6636 	tcph_t	*tcph;
6637 	boolean_t syn_present = B_FALSE;
6638 	conn_t	*connp;
6639 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6640 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6641 
6642 	ASSERT(recv_ill != NULL);
6643 
6644 	first_mp = mp;
6645 	if (mctl_present) {
6646 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6647 		mp = first_mp->b_cont;
6648 		secure = ipsec_in_is_secure(first_mp);
6649 		ASSERT(mp != NULL);
6650 	} else {
6651 		secure = B_FALSE;
6652 	}
6653 
6654 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6655 
6656 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6657 	    zoneid, ipst)) == NULL) {
6658 		/*
6659 		 * No connected connection or listener. Send a
6660 		 * TH_RST via tcp_xmit_listeners_reset.
6661 		 */
6662 
6663 		/* Initiate IPPf processing, if needed. */
6664 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6665 			uint32_t ill_index;
6666 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6667 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6668 			if (first_mp == NULL)
6669 				return;
6670 		}
6671 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6672 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6673 		    zoneid));
6674 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6675 		    ipst->ips_netstack->netstack_tcp, NULL);
6676 		return;
6677 	}
6678 
6679 	/*
6680 	 * Allocate the SYN for the TCP connection here itself
6681 	 */
6682 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6683 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6684 		if (IPCL_IS_TCP(connp)) {
6685 			squeue_t *sqp;
6686 
6687 			/*
6688 			 * For fused tcp loopback, assign the eager's
6689 			 * squeue to be that of the active connect's.
6690 			 * Note that we don't check for IP_FF_LOOPBACK
6691 			 * here since this routine gets called only
6692 			 * for loopback (unlike the IPv6 counterpart).
6693 			 */
6694 			ASSERT(Q_TO_CONN(q) != NULL);
6695 			if (do_tcp_fusion &&
6696 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6697 			    !secure &&
6698 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6699 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6700 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6701 				sqp = Q_TO_CONN(q)->conn_sqp;
6702 			} else {
6703 				sqp = IP_SQUEUE_GET(lbolt);
6704 			}
6705 
6706 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6707 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6708 			syn_present = B_TRUE;
6709 		}
6710 	}
6711 
6712 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6713 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6714 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6715 		if ((flags & TH_RST) || (flags & TH_URG)) {
6716 			CONN_DEC_REF(connp);
6717 			freemsg(first_mp);
6718 			return;
6719 		}
6720 		if (flags & TH_ACK) {
6721 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6722 			    ipst->ips_netstack->netstack_tcp, connp);
6723 			CONN_DEC_REF(connp);
6724 			return;
6725 		}
6726 
6727 		CONN_DEC_REF(connp);
6728 		freemsg(first_mp);
6729 		return;
6730 	}
6731 
6732 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6733 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6734 		    NULL, mctl_present);
6735 		if (first_mp == NULL) {
6736 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6737 			CONN_DEC_REF(connp);
6738 			return;
6739 		}
6740 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6741 			ASSERT(syn_present);
6742 			if (mctl_present) {
6743 				ASSERT(first_mp != mp);
6744 				first_mp->b_datap->db_struioflag |=
6745 				    STRUIO_POLICY;
6746 			} else {
6747 				ASSERT(first_mp == mp);
6748 				mp->b_datap->db_struioflag &=
6749 				    ~STRUIO_EAGER;
6750 				mp->b_datap->db_struioflag |=
6751 				    STRUIO_POLICY;
6752 			}
6753 		} else {
6754 			/*
6755 			 * Discard first_mp early since we're dealing with a
6756 			 * fully-connected conn_t and tcp doesn't do policy in
6757 			 * this case.
6758 			 */
6759 			if (mctl_present) {
6760 				freeb(first_mp);
6761 				mctl_present = B_FALSE;
6762 			}
6763 			first_mp = mp;
6764 		}
6765 	}
6766 
6767 	/*
6768 	 * Initiate policy processing here if needed. If we get here from
6769 	 * icmp_inbound_error_fanout, ip_policy is false.
6770 	 */
6771 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6772 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6773 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6774 		if (mp == NULL) {
6775 			CONN_DEC_REF(connp);
6776 			if (mctl_present)
6777 				freeb(first_mp);
6778 			return;
6779 		} else if (mctl_present) {
6780 			ASSERT(first_mp != mp);
6781 			first_mp->b_cont = mp;
6782 		} else {
6783 			first_mp = mp;
6784 		}
6785 	}
6786 
6787 
6788 
6789 	/* Handle socket options. */
6790 	if (!syn_present &&
6791 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6792 		/* Add header */
6793 		ASSERT(recv_ill != NULL);
6794 		/*
6795 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6796 		 * IPF_RECVIF.
6797 		 */
6798 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6799 		    ipst);
6800 		if (mp == NULL) {
6801 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6802 			CONN_DEC_REF(connp);
6803 			if (mctl_present)
6804 				freeb(first_mp);
6805 			return;
6806 		} else if (mctl_present) {
6807 			/*
6808 			 * ip_add_info might return a new mp.
6809 			 */
6810 			ASSERT(first_mp != mp);
6811 			first_mp->b_cont = mp;
6812 		} else {
6813 			first_mp = mp;
6814 		}
6815 	}
6816 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6817 	if (IPCL_IS_TCP(connp)) {
6818 		/* do not drain, certain use cases can blow the stack */
6819 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6820 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6821 	} else {
6822 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6823 		(connp->conn_recv)(connp, first_mp, NULL);
6824 		CONN_DEC_REF(connp);
6825 	}
6826 }
6827 
6828 /*
6829  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6830  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6831  * is not consumed.
6832  *
6833  * One of four things can happen, all of which affect the passed-in mblk:
6834  *
6835  * 1.) ICMP messages that go through here just get returned TRUE.
6836  *
6837  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6838  *
6839  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6840  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6841  *
6842  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6843  */
6844 static boolean_t
6845 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6846     ipsec_stack_t *ipss)
6847 {
6848 	int shift, plen, iph_len;
6849 	ipha_t *ipha;
6850 	udpha_t *udpha;
6851 	uint32_t *spi;
6852 	uint8_t *orptr;
6853 	boolean_t udp_pkt, free_ire;
6854 
6855 	if (DB_TYPE(mp) == M_CTL) {
6856 		/*
6857 		 * ICMP message with UDP inside.  Don't bother stripping, just
6858 		 * send it up.
6859 		 *
6860 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6861 		 * to ignore errors set by ICMP anyway ('cause they might be
6862 		 * forged), but that's the app's decision, not ours.
6863 		 */
6864 
6865 		/* Bunch of reality checks for DEBUG kernels... */
6866 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6867 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6868 
6869 		return (B_TRUE);
6870 	}
6871 
6872 	ipha = (ipha_t *)mp->b_rptr;
6873 	iph_len = IPH_HDR_LENGTH(ipha);
6874 	plen = ntohs(ipha->ipha_length);
6875 
6876 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6877 		/*
6878 		 * Most likely a keepalive for the benefit of an intervening
6879 		 * NAT.  These aren't for us, per se, so drop it.
6880 		 *
6881 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6882 		 * byte packets (keepalives are 1-byte), but we'll drop them
6883 		 * also.
6884 		 */
6885 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6886 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6887 		return (B_FALSE);
6888 	}
6889 
6890 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6891 		/* might as well pull it all up - it might be ESP. */
6892 		if (!pullupmsg(mp, -1)) {
6893 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6894 			    DROPPER(ipss, ipds_esp_nomem),
6895 			    &ipss->ipsec_dropper);
6896 			return (B_FALSE);
6897 		}
6898 
6899 		ipha = (ipha_t *)mp->b_rptr;
6900 	}
6901 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6902 	if (*spi == 0) {
6903 		/* UDP packet - remove 0-spi. */
6904 		shift = sizeof (uint32_t);
6905 	} else {
6906 		/* ESP-in-UDP packet - reduce to ESP. */
6907 		ipha->ipha_protocol = IPPROTO_ESP;
6908 		shift = sizeof (udpha_t);
6909 	}
6910 
6911 	/* Fix IP header */
6912 	ipha->ipha_length = htons(plen - shift);
6913 	ipha->ipha_hdr_checksum = 0;
6914 
6915 	orptr = mp->b_rptr;
6916 	mp->b_rptr += shift;
6917 
6918 	if (*spi == 0) {
6919 		ASSERT((uint8_t *)ipha == orptr);
6920 		udpha = (udpha_t *)(orptr + iph_len);
6921 		udpha->uha_length = htons(plen - shift - iph_len);
6922 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6923 		udp_pkt = B_TRUE;
6924 	} else {
6925 		udp_pkt = B_FALSE;
6926 	}
6927 	ovbcopy(orptr, orptr + shift, iph_len);
6928 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6929 		ipha = (ipha_t *)(orptr + shift);
6930 
6931 		free_ire = (ire == NULL);
6932 		if (free_ire) {
6933 			/* Re-acquire ire. */
6934 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6935 			    ipss->ipsec_netstack->netstack_ip);
6936 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6937 				if (ire != NULL)
6938 					ire_refrele(ire);
6939 				/*
6940 				 * Do a regular freemsg(), as this is an IP
6941 				 * error (no local route) not an IPsec one.
6942 				 */
6943 				freemsg(mp);
6944 			}
6945 		}
6946 
6947 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6948 		if (free_ire)
6949 			ire_refrele(ire);
6950 	}
6951 
6952 	return (udp_pkt);
6953 }
6954 
6955 /*
6956  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6957  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6958  * Caller is responsible for dropping references to the conn, and freeing
6959  * first_mp.
6960  *
6961  * IPQoS Notes
6962  * Before sending it to the client, invoke IPPF processing. Policy processing
6963  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6964  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6965  * ip_wput_local, ip_policy is false.
6966  */
6967 static void
6968 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6969     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6970     boolean_t ip_policy)
6971 {
6972 	boolean_t	mctl_present = (first_mp != NULL);
6973 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6974 	uint32_t	ill_index;
6975 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6976 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6977 
6978 	ASSERT(ill != NULL);
6979 
6980 	if (mctl_present)
6981 		first_mp->b_cont = mp;
6982 	else
6983 		first_mp = mp;
6984 
6985 	if (CONN_UDP_FLOWCTLD(connp)) {
6986 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6987 		freemsg(first_mp);
6988 		return;
6989 	}
6990 
6991 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6992 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6993 		    NULL, mctl_present);
6994 		if (first_mp == NULL) {
6995 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6996 			return;	/* Freed by ipsec_check_inbound_policy(). */
6997 		}
6998 	}
6999 	if (mctl_present)
7000 		freeb(first_mp);
7001 
7002 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
7003 	if (connp->conn_udp->udp_nat_t_endpoint) {
7004 		if (mctl_present) {
7005 			/* mctl_present *shouldn't* happen. */
7006 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
7007 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7008 			    &ipss->ipsec_dropper);
7009 			return;
7010 		}
7011 
7012 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7013 			return;
7014 	}
7015 
7016 	/* Handle options. */
7017 	if (connp->conn_recvif)
7018 		in_flags = IPF_RECVIF;
7019 	/*
7020 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7021 	 * passed to ip_add_info is based on IP version of connp.
7022 	 */
7023 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7024 		if (connp->conn_af_isv6) {
7025 			/*
7026 			 * V6 only needs index
7027 			 */
7028 			in_flags |= IPF_RECVIF;
7029 		} else {
7030 			/*
7031 			 * V4 needs index + matching address.
7032 			 */
7033 			in_flags |= IPF_RECVADDR;
7034 		}
7035 	}
7036 
7037 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7038 		in_flags |= IPF_RECVSLLA;
7039 
7040 	/*
7041 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7042 	 * freed if the packet is dropped. The caller will do so.
7043 	 */
7044 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7045 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7046 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7047 		if (mp == NULL) {
7048 			return;
7049 		}
7050 	}
7051 	if ((in_flags != 0) &&
7052 	    (mp->b_datap->db_type != M_CTL)) {
7053 		/*
7054 		 * The actual data will be contained in b_cont
7055 		 * upon successful return of the following call
7056 		 * else original mblk is returned
7057 		 */
7058 		ASSERT(recv_ill != NULL);
7059 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7060 		    ipst);
7061 	}
7062 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7063 	/* Send it upstream */
7064 	(connp->conn_recv)(connp, mp, NULL);
7065 }
7066 
7067 /*
7068  * Fanout for UDP packets.
7069  * The caller puts <fport, lport> in the ports parameter.
7070  *
7071  * If SO_REUSEADDR is set all multicast and broadcast packets
7072  * will be delivered to all streams bound to the same port.
7073  *
7074  * Zones notes:
7075  * Multicast and broadcast packets will be distributed to streams in all zones.
7076  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7077  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7078  * packets. To maintain this behavior with multiple zones, the conns are grouped
7079  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7080  * each zone. If unset, all the following conns in the same zone are skipped.
7081  */
7082 static void
7083 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7084     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7085     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7086 {
7087 	uint32_t	dstport, srcport;
7088 	ipaddr_t	dst;
7089 	mblk_t		*first_mp;
7090 	boolean_t	secure;
7091 	in6_addr_t	v6src;
7092 	conn_t		*connp;
7093 	connf_t		*connfp;
7094 	conn_t		*first_connp;
7095 	conn_t		*next_connp;
7096 	mblk_t		*mp1, *first_mp1;
7097 	ipaddr_t	src;
7098 	zoneid_t	last_zoneid;
7099 	boolean_t	reuseaddr;
7100 	boolean_t	shared_addr;
7101 	ip_stack_t	*ipst;
7102 
7103 	ASSERT(recv_ill != NULL);
7104 	ipst = recv_ill->ill_ipst;
7105 
7106 	first_mp = mp;
7107 	if (mctl_present) {
7108 		mp = first_mp->b_cont;
7109 		first_mp->b_cont = NULL;
7110 		secure = ipsec_in_is_secure(first_mp);
7111 		ASSERT(mp != NULL);
7112 	} else {
7113 		first_mp = NULL;
7114 		secure = B_FALSE;
7115 	}
7116 
7117 	/* Extract ports in net byte order */
7118 	dstport = htons(ntohl(ports) & 0xFFFF);
7119 	srcport = htons(ntohl(ports) >> 16);
7120 	dst = ipha->ipha_dst;
7121 	src = ipha->ipha_src;
7122 
7123 	shared_addr = (zoneid == ALL_ZONES);
7124 	if (shared_addr) {
7125 		/*
7126 		 * No need to handle exclusive-stack zones since ALL_ZONES
7127 		 * only applies to the shared stack.
7128 		 */
7129 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7130 		if (zoneid == ALL_ZONES)
7131 			zoneid = tsol_packet_to_zoneid(mp);
7132 	}
7133 
7134 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7135 	mutex_enter(&connfp->connf_lock);
7136 	connp = connfp->connf_head;
7137 	if (!broadcast && !CLASSD(dst)) {
7138 		/*
7139 		 * Not broadcast or multicast. Send to the one (first)
7140 		 * client we find. No need to check conn_wantpacket()
7141 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7142 		 * IPv4 unicast packets.
7143 		 */
7144 		while ((connp != NULL) &&
7145 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7146 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7147 			connp = connp->conn_next;
7148 		}
7149 
7150 		if (connp == NULL || connp->conn_upq == NULL)
7151 			goto notfound;
7152 
7153 		if (is_system_labeled() &&
7154 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7155 		    connp))
7156 			goto notfound;
7157 
7158 		CONN_INC_REF(connp);
7159 		mutex_exit(&connfp->connf_lock);
7160 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7161 		    flags, recv_ill, ip_policy);
7162 		IP_STAT(ipst, ip_udp_fannorm);
7163 		CONN_DEC_REF(connp);
7164 		return;
7165 	}
7166 
7167 	/*
7168 	 * Broadcast and multicast case
7169 	 *
7170 	 * Need to check conn_wantpacket().
7171 	 * If SO_REUSEADDR has been set on the first we send the
7172 	 * packet to all clients that have joined the group and
7173 	 * match the port.
7174 	 */
7175 
7176 	while (connp != NULL) {
7177 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7178 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7179 		    (!is_system_labeled() ||
7180 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7181 		    connp)))
7182 			break;
7183 		connp = connp->conn_next;
7184 	}
7185 
7186 	if (connp == NULL || connp->conn_upq == NULL)
7187 		goto notfound;
7188 
7189 	first_connp = connp;
7190 	/*
7191 	 * When SO_REUSEADDR is not set, send the packet only to the first
7192 	 * matching connection in its zone by keeping track of the zoneid.
7193 	 */
7194 	reuseaddr = first_connp->conn_reuseaddr;
7195 	last_zoneid = first_connp->conn_zoneid;
7196 
7197 	CONN_INC_REF(connp);
7198 	connp = connp->conn_next;
7199 	for (;;) {
7200 		while (connp != NULL) {
7201 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7202 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7203 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7204 			    (!is_system_labeled() ||
7205 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7206 			    shared_addr, connp)))
7207 				break;
7208 			connp = connp->conn_next;
7209 		}
7210 		/*
7211 		 * Just copy the data part alone. The mctl part is
7212 		 * needed just for verifying policy and it is never
7213 		 * sent up.
7214 		 */
7215 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7216 		    ((mp1 = copymsg(mp)) == NULL))) {
7217 			/*
7218 			 * No more interested clients or memory
7219 			 * allocation failed
7220 			 */
7221 			connp = first_connp;
7222 			break;
7223 		}
7224 		if (connp->conn_zoneid != last_zoneid) {
7225 			/*
7226 			 * Update the zoneid so that the packet isn't sent to
7227 			 * any more conns in the same zone unless SO_REUSEADDR
7228 			 * is set.
7229 			 */
7230 			reuseaddr = connp->conn_reuseaddr;
7231 			last_zoneid = connp->conn_zoneid;
7232 		}
7233 		if (first_mp != NULL) {
7234 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7235 			    ipsec_info_type == IPSEC_IN);
7236 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7237 			    ipst->ips_netstack);
7238 			if (first_mp1 == NULL) {
7239 				freemsg(mp1);
7240 				connp = first_connp;
7241 				break;
7242 			}
7243 		} else {
7244 			first_mp1 = NULL;
7245 		}
7246 		CONN_INC_REF(connp);
7247 		mutex_exit(&connfp->connf_lock);
7248 		/*
7249 		 * IPQoS notes: We don't send the packet for policy
7250 		 * processing here, will do it for the last one (below).
7251 		 * i.e. we do it per-packet now, but if we do policy
7252 		 * processing per-conn, then we would need to do it
7253 		 * here too.
7254 		 */
7255 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7256 		    ipha, flags, recv_ill, B_FALSE);
7257 		mutex_enter(&connfp->connf_lock);
7258 		/* Follow the next pointer before releasing the conn. */
7259 		next_connp = connp->conn_next;
7260 		IP_STAT(ipst, ip_udp_fanmb);
7261 		CONN_DEC_REF(connp);
7262 		connp = next_connp;
7263 	}
7264 
7265 	/* Last one.  Send it upstream. */
7266 	mutex_exit(&connfp->connf_lock);
7267 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7268 	    recv_ill, ip_policy);
7269 	IP_STAT(ipst, ip_udp_fanmb);
7270 	CONN_DEC_REF(connp);
7271 	return;
7272 
7273 notfound:
7274 
7275 	mutex_exit(&connfp->connf_lock);
7276 	IP_STAT(ipst, ip_udp_fanothers);
7277 	/*
7278 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7279 	 * have already been matched above, since they live in the IPv4
7280 	 * fanout tables. This implies we only need to
7281 	 * check for IPv6 in6addr_any endpoints here.
7282 	 * Thus we compare using ipv6_all_zeros instead of the destination
7283 	 * address, except for the multicast group membership lookup which
7284 	 * uses the IPv4 destination.
7285 	 */
7286 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7287 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7288 	mutex_enter(&connfp->connf_lock);
7289 	connp = connfp->connf_head;
7290 	if (!broadcast && !CLASSD(dst)) {
7291 		while (connp != NULL) {
7292 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7293 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7294 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7295 			    !connp->conn_ipv6_v6only)
7296 				break;
7297 			connp = connp->conn_next;
7298 		}
7299 
7300 		if (connp != NULL && is_system_labeled() &&
7301 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7302 		    connp))
7303 			connp = NULL;
7304 
7305 		if (connp == NULL || connp->conn_upq == NULL) {
7306 			/*
7307 			 * No one bound to this port.  Is
7308 			 * there a client that wants all
7309 			 * unclaimed datagrams?
7310 			 */
7311 			mutex_exit(&connfp->connf_lock);
7312 
7313 			if (mctl_present)
7314 				first_mp->b_cont = mp;
7315 			else
7316 				first_mp = mp;
7317 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7318 			    connf_head != NULL) {
7319 				ip_fanout_proto(q, first_mp, ill, ipha,
7320 				    flags | IP_FF_RAWIP, mctl_present,
7321 				    ip_policy, recv_ill, zoneid);
7322 			} else {
7323 				if (ip_fanout_send_icmp(q, first_mp, flags,
7324 				    ICMP_DEST_UNREACHABLE,
7325 				    ICMP_PORT_UNREACHABLE,
7326 				    mctl_present, zoneid, ipst)) {
7327 					BUMP_MIB(ill->ill_ip_mib,
7328 					    udpIfStatsNoPorts);
7329 				}
7330 			}
7331 			return;
7332 		}
7333 
7334 		CONN_INC_REF(connp);
7335 		mutex_exit(&connfp->connf_lock);
7336 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7337 		    flags, recv_ill, ip_policy);
7338 		CONN_DEC_REF(connp);
7339 		return;
7340 	}
7341 	/*
7342 	 * IPv4 multicast packet being delivered to an AF_INET6
7343 	 * in6addr_any endpoint.
7344 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7345 	 * and not conn_wantpacket_v6() since any multicast membership is
7346 	 * for an IPv4-mapped multicast address.
7347 	 * The packet is sent to all clients in all zones that have joined the
7348 	 * group and match the port.
7349 	 */
7350 	while (connp != NULL) {
7351 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7352 		    srcport, v6src) &&
7353 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7354 		    (!is_system_labeled() ||
7355 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7356 		    connp)))
7357 			break;
7358 		connp = connp->conn_next;
7359 	}
7360 
7361 	if (connp == NULL || connp->conn_upq == NULL) {
7362 		/*
7363 		 * No one bound to this port.  Is
7364 		 * there a client that wants all
7365 		 * unclaimed datagrams?
7366 		 */
7367 		mutex_exit(&connfp->connf_lock);
7368 
7369 		if (mctl_present)
7370 			first_mp->b_cont = mp;
7371 		else
7372 			first_mp = mp;
7373 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7374 		    NULL) {
7375 			ip_fanout_proto(q, first_mp, ill, ipha,
7376 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7377 			    recv_ill, zoneid);
7378 		} else {
7379 			/*
7380 			 * We used to attempt to send an icmp error here, but
7381 			 * since this is known to be a multicast packet
7382 			 * and we don't send icmp errors in response to
7383 			 * multicast, just drop the packet and give up sooner.
7384 			 */
7385 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7386 			freemsg(first_mp);
7387 		}
7388 		return;
7389 	}
7390 
7391 	first_connp = connp;
7392 
7393 	CONN_INC_REF(connp);
7394 	connp = connp->conn_next;
7395 	for (;;) {
7396 		while (connp != NULL) {
7397 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7398 			    ipv6_all_zeros, srcport, v6src) &&
7399 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7400 			    (!is_system_labeled() ||
7401 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7402 			    shared_addr, connp)))
7403 				break;
7404 			connp = connp->conn_next;
7405 		}
7406 		/*
7407 		 * Just copy the data part alone. The mctl part is
7408 		 * needed just for verifying policy and it is never
7409 		 * sent up.
7410 		 */
7411 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7412 		    ((mp1 = copymsg(mp)) == NULL))) {
7413 			/*
7414 			 * No more intested clients or memory
7415 			 * allocation failed
7416 			 */
7417 			connp = first_connp;
7418 			break;
7419 		}
7420 		if (first_mp != NULL) {
7421 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7422 			    ipsec_info_type == IPSEC_IN);
7423 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7424 			    ipst->ips_netstack);
7425 			if (first_mp1 == NULL) {
7426 				freemsg(mp1);
7427 				connp = first_connp;
7428 				break;
7429 			}
7430 		} else {
7431 			first_mp1 = NULL;
7432 		}
7433 		CONN_INC_REF(connp);
7434 		mutex_exit(&connfp->connf_lock);
7435 		/*
7436 		 * IPQoS notes: We don't send the packet for policy
7437 		 * processing here, will do it for the last one (below).
7438 		 * i.e. we do it per-packet now, but if we do policy
7439 		 * processing per-conn, then we would need to do it
7440 		 * here too.
7441 		 */
7442 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7443 		    ipha, flags, recv_ill, B_FALSE);
7444 		mutex_enter(&connfp->connf_lock);
7445 		/* Follow the next pointer before releasing the conn. */
7446 		next_connp = connp->conn_next;
7447 		CONN_DEC_REF(connp);
7448 		connp = next_connp;
7449 	}
7450 
7451 	/* Last one.  Send it upstream. */
7452 	mutex_exit(&connfp->connf_lock);
7453 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7454 	    recv_ill, ip_policy);
7455 	CONN_DEC_REF(connp);
7456 }
7457 
7458 /*
7459  * Complete the ip_wput header so that it
7460  * is possible to generate ICMP
7461  * errors.
7462  */
7463 int
7464 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7465 {
7466 	ire_t *ire;
7467 
7468 	if (ipha->ipha_src == INADDR_ANY) {
7469 		ire = ire_lookup_local(zoneid, ipst);
7470 		if (ire == NULL) {
7471 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7472 			return (1);
7473 		}
7474 		ipha->ipha_src = ire->ire_addr;
7475 		ire_refrele(ire);
7476 	}
7477 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7478 	ipha->ipha_hdr_checksum = 0;
7479 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7480 	return (0);
7481 }
7482 
7483 /*
7484  * Nobody should be sending
7485  * packets up this stream
7486  */
7487 static void
7488 ip_lrput(queue_t *q, mblk_t *mp)
7489 {
7490 	mblk_t *mp1;
7491 
7492 	switch (mp->b_datap->db_type) {
7493 	case M_FLUSH:
7494 		/* Turn around */
7495 		if (*mp->b_rptr & FLUSHW) {
7496 			*mp->b_rptr &= ~FLUSHR;
7497 			qreply(q, mp);
7498 			return;
7499 		}
7500 		break;
7501 	}
7502 	/* Could receive messages that passed through ar_rput */
7503 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7504 		mp1->b_prev = mp1->b_next = NULL;
7505 	freemsg(mp);
7506 }
7507 
7508 /* Nobody should be sending packets down this stream */
7509 /* ARGSUSED */
7510 void
7511 ip_lwput(queue_t *q, mblk_t *mp)
7512 {
7513 	freemsg(mp);
7514 }
7515 
7516 /*
7517  * Move the first hop in any source route to ipha_dst and remove that part of
7518  * the source route.  Called by other protocols.  Errors in option formatting
7519  * are ignored - will be handled by ip_wput_options Return the final
7520  * destination (either ipha_dst or the last entry in a source route.)
7521  */
7522 ipaddr_t
7523 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7524 {
7525 	ipoptp_t	opts;
7526 	uchar_t		*opt;
7527 	uint8_t		optval;
7528 	uint8_t		optlen;
7529 	ipaddr_t	dst;
7530 	int		i;
7531 	ire_t		*ire;
7532 	ip_stack_t	*ipst = ns->netstack_ip;
7533 
7534 	ip2dbg(("ip_massage_options\n"));
7535 	dst = ipha->ipha_dst;
7536 	for (optval = ipoptp_first(&opts, ipha);
7537 	    optval != IPOPT_EOL;
7538 	    optval = ipoptp_next(&opts)) {
7539 		opt = opts.ipoptp_cur;
7540 		switch (optval) {
7541 			uint8_t off;
7542 		case IPOPT_SSRR:
7543 		case IPOPT_LSRR:
7544 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7545 				ip1dbg(("ip_massage_options: bad src route\n"));
7546 				break;
7547 			}
7548 			optlen = opts.ipoptp_len;
7549 			off = opt[IPOPT_OFFSET];
7550 			off--;
7551 		redo_srr:
7552 			if (optlen < IP_ADDR_LEN ||
7553 			    off > optlen - IP_ADDR_LEN) {
7554 				/* End of source route */
7555 				ip1dbg(("ip_massage_options: end of SR\n"));
7556 				break;
7557 			}
7558 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7559 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7560 			    ntohl(dst)));
7561 			/*
7562 			 * Check if our address is present more than
7563 			 * once as consecutive hops in source route.
7564 			 * XXX verify per-interface ip_forwarding
7565 			 * for source route?
7566 			 */
7567 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7568 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7569 			if (ire != NULL) {
7570 				ire_refrele(ire);
7571 				off += IP_ADDR_LEN;
7572 				goto redo_srr;
7573 			}
7574 			if (dst == htonl(INADDR_LOOPBACK)) {
7575 				ip1dbg(("ip_massage_options: loopback addr in "
7576 				    "source route!\n"));
7577 				break;
7578 			}
7579 			/*
7580 			 * Update ipha_dst to be the first hop and remove the
7581 			 * first hop from the source route (by overwriting
7582 			 * part of the option with NOP options).
7583 			 */
7584 			ipha->ipha_dst = dst;
7585 			/* Put the last entry in dst */
7586 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7587 			    3;
7588 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7589 
7590 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7591 			    ntohl(dst)));
7592 			/* Move down and overwrite */
7593 			opt[IP_ADDR_LEN] = opt[0];
7594 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7595 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7596 			for (i = 0; i < IP_ADDR_LEN; i++)
7597 				opt[i] = IPOPT_NOP;
7598 			break;
7599 		}
7600 	}
7601 	return (dst);
7602 }
7603 
7604 /*
7605  * Return the network mask
7606  * associated with the specified address.
7607  */
7608 ipaddr_t
7609 ip_net_mask(ipaddr_t addr)
7610 {
7611 	uchar_t	*up = (uchar_t *)&addr;
7612 	ipaddr_t mask = 0;
7613 	uchar_t	*maskp = (uchar_t *)&mask;
7614 
7615 #if defined(__i386) || defined(__amd64)
7616 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7617 #endif
7618 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7619 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7620 #endif
7621 	if (CLASSD(addr)) {
7622 		maskp[0] = 0xF0;
7623 		return (mask);
7624 	}
7625 
7626 	/* We assume Class E default netmask to be 32 */
7627 	if (CLASSE(addr))
7628 		return (0xffffffffU);
7629 
7630 	if (addr == 0)
7631 		return (0);
7632 	maskp[0] = 0xFF;
7633 	if ((up[0] & 0x80) == 0)
7634 		return (mask);
7635 
7636 	maskp[1] = 0xFF;
7637 	if ((up[0] & 0xC0) == 0x80)
7638 		return (mask);
7639 
7640 	maskp[2] = 0xFF;
7641 	if ((up[0] & 0xE0) == 0xC0)
7642 		return (mask);
7643 
7644 	/* Otherwise return no mask */
7645 	return ((ipaddr_t)0);
7646 }
7647 
7648 /*
7649  * Select an ill for the packet by considering load spreading across
7650  * a different ill in the group if dst_ill is part of some group.
7651  */
7652 ill_t *
7653 ip_newroute_get_dst_ill(ill_t *dst_ill)
7654 {
7655 	ill_t *ill;
7656 
7657 	/*
7658 	 * We schedule irrespective of whether the source address is
7659 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7660 	 */
7661 	ill = illgrp_scheduler(dst_ill);
7662 	if (ill == NULL)
7663 		return (NULL);
7664 
7665 	/*
7666 	 * For groups with names ip_sioctl_groupname ensures that all
7667 	 * ills are of same type. For groups without names, ifgrp_insert
7668 	 * ensures this.
7669 	 */
7670 	ASSERT(dst_ill->ill_type == ill->ill_type);
7671 
7672 	return (ill);
7673 }
7674 
7675 /*
7676  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7677  */
7678 ill_t *
7679 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7680     ip_stack_t *ipst)
7681 {
7682 	ill_t *ret_ill;
7683 
7684 	ASSERT(ifindex != 0);
7685 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7686 	    ipst);
7687 	if (ret_ill == NULL ||
7688 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7689 		if (isv6) {
7690 			if (ill != NULL) {
7691 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7692 			} else {
7693 				BUMP_MIB(&ipst->ips_ip6_mib,
7694 				    ipIfStatsOutDiscards);
7695 			}
7696 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7697 			    "bad ifindex %d.\n", ifindex));
7698 		} else {
7699 			if (ill != NULL) {
7700 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7701 			} else {
7702 				BUMP_MIB(&ipst->ips_ip_mib,
7703 				    ipIfStatsOutDiscards);
7704 			}
7705 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7706 			    "bad ifindex %d.\n", ifindex));
7707 		}
7708 		if (ret_ill != NULL)
7709 			ill_refrele(ret_ill);
7710 		freemsg(first_mp);
7711 		return (NULL);
7712 	}
7713 
7714 	return (ret_ill);
7715 }
7716 
7717 /*
7718  * IPv4 -
7719  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7720  * out a packet to a destination address for which we do not have specific
7721  * (or sufficient) routing information.
7722  *
7723  * NOTE : These are the scopes of some of the variables that point at IRE,
7724  *	  which needs to be followed while making any future modifications
7725  *	  to avoid memory leaks.
7726  *
7727  *	- ire and sire are the entries looked up initially by
7728  *	  ire_ftable_lookup.
7729  *	- ipif_ire is used to hold the interface ire associated with
7730  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7731  *	  it before branching out to error paths.
7732  *	- save_ire is initialized before ire_create, so that ire returned
7733  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7734  *	  before breaking out of the switch.
7735  *
7736  *	Thus on failures, we have to REFRELE only ire and sire, if they
7737  *	are not NULL.
7738  */
7739 void
7740 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7741     zoneid_t zoneid, ip_stack_t *ipst)
7742 {
7743 	areq_t	*areq;
7744 	ipaddr_t gw = 0;
7745 	ire_t	*ire = NULL;
7746 	mblk_t	*res_mp;
7747 	ipaddr_t *addrp;
7748 	ipaddr_t nexthop_addr;
7749 	ipif_t  *src_ipif = NULL;
7750 	ill_t	*dst_ill = NULL;
7751 	ipha_t  *ipha;
7752 	ire_t	*sire = NULL;
7753 	mblk_t	*first_mp;
7754 	ire_t	*save_ire;
7755 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7756 	ushort_t ire_marks = 0;
7757 	boolean_t mctl_present;
7758 	ipsec_out_t *io;
7759 	mblk_t	*saved_mp;
7760 	ire_t	*first_sire = NULL;
7761 	mblk_t	*copy_mp = NULL;
7762 	mblk_t	*xmit_mp = NULL;
7763 	ipaddr_t save_dst;
7764 	uint32_t multirt_flags =
7765 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7766 	boolean_t multirt_is_resolvable;
7767 	boolean_t multirt_resolve_next;
7768 	boolean_t unspec_src;
7769 	boolean_t do_attach_ill = B_FALSE;
7770 	boolean_t ip_nexthop = B_FALSE;
7771 	tsol_ire_gw_secattr_t *attrp = NULL;
7772 	tsol_gcgrp_t *gcgrp = NULL;
7773 	tsol_gcgrp_addr_t ga;
7774 
7775 	if (ip_debug > 2) {
7776 		/* ip1dbg */
7777 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7778 	}
7779 
7780 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7781 	if (mctl_present) {
7782 		io = (ipsec_out_t *)first_mp->b_rptr;
7783 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7784 		ASSERT(zoneid == io->ipsec_out_zoneid);
7785 		ASSERT(zoneid != ALL_ZONES);
7786 	}
7787 
7788 	ipha = (ipha_t *)mp->b_rptr;
7789 
7790 	/* All multicast lookups come through ip_newroute_ipif() */
7791 	if (CLASSD(dst)) {
7792 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7793 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7794 		freemsg(first_mp);
7795 		return;
7796 	}
7797 
7798 	if (mctl_present && io->ipsec_out_attach_if) {
7799 		/* ip_grab_attach_ill returns a held ill */
7800 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7801 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7802 
7803 		/* Failure case frees things for us. */
7804 		if (attach_ill == NULL)
7805 			return;
7806 
7807 		/*
7808 		 * Check if we need an ire that will not be
7809 		 * looked up by anybody else i.e. HIDDEN.
7810 		 */
7811 		if (ill_is_probeonly(attach_ill))
7812 			ire_marks = IRE_MARK_HIDDEN;
7813 	}
7814 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7815 		ip_nexthop = B_TRUE;
7816 		nexthop_addr = io->ipsec_out_nexthop_addr;
7817 	}
7818 	/*
7819 	 * If this IRE is created for forwarding or it is not for
7820 	 * traffic for congestion controlled protocols, mark it as temporary.
7821 	 */
7822 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7823 		ire_marks |= IRE_MARK_TEMPORARY;
7824 
7825 	/*
7826 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7827 	 * chain until it gets the most specific information available.
7828 	 * For example, we know that there is no IRE_CACHE for this dest,
7829 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7830 	 * ire_ftable_lookup will look up the gateway, etc.
7831 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7832 	 * to the destination, of equal netmask length in the forward table,
7833 	 * will be recursively explored. If no information is available
7834 	 * for the final gateway of that route, we force the returned ire
7835 	 * to be equal to sire using MATCH_IRE_PARENT.
7836 	 * At least, in this case we have a starting point (in the buckets)
7837 	 * to look for other routes to the destination in the forward table.
7838 	 * This is actually used only for multirouting, where a list
7839 	 * of routes has to be processed in sequence.
7840 	 *
7841 	 * In the process of coming up with the most specific information,
7842 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7843 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7844 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7845 	 * Two caveats when handling incomplete ire's in ip_newroute:
7846 	 * - we should be careful when accessing its ire_nce (specifically
7847 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7848 	 * - not all legacy code path callers are prepared to handle
7849 	 *   incomplete ire's, so we should not create/add incomplete
7850 	 *   ire_cache entries here. (See discussion about temporary solution
7851 	 *   further below).
7852 	 *
7853 	 * In order to minimize packet dropping, and to preserve existing
7854 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7855 	 * gateway, and instead use the IF_RESOLVER ire to send out
7856 	 * another request to ARP (this is achieved by passing the
7857 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7858 	 * arp response comes back in ip_wput_nondata, we will create
7859 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7860 	 *
7861 	 * Note that this is a temporary solution; the correct solution is
7862 	 * to create an incomplete  per-dst ire_cache entry, and send the
7863 	 * packet out when the gw's nce is resolved. In order to achieve this,
7864 	 * all packet processing must have been completed prior to calling
7865 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7866 	 * to be modified to accomodate this solution.
7867 	 */
7868 	if (ip_nexthop) {
7869 		/*
7870 		 * The first time we come here, we look for an IRE_INTERFACE
7871 		 * entry for the specified nexthop, set the dst to be the
7872 		 * nexthop address and create an IRE_CACHE entry for the
7873 		 * nexthop. The next time around, we are able to find an
7874 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7875 		 * nexthop address and create an IRE_CACHE entry for the
7876 		 * destination address via the specified nexthop.
7877 		 */
7878 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7879 		    MBLK_GETLABEL(mp), ipst);
7880 		if (ire != NULL) {
7881 			gw = nexthop_addr;
7882 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7883 		} else {
7884 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7885 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7886 			    MBLK_GETLABEL(mp),
7887 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7888 			    ipst);
7889 			if (ire != NULL) {
7890 				dst = nexthop_addr;
7891 			}
7892 		}
7893 	} else if (attach_ill == NULL) {
7894 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7895 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7896 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7897 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7898 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7899 		    ipst);
7900 	} else {
7901 		/*
7902 		 * attach_ill is set only for communicating with
7903 		 * on-link hosts. So, don't look for DEFAULT.
7904 		 */
7905 		ipif_t	*attach_ipif;
7906 
7907 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7908 		if (attach_ipif == NULL) {
7909 			ill_refrele(attach_ill);
7910 			goto icmp_err_ret;
7911 		}
7912 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7913 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7914 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7915 		    MATCH_IRE_SECATTR, ipst);
7916 		ipif_refrele(attach_ipif);
7917 	}
7918 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7919 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7920 
7921 	/*
7922 	 * This loop is run only once in most cases.
7923 	 * We loop to resolve further routes only when the destination
7924 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7925 	 */
7926 	do {
7927 		/* Clear the previous iteration's values */
7928 		if (src_ipif != NULL) {
7929 			ipif_refrele(src_ipif);
7930 			src_ipif = NULL;
7931 		}
7932 		if (dst_ill != NULL) {
7933 			ill_refrele(dst_ill);
7934 			dst_ill = NULL;
7935 		}
7936 
7937 		multirt_resolve_next = B_FALSE;
7938 		/*
7939 		 * We check if packets have to be multirouted.
7940 		 * In this case, given the current <ire, sire> couple,
7941 		 * we look for the next suitable <ire, sire>.
7942 		 * This check is done in ire_multirt_lookup(),
7943 		 * which applies various criteria to find the next route
7944 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7945 		 * unchanged if it detects it has not been tried yet.
7946 		 */
7947 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7948 			ip3dbg(("ip_newroute: starting next_resolution "
7949 			    "with first_mp %p, tag %d\n",
7950 			    (void *)first_mp,
7951 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7952 
7953 			ASSERT(sire != NULL);
7954 			multirt_is_resolvable =
7955 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7956 			    MBLK_GETLABEL(mp), ipst);
7957 
7958 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7959 			    "ire %p, sire %p\n",
7960 			    multirt_is_resolvable,
7961 			    (void *)ire, (void *)sire));
7962 
7963 			if (!multirt_is_resolvable) {
7964 				/*
7965 				 * No more multirt route to resolve; give up
7966 				 * (all routes resolved or no more
7967 				 * resolvable routes).
7968 				 */
7969 				if (ire != NULL) {
7970 					ire_refrele(ire);
7971 					ire = NULL;
7972 				}
7973 			} else {
7974 				ASSERT(sire != NULL);
7975 				ASSERT(ire != NULL);
7976 				/*
7977 				 * We simply use first_sire as a flag that
7978 				 * indicates if a resolvable multirt route
7979 				 * has already been found.
7980 				 * If it is not the case, we may have to send
7981 				 * an ICMP error to report that the
7982 				 * destination is unreachable.
7983 				 * We do not IRE_REFHOLD first_sire.
7984 				 */
7985 				if (first_sire == NULL) {
7986 					first_sire = sire;
7987 				}
7988 			}
7989 		}
7990 		if (ire == NULL) {
7991 			if (ip_debug > 3) {
7992 				/* ip2dbg */
7993 				pr_addr_dbg("ip_newroute: "
7994 				    "can't resolve %s\n", AF_INET, &dst);
7995 			}
7996 			ip3dbg(("ip_newroute: "
7997 			    "ire %p, sire %p, first_sire %p\n",
7998 			    (void *)ire, (void *)sire, (void *)first_sire));
7999 
8000 			if (sire != NULL) {
8001 				ire_refrele(sire);
8002 				sire = NULL;
8003 			}
8004 
8005 			if (first_sire != NULL) {
8006 				/*
8007 				 * At least one multirt route has been found
8008 				 * in the same call to ip_newroute();
8009 				 * there is no need to report an ICMP error.
8010 				 * first_sire was not IRE_REFHOLDed.
8011 				 */
8012 				MULTIRT_DEBUG_UNTAG(first_mp);
8013 				freemsg(first_mp);
8014 				return;
8015 			}
8016 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8017 			    RTA_DST, ipst);
8018 			if (attach_ill != NULL)
8019 				ill_refrele(attach_ill);
8020 			goto icmp_err_ret;
8021 		}
8022 
8023 		/*
8024 		 * Verify that the returned IRE does not have either
8025 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8026 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8027 		 */
8028 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8029 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8030 			if (attach_ill != NULL)
8031 				ill_refrele(attach_ill);
8032 			goto icmp_err_ret;
8033 		}
8034 		/*
8035 		 * Increment the ire_ob_pkt_count field for ire if it is an
8036 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8037 		 * increment the same for the parent IRE, sire, if it is some
8038 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8039 		 */
8040 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8041 			UPDATE_OB_PKT_COUNT(ire);
8042 			ire->ire_last_used_time = lbolt;
8043 		}
8044 
8045 		if (sire != NULL) {
8046 			gw = sire->ire_gateway_addr;
8047 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8048 			    IRE_INTERFACE)) == 0);
8049 			UPDATE_OB_PKT_COUNT(sire);
8050 			sire->ire_last_used_time = lbolt;
8051 		}
8052 		/*
8053 		 * We have a route to reach the destination.
8054 		 *
8055 		 * 1) If the interface is part of ill group, try to get a new
8056 		 *    ill taking load spreading into account.
8057 		 *
8058 		 * 2) After selecting the ill, get a source address that
8059 		 *    might create good inbound load spreading.
8060 		 *    ipif_select_source does this for us.
8061 		 *
8062 		 * If the application specified the ill (ifindex), we still
8063 		 * load spread. Only if the packets needs to go out
8064 		 * specifically on a given ill e.g. binding to
8065 		 * IPIF_NOFAILOVER address, then we don't try to use a
8066 		 * different ill for load spreading.
8067 		 */
8068 		if (attach_ill == NULL) {
8069 			/*
8070 			 * Don't perform outbound load spreading in the
8071 			 * case of an RTF_MULTIRT route, as we actually
8072 			 * typically want to replicate outgoing packets
8073 			 * through particular interfaces.
8074 			 */
8075 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8076 				dst_ill = ire->ire_ipif->ipif_ill;
8077 				/* for uniformity */
8078 				ill_refhold(dst_ill);
8079 			} else {
8080 				/*
8081 				 * If we are here trying to create an IRE_CACHE
8082 				 * for an offlink destination and have the
8083 				 * IRE_CACHE for the next hop and the latter is
8084 				 * using virtual IP source address selection i.e
8085 				 * it's ire->ire_ipif is pointing to a virtual
8086 				 * network interface (vni) then
8087 				 * ip_newroute_get_dst_ll() will return the vni
8088 				 * interface as the dst_ill. Since the vni is
8089 				 * virtual i.e not associated with any physical
8090 				 * interface, it cannot be the dst_ill, hence
8091 				 * in such a case call ip_newroute_get_dst_ll()
8092 				 * with the stq_ill instead of the ire_ipif ILL.
8093 				 * The function returns a refheld ill.
8094 				 */
8095 				if ((ire->ire_type == IRE_CACHE) &&
8096 				    IS_VNI(ire->ire_ipif->ipif_ill))
8097 					dst_ill = ip_newroute_get_dst_ill(
8098 					    ire->ire_stq->q_ptr);
8099 				else
8100 					dst_ill = ip_newroute_get_dst_ill(
8101 					    ire->ire_ipif->ipif_ill);
8102 			}
8103 			if (dst_ill == NULL) {
8104 				if (ip_debug > 2) {
8105 					pr_addr_dbg("ip_newroute: "
8106 					    "no dst ill for dst"
8107 					    " %s\n", AF_INET, &dst);
8108 				}
8109 				goto icmp_err_ret;
8110 			}
8111 		} else {
8112 			dst_ill = ire->ire_ipif->ipif_ill;
8113 			/* for uniformity */
8114 			ill_refhold(dst_ill);
8115 			/*
8116 			 * We should have found a route matching ill as we
8117 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8118 			 * Rather than asserting, when there is a mismatch,
8119 			 * we just drop the packet.
8120 			 */
8121 			if (dst_ill != attach_ill) {
8122 				ip0dbg(("ip_newroute: Packet dropped as "
8123 				    "IPIF_NOFAILOVER ill is %s, "
8124 				    "ire->ire_ipif->ipif_ill is %s\n",
8125 				    attach_ill->ill_name,
8126 				    dst_ill->ill_name));
8127 				ill_refrele(attach_ill);
8128 				goto icmp_err_ret;
8129 			}
8130 		}
8131 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8132 		if (attach_ill != NULL) {
8133 			ill_refrele(attach_ill);
8134 			attach_ill = NULL;
8135 			do_attach_ill = B_TRUE;
8136 		}
8137 		ASSERT(dst_ill != NULL);
8138 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8139 
8140 		/*
8141 		 * Pick the best source address from dst_ill.
8142 		 *
8143 		 * 1) If it is part of a multipathing group, we would
8144 		 *    like to spread the inbound packets across different
8145 		 *    interfaces. ipif_select_source picks a random source
8146 		 *    across the different ills in the group.
8147 		 *
8148 		 * 2) If it is not part of a multipathing group, we try
8149 		 *    to pick the source address from the destination
8150 		 *    route. Clustering assumes that when we have multiple
8151 		 *    prefixes hosted on an interface, the prefix of the
8152 		 *    source address matches the prefix of the destination
8153 		 *    route. We do this only if the address is not
8154 		 *    DEPRECATED.
8155 		 *
8156 		 * 3) If the conn is in a different zone than the ire, we
8157 		 *    need to pick a source address from the right zone.
8158 		 *
8159 		 * NOTE : If we hit case (1) above, the prefix of the source
8160 		 *	  address picked may not match the prefix of the
8161 		 *	  destination routes prefix as ipif_select_source
8162 		 *	  does not look at "dst" while picking a source
8163 		 *	  address.
8164 		 *	  If we want the same behavior as (2), we will need
8165 		 *	  to change the behavior of ipif_select_source.
8166 		 */
8167 		ASSERT(src_ipif == NULL);
8168 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8169 			/*
8170 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8171 			 * Check that the ipif matching the requested source
8172 			 * address still exists.
8173 			 */
8174 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8175 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8176 		}
8177 
8178 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8179 
8180 		if (src_ipif == NULL &&
8181 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8182 			ire_marks |= IRE_MARK_USESRC_CHECK;
8183 			if ((dst_ill->ill_group != NULL) ||
8184 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8185 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8186 			    ire->ire_zoneid != ALL_ZONES) ||
8187 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8188 				/*
8189 				 * If the destination is reachable via a
8190 				 * given gateway, the selected source address
8191 				 * should be in the same subnet as the gateway.
8192 				 * Otherwise, the destination is not reachable.
8193 				 *
8194 				 * If there are no interfaces on the same subnet
8195 				 * as the destination, ipif_select_source gives
8196 				 * first non-deprecated interface which might be
8197 				 * on a different subnet than the gateway.
8198 				 * This is not desirable. Hence pass the dst_ire
8199 				 * source address to ipif_select_source.
8200 				 * It is sure that the destination is reachable
8201 				 * with the dst_ire source address subnet.
8202 				 * So passing dst_ire source address to
8203 				 * ipif_select_source will make sure that the
8204 				 * selected source will be on the same subnet
8205 				 * as dst_ire source address.
8206 				 */
8207 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8208 				src_ipif = ipif_select_source(dst_ill, saddr,
8209 				    zoneid);
8210 				if (src_ipif == NULL) {
8211 					if (ip_debug > 2) {
8212 						pr_addr_dbg("ip_newroute: "
8213 						    "no src for dst %s ",
8214 						    AF_INET, &dst);
8215 						printf("through interface %s\n",
8216 						    dst_ill->ill_name);
8217 					}
8218 					goto icmp_err_ret;
8219 				}
8220 			} else {
8221 				src_ipif = ire->ire_ipif;
8222 				ASSERT(src_ipif != NULL);
8223 				/* hold src_ipif for uniformity */
8224 				ipif_refhold(src_ipif);
8225 			}
8226 		}
8227 
8228 		/*
8229 		 * Assign a source address while we have the conn.
8230 		 * We can't have ip_wput_ire pick a source address when the
8231 		 * packet returns from arp since we need to look at
8232 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8233 		 * going through arp.
8234 		 *
8235 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8236 		 *	  it uses ip6i to store this information.
8237 		 */
8238 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8239 			ipha->ipha_src = src_ipif->ipif_src_addr;
8240 
8241 		if (ip_debug > 3) {
8242 			/* ip2dbg */
8243 			pr_addr_dbg("ip_newroute: first hop %s\n",
8244 			    AF_INET, &gw);
8245 		}
8246 		ip2dbg(("\tire type %s (%d)\n",
8247 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8248 
8249 		/*
8250 		 * The TTL of multirouted packets is bounded by the
8251 		 * ip_multirt_ttl ndd variable.
8252 		 */
8253 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8254 			/* Force TTL of multirouted packets */
8255 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8256 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8257 				ip2dbg(("ip_newroute: forcing multirt TTL "
8258 				    "to %d (was %d), dst 0x%08x\n",
8259 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8260 				    ntohl(sire->ire_addr)));
8261 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8262 			}
8263 		}
8264 		/*
8265 		 * At this point in ip_newroute(), ire is either the
8266 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8267 		 * destination or an IRE_INTERFACE type that should be used
8268 		 * to resolve an on-subnet destination or an on-subnet
8269 		 * next-hop gateway.
8270 		 *
8271 		 * In the IRE_CACHE case, we have the following :
8272 		 *
8273 		 * 1) src_ipif - used for getting a source address.
8274 		 *
8275 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8276 		 *    means packets using this IRE_CACHE will go out on
8277 		 *    dst_ill.
8278 		 *
8279 		 * 3) The IRE sire will point to the prefix that is the
8280 		 *    longest  matching route for the destination. These
8281 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8282 		 *
8283 		 *    The newly created IRE_CACHE entry for the off-subnet
8284 		 *    destination is tied to both the prefix route and the
8285 		 *    interface route used to resolve the next-hop gateway
8286 		 *    via the ire_phandle and ire_ihandle fields,
8287 		 *    respectively.
8288 		 *
8289 		 * In the IRE_INTERFACE case, we have the following :
8290 		 *
8291 		 * 1) src_ipif - used for getting a source address.
8292 		 *
8293 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8294 		 *    means packets using the IRE_CACHE that we will build
8295 		 *    here will go out on dst_ill.
8296 		 *
8297 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8298 		 *    to be created will only be tied to the IRE_INTERFACE
8299 		 *    that was derived from the ire_ihandle field.
8300 		 *
8301 		 *    If sire is non-NULL, it means the destination is
8302 		 *    off-link and we will first create the IRE_CACHE for the
8303 		 *    gateway. Next time through ip_newroute, we will create
8304 		 *    the IRE_CACHE for the final destination as described
8305 		 *    above.
8306 		 *
8307 		 * In both cases, after the current resolution has been
8308 		 * completed (or possibly initialised, in the IRE_INTERFACE
8309 		 * case), the loop may be re-entered to attempt the resolution
8310 		 * of another RTF_MULTIRT route.
8311 		 *
8312 		 * When an IRE_CACHE entry for the off-subnet destination is
8313 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8314 		 * for further processing in emission loops.
8315 		 */
8316 		save_ire = ire;
8317 		switch (ire->ire_type) {
8318 		case IRE_CACHE: {
8319 			ire_t	*ipif_ire;
8320 
8321 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8322 			if (gw == 0)
8323 				gw = ire->ire_gateway_addr;
8324 			/*
8325 			 * We need 3 ire's to create a new cache ire for an
8326 			 * off-link destination from the cache ire of the
8327 			 * gateway.
8328 			 *
8329 			 *	1. The prefix ire 'sire' (Note that this does
8330 			 *	   not apply to the conn_nexthop_set case)
8331 			 *	2. The cache ire of the gateway 'ire'
8332 			 *	3. The interface ire 'ipif_ire'
8333 			 *
8334 			 * We have (1) and (2). We lookup (3) below.
8335 			 *
8336 			 * If there is no interface route to the gateway,
8337 			 * it is a race condition, where we found the cache
8338 			 * but the interface route has been deleted.
8339 			 */
8340 			if (ip_nexthop) {
8341 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8342 			} else {
8343 				ipif_ire =
8344 				    ire_ihandle_lookup_offlink(ire, sire);
8345 			}
8346 			if (ipif_ire == NULL) {
8347 				ip1dbg(("ip_newroute: "
8348 				    "ire_ihandle_lookup_offlink failed\n"));
8349 				goto icmp_err_ret;
8350 			}
8351 
8352 			/*
8353 			 * Check cached gateway IRE for any security
8354 			 * attributes; if found, associate the gateway
8355 			 * credentials group to the destination IRE.
8356 			 */
8357 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8358 				mutex_enter(&attrp->igsa_lock);
8359 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8360 					GCGRP_REFHOLD(gcgrp);
8361 				mutex_exit(&attrp->igsa_lock);
8362 			}
8363 
8364 			/*
8365 			 * XXX For the source of the resolver mp,
8366 			 * we are using the same DL_UNITDATA_REQ
8367 			 * (from save_ire->ire_nce->nce_res_mp)
8368 			 * though the save_ire is not pointing at the same ill.
8369 			 * This is incorrect. We need to send it up to the
8370 			 * resolver to get the right res_mp. For ethernets
8371 			 * this may be okay (ill_type == DL_ETHER).
8372 			 */
8373 
8374 			ire = ire_create(
8375 			    (uchar_t *)&dst,		/* dest address */
8376 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8377 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8378 			    (uchar_t *)&gw,		/* gateway address */
8379 			    &save_ire->ire_max_frag,
8380 			    save_ire->ire_nce,		/* src nce */
8381 			    dst_ill->ill_rq,		/* recv-from queue */
8382 			    dst_ill->ill_wq,		/* send-to queue */
8383 			    IRE_CACHE,			/* IRE type */
8384 			    src_ipif,
8385 			    (sire != NULL) ?
8386 			    sire->ire_mask : 0, 	/* Parent mask */
8387 			    (sire != NULL) ?
8388 			    sire->ire_phandle : 0,	/* Parent handle */
8389 			    ipif_ire->ire_ihandle,	/* Interface handle */
8390 			    (sire != NULL) ? (sire->ire_flags &
8391 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8392 			    (sire != NULL) ?
8393 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8394 			    NULL,
8395 			    gcgrp,
8396 			    ipst);
8397 
8398 			if (ire == NULL) {
8399 				if (gcgrp != NULL) {
8400 					GCGRP_REFRELE(gcgrp);
8401 					gcgrp = NULL;
8402 				}
8403 				ire_refrele(ipif_ire);
8404 				ire_refrele(save_ire);
8405 				break;
8406 			}
8407 
8408 			/* reference now held by IRE */
8409 			gcgrp = NULL;
8410 
8411 			ire->ire_marks |= ire_marks;
8412 
8413 			/*
8414 			 * Prevent sire and ipif_ire from getting deleted.
8415 			 * The newly created ire is tied to both of them via
8416 			 * the phandle and ihandle respectively.
8417 			 */
8418 			if (sire != NULL) {
8419 				IRB_REFHOLD(sire->ire_bucket);
8420 				/* Has it been removed already ? */
8421 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8422 					IRB_REFRELE(sire->ire_bucket);
8423 					ire_refrele(ipif_ire);
8424 					ire_refrele(save_ire);
8425 					break;
8426 				}
8427 			}
8428 
8429 			IRB_REFHOLD(ipif_ire->ire_bucket);
8430 			/* Has it been removed already ? */
8431 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8432 				IRB_REFRELE(ipif_ire->ire_bucket);
8433 				if (sire != NULL)
8434 					IRB_REFRELE(sire->ire_bucket);
8435 				ire_refrele(ipif_ire);
8436 				ire_refrele(save_ire);
8437 				break;
8438 			}
8439 
8440 			xmit_mp = first_mp;
8441 			/*
8442 			 * In the case of multirouting, a copy
8443 			 * of the packet is done before its sending.
8444 			 * The copy is used to attempt another
8445 			 * route resolution, in a next loop.
8446 			 */
8447 			if (ire->ire_flags & RTF_MULTIRT) {
8448 				copy_mp = copymsg(first_mp);
8449 				if (copy_mp != NULL) {
8450 					xmit_mp = copy_mp;
8451 					MULTIRT_DEBUG_TAG(first_mp);
8452 				}
8453 			}
8454 			ire_add_then_send(q, ire, xmit_mp);
8455 			ire_refrele(save_ire);
8456 
8457 			/* Assert that sire is not deleted yet. */
8458 			if (sire != NULL) {
8459 				ASSERT(sire->ire_ptpn != NULL);
8460 				IRB_REFRELE(sire->ire_bucket);
8461 			}
8462 
8463 			/* Assert that ipif_ire is not deleted yet. */
8464 			ASSERT(ipif_ire->ire_ptpn != NULL);
8465 			IRB_REFRELE(ipif_ire->ire_bucket);
8466 			ire_refrele(ipif_ire);
8467 
8468 			/*
8469 			 * If copy_mp is not NULL, multirouting was
8470 			 * requested. We loop to initiate a next
8471 			 * route resolution attempt, starting from sire.
8472 			 */
8473 			if (copy_mp != NULL) {
8474 				/*
8475 				 * Search for the next unresolved
8476 				 * multirt route.
8477 				 */
8478 				copy_mp = NULL;
8479 				ipif_ire = NULL;
8480 				ire = NULL;
8481 				multirt_resolve_next = B_TRUE;
8482 				continue;
8483 			}
8484 			if (sire != NULL)
8485 				ire_refrele(sire);
8486 			ipif_refrele(src_ipif);
8487 			ill_refrele(dst_ill);
8488 			return;
8489 		}
8490 		case IRE_IF_NORESOLVER: {
8491 
8492 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8493 			    dst_ill->ill_resolver_mp == NULL) {
8494 				ip1dbg(("ip_newroute: dst_ill %p "
8495 				    "for IRE_IF_NORESOLVER ire %p has "
8496 				    "no ill_resolver_mp\n",
8497 				    (void *)dst_ill, (void *)ire));
8498 				break;
8499 			}
8500 
8501 			/*
8502 			 * TSol note: We are creating the ire cache for the
8503 			 * destination 'dst'. If 'dst' is offlink, going
8504 			 * through the first hop 'gw', the security attributes
8505 			 * of 'dst' must be set to point to the gateway
8506 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8507 			 * is possible that 'dst' is a potential gateway that is
8508 			 * referenced by some route that has some security
8509 			 * attributes. Thus in the former case, we need to do a
8510 			 * gcgrp_lookup of 'gw' while in the latter case we
8511 			 * need to do gcgrp_lookup of 'dst' itself.
8512 			 */
8513 			ga.ga_af = AF_INET;
8514 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8515 			    &ga.ga_addr);
8516 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8517 
8518 			ire = ire_create(
8519 			    (uchar_t *)&dst,		/* dest address */
8520 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8521 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8522 			    (uchar_t *)&gw,		/* gateway address */
8523 			    &save_ire->ire_max_frag,
8524 			    NULL,			/* no src nce */
8525 			    dst_ill->ill_rq,		/* recv-from queue */
8526 			    dst_ill->ill_wq,		/* send-to queue */
8527 			    IRE_CACHE,
8528 			    src_ipif,
8529 			    save_ire->ire_mask,		/* Parent mask */
8530 			    (sire != NULL) ?		/* Parent handle */
8531 			    sire->ire_phandle : 0,
8532 			    save_ire->ire_ihandle,	/* Interface handle */
8533 			    (sire != NULL) ? sire->ire_flags &
8534 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8535 			    &(save_ire->ire_uinfo),
8536 			    NULL,
8537 			    gcgrp,
8538 			    ipst);
8539 
8540 			if (ire == NULL) {
8541 				if (gcgrp != NULL) {
8542 					GCGRP_REFRELE(gcgrp);
8543 					gcgrp = NULL;
8544 				}
8545 				ire_refrele(save_ire);
8546 				break;
8547 			}
8548 
8549 			/* reference now held by IRE */
8550 			gcgrp = NULL;
8551 
8552 			ire->ire_marks |= ire_marks;
8553 
8554 			/* Prevent save_ire from getting deleted */
8555 			IRB_REFHOLD(save_ire->ire_bucket);
8556 			/* Has it been removed already ? */
8557 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8558 				IRB_REFRELE(save_ire->ire_bucket);
8559 				ire_refrele(save_ire);
8560 				break;
8561 			}
8562 
8563 			/*
8564 			 * In the case of multirouting, a copy
8565 			 * of the packet is made before it is sent.
8566 			 * The copy is used in the next
8567 			 * loop to attempt another resolution.
8568 			 */
8569 			xmit_mp = first_mp;
8570 			if ((sire != NULL) &&
8571 			    (sire->ire_flags & RTF_MULTIRT)) {
8572 				copy_mp = copymsg(first_mp);
8573 				if (copy_mp != NULL) {
8574 					xmit_mp = copy_mp;
8575 					MULTIRT_DEBUG_TAG(first_mp);
8576 				}
8577 			}
8578 			ire_add_then_send(q, ire, xmit_mp);
8579 
8580 			/* Assert that it is not deleted yet. */
8581 			ASSERT(save_ire->ire_ptpn != NULL);
8582 			IRB_REFRELE(save_ire->ire_bucket);
8583 			ire_refrele(save_ire);
8584 
8585 			if (copy_mp != NULL) {
8586 				/*
8587 				 * If we found a (no)resolver, we ignore any
8588 				 * trailing top priority IRE_CACHE in further
8589 				 * loops. This ensures that we do not omit any
8590 				 * (no)resolver.
8591 				 * This IRE_CACHE, if any, will be processed
8592 				 * by another thread entering ip_newroute().
8593 				 * IRE_CACHE entries, if any, will be processed
8594 				 * by another thread entering ip_newroute(),
8595 				 * (upon resolver response, for instance).
8596 				 * This aims to force parallel multirt
8597 				 * resolutions as soon as a packet must be sent.
8598 				 * In the best case, after the tx of only one
8599 				 * packet, all reachable routes are resolved.
8600 				 * Otherwise, the resolution of all RTF_MULTIRT
8601 				 * routes would require several emissions.
8602 				 */
8603 				multirt_flags &= ~MULTIRT_CACHEGW;
8604 
8605 				/*
8606 				 * Search for the next unresolved multirt
8607 				 * route.
8608 				 */
8609 				copy_mp = NULL;
8610 				save_ire = NULL;
8611 				ire = NULL;
8612 				multirt_resolve_next = B_TRUE;
8613 				continue;
8614 			}
8615 
8616 			/*
8617 			 * Don't need sire anymore
8618 			 */
8619 			if (sire != NULL)
8620 				ire_refrele(sire);
8621 
8622 			ipif_refrele(src_ipif);
8623 			ill_refrele(dst_ill);
8624 			return;
8625 		}
8626 		case IRE_IF_RESOLVER:
8627 			/*
8628 			 * We can't build an IRE_CACHE yet, but at least we
8629 			 * found a resolver that can help.
8630 			 */
8631 			res_mp = dst_ill->ill_resolver_mp;
8632 			if (!OK_RESOLVER_MP(res_mp))
8633 				break;
8634 
8635 			/*
8636 			 * To be at this point in the code with a non-zero gw
8637 			 * means that dst is reachable through a gateway that
8638 			 * we have never resolved.  By changing dst to the gw
8639 			 * addr we resolve the gateway first.
8640 			 * When ire_add_then_send() tries to put the IP dg
8641 			 * to dst, it will reenter ip_newroute() at which
8642 			 * time we will find the IRE_CACHE for the gw and
8643 			 * create another IRE_CACHE in case IRE_CACHE above.
8644 			 */
8645 			if (gw != INADDR_ANY) {
8646 				/*
8647 				 * The source ipif that was determined above was
8648 				 * relative to the destination address, not the
8649 				 * gateway's. If src_ipif was not taken out of
8650 				 * the IRE_IF_RESOLVER entry, we'll need to call
8651 				 * ipif_select_source() again.
8652 				 */
8653 				if (src_ipif != ire->ire_ipif) {
8654 					ipif_refrele(src_ipif);
8655 					src_ipif = ipif_select_source(dst_ill,
8656 					    gw, zoneid);
8657 					if (src_ipif == NULL) {
8658 						if (ip_debug > 2) {
8659 							pr_addr_dbg(
8660 							    "ip_newroute: no "
8661 							    "src for gw %s ",
8662 							    AF_INET, &gw);
8663 							printf("through "
8664 							    "interface %s\n",
8665 							    dst_ill->ill_name);
8666 						}
8667 						goto icmp_err_ret;
8668 					}
8669 				}
8670 				save_dst = dst;
8671 				dst = gw;
8672 				gw = INADDR_ANY;
8673 			}
8674 
8675 			/*
8676 			 * We obtain a partial IRE_CACHE which we will pass
8677 			 * along with the resolver query.  When the response
8678 			 * comes back it will be there ready for us to add.
8679 			 * The ire_max_frag is atomically set under the
8680 			 * irebucket lock in ire_add_v[46].
8681 			 */
8682 
8683 			ire = ire_create_mp(
8684 			    (uchar_t *)&dst,		/* dest address */
8685 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8686 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8687 			    (uchar_t *)&gw,		/* gateway address */
8688 			    NULL,			/* ire_max_frag */
8689 			    NULL,			/* no src nce */
8690 			    dst_ill->ill_rq,		/* recv-from queue */
8691 			    dst_ill->ill_wq,		/* send-to queue */
8692 			    IRE_CACHE,
8693 			    src_ipif,			/* Interface ipif */
8694 			    save_ire->ire_mask,		/* Parent mask */
8695 			    0,
8696 			    save_ire->ire_ihandle,	/* Interface handle */
8697 			    0,				/* flags if any */
8698 			    &(save_ire->ire_uinfo),
8699 			    NULL,
8700 			    NULL,
8701 			    ipst);
8702 
8703 			if (ire == NULL) {
8704 				ire_refrele(save_ire);
8705 				break;
8706 			}
8707 
8708 			if ((sire != NULL) &&
8709 			    (sire->ire_flags & RTF_MULTIRT)) {
8710 				copy_mp = copymsg(first_mp);
8711 				if (copy_mp != NULL)
8712 					MULTIRT_DEBUG_TAG(copy_mp);
8713 			}
8714 
8715 			ire->ire_marks |= ire_marks;
8716 
8717 			/*
8718 			 * Construct message chain for the resolver
8719 			 * of the form:
8720 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8721 			 * Packet could contain a IPSEC_OUT mp.
8722 			 *
8723 			 * NOTE : ire will be added later when the response
8724 			 * comes back from ARP. If the response does not
8725 			 * come back, ARP frees the packet. For this reason,
8726 			 * we can't REFHOLD the bucket of save_ire to prevent
8727 			 * deletions. We may not be able to REFRELE the bucket
8728 			 * if the response never comes back. Thus, before
8729 			 * adding the ire, ire_add_v4 will make sure that the
8730 			 * interface route does not get deleted. This is the
8731 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8732 			 * where we can always prevent deletions because of
8733 			 * the synchronous nature of adding IRES i.e
8734 			 * ire_add_then_send is called after creating the IRE.
8735 			 */
8736 			ASSERT(ire->ire_mp != NULL);
8737 			ire->ire_mp->b_cont = first_mp;
8738 			/* Have saved_mp handy, for cleanup if canput fails */
8739 			saved_mp = mp;
8740 			mp = copyb(res_mp);
8741 			if (mp == NULL) {
8742 				/* Prepare for cleanup */
8743 				mp = saved_mp; /* pkt */
8744 				ire_delete(ire); /* ire_mp */
8745 				ire = NULL;
8746 				ire_refrele(save_ire);
8747 				if (copy_mp != NULL) {
8748 					MULTIRT_DEBUG_UNTAG(copy_mp);
8749 					freemsg(copy_mp);
8750 					copy_mp = NULL;
8751 				}
8752 				break;
8753 			}
8754 			linkb(mp, ire->ire_mp);
8755 
8756 			/*
8757 			 * Fill in the source and dest addrs for the resolver.
8758 			 * NOTE: this depends on memory layouts imposed by
8759 			 * ill_init().
8760 			 */
8761 			areq = (areq_t *)mp->b_rptr;
8762 			addrp = (ipaddr_t *)((char *)areq +
8763 			    areq->areq_sender_addr_offset);
8764 			if (do_attach_ill) {
8765 				/*
8766 				 * This is bind to no failover case.
8767 				 * arp packet also must go out on attach_ill.
8768 				 */
8769 				ASSERT(ipha->ipha_src != NULL);
8770 				*addrp = ipha->ipha_src;
8771 			} else {
8772 				*addrp = save_ire->ire_src_addr;
8773 			}
8774 
8775 			ire_refrele(save_ire);
8776 			addrp = (ipaddr_t *)((char *)areq +
8777 			    areq->areq_target_addr_offset);
8778 			*addrp = dst;
8779 			/* Up to the resolver. */
8780 			if (canputnext(dst_ill->ill_rq) &&
8781 			    !(dst_ill->ill_arp_closing)) {
8782 				putnext(dst_ill->ill_rq, mp);
8783 				ire = NULL;
8784 				if (copy_mp != NULL) {
8785 					/*
8786 					 * If we found a resolver, we ignore
8787 					 * any trailing top priority IRE_CACHE
8788 					 * in the further loops. This ensures
8789 					 * that we do not omit any resolver.
8790 					 * IRE_CACHE entries, if any, will be
8791 					 * processed next time we enter
8792 					 * ip_newroute().
8793 					 */
8794 					multirt_flags &= ~MULTIRT_CACHEGW;
8795 					/*
8796 					 * Search for the next unresolved
8797 					 * multirt route.
8798 					 */
8799 					first_mp = copy_mp;
8800 					copy_mp = NULL;
8801 					/* Prepare the next resolution loop. */
8802 					mp = first_mp;
8803 					EXTRACT_PKT_MP(mp, first_mp,
8804 					    mctl_present);
8805 					if (mctl_present)
8806 						io = (ipsec_out_t *)
8807 						    first_mp->b_rptr;
8808 					ipha = (ipha_t *)mp->b_rptr;
8809 
8810 					ASSERT(sire != NULL);
8811 
8812 					dst = save_dst;
8813 					multirt_resolve_next = B_TRUE;
8814 					continue;
8815 				}
8816 
8817 				if (sire != NULL)
8818 					ire_refrele(sire);
8819 
8820 				/*
8821 				 * The response will come back in ip_wput
8822 				 * with db_type IRE_DB_TYPE.
8823 				 */
8824 				ipif_refrele(src_ipif);
8825 				ill_refrele(dst_ill);
8826 				return;
8827 			} else {
8828 				/* Prepare for cleanup */
8829 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8830 				    mp);
8831 				mp->b_cont = NULL;
8832 				freeb(mp); /* areq */
8833 				/*
8834 				 * this is an ire that is not added to the
8835 				 * cache. ire_freemblk will handle the release
8836 				 * of any resources associated with the ire.
8837 				 */
8838 				ire_delete(ire); /* ire_mp */
8839 				mp = saved_mp; /* pkt */
8840 				ire = NULL;
8841 				if (copy_mp != NULL) {
8842 					MULTIRT_DEBUG_UNTAG(copy_mp);
8843 					freemsg(copy_mp);
8844 					copy_mp = NULL;
8845 				}
8846 				break;
8847 			}
8848 		default:
8849 			break;
8850 		}
8851 	} while (multirt_resolve_next);
8852 
8853 	ip1dbg(("ip_newroute: dropped\n"));
8854 	/* Did this packet originate externally? */
8855 	if (mp->b_prev) {
8856 		mp->b_next = NULL;
8857 		mp->b_prev = NULL;
8858 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8859 	} else {
8860 		if (dst_ill != NULL) {
8861 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8862 		} else {
8863 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8864 		}
8865 	}
8866 	ASSERT(copy_mp == NULL);
8867 	MULTIRT_DEBUG_UNTAG(first_mp);
8868 	freemsg(first_mp);
8869 	if (ire != NULL)
8870 		ire_refrele(ire);
8871 	if (sire != NULL)
8872 		ire_refrele(sire);
8873 	if (src_ipif != NULL)
8874 		ipif_refrele(src_ipif);
8875 	if (dst_ill != NULL)
8876 		ill_refrele(dst_ill);
8877 	return;
8878 
8879 icmp_err_ret:
8880 	ip1dbg(("ip_newroute: no route\n"));
8881 	if (src_ipif != NULL)
8882 		ipif_refrele(src_ipif);
8883 	if (dst_ill != NULL)
8884 		ill_refrele(dst_ill);
8885 	if (sire != NULL)
8886 		ire_refrele(sire);
8887 	/* Did this packet originate externally? */
8888 	if (mp->b_prev) {
8889 		mp->b_next = NULL;
8890 		mp->b_prev = NULL;
8891 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8892 		q = WR(q);
8893 	} else {
8894 		/*
8895 		 * There is no outgoing ill, so just increment the
8896 		 * system MIB.
8897 		 */
8898 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8899 		/*
8900 		 * Since ip_wput() isn't close to finished, we fill
8901 		 * in enough of the header for credible error reporting.
8902 		 */
8903 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8904 			/* Failed */
8905 			MULTIRT_DEBUG_UNTAG(first_mp);
8906 			freemsg(first_mp);
8907 			if (ire != NULL)
8908 				ire_refrele(ire);
8909 			return;
8910 		}
8911 	}
8912 
8913 	/*
8914 	 * At this point we will have ire only if RTF_BLACKHOLE
8915 	 * or RTF_REJECT flags are set on the IRE. It will not
8916 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8917 	 */
8918 	if (ire != NULL) {
8919 		if (ire->ire_flags & RTF_BLACKHOLE) {
8920 			ire_refrele(ire);
8921 			MULTIRT_DEBUG_UNTAG(first_mp);
8922 			freemsg(first_mp);
8923 			return;
8924 		}
8925 		ire_refrele(ire);
8926 	}
8927 	if (ip_source_routed(ipha, ipst)) {
8928 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8929 		    zoneid, ipst);
8930 		return;
8931 	}
8932 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8933 }
8934 
8935 ip_opt_info_t zero_info;
8936 
8937 /*
8938  * IPv4 -
8939  * ip_newroute_ipif is called by ip_wput_multicast and
8940  * ip_rput_forward_multicast whenever we need to send
8941  * out a packet to a destination address for which we do not have specific
8942  * routing information. It is used when the packet will be sent out
8943  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8944  * socket option is set or icmp error message wants to go out on a particular
8945  * interface for a unicast packet.
8946  *
8947  * In most cases, the destination address is resolved thanks to the ipif
8948  * intrinsic resolver. However, there are some cases where the call to
8949  * ip_newroute_ipif must take into account the potential presence of
8950  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8951  * that uses the interface. This is specified through flags,
8952  * which can be a combination of:
8953  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8954  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8955  *   and flags. Additionally, the packet source address has to be set to
8956  *   the specified address. The caller is thus expected to set this flag
8957  *   if the packet has no specific source address yet.
8958  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8959  *   flag, the resulting ire will inherit the flag. All unresolved routes
8960  *   to the destination must be explored in the same call to
8961  *   ip_newroute_ipif().
8962  */
8963 static void
8964 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8965     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8966 {
8967 	areq_t	*areq;
8968 	ire_t	*ire = NULL;
8969 	mblk_t	*res_mp;
8970 	ipaddr_t *addrp;
8971 	mblk_t *first_mp;
8972 	ire_t	*save_ire = NULL;
8973 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8974 	ipif_t	*src_ipif = NULL;
8975 	ushort_t ire_marks = 0;
8976 	ill_t	*dst_ill = NULL;
8977 	boolean_t mctl_present;
8978 	ipsec_out_t *io;
8979 	ipha_t *ipha;
8980 	int	ihandle = 0;
8981 	mblk_t	*saved_mp;
8982 	ire_t   *fire = NULL;
8983 	mblk_t  *copy_mp = NULL;
8984 	boolean_t multirt_resolve_next;
8985 	boolean_t unspec_src;
8986 	ipaddr_t ipha_dst;
8987 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8988 
8989 	/*
8990 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8991 	 * here for uniformity
8992 	 */
8993 	ipif_refhold(ipif);
8994 
8995 	/*
8996 	 * This loop is run only once in most cases.
8997 	 * We loop to resolve further routes only when the destination
8998 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8999 	 */
9000 	do {
9001 		if (dst_ill != NULL) {
9002 			ill_refrele(dst_ill);
9003 			dst_ill = NULL;
9004 		}
9005 		if (src_ipif != NULL) {
9006 			ipif_refrele(src_ipif);
9007 			src_ipif = NULL;
9008 		}
9009 		multirt_resolve_next = B_FALSE;
9010 
9011 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9012 		    ipif->ipif_ill->ill_name));
9013 
9014 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9015 		if (mctl_present)
9016 			io = (ipsec_out_t *)first_mp->b_rptr;
9017 
9018 		ipha = (ipha_t *)mp->b_rptr;
9019 
9020 		/*
9021 		 * Save the packet destination address, we may need it after
9022 		 * the packet has been consumed.
9023 		 */
9024 		ipha_dst = ipha->ipha_dst;
9025 
9026 		/*
9027 		 * If the interface is a pt-pt interface we look for an
9028 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9029 		 * local_address and the pt-pt destination address. Otherwise
9030 		 * we just match the local address.
9031 		 * NOTE: dst could be different than ipha->ipha_dst in case
9032 		 * of sending igmp multicast packets over a point-to-point
9033 		 * connection.
9034 		 * Thus we must be careful enough to check ipha_dst to be a
9035 		 * multicast address, otherwise it will take xmit_if path for
9036 		 * multicast packets resulting into kernel stack overflow by
9037 		 * repeated calls to ip_newroute_ipif from ire_send().
9038 		 */
9039 		if (CLASSD(ipha_dst) &&
9040 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9041 			goto err_ret;
9042 		}
9043 
9044 		/*
9045 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9046 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9047 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9048 		 * propagate its flags to the new ire.
9049 		 */
9050 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9051 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9052 			ip2dbg(("ip_newroute_ipif: "
9053 			    "ipif_lookup_multi_ire("
9054 			    "ipif %p, dst %08x) = fire %p\n",
9055 			    (void *)ipif, ntohl(dst), (void *)fire));
9056 		}
9057 
9058 		if (mctl_present && io->ipsec_out_attach_if) {
9059 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9060 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9061 
9062 			/* Failure case frees things for us. */
9063 			if (attach_ill == NULL) {
9064 				ipif_refrele(ipif);
9065 				if (fire != NULL)
9066 					ire_refrele(fire);
9067 				return;
9068 			}
9069 
9070 			/*
9071 			 * Check if we need an ire that will not be
9072 			 * looked up by anybody else i.e. HIDDEN.
9073 			 */
9074 			if (ill_is_probeonly(attach_ill)) {
9075 				ire_marks = IRE_MARK_HIDDEN;
9076 			}
9077 			/*
9078 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9079 			 * case.
9080 			 */
9081 			dst_ill = ipif->ipif_ill;
9082 			/* attach_ill has been refheld by ip_grab_attach_ill */
9083 			ASSERT(dst_ill == attach_ill);
9084 		} else {
9085 			/*
9086 			 * If the interface belongs to an interface group,
9087 			 * make sure the next possible interface in the group
9088 			 * is used.  This encourages load spreading among
9089 			 * peers in an interface group.
9090 			 * Note: load spreading is disabled for RTF_MULTIRT
9091 			 * routes.
9092 			 */
9093 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9094 			    (fire->ire_flags & RTF_MULTIRT)) {
9095 				/*
9096 				 * Don't perform outbound load spreading
9097 				 * in the case of an RTF_MULTIRT issued route,
9098 				 * we actually typically want to replicate
9099 				 * outgoing packets through particular
9100 				 * interfaces.
9101 				 */
9102 				dst_ill = ipif->ipif_ill;
9103 				ill_refhold(dst_ill);
9104 			} else {
9105 				dst_ill = ip_newroute_get_dst_ill(
9106 				    ipif->ipif_ill);
9107 			}
9108 			if (dst_ill == NULL) {
9109 				if (ip_debug > 2) {
9110 					pr_addr_dbg("ip_newroute_ipif: "
9111 					    "no dst ill for dst %s\n",
9112 					    AF_INET, &dst);
9113 				}
9114 				goto err_ret;
9115 			}
9116 		}
9117 
9118 		/*
9119 		 * Pick a source address preferring non-deprecated ones.
9120 		 * Unlike ip_newroute, we don't do any source address
9121 		 * selection here since for multicast it really does not help
9122 		 * in inbound load spreading as in the unicast case.
9123 		 */
9124 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9125 		    (fire->ire_flags & RTF_SETSRC)) {
9126 			/*
9127 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9128 			 * on that interface. This ire has RTF_SETSRC flag, so
9129 			 * the source address of the packet must be changed.
9130 			 * Check that the ipif matching the requested source
9131 			 * address still exists.
9132 			 */
9133 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9134 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9135 		}
9136 
9137 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9138 
9139 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9140 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9141 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9142 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9143 		    (src_ipif == NULL) &&
9144 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9145 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9146 			if (src_ipif == NULL) {
9147 				if (ip_debug > 2) {
9148 					/* ip1dbg */
9149 					pr_addr_dbg("ip_newroute_ipif: "
9150 					    "no src for dst %s",
9151 					    AF_INET, &dst);
9152 				}
9153 				ip1dbg((" through interface %s\n",
9154 				    dst_ill->ill_name));
9155 				goto err_ret;
9156 			}
9157 			ipif_refrele(ipif);
9158 			ipif = src_ipif;
9159 			ipif_refhold(ipif);
9160 		}
9161 		if (src_ipif == NULL) {
9162 			src_ipif = ipif;
9163 			ipif_refhold(src_ipif);
9164 		}
9165 
9166 		/*
9167 		 * Assign a source address while we have the conn.
9168 		 * We can't have ip_wput_ire pick a source address when the
9169 		 * packet returns from arp since conn_unspec_src might be set
9170 		 * and we lose the conn when going through arp.
9171 		 */
9172 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9173 			ipha->ipha_src = src_ipif->ipif_src_addr;
9174 
9175 		/*
9176 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9177 		 * that the outgoing interface does not have an interface ire.
9178 		 */
9179 		if (CLASSD(ipha_dst) && (connp == NULL ||
9180 		    connp->conn_outgoing_ill == NULL) &&
9181 		    infop->ip_opt_ill_index == 0) {
9182 			/* ipif_to_ire returns an held ire */
9183 			ire = ipif_to_ire(ipif);
9184 			if (ire == NULL)
9185 				goto err_ret;
9186 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9187 				goto err_ret;
9188 			/*
9189 			 * ihandle is needed when the ire is added to
9190 			 * cache table.
9191 			 */
9192 			save_ire = ire;
9193 			ihandle = save_ire->ire_ihandle;
9194 
9195 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9196 			    "flags %04x\n",
9197 			    (void *)ire, (void *)ipif, flags));
9198 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9199 			    (fire->ire_flags & RTF_MULTIRT)) {
9200 				/*
9201 				 * As requested by flags, an IRE_OFFSUBNET was
9202 				 * looked up on that interface. This ire has
9203 				 * RTF_MULTIRT flag, so the resolution loop will
9204 				 * be re-entered to resolve additional routes on
9205 				 * other interfaces. For that purpose, a copy of
9206 				 * the packet is performed at this point.
9207 				 */
9208 				fire->ire_last_used_time = lbolt;
9209 				copy_mp = copymsg(first_mp);
9210 				if (copy_mp) {
9211 					MULTIRT_DEBUG_TAG(copy_mp);
9212 				}
9213 			}
9214 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9215 			    (fire->ire_flags & RTF_SETSRC)) {
9216 				/*
9217 				 * As requested by flags, an IRE_OFFSUBET was
9218 				 * looked up on that interface. This ire has
9219 				 * RTF_SETSRC flag, so the source address of the
9220 				 * packet must be changed.
9221 				 */
9222 				ipha->ipha_src = fire->ire_src_addr;
9223 			}
9224 		} else {
9225 			ASSERT((connp == NULL) ||
9226 			    (connp->conn_outgoing_ill != NULL) ||
9227 			    (connp->conn_dontroute) ||
9228 			    infop->ip_opt_ill_index != 0);
9229 			/*
9230 			 * The only ways we can come here are:
9231 			 * 1) IP_BOUND_IF socket option is set
9232 			 * 2) SO_DONTROUTE socket option is set
9233 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9234 			 * In all cases, the new ire will not be added
9235 			 * into cache table.
9236 			 */
9237 			ire_marks |= IRE_MARK_NOADD;
9238 		}
9239 
9240 		switch (ipif->ipif_net_type) {
9241 		case IRE_IF_NORESOLVER: {
9242 			/* We have what we need to build an IRE_CACHE. */
9243 
9244 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9245 			    (dst_ill->ill_resolver_mp == NULL)) {
9246 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9247 				    "for IRE_IF_NORESOLVER ire %p has "
9248 				    "no ill_resolver_mp\n",
9249 				    (void *)dst_ill, (void *)ire));
9250 				break;
9251 			}
9252 
9253 			/*
9254 			 * The new ire inherits the IRE_OFFSUBNET flags
9255 			 * and source address, if this was requested.
9256 			 */
9257 			ire = ire_create(
9258 			    (uchar_t *)&dst,		/* dest address */
9259 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9260 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9261 			    NULL,			/* gateway address */
9262 			    &ipif->ipif_mtu,
9263 			    NULL,			/* no src nce */
9264 			    dst_ill->ill_rq,		/* recv-from queue */
9265 			    dst_ill->ill_wq,		/* send-to queue */
9266 			    IRE_CACHE,
9267 			    src_ipif,
9268 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9269 			    (fire != NULL) ?		/* Parent handle */
9270 			    fire->ire_phandle : 0,
9271 			    ihandle,			/* Interface handle */
9272 			    (fire != NULL) ?
9273 			    (fire->ire_flags &
9274 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9275 			    (save_ire == NULL ? &ire_uinfo_null :
9276 			    &save_ire->ire_uinfo),
9277 			    NULL,
9278 			    NULL,
9279 			    ipst);
9280 
9281 			if (ire == NULL) {
9282 				if (save_ire != NULL)
9283 					ire_refrele(save_ire);
9284 				break;
9285 			}
9286 
9287 			ire->ire_marks |= ire_marks;
9288 
9289 			/*
9290 			 * If IRE_MARK_NOADD is set then we need to convert
9291 			 * the max_fragp to a useable value now. This is
9292 			 * normally done in ire_add_v[46]. We also need to
9293 			 * associate the ire with an nce (normally would be
9294 			 * done in ip_wput_nondata()).
9295 			 *
9296 			 * Note that IRE_MARK_NOADD packets created here
9297 			 * do not have a non-null ire_mp pointer. The null
9298 			 * value of ire_bucket indicates that they were
9299 			 * never added.
9300 			 */
9301 			if (ire->ire_marks & IRE_MARK_NOADD) {
9302 				uint_t  max_frag;
9303 
9304 				max_frag = *ire->ire_max_fragp;
9305 				ire->ire_max_fragp = NULL;
9306 				ire->ire_max_frag = max_frag;
9307 
9308 				if ((ire->ire_nce = ndp_lookup_v4(
9309 				    ire_to_ill(ire),
9310 				    (ire->ire_gateway_addr != INADDR_ANY ?
9311 				    &ire->ire_gateway_addr : &ire->ire_addr),
9312 				    B_FALSE)) == NULL) {
9313 					if (save_ire != NULL)
9314 						ire_refrele(save_ire);
9315 					break;
9316 				}
9317 				ASSERT(ire->ire_nce->nce_state ==
9318 				    ND_REACHABLE);
9319 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9320 			}
9321 
9322 			/* Prevent save_ire from getting deleted */
9323 			if (save_ire != NULL) {
9324 				IRB_REFHOLD(save_ire->ire_bucket);
9325 				/* Has it been removed already ? */
9326 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9327 					IRB_REFRELE(save_ire->ire_bucket);
9328 					ire_refrele(save_ire);
9329 					break;
9330 				}
9331 			}
9332 
9333 			ire_add_then_send(q, ire, first_mp);
9334 
9335 			/* Assert that save_ire is not deleted yet. */
9336 			if (save_ire != NULL) {
9337 				ASSERT(save_ire->ire_ptpn != NULL);
9338 				IRB_REFRELE(save_ire->ire_bucket);
9339 				ire_refrele(save_ire);
9340 				save_ire = NULL;
9341 			}
9342 			if (fire != NULL) {
9343 				ire_refrele(fire);
9344 				fire = NULL;
9345 			}
9346 
9347 			/*
9348 			 * the resolution loop is re-entered if this
9349 			 * was requested through flags and if we
9350 			 * actually are in a multirouting case.
9351 			 */
9352 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9353 				boolean_t need_resolve =
9354 				    ire_multirt_need_resolve(ipha_dst,
9355 				    MBLK_GETLABEL(copy_mp), ipst);
9356 				if (!need_resolve) {
9357 					MULTIRT_DEBUG_UNTAG(copy_mp);
9358 					freemsg(copy_mp);
9359 					copy_mp = NULL;
9360 				} else {
9361 					/*
9362 					 * ipif_lookup_group() calls
9363 					 * ire_lookup_multi() that uses
9364 					 * ire_ftable_lookup() to find
9365 					 * an IRE_INTERFACE for the group.
9366 					 * In the multirt case,
9367 					 * ire_lookup_multi() then invokes
9368 					 * ire_multirt_lookup() to find
9369 					 * the next resolvable ire.
9370 					 * As a result, we obtain an new
9371 					 * interface, derived from the
9372 					 * next ire.
9373 					 */
9374 					ipif_refrele(ipif);
9375 					ipif = ipif_lookup_group(ipha_dst,
9376 					    zoneid, ipst);
9377 					ip2dbg(("ip_newroute_ipif: "
9378 					    "multirt dst %08x, ipif %p\n",
9379 					    htonl(dst), (void *)ipif));
9380 					if (ipif != NULL) {
9381 						mp = copy_mp;
9382 						copy_mp = NULL;
9383 						multirt_resolve_next = B_TRUE;
9384 						continue;
9385 					} else {
9386 						freemsg(copy_mp);
9387 					}
9388 				}
9389 			}
9390 			if (ipif != NULL)
9391 				ipif_refrele(ipif);
9392 			ill_refrele(dst_ill);
9393 			ipif_refrele(src_ipif);
9394 			return;
9395 		}
9396 		case IRE_IF_RESOLVER:
9397 			/*
9398 			 * We can't build an IRE_CACHE yet, but at least
9399 			 * we found a resolver that can help.
9400 			 */
9401 			res_mp = dst_ill->ill_resolver_mp;
9402 			if (!OK_RESOLVER_MP(res_mp))
9403 				break;
9404 
9405 			/*
9406 			 * We obtain a partial IRE_CACHE which we will pass
9407 			 * along with the resolver query.  When the response
9408 			 * comes back it will be there ready for us to add.
9409 			 * The new ire inherits the IRE_OFFSUBNET flags
9410 			 * and source address, if this was requested.
9411 			 * The ire_max_frag is atomically set under the
9412 			 * irebucket lock in ire_add_v[46]. Only in the
9413 			 * case of IRE_MARK_NOADD, we set it here itself.
9414 			 */
9415 			ire = ire_create_mp(
9416 			    (uchar_t *)&dst,		/* dest address */
9417 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9418 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9419 			    NULL,			/* gateway address */
9420 			    (ire_marks & IRE_MARK_NOADD) ?
9421 			    ipif->ipif_mtu : 0,		/* max_frag */
9422 			    NULL,			/* no src nce */
9423 			    dst_ill->ill_rq,		/* recv-from queue */
9424 			    dst_ill->ill_wq,		/* send-to queue */
9425 			    IRE_CACHE,
9426 			    src_ipif,
9427 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9428 			    (fire != NULL) ?		/* Parent handle */
9429 			    fire->ire_phandle : 0,
9430 			    ihandle,			/* Interface handle */
9431 			    (fire != NULL) ?		/* flags if any */
9432 			    (fire->ire_flags &
9433 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9434 			    (save_ire == NULL ? &ire_uinfo_null :
9435 			    &save_ire->ire_uinfo),
9436 			    NULL,
9437 			    NULL,
9438 			    ipst);
9439 
9440 			if (save_ire != NULL) {
9441 				ire_refrele(save_ire);
9442 				save_ire = NULL;
9443 			}
9444 			if (ire == NULL)
9445 				break;
9446 
9447 			ire->ire_marks |= ire_marks;
9448 			/*
9449 			 * Construct message chain for the resolver of the
9450 			 * form:
9451 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9452 			 *
9453 			 * NOTE : ire will be added later when the response
9454 			 * comes back from ARP. If the response does not
9455 			 * come back, ARP frees the packet. For this reason,
9456 			 * we can't REFHOLD the bucket of save_ire to prevent
9457 			 * deletions. We may not be able to REFRELE the
9458 			 * bucket if the response never comes back.
9459 			 * Thus, before adding the ire, ire_add_v4 will make
9460 			 * sure that the interface route does not get deleted.
9461 			 * This is the only case unlike ip_newroute_v6,
9462 			 * ip_newroute_ipif_v6 where we can always prevent
9463 			 * deletions because ire_add_then_send is called after
9464 			 * creating the IRE.
9465 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9466 			 * does not add this IRE into the IRE CACHE.
9467 			 */
9468 			ASSERT(ire->ire_mp != NULL);
9469 			ire->ire_mp->b_cont = first_mp;
9470 			/* Have saved_mp handy, for cleanup if canput fails */
9471 			saved_mp = mp;
9472 			mp = copyb(res_mp);
9473 			if (mp == NULL) {
9474 				/* Prepare for cleanup */
9475 				mp = saved_mp; /* pkt */
9476 				ire_delete(ire); /* ire_mp */
9477 				ire = NULL;
9478 				if (copy_mp != NULL) {
9479 					MULTIRT_DEBUG_UNTAG(copy_mp);
9480 					freemsg(copy_mp);
9481 					copy_mp = NULL;
9482 				}
9483 				break;
9484 			}
9485 			linkb(mp, ire->ire_mp);
9486 
9487 			/*
9488 			 * Fill in the source and dest addrs for the resolver.
9489 			 * NOTE: this depends on memory layouts imposed by
9490 			 * ill_init().
9491 			 */
9492 			areq = (areq_t *)mp->b_rptr;
9493 			addrp = (ipaddr_t *)((char *)areq +
9494 			    areq->areq_sender_addr_offset);
9495 			*addrp = ire->ire_src_addr;
9496 			addrp = (ipaddr_t *)((char *)areq +
9497 			    areq->areq_target_addr_offset);
9498 			*addrp = dst;
9499 			/* Up to the resolver. */
9500 			if (canputnext(dst_ill->ill_rq) &&
9501 			    !(dst_ill->ill_arp_closing)) {
9502 				putnext(dst_ill->ill_rq, mp);
9503 				/*
9504 				 * The response will come back in ip_wput
9505 				 * with db_type IRE_DB_TYPE.
9506 				 */
9507 			} else {
9508 				mp->b_cont = NULL;
9509 				freeb(mp); /* areq */
9510 				ire_delete(ire); /* ire_mp */
9511 				saved_mp->b_next = NULL;
9512 				saved_mp->b_prev = NULL;
9513 				freemsg(first_mp); /* pkt */
9514 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9515 			}
9516 
9517 			if (fire != NULL) {
9518 				ire_refrele(fire);
9519 				fire = NULL;
9520 			}
9521 
9522 
9523 			/*
9524 			 * The resolution loop is re-entered if this was
9525 			 * requested through flags and we actually are
9526 			 * in a multirouting case.
9527 			 */
9528 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9529 				boolean_t need_resolve =
9530 				    ire_multirt_need_resolve(ipha_dst,
9531 				    MBLK_GETLABEL(copy_mp), ipst);
9532 				if (!need_resolve) {
9533 					MULTIRT_DEBUG_UNTAG(copy_mp);
9534 					freemsg(copy_mp);
9535 					copy_mp = NULL;
9536 				} else {
9537 					/*
9538 					 * ipif_lookup_group() calls
9539 					 * ire_lookup_multi() that uses
9540 					 * ire_ftable_lookup() to find
9541 					 * an IRE_INTERFACE for the group.
9542 					 * In the multirt case,
9543 					 * ire_lookup_multi() then invokes
9544 					 * ire_multirt_lookup() to find
9545 					 * the next resolvable ire.
9546 					 * As a result, we obtain an new
9547 					 * interface, derived from the
9548 					 * next ire.
9549 					 */
9550 					ipif_refrele(ipif);
9551 					ipif = ipif_lookup_group(ipha_dst,
9552 					    zoneid, ipst);
9553 					if (ipif != NULL) {
9554 						mp = copy_mp;
9555 						copy_mp = NULL;
9556 						multirt_resolve_next = B_TRUE;
9557 						continue;
9558 					} else {
9559 						freemsg(copy_mp);
9560 					}
9561 				}
9562 			}
9563 			if (ipif != NULL)
9564 				ipif_refrele(ipif);
9565 			ill_refrele(dst_ill);
9566 			ipif_refrele(src_ipif);
9567 			return;
9568 		default:
9569 			break;
9570 		}
9571 	} while (multirt_resolve_next);
9572 
9573 err_ret:
9574 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9575 	if (fire != NULL)
9576 		ire_refrele(fire);
9577 	ipif_refrele(ipif);
9578 	/* Did this packet originate externally? */
9579 	if (dst_ill != NULL)
9580 		ill_refrele(dst_ill);
9581 	if (src_ipif != NULL)
9582 		ipif_refrele(src_ipif);
9583 	if (mp->b_prev || mp->b_next) {
9584 		mp->b_next = NULL;
9585 		mp->b_prev = NULL;
9586 	} else {
9587 		/*
9588 		 * Since ip_wput() isn't close to finished, we fill
9589 		 * in enough of the header for credible error reporting.
9590 		 */
9591 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9592 			/* Failed */
9593 			freemsg(first_mp);
9594 			if (ire != NULL)
9595 				ire_refrele(ire);
9596 			return;
9597 		}
9598 	}
9599 	/*
9600 	 * At this point we will have ire only if RTF_BLACKHOLE
9601 	 * or RTF_REJECT flags are set on the IRE. It will not
9602 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9603 	 */
9604 	if (ire != NULL) {
9605 		if (ire->ire_flags & RTF_BLACKHOLE) {
9606 			ire_refrele(ire);
9607 			freemsg(first_mp);
9608 			return;
9609 		}
9610 		ire_refrele(ire);
9611 	}
9612 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9613 }
9614 
9615 /* Name/Value Table Lookup Routine */
9616 char *
9617 ip_nv_lookup(nv_t *nv, int value)
9618 {
9619 	if (!nv)
9620 		return (NULL);
9621 	for (; nv->nv_name; nv++) {
9622 		if (nv->nv_value == value)
9623 			return (nv->nv_name);
9624 	}
9625 	return ("unknown");
9626 }
9627 
9628 /*
9629  * This is a module open, i.e. this is a control stream for access
9630  * to a DLPI device.  We allocate an ill_t as the instance data in
9631  * this case.
9632  */
9633 int
9634 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9635 {
9636 	ill_t	*ill;
9637 	int	err;
9638 	zoneid_t zoneid;
9639 	netstack_t *ns;
9640 	ip_stack_t *ipst;
9641 
9642 	/*
9643 	 * Prevent unprivileged processes from pushing IP so that
9644 	 * they can't send raw IP.
9645 	 */
9646 	if (secpolicy_net_rawaccess(credp) != 0)
9647 		return (EPERM);
9648 
9649 	ns = netstack_find_by_cred(credp);
9650 	ASSERT(ns != NULL);
9651 	ipst = ns->netstack_ip;
9652 	ASSERT(ipst != NULL);
9653 
9654 	/*
9655 	 * For exclusive stacks we set the zoneid to zero
9656 	 * to make IP operate as if in the global zone.
9657 	 */
9658 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9659 		zoneid = GLOBAL_ZONEID;
9660 	else
9661 		zoneid = crgetzoneid(credp);
9662 
9663 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9664 	q->q_ptr = WR(q)->q_ptr = ill;
9665 	ill->ill_ipst = ipst;
9666 	ill->ill_zoneid = zoneid;
9667 
9668 	/*
9669 	 * ill_init initializes the ill fields and then sends down
9670 	 * down a DL_INFO_REQ after calling qprocson.
9671 	 */
9672 	err = ill_init(q, ill);
9673 	if (err != 0) {
9674 		mi_free(ill);
9675 		netstack_rele(ipst->ips_netstack);
9676 		q->q_ptr = NULL;
9677 		WR(q)->q_ptr = NULL;
9678 		return (err);
9679 	}
9680 
9681 	/* ill_init initializes the ipsq marking this thread as writer */
9682 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9683 	/* Wait for the DL_INFO_ACK */
9684 	mutex_enter(&ill->ill_lock);
9685 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9686 		/*
9687 		 * Return value of 0 indicates a pending signal.
9688 		 */
9689 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9690 		if (err == 0) {
9691 			mutex_exit(&ill->ill_lock);
9692 			(void) ip_close(q, 0);
9693 			return (EINTR);
9694 		}
9695 	}
9696 	mutex_exit(&ill->ill_lock);
9697 
9698 	/*
9699 	 * ip_rput_other could have set an error  in ill_error on
9700 	 * receipt of M_ERROR.
9701 	 */
9702 
9703 	err = ill->ill_error;
9704 	if (err != 0) {
9705 		(void) ip_close(q, 0);
9706 		return (err);
9707 	}
9708 
9709 	ill->ill_credp = credp;
9710 	crhold(credp);
9711 
9712 	mutex_enter(&ipst->ips_ip_mi_lock);
9713 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9714 	    credp);
9715 	mutex_exit(&ipst->ips_ip_mi_lock);
9716 	if (err) {
9717 		(void) ip_close(q, 0);
9718 		return (err);
9719 	}
9720 	return (0);
9721 }
9722 
9723 /* For /dev/ip aka AF_INET open */
9724 int
9725 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9726 {
9727 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9728 }
9729 
9730 /* For /dev/ip6 aka AF_INET6 open */
9731 int
9732 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9733 {
9734 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9735 }
9736 
9737 /* IP open routine. */
9738 int
9739 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9740     boolean_t isv6)
9741 {
9742 	conn_t 		*connp;
9743 	major_t		maj;
9744 	zoneid_t	zoneid;
9745 	netstack_t	*ns;
9746 	ip_stack_t	*ipst;
9747 
9748 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9749 
9750 	/* Allow reopen. */
9751 	if (q->q_ptr != NULL)
9752 		return (0);
9753 
9754 	if (sflag & MODOPEN) {
9755 		/* This is a module open */
9756 		return (ip_modopen(q, devp, flag, sflag, credp));
9757 	}
9758 
9759 	ns = netstack_find_by_cred(credp);
9760 	ASSERT(ns != NULL);
9761 	ipst = ns->netstack_ip;
9762 	ASSERT(ipst != NULL);
9763 
9764 	/*
9765 	 * For exclusive stacks we set the zoneid to zero
9766 	 * to make IP operate as if in the global zone.
9767 	 */
9768 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9769 		zoneid = GLOBAL_ZONEID;
9770 	else
9771 		zoneid = crgetzoneid(credp);
9772 
9773 	/*
9774 	 * We are opening as a device. This is an IP client stream, and we
9775 	 * allocate an conn_t as the instance data.
9776 	 */
9777 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9778 
9779 	/*
9780 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9781 	 * done by netstack_find_by_cred()
9782 	 */
9783 	netstack_rele(ipst->ips_netstack);
9784 
9785 	connp->conn_zoneid = zoneid;
9786 
9787 	connp->conn_upq = q;
9788 	q->q_ptr = WR(q)->q_ptr = connp;
9789 
9790 	if (flag & SO_SOCKSTR)
9791 		connp->conn_flags |= IPCL_SOCKET;
9792 
9793 	/* Minor tells us which /dev entry was opened */
9794 	if (isv6) {
9795 		connp->conn_flags |= IPCL_ISV6;
9796 		connp->conn_af_isv6 = B_TRUE;
9797 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9798 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9799 	} else {
9800 		connp->conn_af_isv6 = B_FALSE;
9801 		connp->conn_pkt_isv6 = B_FALSE;
9802 	}
9803 
9804 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9805 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9806 		connp->conn_minor_arena = ip_minor_arena_la;
9807 	} else {
9808 		/*
9809 		 * Either minor numbers in the large arena were exhausted
9810 		 * or a non socket application is doing the open.
9811 		 * Try to allocate from the small arena.
9812 		 */
9813 		if ((connp->conn_dev =
9814 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9815 			/* CONN_DEC_REF takes care of netstack_rele() */
9816 			q->q_ptr = WR(q)->q_ptr = NULL;
9817 			CONN_DEC_REF(connp);
9818 			return (EBUSY);
9819 		}
9820 		connp->conn_minor_arena = ip_minor_arena_sa;
9821 	}
9822 
9823 	maj = getemajor(*devp);
9824 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9825 
9826 	/*
9827 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9828 	 */
9829 	connp->conn_cred = credp;
9830 
9831 	/*
9832 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9833 	 */
9834 	connp->conn_recv = ip_conn_input;
9835 
9836 	crhold(connp->conn_cred);
9837 
9838 	/*
9839 	 * If the caller has the process-wide flag set, then default to MAC
9840 	 * exempt mode.  This allows read-down to unlabeled hosts.
9841 	 */
9842 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9843 		connp->conn_mac_exempt = B_TRUE;
9844 
9845 	connp->conn_rq = q;
9846 	connp->conn_wq = WR(q);
9847 
9848 	/* Non-zero default values */
9849 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9850 
9851 	/*
9852 	 * Make the conn globally visible to walkers
9853 	 */
9854 	ASSERT(connp->conn_ref == 1);
9855 	mutex_enter(&connp->conn_lock);
9856 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9857 	mutex_exit(&connp->conn_lock);
9858 
9859 	qprocson(q);
9860 
9861 	return (0);
9862 }
9863 
9864 /*
9865  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9866  * Note that there is no race since either ip_output function works - it
9867  * is just an optimization to enter the best ip_output routine directly.
9868  */
9869 void
9870 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9871     ip_stack_t *ipst)
9872 {
9873 	if (isv6)  {
9874 		if (bump_mib) {
9875 			BUMP_MIB(&ipst->ips_ip6_mib,
9876 			    ipIfStatsOutSwitchIPVersion);
9877 		}
9878 		connp->conn_send = ip_output_v6;
9879 		connp->conn_pkt_isv6 = B_TRUE;
9880 	} else {
9881 		if (bump_mib) {
9882 			BUMP_MIB(&ipst->ips_ip_mib,
9883 			    ipIfStatsOutSwitchIPVersion);
9884 		}
9885 		connp->conn_send = ip_output;
9886 		connp->conn_pkt_isv6 = B_FALSE;
9887 	}
9888 
9889 }
9890 
9891 /*
9892  * See if IPsec needs loading because of the options in mp.
9893  */
9894 static boolean_t
9895 ipsec_opt_present(mblk_t *mp)
9896 {
9897 	uint8_t *optcp, *next_optcp, *opt_endcp;
9898 	struct opthdr *opt;
9899 	struct T_opthdr *topt;
9900 	int opthdr_len;
9901 	t_uscalar_t optname, optlevel;
9902 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9903 	ipsec_req_t *ipsr;
9904 
9905 	/*
9906 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9907 	 * return TRUE.
9908 	 */
9909 
9910 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9911 	opt_endcp = optcp + tor->OPT_length;
9912 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9913 		opthdr_len = sizeof (struct T_opthdr);
9914 	} else {		/* O_OPTMGMT_REQ */
9915 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9916 		opthdr_len = sizeof (struct opthdr);
9917 	}
9918 	for (; optcp < opt_endcp; optcp = next_optcp) {
9919 		if (optcp + opthdr_len > opt_endcp)
9920 			return (B_FALSE);	/* Not enough option header. */
9921 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9922 			topt = (struct T_opthdr *)optcp;
9923 			optlevel = topt->level;
9924 			optname = topt->name;
9925 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9926 		} else {
9927 			opt = (struct opthdr *)optcp;
9928 			optlevel = opt->level;
9929 			optname = opt->name;
9930 			next_optcp = optcp + opthdr_len +
9931 			    _TPI_ALIGN_OPT(opt->len);
9932 		}
9933 		if ((next_optcp < optcp) || /* wraparound pointer space */
9934 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9935 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9936 			return (B_FALSE); /* bad option buffer */
9937 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9938 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9939 			/*
9940 			 * Check to see if it's an all-bypass or all-zeroes
9941 			 * IPsec request.  Don't bother loading IPsec if
9942 			 * the socket doesn't want to use it.  (A good example
9943 			 * is a bypass request.)
9944 			 *
9945 			 * Basically, if any of the non-NEVER bits are set,
9946 			 * load IPsec.
9947 			 */
9948 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9949 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9950 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9951 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9952 			    != 0)
9953 				return (B_TRUE);
9954 		}
9955 	}
9956 	return (B_FALSE);
9957 }
9958 
9959 /*
9960  * If conn is is waiting for ipsec to finish loading, kick it.
9961  */
9962 /* ARGSUSED */
9963 static void
9964 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9965 {
9966 	t_scalar_t	optreq_prim;
9967 	mblk_t		*mp;
9968 	cred_t		*cr;
9969 	int		err = 0;
9970 
9971 	/*
9972 	 * This function is called, after ipsec loading is complete.
9973 	 * Since IP checks exclusively and atomically (i.e it prevents
9974 	 * ipsec load from completing until ip_optcom_req completes)
9975 	 * whether ipsec load is complete, there cannot be a race with IP
9976 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9977 	 */
9978 	mutex_enter(&connp->conn_lock);
9979 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9980 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9981 		mp = connp->conn_ipsec_opt_mp;
9982 		connp->conn_ipsec_opt_mp = NULL;
9983 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9984 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9985 		mutex_exit(&connp->conn_lock);
9986 
9987 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9988 
9989 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9990 		if (optreq_prim == T_OPTMGMT_REQ) {
9991 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9992 			    &ip_opt_obj, B_FALSE);
9993 		} else {
9994 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9995 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9996 			    &ip_opt_obj, B_FALSE);
9997 		}
9998 		if (err != EINPROGRESS)
9999 			CONN_OPER_PENDING_DONE(connp);
10000 		return;
10001 	}
10002 	mutex_exit(&connp->conn_lock);
10003 }
10004 
10005 /*
10006  * Called from the ipsec_loader thread, outside any perimeter, to tell
10007  * ip qenable any of the queues waiting for the ipsec loader to
10008  * complete.
10009  */
10010 void
10011 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10012 {
10013 	netstack_t *ns = ipss->ipsec_netstack;
10014 
10015 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10016 }
10017 
10018 /*
10019  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10020  * determines the grp on which it has to become exclusive, queues the mp
10021  * and sq draining restarts the optmgmt
10022  */
10023 static boolean_t
10024 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10025 {
10026 	conn_t *connp = Q_TO_CONN(q);
10027 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10028 
10029 	/*
10030 	 * Take IPsec requests and treat them special.
10031 	 */
10032 	if (ipsec_opt_present(mp)) {
10033 		/* First check if IPsec is loaded. */
10034 		mutex_enter(&ipss->ipsec_loader_lock);
10035 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10036 			mutex_exit(&ipss->ipsec_loader_lock);
10037 			return (B_FALSE);
10038 		}
10039 		mutex_enter(&connp->conn_lock);
10040 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10041 
10042 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10043 		connp->conn_ipsec_opt_mp = mp;
10044 		mutex_exit(&connp->conn_lock);
10045 		mutex_exit(&ipss->ipsec_loader_lock);
10046 
10047 		ipsec_loader_loadnow(ipss);
10048 		return (B_TRUE);
10049 	}
10050 	return (B_FALSE);
10051 }
10052 
10053 /*
10054  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10055  * all of them are copied to the conn_t. If the req is "zero", the policy is
10056  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10057  * fields.
10058  * We keep only the latest setting of the policy and thus policy setting
10059  * is not incremental/cumulative.
10060  *
10061  * Requests to set policies with multiple alternative actions will
10062  * go through a different API.
10063  */
10064 int
10065 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10066 {
10067 	uint_t ah_req = 0;
10068 	uint_t esp_req = 0;
10069 	uint_t se_req = 0;
10070 	ipsec_selkey_t sel;
10071 	ipsec_act_t *actp = NULL;
10072 	uint_t nact;
10073 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10074 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10075 	ipsec_policy_root_t *pr;
10076 	ipsec_policy_head_t *ph;
10077 	int fam;
10078 	boolean_t is_pol_reset;
10079 	int error = 0;
10080 	netstack_t	*ns = connp->conn_netstack;
10081 	ip_stack_t	*ipst = ns->netstack_ip;
10082 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10083 
10084 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10085 
10086 	/*
10087 	 * The IP_SEC_OPT option does not allow variable length parameters,
10088 	 * hence a request cannot be NULL.
10089 	 */
10090 	if (req == NULL)
10091 		return (EINVAL);
10092 
10093 	ah_req = req->ipsr_ah_req;
10094 	esp_req = req->ipsr_esp_req;
10095 	se_req = req->ipsr_self_encap_req;
10096 
10097 	/*
10098 	 * Are we dealing with a request to reset the policy (i.e.
10099 	 * zero requests).
10100 	 */
10101 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10102 	    (esp_req & REQ_MASK) == 0 &&
10103 	    (se_req & REQ_MASK) == 0);
10104 
10105 	if (!is_pol_reset) {
10106 		/*
10107 		 * If we couldn't load IPsec, fail with "protocol
10108 		 * not supported".
10109 		 * IPsec may not have been loaded for a request with zero
10110 		 * policies, so we don't fail in this case.
10111 		 */
10112 		mutex_enter(&ipss->ipsec_loader_lock);
10113 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10114 			mutex_exit(&ipss->ipsec_loader_lock);
10115 			return (EPROTONOSUPPORT);
10116 		}
10117 		mutex_exit(&ipss->ipsec_loader_lock);
10118 
10119 		/*
10120 		 * Test for valid requests. Invalid algorithms
10121 		 * need to be tested by IPsec code because new
10122 		 * algorithms can be added dynamically.
10123 		 */
10124 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10125 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10126 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10127 			return (EINVAL);
10128 		}
10129 
10130 		/*
10131 		 * Only privileged users can issue these
10132 		 * requests.
10133 		 */
10134 		if (((ah_req & IPSEC_PREF_NEVER) ||
10135 		    (esp_req & IPSEC_PREF_NEVER) ||
10136 		    (se_req & IPSEC_PREF_NEVER)) &&
10137 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10138 			return (EPERM);
10139 		}
10140 
10141 		/*
10142 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10143 		 * are mutually exclusive.
10144 		 */
10145 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10146 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10147 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10148 			/* Both of them are set */
10149 			return (EINVAL);
10150 		}
10151 	}
10152 
10153 	mutex_enter(&connp->conn_lock);
10154 
10155 	/*
10156 	 * If we have already cached policies in ip_bind_connected*(), don't
10157 	 * let them change now. We cache policies for connections
10158 	 * whose src,dst [addr, port] is known.
10159 	 */
10160 	if (connp->conn_policy_cached) {
10161 		mutex_exit(&connp->conn_lock);
10162 		return (EINVAL);
10163 	}
10164 
10165 	/*
10166 	 * We have a zero policies, reset the connection policy if already
10167 	 * set. This will cause the connection to inherit the
10168 	 * global policy, if any.
10169 	 */
10170 	if (is_pol_reset) {
10171 		if (connp->conn_policy != NULL) {
10172 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10173 			connp->conn_policy = NULL;
10174 		}
10175 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10176 		connp->conn_in_enforce_policy = B_FALSE;
10177 		connp->conn_out_enforce_policy = B_FALSE;
10178 		mutex_exit(&connp->conn_lock);
10179 		return (0);
10180 	}
10181 
10182 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10183 	    ipst->ips_netstack);
10184 	if (ph == NULL)
10185 		goto enomem;
10186 
10187 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10188 	if (actp == NULL)
10189 		goto enomem;
10190 
10191 	/*
10192 	 * Always allocate IPv4 policy entries, since they can also
10193 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10194 	 */
10195 	bzero(&sel, sizeof (sel));
10196 	sel.ipsl_valid = IPSL_IPV4;
10197 
10198 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10199 	    ipst->ips_netstack);
10200 	if (pin4 == NULL)
10201 		goto enomem;
10202 
10203 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10204 	    ipst->ips_netstack);
10205 	if (pout4 == NULL)
10206 		goto enomem;
10207 
10208 	if (connp->conn_af_isv6) {
10209 		/*
10210 		 * We're looking at a v6 socket, also allocate the
10211 		 * v6-specific entries...
10212 		 */
10213 		sel.ipsl_valid = IPSL_IPV6;
10214 		pin6 = ipsec_policy_create(&sel, actp, nact,
10215 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10216 		if (pin6 == NULL)
10217 			goto enomem;
10218 
10219 		pout6 = ipsec_policy_create(&sel, actp, nact,
10220 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10221 		if (pout6 == NULL)
10222 			goto enomem;
10223 
10224 		/*
10225 		 * .. and file them away in the right place.
10226 		 */
10227 		fam = IPSEC_AF_V6;
10228 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10229 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10230 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10231 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10232 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10233 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10234 	}
10235 
10236 	ipsec_actvec_free(actp, nact);
10237 
10238 	/*
10239 	 * File the v4 policies.
10240 	 */
10241 	fam = IPSEC_AF_V4;
10242 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10243 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10244 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10245 
10246 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10247 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10248 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10249 
10250 	/*
10251 	 * If the requests need security, set enforce_policy.
10252 	 * If the requests are IPSEC_PREF_NEVER, one should
10253 	 * still set conn_out_enforce_policy so that an ipsec_out
10254 	 * gets attached in ip_wput. This is needed so that
10255 	 * for connections that we don't cache policy in ip_bind,
10256 	 * if global policy matches in ip_wput_attach_policy, we
10257 	 * don't wrongly inherit global policy. Similarly, we need
10258 	 * to set conn_in_enforce_policy also so that we don't verify
10259 	 * policy wrongly.
10260 	 */
10261 	if ((ah_req & REQ_MASK) != 0 ||
10262 	    (esp_req & REQ_MASK) != 0 ||
10263 	    (se_req & REQ_MASK) != 0) {
10264 		connp->conn_in_enforce_policy = B_TRUE;
10265 		connp->conn_out_enforce_policy = B_TRUE;
10266 		connp->conn_flags |= IPCL_CHECK_POLICY;
10267 	}
10268 
10269 	mutex_exit(&connp->conn_lock);
10270 	return (error);
10271 #undef REQ_MASK
10272 
10273 	/*
10274 	 * Common memory-allocation-failure exit path.
10275 	 */
10276 enomem:
10277 	mutex_exit(&connp->conn_lock);
10278 	if (actp != NULL)
10279 		ipsec_actvec_free(actp, nact);
10280 	if (pin4 != NULL)
10281 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10282 	if (pout4 != NULL)
10283 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10284 	if (pin6 != NULL)
10285 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10286 	if (pout6 != NULL)
10287 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10288 	return (ENOMEM);
10289 }
10290 
10291 /*
10292  * Only for options that pass in an IP addr. Currently only V4 options
10293  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10294  * So this function assumes level is IPPROTO_IP
10295  */
10296 int
10297 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10298     mblk_t *first_mp)
10299 {
10300 	ipif_t *ipif = NULL;
10301 	int error;
10302 	ill_t *ill;
10303 	int zoneid;
10304 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10305 
10306 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10307 
10308 	if (addr != INADDR_ANY || checkonly) {
10309 		ASSERT(connp != NULL);
10310 		zoneid = IPCL_ZONEID(connp);
10311 		if (option == IP_NEXTHOP) {
10312 			ipif = ipif_lookup_onlink_addr(addr,
10313 			    connp->conn_zoneid, ipst);
10314 		} else {
10315 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10316 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10317 			    &error, ipst);
10318 		}
10319 		if (ipif == NULL) {
10320 			if (error == EINPROGRESS)
10321 				return (error);
10322 			else if ((option == IP_MULTICAST_IF) ||
10323 			    (option == IP_NEXTHOP))
10324 				return (EHOSTUNREACH);
10325 			else
10326 				return (EINVAL);
10327 		} else if (checkonly) {
10328 			if (option == IP_MULTICAST_IF) {
10329 				ill = ipif->ipif_ill;
10330 				/* not supported by the virtual network iface */
10331 				if (IS_VNI(ill)) {
10332 					ipif_refrele(ipif);
10333 					return (EINVAL);
10334 				}
10335 			}
10336 			ipif_refrele(ipif);
10337 			return (0);
10338 		}
10339 		ill = ipif->ipif_ill;
10340 		mutex_enter(&connp->conn_lock);
10341 		mutex_enter(&ill->ill_lock);
10342 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10343 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10344 			mutex_exit(&ill->ill_lock);
10345 			mutex_exit(&connp->conn_lock);
10346 			ipif_refrele(ipif);
10347 			return (option == IP_MULTICAST_IF ?
10348 			    EHOSTUNREACH : EINVAL);
10349 		}
10350 	} else {
10351 		mutex_enter(&connp->conn_lock);
10352 	}
10353 
10354 	/* None of the options below are supported on the VNI */
10355 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10356 		mutex_exit(&ill->ill_lock);
10357 		mutex_exit(&connp->conn_lock);
10358 		ipif_refrele(ipif);
10359 		return (EINVAL);
10360 	}
10361 
10362 	switch (option) {
10363 	case IP_DONTFAILOVER_IF:
10364 		/*
10365 		 * This option is used by in.mpathd to ensure
10366 		 * that IPMP probe packets only go out on the
10367 		 * test interfaces. in.mpathd sets this option
10368 		 * on the non-failover interfaces.
10369 		 * For backward compatibility, this option
10370 		 * implicitly sets IP_MULTICAST_IF, as used
10371 		 * be done in bind(), so that ip_wput gets
10372 		 * this ipif to send mcast packets.
10373 		 */
10374 		if (ipif != NULL) {
10375 			ASSERT(addr != INADDR_ANY);
10376 			connp->conn_nofailover_ill = ipif->ipif_ill;
10377 			connp->conn_multicast_ipif = ipif;
10378 		} else {
10379 			ASSERT(addr == INADDR_ANY);
10380 			connp->conn_nofailover_ill = NULL;
10381 			connp->conn_multicast_ipif = NULL;
10382 		}
10383 		break;
10384 
10385 	case IP_MULTICAST_IF:
10386 		connp->conn_multicast_ipif = ipif;
10387 		break;
10388 	case IP_NEXTHOP:
10389 		connp->conn_nexthop_v4 = addr;
10390 		connp->conn_nexthop_set = B_TRUE;
10391 		break;
10392 	}
10393 
10394 	if (ipif != NULL) {
10395 		mutex_exit(&ill->ill_lock);
10396 		mutex_exit(&connp->conn_lock);
10397 		ipif_refrele(ipif);
10398 		return (0);
10399 	}
10400 	mutex_exit(&connp->conn_lock);
10401 	/* We succeded in cleared the option */
10402 	return (0);
10403 }
10404 
10405 /*
10406  * For options that pass in an ifindex specifying the ill. V6 options always
10407  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10408  */
10409 int
10410 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10411     int level, int option, mblk_t *first_mp)
10412 {
10413 	ill_t *ill = NULL;
10414 	int error = 0;
10415 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10416 
10417 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10418 	if (ifindex != 0) {
10419 		ASSERT(connp != NULL);
10420 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10421 		    first_mp, ip_restart_optmgmt, &error, ipst);
10422 		if (ill != NULL) {
10423 			if (checkonly) {
10424 				/* not supported by the virtual network iface */
10425 				if (IS_VNI(ill)) {
10426 					ill_refrele(ill);
10427 					return (EINVAL);
10428 				}
10429 				ill_refrele(ill);
10430 				return (0);
10431 			}
10432 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10433 			    0, NULL)) {
10434 				ill_refrele(ill);
10435 				ill = NULL;
10436 				mutex_enter(&connp->conn_lock);
10437 				goto setit;
10438 			}
10439 			mutex_enter(&connp->conn_lock);
10440 			mutex_enter(&ill->ill_lock);
10441 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10442 				mutex_exit(&ill->ill_lock);
10443 				mutex_exit(&connp->conn_lock);
10444 				ill_refrele(ill);
10445 				ill = NULL;
10446 				mutex_enter(&connp->conn_lock);
10447 			}
10448 			goto setit;
10449 		} else if (error == EINPROGRESS) {
10450 			return (error);
10451 		} else {
10452 			error = 0;
10453 		}
10454 	}
10455 	mutex_enter(&connp->conn_lock);
10456 setit:
10457 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10458 
10459 	/*
10460 	 * The options below assume that the ILL (if any) transmits and/or
10461 	 * receives traffic. Neither of which is true for the virtual network
10462 	 * interface, so fail setting these on a VNI.
10463 	 */
10464 	if (IS_VNI(ill)) {
10465 		ASSERT(ill != NULL);
10466 		mutex_exit(&ill->ill_lock);
10467 		mutex_exit(&connp->conn_lock);
10468 		ill_refrele(ill);
10469 		return (EINVAL);
10470 	}
10471 
10472 	if (level == IPPROTO_IP) {
10473 		switch (option) {
10474 		case IP_BOUND_IF:
10475 			connp->conn_incoming_ill = ill;
10476 			connp->conn_outgoing_ill = ill;
10477 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10478 			    0 : ifindex;
10479 			break;
10480 
10481 		case IP_MULTICAST_IF:
10482 			/*
10483 			 * This option is an internal special. The socket
10484 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10485 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10486 			 * specifies an ifindex and we try first on V6 ill's.
10487 			 * If we don't find one, we they try using on v4 ill's
10488 			 * intenally and we come here.
10489 			 */
10490 			if (!checkonly && ill != NULL) {
10491 				ipif_t	*ipif;
10492 				ipif = ill->ill_ipif;
10493 
10494 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10495 					mutex_exit(&ill->ill_lock);
10496 					mutex_exit(&connp->conn_lock);
10497 					ill_refrele(ill);
10498 					ill = NULL;
10499 					mutex_enter(&connp->conn_lock);
10500 				} else {
10501 					connp->conn_multicast_ipif = ipif;
10502 				}
10503 			}
10504 			break;
10505 
10506 		case IP_DHCPINIT_IF:
10507 			if (connp->conn_dhcpinit_ill != NULL) {
10508 				/*
10509 				 * We've locked the conn so conn_cleanup_ill()
10510 				 * cannot clear conn_dhcpinit_ill -- so it's
10511 				 * safe to access the ill.
10512 				 */
10513 				ill_t *oill = connp->conn_dhcpinit_ill;
10514 
10515 				ASSERT(oill->ill_dhcpinit != 0);
10516 				atomic_dec_32(&oill->ill_dhcpinit);
10517 				connp->conn_dhcpinit_ill = NULL;
10518 			}
10519 
10520 			if (ill != NULL) {
10521 				connp->conn_dhcpinit_ill = ill;
10522 				atomic_inc_32(&ill->ill_dhcpinit);
10523 			}
10524 			break;
10525 		}
10526 	} else {
10527 		switch (option) {
10528 		case IPV6_BOUND_IF:
10529 			connp->conn_incoming_ill = ill;
10530 			connp->conn_outgoing_ill = ill;
10531 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10532 			    0 : ifindex;
10533 			break;
10534 
10535 		case IPV6_BOUND_PIF:
10536 			/*
10537 			 * Limit all transmit to this ill.
10538 			 * Unlike IPV6_BOUND_IF, using this option
10539 			 * prevents load spreading and failover from
10540 			 * happening when the interface is part of the
10541 			 * group. That's why we don't need to remember
10542 			 * the ifindex in orig_bound_ifindex as in
10543 			 * IPV6_BOUND_IF.
10544 			 */
10545 			connp->conn_outgoing_pill = ill;
10546 			break;
10547 
10548 		case IPV6_DONTFAILOVER_IF:
10549 			/*
10550 			 * This option is used by in.mpathd to ensure
10551 			 * that IPMP probe packets only go out on the
10552 			 * test interfaces. in.mpathd sets this option
10553 			 * on the non-failover interfaces.
10554 			 */
10555 			connp->conn_nofailover_ill = ill;
10556 			/*
10557 			 * For backward compatibility, this option
10558 			 * implicitly sets ip_multicast_ill as used in
10559 			 * IPV6_MULTICAST_IF so that ip_wput gets
10560 			 * this ill to send mcast packets.
10561 			 */
10562 			connp->conn_multicast_ill = ill;
10563 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10564 			    0 : ifindex;
10565 			break;
10566 
10567 		case IPV6_MULTICAST_IF:
10568 			/*
10569 			 * Set conn_multicast_ill to be the IPv6 ill.
10570 			 * Set conn_multicast_ipif to be an IPv4 ipif
10571 			 * for ifindex to make IPv4 mapped addresses
10572 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10573 			 * Even if no IPv6 ill exists for the ifindex
10574 			 * we need to check for an IPv4 ifindex in order
10575 			 * for this to work with mapped addresses. In that
10576 			 * case only set conn_multicast_ipif.
10577 			 */
10578 			if (!checkonly) {
10579 				if (ifindex == 0) {
10580 					connp->conn_multicast_ill = NULL;
10581 					connp->conn_orig_multicast_ifindex = 0;
10582 					connp->conn_multicast_ipif = NULL;
10583 				} else if (ill != NULL) {
10584 					connp->conn_multicast_ill = ill;
10585 					connp->conn_orig_multicast_ifindex =
10586 					    ifindex;
10587 				}
10588 			}
10589 			break;
10590 		}
10591 	}
10592 
10593 	if (ill != NULL) {
10594 		mutex_exit(&ill->ill_lock);
10595 		mutex_exit(&connp->conn_lock);
10596 		ill_refrele(ill);
10597 		return (0);
10598 	}
10599 	mutex_exit(&connp->conn_lock);
10600 	/*
10601 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10602 	 * locate the ill and could not set the option (ifindex != 0)
10603 	 */
10604 	return (ifindex == 0 ? 0 : EINVAL);
10605 }
10606 
10607 /* This routine sets socket options. */
10608 /* ARGSUSED */
10609 int
10610 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10611     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10612     void *dummy, cred_t *cr, mblk_t *first_mp)
10613 {
10614 	int		*i1 = (int *)invalp;
10615 	conn_t		*connp = Q_TO_CONN(q);
10616 	int		error = 0;
10617 	boolean_t	checkonly;
10618 	ire_t		*ire;
10619 	boolean_t	found;
10620 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10621 
10622 	switch (optset_context) {
10623 
10624 	case SETFN_OPTCOM_CHECKONLY:
10625 		checkonly = B_TRUE;
10626 		/*
10627 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10628 		 * inlen != 0 implies value supplied and
10629 		 * 	we have to "pretend" to set it.
10630 		 * inlen == 0 implies that there is no
10631 		 * 	value part in T_CHECK request and just validation
10632 		 * done elsewhere should be enough, we just return here.
10633 		 */
10634 		if (inlen == 0) {
10635 			*outlenp = 0;
10636 			return (0);
10637 		}
10638 		break;
10639 	case SETFN_OPTCOM_NEGOTIATE:
10640 	case SETFN_UD_NEGOTIATE:
10641 	case SETFN_CONN_NEGOTIATE:
10642 		checkonly = B_FALSE;
10643 		break;
10644 	default:
10645 		/*
10646 		 * We should never get here
10647 		 */
10648 		*outlenp = 0;
10649 		return (EINVAL);
10650 	}
10651 
10652 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10653 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10654 
10655 	/*
10656 	 * For fixed length options, no sanity check
10657 	 * of passed in length is done. It is assumed *_optcom_req()
10658 	 * routines do the right thing.
10659 	 */
10660 
10661 	switch (level) {
10662 	case SOL_SOCKET:
10663 		/*
10664 		 * conn_lock protects the bitfields, and is used to
10665 		 * set the fields atomically.
10666 		 */
10667 		switch (name) {
10668 		case SO_BROADCAST:
10669 			if (!checkonly) {
10670 				/* TODO: use value someplace? */
10671 				mutex_enter(&connp->conn_lock);
10672 				connp->conn_broadcast = *i1 ? 1 : 0;
10673 				mutex_exit(&connp->conn_lock);
10674 			}
10675 			break;	/* goto sizeof (int) option return */
10676 		case SO_USELOOPBACK:
10677 			if (!checkonly) {
10678 				/* TODO: use value someplace? */
10679 				mutex_enter(&connp->conn_lock);
10680 				connp->conn_loopback = *i1 ? 1 : 0;
10681 				mutex_exit(&connp->conn_lock);
10682 			}
10683 			break;	/* goto sizeof (int) option return */
10684 		case SO_DONTROUTE:
10685 			if (!checkonly) {
10686 				mutex_enter(&connp->conn_lock);
10687 				connp->conn_dontroute = *i1 ? 1 : 0;
10688 				mutex_exit(&connp->conn_lock);
10689 			}
10690 			break;	/* goto sizeof (int) option return */
10691 		case SO_REUSEADDR:
10692 			if (!checkonly) {
10693 				mutex_enter(&connp->conn_lock);
10694 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10695 				mutex_exit(&connp->conn_lock);
10696 			}
10697 			break;	/* goto sizeof (int) option return */
10698 		case SO_PROTOTYPE:
10699 			if (!checkonly) {
10700 				mutex_enter(&connp->conn_lock);
10701 				connp->conn_proto = *i1;
10702 				mutex_exit(&connp->conn_lock);
10703 			}
10704 			break;	/* goto sizeof (int) option return */
10705 		case SO_ALLZONES:
10706 			if (!checkonly) {
10707 				mutex_enter(&connp->conn_lock);
10708 				if (IPCL_IS_BOUND(connp)) {
10709 					mutex_exit(&connp->conn_lock);
10710 					return (EINVAL);
10711 				}
10712 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10713 				mutex_exit(&connp->conn_lock);
10714 			}
10715 			break;	/* goto sizeof (int) option return */
10716 		case SO_ANON_MLP:
10717 			if (!checkonly) {
10718 				mutex_enter(&connp->conn_lock);
10719 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10720 				mutex_exit(&connp->conn_lock);
10721 			}
10722 			break;	/* goto sizeof (int) option return */
10723 		case SO_MAC_EXEMPT:
10724 			if (secpolicy_net_mac_aware(cr) != 0 ||
10725 			    IPCL_IS_BOUND(connp))
10726 				return (EACCES);
10727 			if (!checkonly) {
10728 				mutex_enter(&connp->conn_lock);
10729 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10730 				mutex_exit(&connp->conn_lock);
10731 			}
10732 			break;	/* goto sizeof (int) option return */
10733 		default:
10734 			/*
10735 			 * "soft" error (negative)
10736 			 * option not handled at this level
10737 			 * Note: Do not modify *outlenp
10738 			 */
10739 			return (-EINVAL);
10740 		}
10741 		break;
10742 	case IPPROTO_IP:
10743 		switch (name) {
10744 		case IP_NEXTHOP:
10745 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10746 				return (EPERM);
10747 			/* FALLTHRU */
10748 		case IP_MULTICAST_IF:
10749 		case IP_DONTFAILOVER_IF: {
10750 			ipaddr_t addr = *i1;
10751 
10752 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10753 			    first_mp);
10754 			if (error != 0)
10755 				return (error);
10756 			break;	/* goto sizeof (int) option return */
10757 		}
10758 
10759 		case IP_MULTICAST_TTL:
10760 			/* Recorded in transport above IP */
10761 			*outvalp = *invalp;
10762 			*outlenp = sizeof (uchar_t);
10763 			return (0);
10764 		case IP_MULTICAST_LOOP:
10765 			if (!checkonly) {
10766 				mutex_enter(&connp->conn_lock);
10767 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10768 				mutex_exit(&connp->conn_lock);
10769 			}
10770 			*outvalp = *invalp;
10771 			*outlenp = sizeof (uchar_t);
10772 			return (0);
10773 		case IP_ADD_MEMBERSHIP:
10774 		case MCAST_JOIN_GROUP:
10775 		case IP_DROP_MEMBERSHIP:
10776 		case MCAST_LEAVE_GROUP: {
10777 			struct ip_mreq *mreqp;
10778 			struct group_req *greqp;
10779 			ire_t *ire;
10780 			boolean_t done = B_FALSE;
10781 			ipaddr_t group, ifaddr;
10782 			struct sockaddr_in *sin;
10783 			uint32_t *ifindexp;
10784 			boolean_t mcast_opt = B_TRUE;
10785 			mcast_record_t fmode;
10786 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10787 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10788 
10789 			switch (name) {
10790 			case IP_ADD_MEMBERSHIP:
10791 				mcast_opt = B_FALSE;
10792 				/* FALLTHRU */
10793 			case MCAST_JOIN_GROUP:
10794 				fmode = MODE_IS_EXCLUDE;
10795 				optfn = ip_opt_add_group;
10796 				break;
10797 
10798 			case IP_DROP_MEMBERSHIP:
10799 				mcast_opt = B_FALSE;
10800 				/* FALLTHRU */
10801 			case MCAST_LEAVE_GROUP:
10802 				fmode = MODE_IS_INCLUDE;
10803 				optfn = ip_opt_delete_group;
10804 				break;
10805 			}
10806 
10807 			if (mcast_opt) {
10808 				greqp = (struct group_req *)i1;
10809 				sin = (struct sockaddr_in *)&greqp->gr_group;
10810 				if (sin->sin_family != AF_INET) {
10811 					*outlenp = 0;
10812 					return (ENOPROTOOPT);
10813 				}
10814 				group = (ipaddr_t)sin->sin_addr.s_addr;
10815 				ifaddr = INADDR_ANY;
10816 				ifindexp = &greqp->gr_interface;
10817 			} else {
10818 				mreqp = (struct ip_mreq *)i1;
10819 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10820 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10821 				ifindexp = NULL;
10822 			}
10823 
10824 			/*
10825 			 * In the multirouting case, we need to replicate
10826 			 * the request on all interfaces that will take part
10827 			 * in replication.  We do so because multirouting is
10828 			 * reflective, thus we will probably receive multi-
10829 			 * casts on those interfaces.
10830 			 * The ip_multirt_apply_membership() succeeds if the
10831 			 * operation succeeds on at least one interface.
10832 			 */
10833 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10834 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10835 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10836 			if (ire != NULL) {
10837 				if (ire->ire_flags & RTF_MULTIRT) {
10838 					error = ip_multirt_apply_membership(
10839 					    optfn, ire, connp, checkonly, group,
10840 					    fmode, INADDR_ANY, first_mp);
10841 					done = B_TRUE;
10842 				}
10843 				ire_refrele(ire);
10844 			}
10845 			if (!done) {
10846 				error = optfn(connp, checkonly, group, ifaddr,
10847 				    ifindexp, fmode, INADDR_ANY, first_mp);
10848 			}
10849 			if (error) {
10850 				/*
10851 				 * EINPROGRESS is a soft error, needs retry
10852 				 * so don't make *outlenp zero.
10853 				 */
10854 				if (error != EINPROGRESS)
10855 					*outlenp = 0;
10856 				return (error);
10857 			}
10858 			/* OK return - copy input buffer into output buffer */
10859 			if (invalp != outvalp) {
10860 				/* don't trust bcopy for identical src/dst */
10861 				bcopy(invalp, outvalp, inlen);
10862 			}
10863 			*outlenp = inlen;
10864 			return (0);
10865 		}
10866 		case IP_BLOCK_SOURCE:
10867 		case IP_UNBLOCK_SOURCE:
10868 		case IP_ADD_SOURCE_MEMBERSHIP:
10869 		case IP_DROP_SOURCE_MEMBERSHIP:
10870 		case MCAST_BLOCK_SOURCE:
10871 		case MCAST_UNBLOCK_SOURCE:
10872 		case MCAST_JOIN_SOURCE_GROUP:
10873 		case MCAST_LEAVE_SOURCE_GROUP: {
10874 			struct ip_mreq_source *imreqp;
10875 			struct group_source_req *gsreqp;
10876 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10877 			uint32_t ifindex = 0;
10878 			mcast_record_t fmode;
10879 			struct sockaddr_in *sin;
10880 			ire_t *ire;
10881 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10882 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10883 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10884 
10885 			switch (name) {
10886 			case IP_BLOCK_SOURCE:
10887 				mcast_opt = B_FALSE;
10888 				/* FALLTHRU */
10889 			case MCAST_BLOCK_SOURCE:
10890 				fmode = MODE_IS_EXCLUDE;
10891 				optfn = ip_opt_add_group;
10892 				break;
10893 
10894 			case IP_UNBLOCK_SOURCE:
10895 				mcast_opt = B_FALSE;
10896 				/* FALLTHRU */
10897 			case MCAST_UNBLOCK_SOURCE:
10898 				fmode = MODE_IS_EXCLUDE;
10899 				optfn = ip_opt_delete_group;
10900 				break;
10901 
10902 			case IP_ADD_SOURCE_MEMBERSHIP:
10903 				mcast_opt = B_FALSE;
10904 				/* FALLTHRU */
10905 			case MCAST_JOIN_SOURCE_GROUP:
10906 				fmode = MODE_IS_INCLUDE;
10907 				optfn = ip_opt_add_group;
10908 				break;
10909 
10910 			case IP_DROP_SOURCE_MEMBERSHIP:
10911 				mcast_opt = B_FALSE;
10912 				/* FALLTHRU */
10913 			case MCAST_LEAVE_SOURCE_GROUP:
10914 				fmode = MODE_IS_INCLUDE;
10915 				optfn = ip_opt_delete_group;
10916 				break;
10917 			}
10918 
10919 			if (mcast_opt) {
10920 				gsreqp = (struct group_source_req *)i1;
10921 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10922 					*outlenp = 0;
10923 					return (ENOPROTOOPT);
10924 				}
10925 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10926 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10927 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10928 				src = (ipaddr_t)sin->sin_addr.s_addr;
10929 				ifindex = gsreqp->gsr_interface;
10930 			} else {
10931 				imreqp = (struct ip_mreq_source *)i1;
10932 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10933 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10934 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10935 			}
10936 
10937 			/*
10938 			 * In the multirouting case, we need to replicate
10939 			 * the request as noted in the mcast cases above.
10940 			 */
10941 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10942 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10943 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10944 			if (ire != NULL) {
10945 				if (ire->ire_flags & RTF_MULTIRT) {
10946 					error = ip_multirt_apply_membership(
10947 					    optfn, ire, connp, checkonly, grp,
10948 					    fmode, src, first_mp);
10949 					done = B_TRUE;
10950 				}
10951 				ire_refrele(ire);
10952 			}
10953 			if (!done) {
10954 				error = optfn(connp, checkonly, grp, ifaddr,
10955 				    &ifindex, fmode, src, first_mp);
10956 			}
10957 			if (error != 0) {
10958 				/*
10959 				 * EINPROGRESS is a soft error, needs retry
10960 				 * so don't make *outlenp zero.
10961 				 */
10962 				if (error != EINPROGRESS)
10963 					*outlenp = 0;
10964 				return (error);
10965 			}
10966 			/* OK return - copy input buffer into output buffer */
10967 			if (invalp != outvalp) {
10968 				bcopy(invalp, outvalp, inlen);
10969 			}
10970 			*outlenp = inlen;
10971 			return (0);
10972 		}
10973 		case IP_SEC_OPT:
10974 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10975 			if (error != 0) {
10976 				*outlenp = 0;
10977 				return (error);
10978 			}
10979 			break;
10980 		case IP_HDRINCL:
10981 		case IP_OPTIONS:
10982 		case T_IP_OPTIONS:
10983 		case IP_TOS:
10984 		case T_IP_TOS:
10985 		case IP_TTL:
10986 		case IP_RECVDSTADDR:
10987 		case IP_RECVOPTS:
10988 			/* OK return - copy input buffer into output buffer */
10989 			if (invalp != outvalp) {
10990 				/* don't trust bcopy for identical src/dst */
10991 				bcopy(invalp, outvalp, inlen);
10992 			}
10993 			*outlenp = inlen;
10994 			return (0);
10995 		case IP_RECVIF:
10996 			/* Retrieve the inbound interface index */
10997 			if (!checkonly) {
10998 				mutex_enter(&connp->conn_lock);
10999 				connp->conn_recvif = *i1 ? 1 : 0;
11000 				mutex_exit(&connp->conn_lock);
11001 			}
11002 			break;	/* goto sizeof (int) option return */
11003 		case IP_RECVPKTINFO:
11004 			if (!checkonly) {
11005 				mutex_enter(&connp->conn_lock);
11006 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11007 				mutex_exit(&connp->conn_lock);
11008 			}
11009 			break;	/* goto sizeof (int) option return */
11010 		case IP_RECVSLLA:
11011 			/* Retrieve the source link layer address */
11012 			if (!checkonly) {
11013 				mutex_enter(&connp->conn_lock);
11014 				connp->conn_recvslla = *i1 ? 1 : 0;
11015 				mutex_exit(&connp->conn_lock);
11016 			}
11017 			break;	/* goto sizeof (int) option return */
11018 		case MRT_INIT:
11019 		case MRT_DONE:
11020 		case MRT_ADD_VIF:
11021 		case MRT_DEL_VIF:
11022 		case MRT_ADD_MFC:
11023 		case MRT_DEL_MFC:
11024 		case MRT_ASSERT:
11025 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11026 				*outlenp = 0;
11027 				return (error);
11028 			}
11029 			error = ip_mrouter_set((int)name, q, checkonly,
11030 			    (uchar_t *)invalp, inlen, first_mp);
11031 			if (error) {
11032 				*outlenp = 0;
11033 				return (error);
11034 			}
11035 			/* OK return - copy input buffer into output buffer */
11036 			if (invalp != outvalp) {
11037 				/* don't trust bcopy for identical src/dst */
11038 				bcopy(invalp, outvalp, inlen);
11039 			}
11040 			*outlenp = inlen;
11041 			return (0);
11042 		case IP_BOUND_IF:
11043 		case IP_DHCPINIT_IF:
11044 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11045 			    level, name, first_mp);
11046 			if (error != 0)
11047 				return (error);
11048 			break; 		/* goto sizeof (int) option return */
11049 
11050 		case IP_UNSPEC_SRC:
11051 			/* Allow sending with a zero source address */
11052 			if (!checkonly) {
11053 				mutex_enter(&connp->conn_lock);
11054 				connp->conn_unspec_src = *i1 ? 1 : 0;
11055 				mutex_exit(&connp->conn_lock);
11056 			}
11057 			break;	/* goto sizeof (int) option return */
11058 		default:
11059 			/*
11060 			 * "soft" error (negative)
11061 			 * option not handled at this level
11062 			 * Note: Do not modify *outlenp
11063 			 */
11064 			return (-EINVAL);
11065 		}
11066 		break;
11067 	case IPPROTO_IPV6:
11068 		switch (name) {
11069 		case IPV6_BOUND_IF:
11070 		case IPV6_BOUND_PIF:
11071 		case IPV6_DONTFAILOVER_IF:
11072 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11073 			    level, name, first_mp);
11074 			if (error != 0)
11075 				return (error);
11076 			break; 		/* goto sizeof (int) option return */
11077 
11078 		case IPV6_MULTICAST_IF:
11079 			/*
11080 			 * The only possible errors are EINPROGRESS and
11081 			 * EINVAL. EINPROGRESS will be restarted and is not
11082 			 * a hard error. We call this option on both V4 and V6
11083 			 * If both return EINVAL, then this call returns
11084 			 * EINVAL. If at least one of them succeeds we
11085 			 * return success.
11086 			 */
11087 			found = B_FALSE;
11088 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11089 			    level, name, first_mp);
11090 			if (error == EINPROGRESS)
11091 				return (error);
11092 			if (error == 0)
11093 				found = B_TRUE;
11094 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11095 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11096 			if (error == 0)
11097 				found = B_TRUE;
11098 			if (!found)
11099 				return (error);
11100 			break; 		/* goto sizeof (int) option return */
11101 
11102 		case IPV6_MULTICAST_HOPS:
11103 			/* Recorded in transport above IP */
11104 			break;	/* goto sizeof (int) option return */
11105 		case IPV6_MULTICAST_LOOP:
11106 			if (!checkonly) {
11107 				mutex_enter(&connp->conn_lock);
11108 				connp->conn_multicast_loop = *i1;
11109 				mutex_exit(&connp->conn_lock);
11110 			}
11111 			break;	/* goto sizeof (int) option return */
11112 		case IPV6_JOIN_GROUP:
11113 		case MCAST_JOIN_GROUP:
11114 		case IPV6_LEAVE_GROUP:
11115 		case MCAST_LEAVE_GROUP: {
11116 			struct ipv6_mreq *ip_mreqp;
11117 			struct group_req *greqp;
11118 			ire_t *ire;
11119 			boolean_t done = B_FALSE;
11120 			in6_addr_t groupv6;
11121 			uint32_t ifindex;
11122 			boolean_t mcast_opt = B_TRUE;
11123 			mcast_record_t fmode;
11124 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11125 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11126 
11127 			switch (name) {
11128 			case IPV6_JOIN_GROUP:
11129 				mcast_opt = B_FALSE;
11130 				/* FALLTHRU */
11131 			case MCAST_JOIN_GROUP:
11132 				fmode = MODE_IS_EXCLUDE;
11133 				optfn = ip_opt_add_group_v6;
11134 				break;
11135 
11136 			case IPV6_LEAVE_GROUP:
11137 				mcast_opt = B_FALSE;
11138 				/* FALLTHRU */
11139 			case MCAST_LEAVE_GROUP:
11140 				fmode = MODE_IS_INCLUDE;
11141 				optfn = ip_opt_delete_group_v6;
11142 				break;
11143 			}
11144 
11145 			if (mcast_opt) {
11146 				struct sockaddr_in *sin;
11147 				struct sockaddr_in6 *sin6;
11148 				greqp = (struct group_req *)i1;
11149 				if (greqp->gr_group.ss_family == AF_INET) {
11150 					sin = (struct sockaddr_in *)
11151 					    &(greqp->gr_group);
11152 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11153 					    &groupv6);
11154 				} else {
11155 					sin6 = (struct sockaddr_in6 *)
11156 					    &(greqp->gr_group);
11157 					groupv6 = sin6->sin6_addr;
11158 				}
11159 				ifindex = greqp->gr_interface;
11160 			} else {
11161 				ip_mreqp = (struct ipv6_mreq *)i1;
11162 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11163 				ifindex = ip_mreqp->ipv6mr_interface;
11164 			}
11165 			/*
11166 			 * In the multirouting case, we need to replicate
11167 			 * the request on all interfaces that will take part
11168 			 * in replication.  We do so because multirouting is
11169 			 * reflective, thus we will probably receive multi-
11170 			 * casts on those interfaces.
11171 			 * The ip_multirt_apply_membership_v6() succeeds if
11172 			 * the operation succeeds on at least one interface.
11173 			 */
11174 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11175 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11176 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11177 			if (ire != NULL) {
11178 				if (ire->ire_flags & RTF_MULTIRT) {
11179 					error = ip_multirt_apply_membership_v6(
11180 					    optfn, ire, connp, checkonly,
11181 					    &groupv6, fmode, &ipv6_all_zeros,
11182 					    first_mp);
11183 					done = B_TRUE;
11184 				}
11185 				ire_refrele(ire);
11186 			}
11187 			if (!done) {
11188 				error = optfn(connp, checkonly, &groupv6,
11189 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11190 			}
11191 			if (error) {
11192 				/*
11193 				 * EINPROGRESS is a soft error, needs retry
11194 				 * so don't make *outlenp zero.
11195 				 */
11196 				if (error != EINPROGRESS)
11197 					*outlenp = 0;
11198 				return (error);
11199 			}
11200 			/* OK return - copy input buffer into output buffer */
11201 			if (invalp != outvalp) {
11202 				/* don't trust bcopy for identical src/dst */
11203 				bcopy(invalp, outvalp, inlen);
11204 			}
11205 			*outlenp = inlen;
11206 			return (0);
11207 		}
11208 		case MCAST_BLOCK_SOURCE:
11209 		case MCAST_UNBLOCK_SOURCE:
11210 		case MCAST_JOIN_SOURCE_GROUP:
11211 		case MCAST_LEAVE_SOURCE_GROUP: {
11212 			struct group_source_req *gsreqp;
11213 			in6_addr_t v6grp, v6src;
11214 			uint32_t ifindex;
11215 			mcast_record_t fmode;
11216 			ire_t *ire;
11217 			boolean_t done = B_FALSE;
11218 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11219 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11220 
11221 			switch (name) {
11222 			case MCAST_BLOCK_SOURCE:
11223 				fmode = MODE_IS_EXCLUDE;
11224 				optfn = ip_opt_add_group_v6;
11225 				break;
11226 			case MCAST_UNBLOCK_SOURCE:
11227 				fmode = MODE_IS_EXCLUDE;
11228 				optfn = ip_opt_delete_group_v6;
11229 				break;
11230 			case MCAST_JOIN_SOURCE_GROUP:
11231 				fmode = MODE_IS_INCLUDE;
11232 				optfn = ip_opt_add_group_v6;
11233 				break;
11234 			case MCAST_LEAVE_SOURCE_GROUP:
11235 				fmode = MODE_IS_INCLUDE;
11236 				optfn = ip_opt_delete_group_v6;
11237 				break;
11238 			}
11239 
11240 			gsreqp = (struct group_source_req *)i1;
11241 			ifindex = gsreqp->gsr_interface;
11242 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11243 				struct sockaddr_in *s;
11244 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11245 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11246 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11247 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11248 			} else {
11249 				struct sockaddr_in6 *s6;
11250 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11251 				v6grp = s6->sin6_addr;
11252 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11253 				v6src = s6->sin6_addr;
11254 			}
11255 
11256 			/*
11257 			 * In the multirouting case, we need to replicate
11258 			 * the request as noted in the mcast cases above.
11259 			 */
11260 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11261 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11262 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11263 			if (ire != NULL) {
11264 				if (ire->ire_flags & RTF_MULTIRT) {
11265 					error = ip_multirt_apply_membership_v6(
11266 					    optfn, ire, connp, checkonly,
11267 					    &v6grp, fmode, &v6src, first_mp);
11268 					done = B_TRUE;
11269 				}
11270 				ire_refrele(ire);
11271 			}
11272 			if (!done) {
11273 				error = optfn(connp, checkonly, &v6grp,
11274 				    ifindex, fmode, &v6src, first_mp);
11275 			}
11276 			if (error != 0) {
11277 				/*
11278 				 * EINPROGRESS is a soft error, needs retry
11279 				 * so don't make *outlenp zero.
11280 				 */
11281 				if (error != EINPROGRESS)
11282 					*outlenp = 0;
11283 				return (error);
11284 			}
11285 			/* OK return - copy input buffer into output buffer */
11286 			if (invalp != outvalp) {
11287 				bcopy(invalp, outvalp, inlen);
11288 			}
11289 			*outlenp = inlen;
11290 			return (0);
11291 		}
11292 		case IPV6_UNICAST_HOPS:
11293 			/* Recorded in transport above IP */
11294 			break;	/* goto sizeof (int) option return */
11295 		case IPV6_UNSPEC_SRC:
11296 			/* Allow sending with a zero source address */
11297 			if (!checkonly) {
11298 				mutex_enter(&connp->conn_lock);
11299 				connp->conn_unspec_src = *i1 ? 1 : 0;
11300 				mutex_exit(&connp->conn_lock);
11301 			}
11302 			break;	/* goto sizeof (int) option return */
11303 		case IPV6_RECVPKTINFO:
11304 			if (!checkonly) {
11305 				mutex_enter(&connp->conn_lock);
11306 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11307 				mutex_exit(&connp->conn_lock);
11308 			}
11309 			break;	/* goto sizeof (int) option return */
11310 		case IPV6_RECVTCLASS:
11311 			if (!checkonly) {
11312 				if (*i1 < 0 || *i1 > 1) {
11313 					return (EINVAL);
11314 				}
11315 				mutex_enter(&connp->conn_lock);
11316 				connp->conn_ipv6_recvtclass = *i1;
11317 				mutex_exit(&connp->conn_lock);
11318 			}
11319 			break;
11320 		case IPV6_RECVPATHMTU:
11321 			if (!checkonly) {
11322 				if (*i1 < 0 || *i1 > 1) {
11323 					return (EINVAL);
11324 				}
11325 				mutex_enter(&connp->conn_lock);
11326 				connp->conn_ipv6_recvpathmtu = *i1;
11327 				mutex_exit(&connp->conn_lock);
11328 			}
11329 			break;
11330 		case IPV6_RECVHOPLIMIT:
11331 			if (!checkonly) {
11332 				mutex_enter(&connp->conn_lock);
11333 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11334 				mutex_exit(&connp->conn_lock);
11335 			}
11336 			break;	/* goto sizeof (int) option return */
11337 		case IPV6_RECVHOPOPTS:
11338 			if (!checkonly) {
11339 				mutex_enter(&connp->conn_lock);
11340 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11341 				mutex_exit(&connp->conn_lock);
11342 			}
11343 			break;	/* goto sizeof (int) option return */
11344 		case IPV6_RECVDSTOPTS:
11345 			if (!checkonly) {
11346 				mutex_enter(&connp->conn_lock);
11347 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11348 				mutex_exit(&connp->conn_lock);
11349 			}
11350 			break;	/* goto sizeof (int) option return */
11351 		case IPV6_RECVRTHDR:
11352 			if (!checkonly) {
11353 				mutex_enter(&connp->conn_lock);
11354 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11355 				mutex_exit(&connp->conn_lock);
11356 			}
11357 			break;	/* goto sizeof (int) option return */
11358 		case IPV6_RECVRTHDRDSTOPTS:
11359 			if (!checkonly) {
11360 				mutex_enter(&connp->conn_lock);
11361 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11362 				mutex_exit(&connp->conn_lock);
11363 			}
11364 			break;	/* goto sizeof (int) option return */
11365 		case IPV6_PKTINFO:
11366 			if (inlen == 0)
11367 				return (-EINVAL);	/* clearing option */
11368 			error = ip6_set_pktinfo(cr, connp,
11369 			    (struct in6_pktinfo *)invalp, first_mp);
11370 			if (error != 0)
11371 				*outlenp = 0;
11372 			else
11373 				*outlenp = inlen;
11374 			return (error);
11375 		case IPV6_NEXTHOP: {
11376 			struct sockaddr_in6 *sin6;
11377 
11378 			/* Verify that the nexthop is reachable */
11379 			if (inlen == 0)
11380 				return (-EINVAL);	/* clearing option */
11381 
11382 			sin6 = (struct sockaddr_in6 *)invalp;
11383 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11384 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11385 			    NULL, MATCH_IRE_DEFAULT, ipst);
11386 
11387 			if (ire == NULL) {
11388 				*outlenp = 0;
11389 				return (EHOSTUNREACH);
11390 			}
11391 			ire_refrele(ire);
11392 			return (-EINVAL);
11393 		}
11394 		case IPV6_SEC_OPT:
11395 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11396 			if (error != 0) {
11397 				*outlenp = 0;
11398 				return (error);
11399 			}
11400 			break;
11401 		case IPV6_SRC_PREFERENCES: {
11402 			/*
11403 			 * This is implemented strictly in the ip module
11404 			 * (here and in tcp_opt_*() to accomodate tcp
11405 			 * sockets).  Modules above ip pass this option
11406 			 * down here since ip is the only one that needs to
11407 			 * be aware of source address preferences.
11408 			 *
11409 			 * This socket option only affects connected
11410 			 * sockets that haven't already bound to a specific
11411 			 * IPv6 address.  In other words, sockets that
11412 			 * don't call bind() with an address other than the
11413 			 * unspecified address and that call connect().
11414 			 * ip_bind_connected_v6() passes these preferences
11415 			 * to the ipif_select_source_v6() function.
11416 			 */
11417 			if (inlen != sizeof (uint32_t))
11418 				return (EINVAL);
11419 			error = ip6_set_src_preferences(connp,
11420 			    *(uint32_t *)invalp);
11421 			if (error != 0) {
11422 				*outlenp = 0;
11423 				return (error);
11424 			} else {
11425 				*outlenp = sizeof (uint32_t);
11426 			}
11427 			break;
11428 		}
11429 		case IPV6_V6ONLY:
11430 			if (*i1 < 0 || *i1 > 1) {
11431 				return (EINVAL);
11432 			}
11433 			mutex_enter(&connp->conn_lock);
11434 			connp->conn_ipv6_v6only = *i1;
11435 			mutex_exit(&connp->conn_lock);
11436 			break;
11437 		default:
11438 			return (-EINVAL);
11439 		}
11440 		break;
11441 	default:
11442 		/*
11443 		 * "soft" error (negative)
11444 		 * option not handled at this level
11445 		 * Note: Do not modify *outlenp
11446 		 */
11447 		return (-EINVAL);
11448 	}
11449 	/*
11450 	 * Common case of return from an option that is sizeof (int)
11451 	 */
11452 	*(int *)outvalp = *i1;
11453 	*outlenp = sizeof (int);
11454 	return (0);
11455 }
11456 
11457 /*
11458  * This routine gets default values of certain options whose default
11459  * values are maintained by protocol specific code
11460  */
11461 /* ARGSUSED */
11462 int
11463 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11464 {
11465 	int *i1 = (int *)ptr;
11466 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11467 
11468 	switch (level) {
11469 	case IPPROTO_IP:
11470 		switch (name) {
11471 		case IP_MULTICAST_TTL:
11472 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11473 			return (sizeof (uchar_t));
11474 		case IP_MULTICAST_LOOP:
11475 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11476 			return (sizeof (uchar_t));
11477 		default:
11478 			return (-1);
11479 		}
11480 	case IPPROTO_IPV6:
11481 		switch (name) {
11482 		case IPV6_UNICAST_HOPS:
11483 			*i1 = ipst->ips_ipv6_def_hops;
11484 			return (sizeof (int));
11485 		case IPV6_MULTICAST_HOPS:
11486 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11487 			return (sizeof (int));
11488 		case IPV6_MULTICAST_LOOP:
11489 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11490 			return (sizeof (int));
11491 		case IPV6_V6ONLY:
11492 			*i1 = 1;
11493 			return (sizeof (int));
11494 		default:
11495 			return (-1);
11496 		}
11497 	default:
11498 		return (-1);
11499 	}
11500 	/* NOTREACHED */
11501 }
11502 
11503 /*
11504  * Given a destination address and a pointer to where to put the information
11505  * this routine fills in the mtuinfo.
11506  */
11507 int
11508 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11509     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11510 {
11511 	ire_t *ire;
11512 	ip_stack_t	*ipst = ns->netstack_ip;
11513 
11514 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11515 		return (-1);
11516 
11517 	bzero(mtuinfo, sizeof (*mtuinfo));
11518 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11519 	mtuinfo->ip6m_addr.sin6_port = port;
11520 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11521 
11522 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11523 	if (ire != NULL) {
11524 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11525 		ire_refrele(ire);
11526 	} else {
11527 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11528 	}
11529 	return (sizeof (struct ip6_mtuinfo));
11530 }
11531 
11532 /*
11533  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11534  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11535  * isn't.  This doesn't matter as the error checking is done properly for the
11536  * other MRT options coming in through ip_opt_set.
11537  */
11538 int
11539 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11540 {
11541 	conn_t		*connp = Q_TO_CONN(q);
11542 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11543 
11544 	switch (level) {
11545 	case IPPROTO_IP:
11546 		switch (name) {
11547 		case MRT_VERSION:
11548 		case MRT_ASSERT:
11549 			(void) ip_mrouter_get(name, q, ptr);
11550 			return (sizeof (int));
11551 		case IP_SEC_OPT:
11552 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11553 		case IP_NEXTHOP:
11554 			if (connp->conn_nexthop_set) {
11555 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11556 				return (sizeof (ipaddr_t));
11557 			} else
11558 				return (0);
11559 		case IP_RECVPKTINFO:
11560 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11561 			return (sizeof (int));
11562 		default:
11563 			break;
11564 		}
11565 		break;
11566 	case IPPROTO_IPV6:
11567 		switch (name) {
11568 		case IPV6_SEC_OPT:
11569 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11570 		case IPV6_SRC_PREFERENCES: {
11571 			return (ip6_get_src_preferences(connp,
11572 			    (uint32_t *)ptr));
11573 		}
11574 		case IPV6_V6ONLY:
11575 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11576 			return (sizeof (int));
11577 		case IPV6_PATHMTU:
11578 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11579 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11580 		default:
11581 			break;
11582 		}
11583 		break;
11584 	default:
11585 		break;
11586 	}
11587 	return (-1);
11588 }
11589 
11590 /* Named Dispatch routine to get a current value out of our parameter table. */
11591 /* ARGSUSED */
11592 static int
11593 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11594 {
11595 	ipparam_t *ippa = (ipparam_t *)cp;
11596 
11597 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11598 	return (0);
11599 }
11600 
11601 /* ARGSUSED */
11602 static int
11603 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11604 {
11605 
11606 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11607 	return (0);
11608 }
11609 
11610 /*
11611  * Set ip{,6}_forwarding values.  This means walking through all of the
11612  * ill's and toggling their forwarding values.
11613  */
11614 /* ARGSUSED */
11615 static int
11616 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11617 {
11618 	long new_value;
11619 	int *forwarding_value = (int *)cp;
11620 	ill_t *ill;
11621 	boolean_t isv6;
11622 	ill_walk_context_t ctx;
11623 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11624 
11625 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11626 
11627 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11628 	    new_value < 0 || new_value > 1) {
11629 		return (EINVAL);
11630 	}
11631 
11632 	*forwarding_value = new_value;
11633 
11634 	/*
11635 	 * Regardless of the current value of ip_forwarding, set all per-ill
11636 	 * values of ip_forwarding to the value being set.
11637 	 *
11638 	 * Bring all the ill's up to date with the new global value.
11639 	 */
11640 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11641 
11642 	if (isv6)
11643 		ill = ILL_START_WALK_V6(&ctx, ipst);
11644 	else
11645 		ill = ILL_START_WALK_V4(&ctx, ipst);
11646 
11647 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11648 		(void) ill_forward_set(ill, new_value != 0);
11649 
11650 	rw_exit(&ipst->ips_ill_g_lock);
11651 	return (0);
11652 }
11653 
11654 /*
11655  * Walk through the param array specified registering each element with the
11656  * Named Dispatch handler. This is called only during init. So it is ok
11657  * not to acquire any locks
11658  */
11659 static boolean_t
11660 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11661     ipndp_t *ipnd, size_t ipnd_cnt)
11662 {
11663 	for (; ippa_cnt-- > 0; ippa++) {
11664 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11665 			if (!nd_load(ndp, ippa->ip_param_name,
11666 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11667 				nd_free(ndp);
11668 				return (B_FALSE);
11669 			}
11670 		}
11671 	}
11672 
11673 	for (; ipnd_cnt-- > 0; ipnd++) {
11674 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11675 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11676 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11677 			    ipnd->ip_ndp_data)) {
11678 				nd_free(ndp);
11679 				return (B_FALSE);
11680 			}
11681 		}
11682 	}
11683 
11684 	return (B_TRUE);
11685 }
11686 
11687 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11688 /* ARGSUSED */
11689 static int
11690 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11691 {
11692 	long		new_value;
11693 	ipparam_t	*ippa = (ipparam_t *)cp;
11694 
11695 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11696 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11697 		return (EINVAL);
11698 	}
11699 	ippa->ip_param_value = new_value;
11700 	return (0);
11701 }
11702 
11703 /*
11704  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11705  * When an ipf is passed here for the first time, if
11706  * we already have in-order fragments on the queue, we convert from the fast-
11707  * path reassembly scheme to the hard-case scheme.  From then on, additional
11708  * fragments are reassembled here.  We keep track of the start and end offsets
11709  * of each piece, and the number of holes in the chain.  When the hole count
11710  * goes to zero, we are done!
11711  *
11712  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11713  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11714  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11715  * after the call to ip_reassemble().
11716  */
11717 int
11718 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11719     size_t msg_len)
11720 {
11721 	uint_t	end;
11722 	mblk_t	*next_mp;
11723 	mblk_t	*mp1;
11724 	uint_t	offset;
11725 	boolean_t incr_dups = B_TRUE;
11726 	boolean_t offset_zero_seen = B_FALSE;
11727 	boolean_t pkt_boundary_checked = B_FALSE;
11728 
11729 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11730 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11731 
11732 	/* Add in byte count */
11733 	ipf->ipf_count += msg_len;
11734 	if (ipf->ipf_end) {
11735 		/*
11736 		 * We were part way through in-order reassembly, but now there
11737 		 * is a hole.  We walk through messages already queued, and
11738 		 * mark them for hard case reassembly.  We know that up till
11739 		 * now they were in order starting from offset zero.
11740 		 */
11741 		offset = 0;
11742 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11743 			IP_REASS_SET_START(mp1, offset);
11744 			if (offset == 0) {
11745 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11746 				offset = -ipf->ipf_nf_hdr_len;
11747 			}
11748 			offset += mp1->b_wptr - mp1->b_rptr;
11749 			IP_REASS_SET_END(mp1, offset);
11750 		}
11751 		/* One hole at the end. */
11752 		ipf->ipf_hole_cnt = 1;
11753 		/* Brand it as a hard case, forever. */
11754 		ipf->ipf_end = 0;
11755 	}
11756 	/* Walk through all the new pieces. */
11757 	do {
11758 		end = start + (mp->b_wptr - mp->b_rptr);
11759 		/*
11760 		 * If start is 0, decrease 'end' only for the first mblk of
11761 		 * the fragment. Otherwise 'end' can get wrong value in the
11762 		 * second pass of the loop if first mblk is exactly the
11763 		 * size of ipf_nf_hdr_len.
11764 		 */
11765 		if (start == 0 && !offset_zero_seen) {
11766 			/* First segment */
11767 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11768 			end -= ipf->ipf_nf_hdr_len;
11769 			offset_zero_seen = B_TRUE;
11770 		}
11771 		next_mp = mp->b_cont;
11772 		/*
11773 		 * We are checking to see if there is any interesing data
11774 		 * to process.  If there isn't and the mblk isn't the
11775 		 * one which carries the unfragmentable header then we
11776 		 * drop it.  It's possible to have just the unfragmentable
11777 		 * header come through without any data.  That needs to be
11778 		 * saved.
11779 		 *
11780 		 * If the assert at the top of this function holds then the
11781 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11782 		 * is infrequently traveled enough that the test is left in
11783 		 * to protect against future code changes which break that
11784 		 * invariant.
11785 		 */
11786 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11787 			/* Empty.  Blast it. */
11788 			IP_REASS_SET_START(mp, 0);
11789 			IP_REASS_SET_END(mp, 0);
11790 			/*
11791 			 * If the ipf points to the mblk we are about to free,
11792 			 * update ipf to point to the next mblk (or NULL
11793 			 * if none).
11794 			 */
11795 			if (ipf->ipf_mp->b_cont == mp)
11796 				ipf->ipf_mp->b_cont = next_mp;
11797 			freeb(mp);
11798 			continue;
11799 		}
11800 		mp->b_cont = NULL;
11801 		IP_REASS_SET_START(mp, start);
11802 		IP_REASS_SET_END(mp, end);
11803 		if (!ipf->ipf_tail_mp) {
11804 			ipf->ipf_tail_mp = mp;
11805 			ipf->ipf_mp->b_cont = mp;
11806 			if (start == 0 || !more) {
11807 				ipf->ipf_hole_cnt = 1;
11808 				/*
11809 				 * if the first fragment comes in more than one
11810 				 * mblk, this loop will be executed for each
11811 				 * mblk. Need to adjust hole count so exiting
11812 				 * this routine will leave hole count at 1.
11813 				 */
11814 				if (next_mp)
11815 					ipf->ipf_hole_cnt++;
11816 			} else
11817 				ipf->ipf_hole_cnt = 2;
11818 			continue;
11819 		} else if (ipf->ipf_last_frag_seen && !more &&
11820 		    !pkt_boundary_checked) {
11821 			/*
11822 			 * We check datagram boundary only if this fragment
11823 			 * claims to be the last fragment and we have seen a
11824 			 * last fragment in the past too. We do this only
11825 			 * once for a given fragment.
11826 			 *
11827 			 * start cannot be 0 here as fragments with start=0
11828 			 * and MF=0 gets handled as a complete packet. These
11829 			 * fragments should not reach here.
11830 			 */
11831 
11832 			if (start + msgdsize(mp) !=
11833 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11834 				/*
11835 				 * We have two fragments both of which claim
11836 				 * to be the last fragment but gives conflicting
11837 				 * information about the whole datagram size.
11838 				 * Something fishy is going on. Drop the
11839 				 * fragment and free up the reassembly list.
11840 				 */
11841 				return (IP_REASS_FAILED);
11842 			}
11843 
11844 			/*
11845 			 * We shouldn't come to this code block again for this
11846 			 * particular fragment.
11847 			 */
11848 			pkt_boundary_checked = B_TRUE;
11849 		}
11850 
11851 		/* New stuff at or beyond tail? */
11852 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11853 		if (start >= offset) {
11854 			if (ipf->ipf_last_frag_seen) {
11855 				/* current fragment is beyond last fragment */
11856 				return (IP_REASS_FAILED);
11857 			}
11858 			/* Link it on end. */
11859 			ipf->ipf_tail_mp->b_cont = mp;
11860 			ipf->ipf_tail_mp = mp;
11861 			if (more) {
11862 				if (start != offset)
11863 					ipf->ipf_hole_cnt++;
11864 			} else if (start == offset && next_mp == NULL)
11865 					ipf->ipf_hole_cnt--;
11866 			continue;
11867 		}
11868 		mp1 = ipf->ipf_mp->b_cont;
11869 		offset = IP_REASS_START(mp1);
11870 		/* New stuff at the front? */
11871 		if (start < offset) {
11872 			if (start == 0) {
11873 				if (end >= offset) {
11874 					/* Nailed the hole at the begining. */
11875 					ipf->ipf_hole_cnt--;
11876 				}
11877 			} else if (end < offset) {
11878 				/*
11879 				 * A hole, stuff, and a hole where there used
11880 				 * to be just a hole.
11881 				 */
11882 				ipf->ipf_hole_cnt++;
11883 			}
11884 			mp->b_cont = mp1;
11885 			/* Check for overlap. */
11886 			while (end > offset) {
11887 				if (end < IP_REASS_END(mp1)) {
11888 					mp->b_wptr -= end - offset;
11889 					IP_REASS_SET_END(mp, offset);
11890 					BUMP_MIB(ill->ill_ip_mib,
11891 					    ipIfStatsReasmPartDups);
11892 					break;
11893 				}
11894 				/* Did we cover another hole? */
11895 				if ((mp1->b_cont &&
11896 				    IP_REASS_END(mp1) !=
11897 				    IP_REASS_START(mp1->b_cont) &&
11898 				    end >= IP_REASS_START(mp1->b_cont)) ||
11899 				    (!ipf->ipf_last_frag_seen && !more)) {
11900 					ipf->ipf_hole_cnt--;
11901 				}
11902 				/* Clip out mp1. */
11903 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11904 					/*
11905 					 * After clipping out mp1, this guy
11906 					 * is now hanging off the end.
11907 					 */
11908 					ipf->ipf_tail_mp = mp;
11909 				}
11910 				IP_REASS_SET_START(mp1, 0);
11911 				IP_REASS_SET_END(mp1, 0);
11912 				/* Subtract byte count */
11913 				ipf->ipf_count -= mp1->b_datap->db_lim -
11914 				    mp1->b_datap->db_base;
11915 				freeb(mp1);
11916 				BUMP_MIB(ill->ill_ip_mib,
11917 				    ipIfStatsReasmPartDups);
11918 				mp1 = mp->b_cont;
11919 				if (!mp1)
11920 					break;
11921 				offset = IP_REASS_START(mp1);
11922 			}
11923 			ipf->ipf_mp->b_cont = mp;
11924 			continue;
11925 		}
11926 		/*
11927 		 * The new piece starts somewhere between the start of the head
11928 		 * and before the end of the tail.
11929 		 */
11930 		for (; mp1; mp1 = mp1->b_cont) {
11931 			offset = IP_REASS_END(mp1);
11932 			if (start < offset) {
11933 				if (end <= offset) {
11934 					/* Nothing new. */
11935 					IP_REASS_SET_START(mp, 0);
11936 					IP_REASS_SET_END(mp, 0);
11937 					/* Subtract byte count */
11938 					ipf->ipf_count -= mp->b_datap->db_lim -
11939 					    mp->b_datap->db_base;
11940 					if (incr_dups) {
11941 						ipf->ipf_num_dups++;
11942 						incr_dups = B_FALSE;
11943 					}
11944 					freeb(mp);
11945 					BUMP_MIB(ill->ill_ip_mib,
11946 					    ipIfStatsReasmDuplicates);
11947 					break;
11948 				}
11949 				/*
11950 				 * Trim redundant stuff off beginning of new
11951 				 * piece.
11952 				 */
11953 				IP_REASS_SET_START(mp, offset);
11954 				mp->b_rptr += offset - start;
11955 				BUMP_MIB(ill->ill_ip_mib,
11956 				    ipIfStatsReasmPartDups);
11957 				start = offset;
11958 				if (!mp1->b_cont) {
11959 					/*
11960 					 * After trimming, this guy is now
11961 					 * hanging off the end.
11962 					 */
11963 					mp1->b_cont = mp;
11964 					ipf->ipf_tail_mp = mp;
11965 					if (!more) {
11966 						ipf->ipf_hole_cnt--;
11967 					}
11968 					break;
11969 				}
11970 			}
11971 			if (start >= IP_REASS_START(mp1->b_cont))
11972 				continue;
11973 			/* Fill a hole */
11974 			if (start > offset)
11975 				ipf->ipf_hole_cnt++;
11976 			mp->b_cont = mp1->b_cont;
11977 			mp1->b_cont = mp;
11978 			mp1 = mp->b_cont;
11979 			offset = IP_REASS_START(mp1);
11980 			if (end >= offset) {
11981 				ipf->ipf_hole_cnt--;
11982 				/* Check for overlap. */
11983 				while (end > offset) {
11984 					if (end < IP_REASS_END(mp1)) {
11985 						mp->b_wptr -= end - offset;
11986 						IP_REASS_SET_END(mp, offset);
11987 						/*
11988 						 * TODO we might bump
11989 						 * this up twice if there is
11990 						 * overlap at both ends.
11991 						 */
11992 						BUMP_MIB(ill->ill_ip_mib,
11993 						    ipIfStatsReasmPartDups);
11994 						break;
11995 					}
11996 					/* Did we cover another hole? */
11997 					if ((mp1->b_cont &&
11998 					    IP_REASS_END(mp1)
11999 					    != IP_REASS_START(mp1->b_cont) &&
12000 					    end >=
12001 					    IP_REASS_START(mp1->b_cont)) ||
12002 					    (!ipf->ipf_last_frag_seen &&
12003 					    !more)) {
12004 						ipf->ipf_hole_cnt--;
12005 					}
12006 					/* Clip out mp1. */
12007 					if ((mp->b_cont = mp1->b_cont) ==
12008 					    NULL) {
12009 						/*
12010 						 * After clipping out mp1,
12011 						 * this guy is now hanging
12012 						 * off the end.
12013 						 */
12014 						ipf->ipf_tail_mp = mp;
12015 					}
12016 					IP_REASS_SET_START(mp1, 0);
12017 					IP_REASS_SET_END(mp1, 0);
12018 					/* Subtract byte count */
12019 					ipf->ipf_count -=
12020 					    mp1->b_datap->db_lim -
12021 					    mp1->b_datap->db_base;
12022 					freeb(mp1);
12023 					BUMP_MIB(ill->ill_ip_mib,
12024 					    ipIfStatsReasmPartDups);
12025 					mp1 = mp->b_cont;
12026 					if (!mp1)
12027 						break;
12028 					offset = IP_REASS_START(mp1);
12029 				}
12030 			}
12031 			break;
12032 		}
12033 	} while (start = end, mp = next_mp);
12034 
12035 	/* Fragment just processed could be the last one. Remember this fact */
12036 	if (!more)
12037 		ipf->ipf_last_frag_seen = B_TRUE;
12038 
12039 	/* Still got holes? */
12040 	if (ipf->ipf_hole_cnt)
12041 		return (IP_REASS_PARTIAL);
12042 	/* Clean up overloaded fields to avoid upstream disasters. */
12043 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12044 		IP_REASS_SET_START(mp1, 0);
12045 		IP_REASS_SET_END(mp1, 0);
12046 	}
12047 	return (IP_REASS_COMPLETE);
12048 }
12049 
12050 /*
12051  * ipsec processing for the fast path, used for input UDP Packets
12052  * Returns true if ready for passup to UDP.
12053  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12054  * was an ESP-in-UDP packet, etc.).
12055  */
12056 static boolean_t
12057 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12058     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12059 {
12060 	uint32_t	ill_index;
12061 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12062 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12063 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12064 	udp_t		*udp = connp->conn_udp;
12065 
12066 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12067 	/* The ill_index of the incoming ILL */
12068 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12069 
12070 	/* pass packet up to the transport */
12071 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12072 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12073 		    NULL, mctl_present);
12074 		if (*first_mpp == NULL) {
12075 			return (B_FALSE);
12076 		}
12077 	}
12078 
12079 	/* Initiate IPPF processing for fastpath UDP */
12080 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12081 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12082 		if (*mpp == NULL) {
12083 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12084 			    "deferred/dropped during IPPF processing\n"));
12085 			return (B_FALSE);
12086 		}
12087 	}
12088 	/*
12089 	 * Remove 0-spi if it's 0, or move everything behind
12090 	 * the UDP header over it and forward to ESP via
12091 	 * ip_proto_input().
12092 	 */
12093 	if (udp->udp_nat_t_endpoint) {
12094 		if (mctl_present) {
12095 			/* mctl_present *shouldn't* happen. */
12096 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12097 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12098 			    &ipss->ipsec_dropper);
12099 			*first_mpp = NULL;
12100 			return (B_FALSE);
12101 		}
12102 
12103 		/* "ill" is "recv_ill" in actuality. */
12104 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12105 			return (B_FALSE);
12106 
12107 		/* Else continue like a normal UDP packet. */
12108 	}
12109 
12110 	/*
12111 	 * We make the checks as below since we are in the fast path
12112 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12113 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12114 	 */
12115 	if (connp->conn_recvif || connp->conn_recvslla ||
12116 	    connp->conn_ip_recvpktinfo) {
12117 		if (connp->conn_recvif) {
12118 			in_flags = IPF_RECVIF;
12119 		}
12120 		/*
12121 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12122 		 * so the flag passed to ip_add_info is based on IP version
12123 		 * of connp.
12124 		 */
12125 		if (connp->conn_ip_recvpktinfo) {
12126 			if (connp->conn_af_isv6) {
12127 				/*
12128 				 * V6 only needs index
12129 				 */
12130 				in_flags |= IPF_RECVIF;
12131 			} else {
12132 				/*
12133 				 * V4 needs index + matching address.
12134 				 */
12135 				in_flags |= IPF_RECVADDR;
12136 			}
12137 		}
12138 		if (connp->conn_recvslla) {
12139 			in_flags |= IPF_RECVSLLA;
12140 		}
12141 		/*
12142 		 * since in_flags are being set ill will be
12143 		 * referenced in ip_add_info, so it better not
12144 		 * be NULL.
12145 		 */
12146 		/*
12147 		 * the actual data will be contained in b_cont
12148 		 * upon successful return of the following call.
12149 		 * If the call fails then the original mblk is
12150 		 * returned.
12151 		 */
12152 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12153 		    ipst);
12154 	}
12155 
12156 	return (B_TRUE);
12157 }
12158 
12159 /*
12160  * Fragmentation reassembly.  Each ILL has a hash table for
12161  * queuing packets undergoing reassembly for all IPIFs
12162  * associated with the ILL.  The hash is based on the packet
12163  * IP ident field.  The ILL frag hash table was allocated
12164  * as a timer block at the time the ILL was created.  Whenever
12165  * there is anything on the reassembly queue, the timer will
12166  * be running.  Returns B_TRUE if successful else B_FALSE;
12167  * frees mp on failure.
12168  */
12169 static boolean_t
12170 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12171     uint32_t *cksum_val, uint16_t *cksum_flags)
12172 {
12173 	uint32_t	frag_offset_flags;
12174 	ill_t		*ill = (ill_t *)q->q_ptr;
12175 	mblk_t		*mp = *mpp;
12176 	mblk_t		*t_mp;
12177 	ipaddr_t	dst;
12178 	uint8_t		proto = ipha->ipha_protocol;
12179 	uint32_t	sum_val;
12180 	uint16_t	sum_flags;
12181 	ipf_t		*ipf;
12182 	ipf_t		**ipfp;
12183 	ipfb_t		*ipfb;
12184 	uint16_t	ident;
12185 	uint32_t	offset;
12186 	ipaddr_t	src;
12187 	uint_t		hdr_length;
12188 	uint32_t	end;
12189 	mblk_t		*mp1;
12190 	mblk_t		*tail_mp;
12191 	size_t		count;
12192 	size_t		msg_len;
12193 	uint8_t		ecn_info = 0;
12194 	uint32_t	packet_size;
12195 	boolean_t	pruned = B_FALSE;
12196 	ip_stack_t *ipst = ill->ill_ipst;
12197 
12198 	if (cksum_val != NULL)
12199 		*cksum_val = 0;
12200 	if (cksum_flags != NULL)
12201 		*cksum_flags = 0;
12202 
12203 	/*
12204 	 * Drop the fragmented as early as possible, if
12205 	 * we don't have resource(s) to re-assemble.
12206 	 */
12207 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12208 		freemsg(mp);
12209 		return (B_FALSE);
12210 	}
12211 
12212 	/* Check for fragmentation offset; return if there's none */
12213 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12214 	    (IPH_MF | IPH_OFFSET)) == 0)
12215 		return (B_TRUE);
12216 
12217 	/*
12218 	 * We utilize hardware computed checksum info only for UDP since
12219 	 * IP fragmentation is a normal occurence for the protocol.  In
12220 	 * addition, checksum offload support for IP fragments carrying
12221 	 * UDP payload is commonly implemented across network adapters.
12222 	 */
12223 	ASSERT(ill != NULL);
12224 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12225 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12226 		mblk_t *mp1 = mp->b_cont;
12227 		int32_t len;
12228 
12229 		/* Record checksum information from the packet */
12230 		sum_val = (uint32_t)DB_CKSUM16(mp);
12231 		sum_flags = DB_CKSUMFLAGS(mp);
12232 
12233 		/* IP payload offset from beginning of mblk */
12234 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12235 
12236 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12237 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12238 		    offset >= DB_CKSUMSTART(mp) &&
12239 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12240 			uint32_t adj;
12241 			/*
12242 			 * Partial checksum has been calculated by hardware
12243 			 * and attached to the packet; in addition, any
12244 			 * prepended extraneous data is even byte aligned.
12245 			 * If any such data exists, we adjust the checksum;
12246 			 * this would also handle any postpended data.
12247 			 */
12248 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12249 			    mp, mp1, len, adj);
12250 
12251 			/* One's complement subtract extraneous checksum */
12252 			if (adj >= sum_val)
12253 				sum_val = ~(adj - sum_val) & 0xFFFF;
12254 			else
12255 				sum_val -= adj;
12256 		}
12257 	} else {
12258 		sum_val = 0;
12259 		sum_flags = 0;
12260 	}
12261 
12262 	/* Clear hardware checksumming flag */
12263 	DB_CKSUMFLAGS(mp) = 0;
12264 
12265 	ident = ipha->ipha_ident;
12266 	offset = (frag_offset_flags << 3) & 0xFFFF;
12267 	src = ipha->ipha_src;
12268 	dst = ipha->ipha_dst;
12269 	hdr_length = IPH_HDR_LENGTH(ipha);
12270 	end = ntohs(ipha->ipha_length) - hdr_length;
12271 
12272 	/* If end == 0 then we have a packet with no data, so just free it */
12273 	if (end == 0) {
12274 		freemsg(mp);
12275 		return (B_FALSE);
12276 	}
12277 
12278 	/* Record the ECN field info. */
12279 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12280 	if (offset != 0) {
12281 		/*
12282 		 * If this isn't the first piece, strip the header, and
12283 		 * add the offset to the end value.
12284 		 */
12285 		mp->b_rptr += hdr_length;
12286 		end += offset;
12287 	}
12288 
12289 	msg_len = MBLKSIZE(mp);
12290 	tail_mp = mp;
12291 	while (tail_mp->b_cont != NULL) {
12292 		tail_mp = tail_mp->b_cont;
12293 		msg_len += MBLKSIZE(tail_mp);
12294 	}
12295 
12296 	/* If the reassembly list for this ILL will get too big, prune it */
12297 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12298 	    ipst->ips_ip_reass_queue_bytes) {
12299 		ill_frag_prune(ill,
12300 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12301 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12302 		pruned = B_TRUE;
12303 	}
12304 
12305 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12306 	mutex_enter(&ipfb->ipfb_lock);
12307 
12308 	ipfp = &ipfb->ipfb_ipf;
12309 	/* Try to find an existing fragment queue for this packet. */
12310 	for (;;) {
12311 		ipf = ipfp[0];
12312 		if (ipf != NULL) {
12313 			/*
12314 			 * It has to match on ident and src/dst address.
12315 			 */
12316 			if (ipf->ipf_ident == ident &&
12317 			    ipf->ipf_src == src &&
12318 			    ipf->ipf_dst == dst &&
12319 			    ipf->ipf_protocol == proto) {
12320 				/*
12321 				 * If we have received too many
12322 				 * duplicate fragments for this packet
12323 				 * free it.
12324 				 */
12325 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12326 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12327 					freemsg(mp);
12328 					mutex_exit(&ipfb->ipfb_lock);
12329 					return (B_FALSE);
12330 				}
12331 				/* Found it. */
12332 				break;
12333 			}
12334 			ipfp = &ipf->ipf_hash_next;
12335 			continue;
12336 		}
12337 
12338 		/*
12339 		 * If we pruned the list, do we want to store this new
12340 		 * fragment?. We apply an optimization here based on the
12341 		 * fact that most fragments will be received in order.
12342 		 * So if the offset of this incoming fragment is zero,
12343 		 * it is the first fragment of a new packet. We will
12344 		 * keep it.  Otherwise drop the fragment, as we have
12345 		 * probably pruned the packet already (since the
12346 		 * packet cannot be found).
12347 		 */
12348 		if (pruned && offset != 0) {
12349 			mutex_exit(&ipfb->ipfb_lock);
12350 			freemsg(mp);
12351 			return (B_FALSE);
12352 		}
12353 
12354 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12355 			/*
12356 			 * Too many fragmented packets in this hash
12357 			 * bucket. Free the oldest.
12358 			 */
12359 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12360 		}
12361 
12362 		/* New guy.  Allocate a frag message. */
12363 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12364 		if (mp1 == NULL) {
12365 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12366 			freemsg(mp);
12367 reass_done:
12368 			mutex_exit(&ipfb->ipfb_lock);
12369 			return (B_FALSE);
12370 		}
12371 
12372 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12373 		mp1->b_cont = mp;
12374 
12375 		/* Initialize the fragment header. */
12376 		ipf = (ipf_t *)mp1->b_rptr;
12377 		ipf->ipf_mp = mp1;
12378 		ipf->ipf_ptphn = ipfp;
12379 		ipfp[0] = ipf;
12380 		ipf->ipf_hash_next = NULL;
12381 		ipf->ipf_ident = ident;
12382 		ipf->ipf_protocol = proto;
12383 		ipf->ipf_src = src;
12384 		ipf->ipf_dst = dst;
12385 		ipf->ipf_nf_hdr_len = 0;
12386 		/* Record reassembly start time. */
12387 		ipf->ipf_timestamp = gethrestime_sec();
12388 		/* Record ipf generation and account for frag header */
12389 		ipf->ipf_gen = ill->ill_ipf_gen++;
12390 		ipf->ipf_count = MBLKSIZE(mp1);
12391 		ipf->ipf_last_frag_seen = B_FALSE;
12392 		ipf->ipf_ecn = ecn_info;
12393 		ipf->ipf_num_dups = 0;
12394 		ipfb->ipfb_frag_pkts++;
12395 		ipf->ipf_checksum = 0;
12396 		ipf->ipf_checksum_flags = 0;
12397 
12398 		/* Store checksum value in fragment header */
12399 		if (sum_flags != 0) {
12400 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12401 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12402 			ipf->ipf_checksum = sum_val;
12403 			ipf->ipf_checksum_flags = sum_flags;
12404 		}
12405 
12406 		/*
12407 		 * We handle reassembly two ways.  In the easy case,
12408 		 * where all the fragments show up in order, we do
12409 		 * minimal bookkeeping, and just clip new pieces on
12410 		 * the end.  If we ever see a hole, then we go off
12411 		 * to ip_reassemble which has to mark the pieces and
12412 		 * keep track of the number of holes, etc.  Obviously,
12413 		 * the point of having both mechanisms is so we can
12414 		 * handle the easy case as efficiently as possible.
12415 		 */
12416 		if (offset == 0) {
12417 			/* Easy case, in-order reassembly so far. */
12418 			ipf->ipf_count += msg_len;
12419 			ipf->ipf_tail_mp = tail_mp;
12420 			/*
12421 			 * Keep track of next expected offset in
12422 			 * ipf_end.
12423 			 */
12424 			ipf->ipf_end = end;
12425 			ipf->ipf_nf_hdr_len = hdr_length;
12426 		} else {
12427 			/* Hard case, hole at the beginning. */
12428 			ipf->ipf_tail_mp = NULL;
12429 			/*
12430 			 * ipf_end == 0 means that we have given up
12431 			 * on easy reassembly.
12432 			 */
12433 			ipf->ipf_end = 0;
12434 
12435 			/* Forget checksum offload from now on */
12436 			ipf->ipf_checksum_flags = 0;
12437 
12438 			/*
12439 			 * ipf_hole_cnt is set by ip_reassemble.
12440 			 * ipf_count is updated by ip_reassemble.
12441 			 * No need to check for return value here
12442 			 * as we don't expect reassembly to complete
12443 			 * or fail for the first fragment itself.
12444 			 */
12445 			(void) ip_reassemble(mp, ipf,
12446 			    (frag_offset_flags & IPH_OFFSET) << 3,
12447 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12448 		}
12449 		/* Update per ipfb and ill byte counts */
12450 		ipfb->ipfb_count += ipf->ipf_count;
12451 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12452 		ill->ill_frag_count += ipf->ipf_count;
12453 		/* If the frag timer wasn't already going, start it. */
12454 		mutex_enter(&ill->ill_lock);
12455 		ill_frag_timer_start(ill);
12456 		mutex_exit(&ill->ill_lock);
12457 		goto reass_done;
12458 	}
12459 
12460 	/*
12461 	 * If the packet's flag has changed (it could be coming up
12462 	 * from an interface different than the previous, therefore
12463 	 * possibly different checksum capability), then forget about
12464 	 * any stored checksum states.  Otherwise add the value to
12465 	 * the existing one stored in the fragment header.
12466 	 */
12467 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12468 		sum_val += ipf->ipf_checksum;
12469 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12470 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12471 		ipf->ipf_checksum = sum_val;
12472 	} else if (ipf->ipf_checksum_flags != 0) {
12473 		/* Forget checksum offload from now on */
12474 		ipf->ipf_checksum_flags = 0;
12475 	}
12476 
12477 	/*
12478 	 * We have a new piece of a datagram which is already being
12479 	 * reassembled.  Update the ECN info if all IP fragments
12480 	 * are ECN capable.  If there is one which is not, clear
12481 	 * all the info.  If there is at least one which has CE
12482 	 * code point, IP needs to report that up to transport.
12483 	 */
12484 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12485 		if (ecn_info == IPH_ECN_CE)
12486 			ipf->ipf_ecn = IPH_ECN_CE;
12487 	} else {
12488 		ipf->ipf_ecn = IPH_ECN_NECT;
12489 	}
12490 	if (offset && ipf->ipf_end == offset) {
12491 		/* The new fragment fits at the end */
12492 		ipf->ipf_tail_mp->b_cont = mp;
12493 		/* Update the byte count */
12494 		ipf->ipf_count += msg_len;
12495 		/* Update per ipfb and ill byte counts */
12496 		ipfb->ipfb_count += msg_len;
12497 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12498 		ill->ill_frag_count += msg_len;
12499 		if (frag_offset_flags & IPH_MF) {
12500 			/* More to come. */
12501 			ipf->ipf_end = end;
12502 			ipf->ipf_tail_mp = tail_mp;
12503 			goto reass_done;
12504 		}
12505 	} else {
12506 		/* Go do the hard cases. */
12507 		int ret;
12508 
12509 		if (offset == 0)
12510 			ipf->ipf_nf_hdr_len = hdr_length;
12511 
12512 		/* Save current byte count */
12513 		count = ipf->ipf_count;
12514 		ret = ip_reassemble(mp, ipf,
12515 		    (frag_offset_flags & IPH_OFFSET) << 3,
12516 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12517 		/* Count of bytes added and subtracted (freeb()ed) */
12518 		count = ipf->ipf_count - count;
12519 		if (count) {
12520 			/* Update per ipfb and ill byte counts */
12521 			ipfb->ipfb_count += count;
12522 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12523 			ill->ill_frag_count += count;
12524 		}
12525 		if (ret == IP_REASS_PARTIAL) {
12526 			goto reass_done;
12527 		} else if (ret == IP_REASS_FAILED) {
12528 			/* Reassembly failed. Free up all resources */
12529 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12530 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12531 				IP_REASS_SET_START(t_mp, 0);
12532 				IP_REASS_SET_END(t_mp, 0);
12533 			}
12534 			freemsg(mp);
12535 			goto reass_done;
12536 		}
12537 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12538 	}
12539 	/*
12540 	 * We have completed reassembly.  Unhook the frag header from
12541 	 * the reassembly list.
12542 	 *
12543 	 * Before we free the frag header, record the ECN info
12544 	 * to report back to the transport.
12545 	 */
12546 	ecn_info = ipf->ipf_ecn;
12547 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12548 	ipfp = ipf->ipf_ptphn;
12549 
12550 	/* We need to supply these to caller */
12551 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12552 		sum_val = ipf->ipf_checksum;
12553 	else
12554 		sum_val = 0;
12555 
12556 	mp1 = ipf->ipf_mp;
12557 	count = ipf->ipf_count;
12558 	ipf = ipf->ipf_hash_next;
12559 	if (ipf != NULL)
12560 		ipf->ipf_ptphn = ipfp;
12561 	ipfp[0] = ipf;
12562 	ill->ill_frag_count -= count;
12563 	ASSERT(ipfb->ipfb_count >= count);
12564 	ipfb->ipfb_count -= count;
12565 	ipfb->ipfb_frag_pkts--;
12566 	mutex_exit(&ipfb->ipfb_lock);
12567 	/* Ditch the frag header. */
12568 	mp = mp1->b_cont;
12569 
12570 	freeb(mp1);
12571 
12572 	/* Restore original IP length in header. */
12573 	packet_size = (uint32_t)msgdsize(mp);
12574 	if (packet_size > IP_MAXPACKET) {
12575 		freemsg(mp);
12576 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12577 		return (B_FALSE);
12578 	}
12579 
12580 	if (DB_REF(mp) > 1) {
12581 		mblk_t *mp2 = copymsg(mp);
12582 
12583 		freemsg(mp);
12584 		if (mp2 == NULL) {
12585 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12586 			return (B_FALSE);
12587 		}
12588 		mp = mp2;
12589 	}
12590 	ipha = (ipha_t *)mp->b_rptr;
12591 
12592 	ipha->ipha_length = htons((uint16_t)packet_size);
12593 	/* We're now complete, zip the frag state */
12594 	ipha->ipha_fragment_offset_and_flags = 0;
12595 	/* Record the ECN info. */
12596 	ipha->ipha_type_of_service &= 0xFC;
12597 	ipha->ipha_type_of_service |= ecn_info;
12598 	*mpp = mp;
12599 
12600 	/* Reassembly is successful; return checksum information if needed */
12601 	if (cksum_val != NULL)
12602 		*cksum_val = sum_val;
12603 	if (cksum_flags != NULL)
12604 		*cksum_flags = sum_flags;
12605 
12606 	return (B_TRUE);
12607 }
12608 
12609 /*
12610  * Perform ip header check sum update local options.
12611  * return B_TRUE if all is well, else return B_FALSE and release
12612  * the mp. caller is responsible for decrementing ire ref cnt.
12613  */
12614 static boolean_t
12615 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12616     ip_stack_t *ipst)
12617 {
12618 	mblk_t		*first_mp;
12619 	boolean_t	mctl_present;
12620 	uint16_t	sum;
12621 
12622 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12623 	/*
12624 	 * Don't do the checksum if it has gone through AH/ESP
12625 	 * processing.
12626 	 */
12627 	if (!mctl_present) {
12628 		sum = ip_csum_hdr(ipha);
12629 		if (sum != 0) {
12630 			if (ill != NULL) {
12631 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12632 			} else {
12633 				BUMP_MIB(&ipst->ips_ip_mib,
12634 				    ipIfStatsInCksumErrs);
12635 			}
12636 			freemsg(first_mp);
12637 			return (B_FALSE);
12638 		}
12639 	}
12640 
12641 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12642 		if (mctl_present)
12643 			freeb(first_mp);
12644 		return (B_FALSE);
12645 	}
12646 
12647 	return (B_TRUE);
12648 }
12649 
12650 /*
12651  * All udp packet are delivered to the local host via this routine.
12652  */
12653 void
12654 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12655     ill_t *recv_ill)
12656 {
12657 	uint32_t	sum;
12658 	uint32_t	u1;
12659 	boolean_t	mctl_present;
12660 	conn_t		*connp;
12661 	mblk_t		*first_mp;
12662 	uint16_t	*up;
12663 	ill_t		*ill = (ill_t *)q->q_ptr;
12664 	uint16_t	reass_hck_flags = 0;
12665 	ip_stack_t	*ipst;
12666 
12667 	ASSERT(recv_ill != NULL);
12668 	ipst = recv_ill->ill_ipst;
12669 
12670 #define	rptr    ((uchar_t *)ipha)
12671 
12672 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12673 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12674 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12675 	ASSERT(ill != NULL);
12676 
12677 	/*
12678 	 * FAST PATH for udp packets
12679 	 */
12680 
12681 	/* u1 is # words of IP options */
12682 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12683 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12684 
12685 	/* IP options present */
12686 	if (u1 != 0)
12687 		goto ipoptions;
12688 
12689 	/* Check the IP header checksum.  */
12690 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12691 		/* Clear the IP header h/w cksum flag */
12692 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12693 	} else if (!mctl_present) {
12694 		/*
12695 		 * Don't verify header checksum if this packet is coming
12696 		 * back from AH/ESP as we already did it.
12697 		 */
12698 #define	uph	((uint16_t *)ipha)
12699 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12700 		    uph[6] + uph[7] + uph[8] + uph[9];
12701 #undef	uph
12702 		/* finish doing IP checksum */
12703 		sum = (sum & 0xFFFF) + (sum >> 16);
12704 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12705 		if (sum != 0 && sum != 0xFFFF) {
12706 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12707 			freemsg(first_mp);
12708 			return;
12709 		}
12710 	}
12711 
12712 	/*
12713 	 * Count for SNMP of inbound packets for ire.
12714 	 * if mctl is present this might be a secure packet and
12715 	 * has already been counted for in ip_proto_input().
12716 	 */
12717 	if (!mctl_present) {
12718 		UPDATE_IB_PKT_COUNT(ire);
12719 		ire->ire_last_used_time = lbolt;
12720 	}
12721 
12722 	/* packet part of fragmented IP packet? */
12723 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12724 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12725 		goto fragmented;
12726 	}
12727 
12728 	/* u1 = IP header length (20 bytes) */
12729 	u1 = IP_SIMPLE_HDR_LENGTH;
12730 
12731 	/* packet does not contain complete IP & UDP headers */
12732 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12733 		goto udppullup;
12734 
12735 	/* up points to UDP header */
12736 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12737 #define	iphs    ((uint16_t *)ipha)
12738 
12739 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12740 	if (up[3] != 0) {
12741 		mblk_t *mp1 = mp->b_cont;
12742 		boolean_t cksum_err;
12743 		uint16_t hck_flags = 0;
12744 
12745 		/* Pseudo-header checksum */
12746 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12747 		    iphs[9] + up[2];
12748 
12749 		/*
12750 		 * Revert to software checksum calculation if the interface
12751 		 * isn't capable of checksum offload or if IPsec is present.
12752 		 */
12753 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12754 			hck_flags = DB_CKSUMFLAGS(mp);
12755 
12756 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12757 			IP_STAT(ipst, ip_in_sw_cksum);
12758 
12759 		IP_CKSUM_RECV(hck_flags, u1,
12760 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12761 		    (int32_t)((uchar_t *)up - rptr),
12762 		    mp, mp1, cksum_err);
12763 
12764 		if (cksum_err) {
12765 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12766 			if (hck_flags & HCK_FULLCKSUM)
12767 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12768 			else if (hck_flags & HCK_PARTIALCKSUM)
12769 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12770 			else
12771 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12772 
12773 			freemsg(first_mp);
12774 			return;
12775 		}
12776 	}
12777 
12778 	/* Non-fragmented broadcast or multicast packet? */
12779 	if (ire->ire_type == IRE_BROADCAST)
12780 		goto udpslowpath;
12781 
12782 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12783 	    ire->ire_zoneid, ipst)) != NULL) {
12784 		ASSERT(connp->conn_upq != NULL);
12785 		IP_STAT(ipst, ip_udp_fast_path);
12786 
12787 		if (CONN_UDP_FLOWCTLD(connp)) {
12788 			freemsg(mp);
12789 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12790 		} else {
12791 			if (!mctl_present) {
12792 				BUMP_MIB(ill->ill_ip_mib,
12793 				    ipIfStatsHCInDelivers);
12794 			}
12795 			/*
12796 			 * mp and first_mp can change.
12797 			 */
12798 			if (ip_udp_check(q, connp, recv_ill,
12799 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12800 				/* Send it upstream */
12801 				(connp->conn_recv)(connp, mp, NULL);
12802 			}
12803 		}
12804 		/*
12805 		 * freeb() cannot deal with null mblk being passed
12806 		 * in and first_mp can be set to null in the call
12807 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12808 		 */
12809 		if (mctl_present && first_mp != NULL) {
12810 			freeb(first_mp);
12811 		}
12812 		CONN_DEC_REF(connp);
12813 		return;
12814 	}
12815 
12816 	/*
12817 	 * if we got here we know the packet is not fragmented and
12818 	 * has no options. The classifier could not find a conn_t and
12819 	 * most likely its an icmp packet so send it through slow path.
12820 	 */
12821 
12822 	goto udpslowpath;
12823 
12824 ipoptions:
12825 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12826 		goto slow_done;
12827 	}
12828 
12829 	UPDATE_IB_PKT_COUNT(ire);
12830 	ire->ire_last_used_time = lbolt;
12831 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12832 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12833 fragmented:
12834 		/*
12835 		 * "sum" and "reass_hck_flags" are non-zero if the
12836 		 * reassembled packet has a valid hardware computed
12837 		 * checksum information associated with it.
12838 		 */
12839 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12840 			goto slow_done;
12841 		/*
12842 		 * Make sure that first_mp points back to mp as
12843 		 * the mp we came in with could have changed in
12844 		 * ip_rput_fragment().
12845 		 */
12846 		ASSERT(!mctl_present);
12847 		ipha = (ipha_t *)mp->b_rptr;
12848 		first_mp = mp;
12849 	}
12850 
12851 	/* Now we have a complete datagram, destined for this machine. */
12852 	u1 = IPH_HDR_LENGTH(ipha);
12853 	/* Pull up the UDP header, if necessary. */
12854 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12855 udppullup:
12856 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12857 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12858 			freemsg(first_mp);
12859 			goto slow_done;
12860 		}
12861 		ipha = (ipha_t *)mp->b_rptr;
12862 	}
12863 
12864 	/*
12865 	 * Validate the checksum for the reassembled packet; for the
12866 	 * pullup case we calculate the payload checksum in software.
12867 	 */
12868 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12869 	if (up[3] != 0) {
12870 		boolean_t cksum_err;
12871 
12872 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12873 			IP_STAT(ipst, ip_in_sw_cksum);
12874 
12875 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12876 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12877 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12878 		    iphs[9] + up[2], sum, cksum_err);
12879 
12880 		if (cksum_err) {
12881 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12882 
12883 			if (reass_hck_flags & HCK_FULLCKSUM)
12884 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12885 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12886 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12887 			else
12888 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12889 
12890 			freemsg(first_mp);
12891 			goto slow_done;
12892 		}
12893 	}
12894 udpslowpath:
12895 
12896 	/* Clear hardware checksum flag to be safe */
12897 	DB_CKSUMFLAGS(mp) = 0;
12898 
12899 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12900 	    (ire->ire_type == IRE_BROADCAST),
12901 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12902 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12903 
12904 slow_done:
12905 	IP_STAT(ipst, ip_udp_slow_path);
12906 	return;
12907 
12908 #undef  iphs
12909 #undef  rptr
12910 }
12911 
12912 /* ARGSUSED */
12913 static mblk_t *
12914 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12915     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12916     ill_rx_ring_t *ill_ring)
12917 {
12918 	conn_t		*connp;
12919 	uint32_t	sum;
12920 	uint32_t	u1;
12921 	uint16_t	*up;
12922 	int		offset;
12923 	ssize_t		len;
12924 	mblk_t		*mp1;
12925 	boolean_t	syn_present = B_FALSE;
12926 	tcph_t		*tcph;
12927 	uint_t		ip_hdr_len;
12928 	ill_t		*ill = (ill_t *)q->q_ptr;
12929 	zoneid_t	zoneid = ire->ire_zoneid;
12930 	boolean_t	cksum_err;
12931 	uint16_t	hck_flags = 0;
12932 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12933 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12934 
12935 #define	rptr	((uchar_t *)ipha)
12936 
12937 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12938 	ASSERT(ill != NULL);
12939 
12940 	/*
12941 	 * FAST PATH for tcp packets
12942 	 */
12943 
12944 	/* u1 is # words of IP options */
12945 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12946 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12947 
12948 	/* IP options present */
12949 	if (u1) {
12950 		goto ipoptions;
12951 	} else if (!mctl_present) {
12952 		/* Check the IP header checksum.  */
12953 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12954 			/* Clear the IP header h/w cksum flag */
12955 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12956 		} else if (!mctl_present) {
12957 			/*
12958 			 * Don't verify header checksum if this packet
12959 			 * is coming back from AH/ESP as we already did it.
12960 			 */
12961 #define	uph	((uint16_t *)ipha)
12962 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12963 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12964 #undef	uph
12965 			/* finish doing IP checksum */
12966 			sum = (sum & 0xFFFF) + (sum >> 16);
12967 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12968 			if (sum != 0 && sum != 0xFFFF) {
12969 				BUMP_MIB(ill->ill_ip_mib,
12970 				    ipIfStatsInCksumErrs);
12971 				goto error;
12972 			}
12973 		}
12974 	}
12975 
12976 	if (!mctl_present) {
12977 		UPDATE_IB_PKT_COUNT(ire);
12978 		ire->ire_last_used_time = lbolt;
12979 	}
12980 
12981 	/* packet part of fragmented IP packet? */
12982 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12983 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12984 		goto fragmented;
12985 	}
12986 
12987 	/* u1 = IP header length (20 bytes) */
12988 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12989 
12990 	/* does packet contain IP+TCP headers? */
12991 	len = mp->b_wptr - rptr;
12992 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12993 		IP_STAT(ipst, ip_tcppullup);
12994 		goto tcppullup;
12995 	}
12996 
12997 	/* TCP options present? */
12998 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12999 
13000 	/*
13001 	 * If options need to be pulled up, then goto tcpoptions.
13002 	 * otherwise we are still in the fast path
13003 	 */
13004 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13005 		IP_STAT(ipst, ip_tcpoptions);
13006 		goto tcpoptions;
13007 	}
13008 
13009 	/* multiple mblks of tcp data? */
13010 	if ((mp1 = mp->b_cont) != NULL) {
13011 		/* more then two? */
13012 		if (mp1->b_cont != NULL) {
13013 			IP_STAT(ipst, ip_multipkttcp);
13014 			goto multipkttcp;
13015 		}
13016 		len += mp1->b_wptr - mp1->b_rptr;
13017 	}
13018 
13019 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13020 
13021 	/* part of pseudo checksum */
13022 
13023 	/* TCP datagram length */
13024 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13025 
13026 #define	iphs    ((uint16_t *)ipha)
13027 
13028 #ifdef	_BIG_ENDIAN
13029 	u1 += IPPROTO_TCP;
13030 #else
13031 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13032 #endif
13033 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13034 
13035 	/*
13036 	 * Revert to software checksum calculation if the interface
13037 	 * isn't capable of checksum offload or if IPsec is present.
13038 	 */
13039 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13040 		hck_flags = DB_CKSUMFLAGS(mp);
13041 
13042 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13043 		IP_STAT(ipst, ip_in_sw_cksum);
13044 
13045 	IP_CKSUM_RECV(hck_flags, u1,
13046 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13047 	    (int32_t)((uchar_t *)up - rptr),
13048 	    mp, mp1, cksum_err);
13049 
13050 	if (cksum_err) {
13051 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13052 
13053 		if (hck_flags & HCK_FULLCKSUM)
13054 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13055 		else if (hck_flags & HCK_PARTIALCKSUM)
13056 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13057 		else
13058 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13059 
13060 		goto error;
13061 	}
13062 
13063 try_again:
13064 
13065 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13066 	    zoneid, ipst)) == NULL) {
13067 		/* Send the TH_RST */
13068 		goto no_conn;
13069 	}
13070 
13071 	/*
13072 	 * TCP FAST PATH for AF_INET socket.
13073 	 *
13074 	 * TCP fast path to avoid extra work. An AF_INET socket type
13075 	 * does not have facility to receive extra information via
13076 	 * ip_process or ip_add_info. Also, when the connection was
13077 	 * established, we made a check if this connection is impacted
13078 	 * by any global IPsec policy or per connection policy (a
13079 	 * policy that comes in effect later will not apply to this
13080 	 * connection). Since all this can be determined at the
13081 	 * connection establishment time, a quick check of flags
13082 	 * can avoid extra work.
13083 	 */
13084 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13085 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13086 		ASSERT(first_mp == mp);
13087 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13088 		SET_SQUEUE(mp, tcp_rput_data, connp);
13089 		return (mp);
13090 	}
13091 
13092 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13093 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13094 		if (IPCL_IS_TCP(connp)) {
13095 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13096 			DB_CKSUMSTART(mp) =
13097 			    (intptr_t)ip_squeue_get(ill_ring);
13098 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13099 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13100 				BUMP_MIB(ill->ill_ip_mib,
13101 				    ipIfStatsHCInDelivers);
13102 				SET_SQUEUE(mp, connp->conn_recv, connp);
13103 				return (mp);
13104 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13105 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13106 				BUMP_MIB(ill->ill_ip_mib,
13107 				    ipIfStatsHCInDelivers);
13108 				ip_squeue_enter_unbound++;
13109 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13110 				    connp);
13111 				return (mp);
13112 			}
13113 			syn_present = B_TRUE;
13114 		}
13115 
13116 	}
13117 
13118 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13119 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13120 
13121 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13122 		/* No need to send this packet to TCP */
13123 		if ((flags & TH_RST) || (flags & TH_URG)) {
13124 			CONN_DEC_REF(connp);
13125 			freemsg(first_mp);
13126 			return (NULL);
13127 		}
13128 		if (flags & TH_ACK) {
13129 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13130 			    ipst->ips_netstack->netstack_tcp, connp);
13131 			CONN_DEC_REF(connp);
13132 			return (NULL);
13133 		}
13134 
13135 		CONN_DEC_REF(connp);
13136 		freemsg(first_mp);
13137 		return (NULL);
13138 	}
13139 
13140 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13141 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13142 		    ipha, NULL, mctl_present);
13143 		if (first_mp == NULL) {
13144 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13145 			CONN_DEC_REF(connp);
13146 			return (NULL);
13147 		}
13148 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13149 			ASSERT(syn_present);
13150 			if (mctl_present) {
13151 				ASSERT(first_mp != mp);
13152 				first_mp->b_datap->db_struioflag |=
13153 				    STRUIO_POLICY;
13154 			} else {
13155 				ASSERT(first_mp == mp);
13156 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13157 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13158 			}
13159 		} else {
13160 			/*
13161 			 * Discard first_mp early since we're dealing with a
13162 			 * fully-connected conn_t and tcp doesn't do policy in
13163 			 * this case.
13164 			 */
13165 			if (mctl_present) {
13166 				freeb(first_mp);
13167 				mctl_present = B_FALSE;
13168 			}
13169 			first_mp = mp;
13170 		}
13171 	}
13172 
13173 	/* Initiate IPPF processing for fastpath */
13174 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13175 		uint32_t	ill_index;
13176 
13177 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13178 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13179 		if (mp == NULL) {
13180 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13181 			    "deferred/dropped during IPPF processing\n"));
13182 			CONN_DEC_REF(connp);
13183 			if (mctl_present)
13184 				freeb(first_mp);
13185 			return (NULL);
13186 		} else if (mctl_present) {
13187 			/*
13188 			 * ip_process might return a new mp.
13189 			 */
13190 			ASSERT(first_mp != mp);
13191 			first_mp->b_cont = mp;
13192 		} else {
13193 			first_mp = mp;
13194 		}
13195 
13196 	}
13197 
13198 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13199 		/*
13200 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13201 		 * make sure IPF_RECVIF is passed to ip_add_info.
13202 		 */
13203 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13204 		    IPCL_ZONEID(connp), ipst);
13205 		if (mp == NULL) {
13206 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13207 			CONN_DEC_REF(connp);
13208 			if (mctl_present)
13209 				freeb(first_mp);
13210 			return (NULL);
13211 		} else if (mctl_present) {
13212 			/*
13213 			 * ip_add_info might return a new mp.
13214 			 */
13215 			ASSERT(first_mp != mp);
13216 			first_mp->b_cont = mp;
13217 		} else {
13218 			first_mp = mp;
13219 		}
13220 	}
13221 
13222 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13223 	if (IPCL_IS_TCP(connp)) {
13224 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13225 		return (first_mp);
13226 	} else {
13227 		/* SOCK_RAW, IPPROTO_TCP case */
13228 		(connp->conn_recv)(connp, first_mp, NULL);
13229 		CONN_DEC_REF(connp);
13230 		return (NULL);
13231 	}
13232 
13233 no_conn:
13234 	/* Initiate IPPf processing, if needed. */
13235 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13236 		uint32_t ill_index;
13237 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13238 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13239 		if (first_mp == NULL) {
13240 			return (NULL);
13241 		}
13242 	}
13243 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13244 
13245 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13246 	    ipst->ips_netstack->netstack_tcp, NULL);
13247 	return (NULL);
13248 ipoptions:
13249 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13250 		goto slow_done;
13251 	}
13252 
13253 	UPDATE_IB_PKT_COUNT(ire);
13254 	ire->ire_last_used_time = lbolt;
13255 
13256 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13257 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13258 fragmented:
13259 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13260 			if (mctl_present)
13261 				freeb(first_mp);
13262 			goto slow_done;
13263 		}
13264 		/*
13265 		 * Make sure that first_mp points back to mp as
13266 		 * the mp we came in with could have changed in
13267 		 * ip_rput_fragment().
13268 		 */
13269 		ASSERT(!mctl_present);
13270 		ipha = (ipha_t *)mp->b_rptr;
13271 		first_mp = mp;
13272 	}
13273 
13274 	/* Now we have a complete datagram, destined for this machine. */
13275 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13276 
13277 	len = mp->b_wptr - mp->b_rptr;
13278 	/* Pull up a minimal TCP header, if necessary. */
13279 	if (len < (u1 + 20)) {
13280 tcppullup:
13281 		if (!pullupmsg(mp, u1 + 20)) {
13282 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13283 			goto error;
13284 		}
13285 		ipha = (ipha_t *)mp->b_rptr;
13286 		len = mp->b_wptr - mp->b_rptr;
13287 	}
13288 
13289 	/*
13290 	 * Extract the offset field from the TCP header.  As usual, we
13291 	 * try to help the compiler more than the reader.
13292 	 */
13293 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13294 	if (offset != 5) {
13295 tcpoptions:
13296 		if (offset < 5) {
13297 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13298 			goto error;
13299 		}
13300 		/*
13301 		 * There must be TCP options.
13302 		 * Make sure we can grab them.
13303 		 */
13304 		offset <<= 2;
13305 		offset += u1;
13306 		if (len < offset) {
13307 			if (!pullupmsg(mp, offset)) {
13308 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13309 				goto error;
13310 			}
13311 			ipha = (ipha_t *)mp->b_rptr;
13312 			len = mp->b_wptr - rptr;
13313 		}
13314 	}
13315 
13316 	/* Get the total packet length in len, including headers. */
13317 	if (mp->b_cont) {
13318 multipkttcp:
13319 		len = msgdsize(mp);
13320 	}
13321 
13322 	/*
13323 	 * Check the TCP checksum by pulling together the pseudo-
13324 	 * header checksum, and passing it to ip_csum to be added in
13325 	 * with the TCP datagram.
13326 	 *
13327 	 * Since we are not using the hwcksum if available we must
13328 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13329 	 * If either of these fails along the way the mblk is freed.
13330 	 * If this logic ever changes and mblk is reused to say send
13331 	 * ICMP's back, then this flag may need to be cleared in
13332 	 * other places as well.
13333 	 */
13334 	DB_CKSUMFLAGS(mp) = 0;
13335 
13336 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13337 
13338 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13339 #ifdef	_BIG_ENDIAN
13340 	u1 += IPPROTO_TCP;
13341 #else
13342 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13343 #endif
13344 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13345 	/*
13346 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13347 	 */
13348 	IP_STAT(ipst, ip_in_sw_cksum);
13349 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13350 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13351 		goto error;
13352 	}
13353 
13354 	IP_STAT(ipst, ip_tcp_slow_path);
13355 	goto try_again;
13356 #undef  iphs
13357 #undef  rptr
13358 
13359 error:
13360 	freemsg(first_mp);
13361 slow_done:
13362 	return (NULL);
13363 }
13364 
13365 /* ARGSUSED */
13366 static void
13367 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13368     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13369 {
13370 	conn_t		*connp;
13371 	uint32_t	sum;
13372 	uint32_t	u1;
13373 	ssize_t		len;
13374 	sctp_hdr_t	*sctph;
13375 	zoneid_t	zoneid = ire->ire_zoneid;
13376 	uint32_t	pktsum;
13377 	uint32_t	calcsum;
13378 	uint32_t	ports;
13379 	in6_addr_t	map_src, map_dst;
13380 	ill_t		*ill = (ill_t *)q->q_ptr;
13381 	ip_stack_t	*ipst;
13382 	sctp_stack_t	*sctps;
13383 	boolean_t	sctp_csum_err = B_FALSE;
13384 
13385 	ASSERT(recv_ill != NULL);
13386 	ipst = recv_ill->ill_ipst;
13387 	sctps = ipst->ips_netstack->netstack_sctp;
13388 
13389 #define	rptr	((uchar_t *)ipha)
13390 
13391 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13392 	ASSERT(ill != NULL);
13393 
13394 	/* u1 is # words of IP options */
13395 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13396 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13397 
13398 	/* IP options present */
13399 	if (u1 > 0) {
13400 		goto ipoptions;
13401 	} else {
13402 		/* Check the IP header checksum.  */
13403 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13404 		    !mctl_present) {
13405 #define	uph	((uint16_t *)ipha)
13406 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13407 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13408 #undef	uph
13409 			/* finish doing IP checksum */
13410 			sum = (sum & 0xFFFF) + (sum >> 16);
13411 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13412 			/*
13413 			 * Don't verify header checksum if this packet
13414 			 * is coming back from AH/ESP as we already did it.
13415 			 */
13416 			if (sum != 0 && sum != 0xFFFF) {
13417 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13418 				goto error;
13419 			}
13420 		}
13421 		/*
13422 		 * Since there is no SCTP h/w cksum support yet, just
13423 		 * clear the flag.
13424 		 */
13425 		DB_CKSUMFLAGS(mp) = 0;
13426 	}
13427 
13428 	/*
13429 	 * Don't verify header checksum if this packet is coming
13430 	 * back from AH/ESP as we already did it.
13431 	 */
13432 	if (!mctl_present) {
13433 		UPDATE_IB_PKT_COUNT(ire);
13434 		ire->ire_last_used_time = lbolt;
13435 	}
13436 
13437 	/* packet part of fragmented IP packet? */
13438 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13439 	if (u1 & (IPH_MF | IPH_OFFSET))
13440 		goto fragmented;
13441 
13442 	/* u1 = IP header length (20 bytes) */
13443 	u1 = IP_SIMPLE_HDR_LENGTH;
13444 
13445 find_sctp_client:
13446 	/* Pullup if we don't have the sctp common header. */
13447 	len = MBLKL(mp);
13448 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13449 		if (mp->b_cont == NULL ||
13450 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13451 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13452 			goto error;
13453 		}
13454 		ipha = (ipha_t *)mp->b_rptr;
13455 		len = MBLKL(mp);
13456 	}
13457 
13458 	sctph = (sctp_hdr_t *)(rptr + u1);
13459 #ifdef	DEBUG
13460 	if (!skip_sctp_cksum) {
13461 #endif
13462 		pktsum = sctph->sh_chksum;
13463 		sctph->sh_chksum = 0;
13464 		calcsum = sctp_cksum(mp, u1);
13465 		sctph->sh_chksum = pktsum;
13466 		if (calcsum != pktsum)
13467 			sctp_csum_err = B_TRUE;
13468 #ifdef	DEBUG	/* skip_sctp_cksum */
13469 	}
13470 #endif
13471 	/* get the ports */
13472 	ports = *(uint32_t *)&sctph->sh_sport;
13473 
13474 	IRE_REFRELE(ire);
13475 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13476 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13477 	if (sctp_csum_err) {
13478 		/*
13479 		 * No potential sctp checksum errors go to the Sun
13480 		 * sctp stack however they might be Adler-32 summed
13481 		 * packets a userland stack bound to a raw IP socket
13482 		 * could reasonably use. Note though that Adler-32 is
13483 		 * a long deprecated algorithm and customer sctp
13484 		 * networks should eventually migrate to CRC-32 at
13485 		 * which time this facility should be removed.
13486 		 */
13487 		flags |= IP_FF_SCTP_CSUM_ERR;
13488 		goto no_conn;
13489 	}
13490 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13491 	    sctps)) == NULL) {
13492 		/* Check for raw socket or OOTB handling */
13493 		goto no_conn;
13494 	}
13495 
13496 	/* Found a client; up it goes */
13497 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13498 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13499 	return;
13500 
13501 no_conn:
13502 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13503 	    ports, mctl_present, flags, B_TRUE, zoneid);
13504 	return;
13505 
13506 ipoptions:
13507 	DB_CKSUMFLAGS(mp) = 0;
13508 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13509 		goto slow_done;
13510 
13511 	UPDATE_IB_PKT_COUNT(ire);
13512 	ire->ire_last_used_time = lbolt;
13513 
13514 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13515 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13516 fragmented:
13517 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13518 			goto slow_done;
13519 		/*
13520 		 * Make sure that first_mp points back to mp as
13521 		 * the mp we came in with could have changed in
13522 		 * ip_rput_fragment().
13523 		 */
13524 		ASSERT(!mctl_present);
13525 		ipha = (ipha_t *)mp->b_rptr;
13526 		first_mp = mp;
13527 	}
13528 
13529 	/* Now we have a complete datagram, destined for this machine. */
13530 	u1 = IPH_HDR_LENGTH(ipha);
13531 	goto find_sctp_client;
13532 #undef  iphs
13533 #undef  rptr
13534 
13535 error:
13536 	freemsg(first_mp);
13537 slow_done:
13538 	IRE_REFRELE(ire);
13539 }
13540 
13541 #define	VER_BITS	0xF0
13542 #define	VERSION_6	0x60
13543 
13544 static boolean_t
13545 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13546     ipaddr_t *dstp, ip_stack_t *ipst)
13547 {
13548 	uint_t	opt_len;
13549 	ipha_t *ipha;
13550 	ssize_t len;
13551 	uint_t	pkt_len;
13552 
13553 	ASSERT(ill != NULL);
13554 	IP_STAT(ipst, ip_ipoptions);
13555 	ipha = *iphapp;
13556 
13557 #define	rptr    ((uchar_t *)ipha)
13558 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13559 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13560 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13561 		freemsg(mp);
13562 		return (B_FALSE);
13563 	}
13564 
13565 	/* multiple mblk or too short */
13566 	pkt_len = ntohs(ipha->ipha_length);
13567 
13568 	/* Get the number of words of IP options in the IP header. */
13569 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13570 	if (opt_len) {
13571 		/* IP Options present!  Validate and process. */
13572 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13573 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13574 			goto done;
13575 		}
13576 		/*
13577 		 * Recompute complete header length and make sure we
13578 		 * have access to all of it.
13579 		 */
13580 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13581 		if (len > (mp->b_wptr - rptr)) {
13582 			if (len > pkt_len) {
13583 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13584 				goto done;
13585 			}
13586 			if (!pullupmsg(mp, len)) {
13587 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13588 				goto done;
13589 			}
13590 			ipha = (ipha_t *)mp->b_rptr;
13591 		}
13592 		/*
13593 		 * Go off to ip_rput_options which returns the next hop
13594 		 * destination address, which may have been affected
13595 		 * by source routing.
13596 		 */
13597 		IP_STAT(ipst, ip_opt);
13598 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13599 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13600 			return (B_FALSE);
13601 		}
13602 	}
13603 	*iphapp = ipha;
13604 	return (B_TRUE);
13605 done:
13606 	/* clear b_prev - used by ip_mroute_decap */
13607 	mp->b_prev = NULL;
13608 	freemsg(mp);
13609 	return (B_FALSE);
13610 #undef  rptr
13611 }
13612 
13613 /*
13614  * Deal with the fact that there is no ire for the destination.
13615  */
13616 static ire_t *
13617 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13618 {
13619 	ipha_t	*ipha;
13620 	ill_t	*ill;
13621 	ire_t	*ire;
13622 	ip_stack_t *ipst;
13623 	enum	ire_forward_action ret_action;
13624 
13625 	ipha = (ipha_t *)mp->b_rptr;
13626 	ill = (ill_t *)q->q_ptr;
13627 
13628 	ASSERT(ill != NULL);
13629 	ipst = ill->ill_ipst;
13630 
13631 	/*
13632 	 * No IRE for this destination, so it can't be for us.
13633 	 * Unless we are forwarding, drop the packet.
13634 	 * We have to let source routed packets through
13635 	 * since we don't yet know if they are 'ping -l'
13636 	 * packets i.e. if they will go out over the
13637 	 * same interface as they came in on.
13638 	 */
13639 	if (ll_multicast) {
13640 		freemsg(mp);
13641 		return (NULL);
13642 	}
13643 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13644 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13645 		freemsg(mp);
13646 		return (NULL);
13647 	}
13648 
13649 	/*
13650 	 * Mark this packet as having originated externally.
13651 	 *
13652 	 * For non-forwarding code path, ire_send later double
13653 	 * checks this interface to see if it is still exists
13654 	 * post-ARP resolution.
13655 	 *
13656 	 * Also, IPQOS uses this to differentiate between
13657 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13658 	 * QOS packet processing in ip_wput_attach_llhdr().
13659 	 * The QoS module can mark the b_band for a fastpath message
13660 	 * or the dl_priority field in a unitdata_req header for
13661 	 * CoS marking. This info can only be found in
13662 	 * ip_wput_attach_llhdr().
13663 	 */
13664 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13665 	/*
13666 	 * Clear the indication that this may have a hardware checksum
13667 	 * as we are not using it
13668 	 */
13669 	DB_CKSUMFLAGS(mp) = 0;
13670 
13671 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13672 	    MBLK_GETLABEL(mp), ipst);
13673 
13674 	if (ire == NULL && ret_action == Forward_check_multirt) {
13675 		/* Let ip_newroute handle CGTP  */
13676 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13677 		return (NULL);
13678 	}
13679 
13680 	if (ire != NULL)
13681 		return (ire);
13682 
13683 	mp->b_prev = mp->b_next = 0;
13684 
13685 	if (ret_action == Forward_blackhole) {
13686 		freemsg(mp);
13687 		return (NULL);
13688 	}
13689 	/* send icmp unreachable */
13690 	q = WR(q);
13691 	/* Sent by forwarding path, and router is global zone */
13692 	if (ip_source_routed(ipha, ipst)) {
13693 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13694 		    GLOBAL_ZONEID, ipst);
13695 	} else {
13696 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13697 		    ipst);
13698 	}
13699 
13700 	return (NULL);
13701 
13702 }
13703 
13704 /*
13705  * check ip header length and align it.
13706  */
13707 static boolean_t
13708 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13709 {
13710 	ssize_t len;
13711 	ill_t *ill;
13712 	ipha_t	*ipha;
13713 
13714 	len = MBLKL(mp);
13715 
13716 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13717 		ill = (ill_t *)q->q_ptr;
13718 
13719 		if (!OK_32PTR(mp->b_rptr))
13720 			IP_STAT(ipst, ip_notaligned1);
13721 		else
13722 			IP_STAT(ipst, ip_notaligned2);
13723 		/* Guard against bogus device drivers */
13724 		if (len < 0) {
13725 			/* clear b_prev - used by ip_mroute_decap */
13726 			mp->b_prev = NULL;
13727 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13728 			freemsg(mp);
13729 			return (B_FALSE);
13730 		}
13731 
13732 		if (ip_rput_pullups++ == 0) {
13733 			ipha = (ipha_t *)mp->b_rptr;
13734 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13735 			    "ip_check_and_align_header: %s forced us to "
13736 			    " pullup pkt, hdr len %ld, hdr addr %p",
13737 			    ill->ill_name, len, ipha);
13738 		}
13739 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13740 			/* clear b_prev - used by ip_mroute_decap */
13741 			mp->b_prev = NULL;
13742 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13743 			freemsg(mp);
13744 			return (B_FALSE);
13745 		}
13746 	}
13747 	return (B_TRUE);
13748 }
13749 
13750 ire_t *
13751 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13752 {
13753 	ire_t		*new_ire;
13754 	ill_t		*ire_ill;
13755 	uint_t		ifindex;
13756 	ip_stack_t	*ipst = ill->ill_ipst;
13757 	boolean_t	strict_check = B_FALSE;
13758 
13759 	/*
13760 	 * This packet came in on an interface other than the one associated
13761 	 * with the first ire we found for the destination address. We do
13762 	 * another ire lookup here, using the ingress ill, to see if the
13763 	 * interface is in an interface group.
13764 	 * As long as the ills belong to the same group, we don't consider
13765 	 * them to be arriving on the wrong interface. Thus, if the switch
13766 	 * is doing inbound load spreading, we won't drop packets when the
13767 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13768 	 * for 'usesrc groups' where the destination address may belong to
13769 	 * another interface to allow multipathing to happen.
13770 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13771 	 * where the local address may not be unique. In this case we were
13772 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13773 	 * actually returned. The new lookup, which is more specific, should
13774 	 * only find the IRE_LOCAL associated with the ingress ill if one
13775 	 * exists.
13776 	 */
13777 
13778 	if (ire->ire_ipversion == IPV4_VERSION) {
13779 		if (ipst->ips_ip_strict_dst_multihoming)
13780 			strict_check = B_TRUE;
13781 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13782 		    ill->ill_ipif, ALL_ZONES, NULL,
13783 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13784 	} else {
13785 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13786 		if (ipst->ips_ipv6_strict_dst_multihoming)
13787 			strict_check = B_TRUE;
13788 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13789 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13790 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13791 	}
13792 	/*
13793 	 * If the same ire that was returned in ip_input() is found then this
13794 	 * is an indication that interface groups are in use. The packet
13795 	 * arrived on a different ill in the group than the one associated with
13796 	 * the destination address.  If a different ire was found then the same
13797 	 * IP address must be hosted on multiple ills. This is possible with
13798 	 * unnumbered point2point interfaces. We switch to use this new ire in
13799 	 * order to have accurate interface statistics.
13800 	 */
13801 	if (new_ire != NULL) {
13802 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13803 			ire_refrele(ire);
13804 			ire = new_ire;
13805 		} else {
13806 			ire_refrele(new_ire);
13807 		}
13808 		return (ire);
13809 	} else if ((ire->ire_rfq == NULL) &&
13810 	    (ire->ire_ipversion == IPV4_VERSION)) {
13811 		/*
13812 		 * The best match could have been the original ire which
13813 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13814 		 * the strict multihoming checks are irrelevant as we consider
13815 		 * local addresses hosted on lo0 to be interface agnostic. We
13816 		 * only expect a null ire_rfq on IREs which are associated with
13817 		 * lo0 hence we can return now.
13818 		 */
13819 		return (ire);
13820 	}
13821 
13822 	/*
13823 	 * Chase pointers once and store locally.
13824 	 */
13825 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13826 	    (ill_t *)(ire->ire_rfq->q_ptr);
13827 	ifindex = ill->ill_usesrc_ifindex;
13828 
13829 	/*
13830 	 * Check if it's a legal address on the 'usesrc' interface.
13831 	 */
13832 	if ((ifindex != 0) && (ire_ill != NULL) &&
13833 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13834 		return (ire);
13835 	}
13836 
13837 	/*
13838 	 * If the ip*_strict_dst_multihoming switch is on then we can
13839 	 * only accept this packet if the interface is marked as routing.
13840 	 */
13841 	if (!(strict_check))
13842 		return (ire);
13843 
13844 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13845 	    ILLF_ROUTER) != 0) {
13846 		return (ire);
13847 	}
13848 
13849 	ire_refrele(ire);
13850 	return (NULL);
13851 }
13852 
13853 ire_t *
13854 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13855 {
13856 	ipha_t	*ipha;
13857 	ire_t	*src_ire;
13858 	ill_t	*stq_ill;
13859 	uint_t	hlen;
13860 	uint_t	pkt_len;
13861 	uint32_t sum;
13862 	queue_t	*dev_q;
13863 	ip_stack_t *ipst = ill->ill_ipst;
13864 	mblk_t *fpmp;
13865 	enum	ire_forward_action ret_action;
13866 
13867 	ipha = (ipha_t *)mp->b_rptr;
13868 
13869 	/*
13870 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13871 	 * The loopback address check for both src and dst has already
13872 	 * been checked in ip_input
13873 	 */
13874 
13875 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13876 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13877 		goto drop;
13878 	}
13879 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13880 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13881 
13882 	if (src_ire != NULL) {
13883 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13884 		ire_refrele(src_ire);
13885 		goto drop;
13886 	}
13887 
13888 
13889 	/* No ire cache of nexthop. So first create one  */
13890 	if (ire == NULL) {
13891 
13892 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13893 		    NULL, ipst);
13894 		/*
13895 		 * We only come to ip_fast_forward if ip_cgtp_filter
13896 		 * is not set. So ire_forward() should not return with
13897 		 * Forward_check_multirt as the next action.
13898 		 */
13899 		ASSERT(ret_action != Forward_check_multirt);
13900 		if (ire == NULL) {
13901 			/* An attempt was made to forward the packet */
13902 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13903 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13904 			mp->b_prev = mp->b_next = 0;
13905 			/* send icmp unreachable */
13906 			/* Sent by forwarding path, and router is global zone */
13907 			if (ret_action == Forward_ret_icmp_err) {
13908 				if (ip_source_routed(ipha, ipst)) {
13909 					icmp_unreachable(ill->ill_wq, mp,
13910 					    ICMP_SOURCE_ROUTE_FAILED,
13911 					    GLOBAL_ZONEID, ipst);
13912 				} else {
13913 					icmp_unreachable(ill->ill_wq, mp,
13914 					    ICMP_HOST_UNREACHABLE,
13915 					    GLOBAL_ZONEID, ipst);
13916 				}
13917 			} else {
13918 				freemsg(mp);
13919 			}
13920 			return (NULL);
13921 		}
13922 	}
13923 
13924 	/*
13925 	 * Forwarding fastpath exception case:
13926 	 * If either of the follwoing case is true, we take
13927 	 * the slowpath
13928 	 *	o forwarding is not enabled
13929 	 *	o incoming and outgoing interface are the same, or the same
13930 	 *	  IPMP group
13931 	 *	o corresponding ire is in incomplete state
13932 	 *	o packet needs fragmentation
13933 	 *	o ARP cache is not resolved
13934 	 *
13935 	 * The codeflow from here on is thus:
13936 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13937 	 */
13938 	pkt_len = ntohs(ipha->ipha_length);
13939 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13940 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13941 	    !(ill->ill_flags & ILLF_ROUTER) ||
13942 	    (ill == stq_ill) ||
13943 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13944 	    (ire->ire_nce == NULL) ||
13945 	    (pkt_len > ire->ire_max_frag) ||
13946 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13947 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13948 	    ipha->ipha_ttl <= 1) {
13949 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13950 		    ipha, ill, B_FALSE);
13951 		return (ire);
13952 	}
13953 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13954 
13955 	DTRACE_PROBE4(ip4__forwarding__start,
13956 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13957 
13958 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13959 	    ipst->ips_ipv4firewall_forwarding,
13960 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13961 
13962 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13963 
13964 	if (mp == NULL)
13965 		goto drop;
13966 
13967 	mp->b_datap->db_struioun.cksum.flags = 0;
13968 	/* Adjust the checksum to reflect the ttl decrement. */
13969 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13970 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13971 	ipha->ipha_ttl--;
13972 
13973 	/*
13974 	 * Write the link layer header.  We can do this safely here,
13975 	 * because we have already tested to make sure that the IP
13976 	 * policy is not set, and that we have a fast path destination
13977 	 * header.
13978 	 */
13979 	mp->b_rptr -= hlen;
13980 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13981 
13982 	UPDATE_IB_PKT_COUNT(ire);
13983 	ire->ire_last_used_time = lbolt;
13984 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13985 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13986 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13987 
13988 	dev_q = ire->ire_stq->q_next;
13989 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
13990 	    !canputnext(ire->ire_stq)) {
13991 		goto indiscard;
13992 	}
13993 	if (ILL_DLS_CAPABLE(stq_ill)) {
13994 		/*
13995 		 * Send the packet directly to DLD, where it
13996 		 * may be queued depending on the availability
13997 		 * of transmit resources at the media layer.
13998 		 */
13999 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
14000 	} else {
14001 		DTRACE_PROBE4(ip4__physical__out__start,
14002 		    ill_t *, NULL, ill_t *, stq_ill,
14003 		    ipha_t *, ipha, mblk_t *, mp);
14004 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14005 		    ipst->ips_ipv4firewall_physical_out,
14006 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14007 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14008 		if (mp == NULL)
14009 			goto drop;
14010 		putnext(ire->ire_stq, mp);
14011 	}
14012 	return (ire);
14013 
14014 indiscard:
14015 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14016 drop:
14017 	if (mp != NULL)
14018 		freemsg(mp);
14019 	return (ire);
14020 
14021 }
14022 
14023 /*
14024  * This function is called in the forwarding slowpath, when
14025  * either the ire lacks the link-layer address, or the packet needs
14026  * further processing(eg. fragmentation), before transmission.
14027  */
14028 
14029 static void
14030 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14031     ill_t *ill, boolean_t ll_multicast)
14032 {
14033 	ill_group_t	*ill_group;
14034 	ill_group_t	*ire_group;
14035 	queue_t		*dev_q;
14036 	ire_t		*src_ire;
14037 	ip_stack_t	*ipst = ill->ill_ipst;
14038 
14039 	ASSERT(ire->ire_stq != NULL);
14040 
14041 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14042 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14043 
14044 	if (ll_multicast != 0) {
14045 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14046 		goto drop_pkt;
14047 	}
14048 
14049 	/*
14050 	 * check if ipha_src is a broadcast address. Note that this
14051 	 * check is redundant when we get here from ip_fast_forward()
14052 	 * which has already done this check. However, since we can
14053 	 * also get here from ip_rput_process_broadcast() or, for
14054 	 * for the slow path through ip_fast_forward(), we perform
14055 	 * the check again for code-reusability
14056 	 */
14057 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14058 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14059 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14060 		if (src_ire != NULL)
14061 			ire_refrele(src_ire);
14062 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14063 		ip2dbg(("ip_rput_process_forward: Received packet with"
14064 		    " bad src/dst address on %s\n", ill->ill_name));
14065 		goto drop_pkt;
14066 	}
14067 
14068 	ill_group = ill->ill_group;
14069 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14070 	/*
14071 	 * Check if we want to forward this one at this time.
14072 	 * We allow source routed packets on a host provided that
14073 	 * they go out the same interface or same interface group
14074 	 * as they came in on.
14075 	 *
14076 	 * XXX To be quicker, we may wish to not chase pointers to
14077 	 * get the ILLF_ROUTER flag and instead store the
14078 	 * forwarding policy in the ire.  An unfortunate
14079 	 * side-effect of that would be requiring an ire flush
14080 	 * whenever the ILLF_ROUTER flag changes.
14081 	 */
14082 	if (((ill->ill_flags &
14083 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14084 	    ILLF_ROUTER) == 0) &&
14085 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14086 	    (ill_group != NULL && ill_group == ire_group)))) {
14087 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14088 		if (ip_source_routed(ipha, ipst)) {
14089 			q = WR(q);
14090 			/*
14091 			 * Clear the indication that this may have
14092 			 * hardware checksum as we are not using it.
14093 			 */
14094 			DB_CKSUMFLAGS(mp) = 0;
14095 			/* Sent by forwarding path, and router is global zone */
14096 			icmp_unreachable(q, mp,
14097 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14098 			return;
14099 		}
14100 		goto drop_pkt;
14101 	}
14102 
14103 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14104 
14105 	/* Packet is being forwarded. Turning off hwcksum flag. */
14106 	DB_CKSUMFLAGS(mp) = 0;
14107 	if (ipst->ips_ip_g_send_redirects) {
14108 		/*
14109 		 * Check whether the incoming interface and outgoing
14110 		 * interface is part of the same group. If so,
14111 		 * send redirects.
14112 		 *
14113 		 * Check the source address to see if it originated
14114 		 * on the same logical subnet it is going back out on.
14115 		 * If so, we should be able to send it a redirect.
14116 		 * Avoid sending a redirect if the destination
14117 		 * is directly connected (i.e., ipha_dst is the same
14118 		 * as ire_gateway_addr or the ire_addr of the
14119 		 * nexthop IRE_CACHE ), or if the packet was source
14120 		 * routed out this interface.
14121 		 */
14122 		ipaddr_t src, nhop;
14123 		mblk_t	*mp1;
14124 		ire_t	*nhop_ire = NULL;
14125 
14126 		/*
14127 		 * Check whether ire_rfq and q are from the same ill
14128 		 * or if they are not same, they at least belong
14129 		 * to the same group. If so, send redirects.
14130 		 */
14131 		if ((ire->ire_rfq == q ||
14132 		    (ill_group != NULL && ill_group == ire_group)) &&
14133 		    !ip_source_routed(ipha, ipst)) {
14134 
14135 			nhop = (ire->ire_gateway_addr != 0 ?
14136 			    ire->ire_gateway_addr : ire->ire_addr);
14137 
14138 			if (ipha->ipha_dst == nhop) {
14139 				/*
14140 				 * We avoid sending a redirect if the
14141 				 * destination is directly connected
14142 				 * because it is possible that multiple
14143 				 * IP subnets may have been configured on
14144 				 * the link, and the source may not
14145 				 * be on the same subnet as ip destination,
14146 				 * even though they are on the same
14147 				 * physical link.
14148 				 */
14149 				goto sendit;
14150 			}
14151 
14152 			src = ipha->ipha_src;
14153 
14154 			/*
14155 			 * We look up the interface ire for the nexthop,
14156 			 * to see if ipha_src is in the same subnet
14157 			 * as the nexthop.
14158 			 *
14159 			 * Note that, if, in the future, IRE_CACHE entries
14160 			 * are obsoleted,  this lookup will not be needed,
14161 			 * as the ire passed to this function will be the
14162 			 * same as the nhop_ire computed below.
14163 			 */
14164 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14165 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14166 			    0, NULL, MATCH_IRE_TYPE, ipst);
14167 
14168 			if (nhop_ire != NULL) {
14169 				if ((src & nhop_ire->ire_mask) ==
14170 				    (nhop & nhop_ire->ire_mask)) {
14171 					/*
14172 					 * The source is directly connected.
14173 					 * Just copy the ip header (which is
14174 					 * in the first mblk)
14175 					 */
14176 					mp1 = copyb(mp);
14177 					if (mp1 != NULL) {
14178 						icmp_send_redirect(WR(q), mp1,
14179 						    nhop, ipst);
14180 					}
14181 				}
14182 				ire_refrele(nhop_ire);
14183 			}
14184 		}
14185 	}
14186 sendit:
14187 	dev_q = ire->ire_stq->q_next;
14188 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14189 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14190 		freemsg(mp);
14191 		return;
14192 	}
14193 
14194 	ip_rput_forward(ire, ipha, mp, ill);
14195 	return;
14196 
14197 drop_pkt:
14198 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14199 	freemsg(mp);
14200 }
14201 
14202 ire_t *
14203 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14204     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14205 {
14206 	queue_t		*q;
14207 	uint16_t	hcksumflags;
14208 	ip_stack_t	*ipst = ill->ill_ipst;
14209 
14210 	q = *qp;
14211 
14212 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14213 
14214 	/*
14215 	 * Clear the indication that this may have hardware
14216 	 * checksum as we are not using it for forwarding.
14217 	 */
14218 	hcksumflags = DB_CKSUMFLAGS(mp);
14219 	DB_CKSUMFLAGS(mp) = 0;
14220 
14221 	/*
14222 	 * Directed broadcast forwarding: if the packet came in over a
14223 	 * different interface then it is routed out over we can forward it.
14224 	 */
14225 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14226 		ire_refrele(ire);
14227 		freemsg(mp);
14228 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14229 		return (NULL);
14230 	}
14231 	/*
14232 	 * For multicast we have set dst to be INADDR_BROADCAST
14233 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14234 	 * only for broadcast packets.
14235 	 */
14236 	if (!CLASSD(ipha->ipha_dst)) {
14237 		ire_t *new_ire;
14238 		ipif_t *ipif;
14239 		/*
14240 		 * For ill groups, as the switch duplicates broadcasts
14241 		 * across all the ports, we need to filter out and
14242 		 * send up only one copy. There is one copy for every
14243 		 * broadcast address on each ill. Thus, we look for a
14244 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14245 		 * later to see whether this ill is eligible to receive
14246 		 * them or not. ill_nominate_bcast_rcv() nominates only
14247 		 * one set of IREs for receiving.
14248 		 */
14249 
14250 		ipif = ipif_get_next_ipif(NULL, ill);
14251 		if (ipif == NULL) {
14252 			ire_refrele(ire);
14253 			freemsg(mp);
14254 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14255 			return (NULL);
14256 		}
14257 		new_ire = ire_ctable_lookup(dst, 0, 0,
14258 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14259 		ipif_refrele(ipif);
14260 
14261 		if (new_ire != NULL) {
14262 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14263 				ire_refrele(ire);
14264 				ire_refrele(new_ire);
14265 				freemsg(mp);
14266 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14267 				return (NULL);
14268 			}
14269 			/*
14270 			 * In the special case of multirouted broadcast
14271 			 * packets, we unconditionally need to "gateway"
14272 			 * them to the appropriate interface here.
14273 			 * In the normal case, this cannot happen, because
14274 			 * there is no broadcast IRE tagged with the
14275 			 * RTF_MULTIRT flag.
14276 			 */
14277 			if (new_ire->ire_flags & RTF_MULTIRT) {
14278 				ire_refrele(new_ire);
14279 				if (ire->ire_rfq != NULL) {
14280 					q = ire->ire_rfq;
14281 					*qp = q;
14282 				}
14283 			} else {
14284 				ire_refrele(ire);
14285 				ire = new_ire;
14286 			}
14287 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14288 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14289 				/*
14290 				 * Free the message if
14291 				 * ip_g_forward_directed_bcast is turned
14292 				 * off for non-local broadcast.
14293 				 */
14294 				ire_refrele(ire);
14295 				freemsg(mp);
14296 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14297 				return (NULL);
14298 			}
14299 		} else {
14300 			/*
14301 			 * This CGTP packet successfully passed the
14302 			 * CGTP filter, but the related CGTP
14303 			 * broadcast IRE has not been found,
14304 			 * meaning that the redundant ipif is
14305 			 * probably down. However, if we discarded
14306 			 * this packet, its duplicate would be
14307 			 * filtered out by the CGTP filter so none
14308 			 * of them would get through. So we keep
14309 			 * going with this one.
14310 			 */
14311 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14312 			if (ire->ire_rfq != NULL) {
14313 				q = ire->ire_rfq;
14314 				*qp = q;
14315 			}
14316 		}
14317 	}
14318 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14319 		/*
14320 		 * Verify that there are not more then one
14321 		 * IRE_BROADCAST with this broadcast address which
14322 		 * has ire_stq set.
14323 		 * TODO: simplify, loop over all IRE's
14324 		 */
14325 		ire_t	*ire1;
14326 		int	num_stq = 0;
14327 		mblk_t	*mp1;
14328 
14329 		/* Find the first one with ire_stq set */
14330 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14331 		for (ire1 = ire; ire1 &&
14332 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14333 		    ire1 = ire1->ire_next)
14334 			;
14335 		if (ire1) {
14336 			ire_refrele(ire);
14337 			ire = ire1;
14338 			IRE_REFHOLD(ire);
14339 		}
14340 
14341 		/* Check if there are additional ones with stq set */
14342 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14343 			if (ire->ire_addr != ire1->ire_addr)
14344 				break;
14345 			if (ire1->ire_stq) {
14346 				num_stq++;
14347 				break;
14348 			}
14349 		}
14350 		rw_exit(&ire->ire_bucket->irb_lock);
14351 		if (num_stq == 1 && ire->ire_stq != NULL) {
14352 			ip1dbg(("ip_rput_process_broadcast: directed "
14353 			    "broadcast to 0x%x\n",
14354 			    ntohl(ire->ire_addr)));
14355 			mp1 = copymsg(mp);
14356 			if (mp1) {
14357 				switch (ipha->ipha_protocol) {
14358 				case IPPROTO_UDP:
14359 					ip_udp_input(q, mp1, ipha, ire, ill);
14360 					break;
14361 				default:
14362 					ip_proto_input(q, mp1, ipha, ire, ill,
14363 					    B_FALSE);
14364 					break;
14365 				}
14366 			}
14367 			/*
14368 			 * Adjust ttl to 2 (1+1 - the forward engine
14369 			 * will decrement it by one.
14370 			 */
14371 			if (ip_csum_hdr(ipha)) {
14372 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14373 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14374 				freemsg(mp);
14375 				ire_refrele(ire);
14376 				return (NULL);
14377 			}
14378 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14379 			ipha->ipha_hdr_checksum = 0;
14380 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14381 			ip_rput_process_forward(q, mp, ire, ipha,
14382 			    ill, ll_multicast);
14383 			ire_refrele(ire);
14384 			return (NULL);
14385 		}
14386 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14387 		    ntohl(ire->ire_addr)));
14388 	}
14389 
14390 
14391 	/* Restore any hardware checksum flags */
14392 	DB_CKSUMFLAGS(mp) = hcksumflags;
14393 	return (ire);
14394 }
14395 
14396 /* ARGSUSED */
14397 static boolean_t
14398 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14399     int *ll_multicast, ipaddr_t *dstp)
14400 {
14401 	ip_stack_t	*ipst = ill->ill_ipst;
14402 
14403 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14404 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14405 	    ntohs(ipha->ipha_length));
14406 
14407 	/*
14408 	 * Forward packets only if we have joined the allmulti
14409 	 * group on this interface.
14410 	 */
14411 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14412 		int retval;
14413 
14414 		/*
14415 		 * Clear the indication that this may have hardware
14416 		 * checksum as we are not using it.
14417 		 */
14418 		DB_CKSUMFLAGS(mp) = 0;
14419 		retval = ip_mforward(ill, ipha, mp);
14420 		/* ip_mforward updates mib variables if needed */
14421 		/* clear b_prev - used by ip_mroute_decap */
14422 		mp->b_prev = NULL;
14423 
14424 		switch (retval) {
14425 		case 0:
14426 			/*
14427 			 * pkt is okay and arrived on phyint.
14428 			 *
14429 			 * If we are running as a multicast router
14430 			 * we need to see all IGMP and/or PIM packets.
14431 			 */
14432 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14433 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14434 				goto done;
14435 			}
14436 			break;
14437 		case -1:
14438 			/* pkt is mal-formed, toss it */
14439 			goto drop_pkt;
14440 		case 1:
14441 			/* pkt is okay and arrived on a tunnel */
14442 			/*
14443 			 * If we are running a multicast router
14444 			 *  we need to see all igmp packets.
14445 			 */
14446 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14447 				*dstp = INADDR_BROADCAST;
14448 				*ll_multicast = 1;
14449 				return (B_FALSE);
14450 			}
14451 
14452 			goto drop_pkt;
14453 		}
14454 	}
14455 
14456 	ILM_WALKER_HOLD(ill);
14457 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14458 		/*
14459 		 * This might just be caused by the fact that
14460 		 * multiple IP Multicast addresses map to the same
14461 		 * link layer multicast - no need to increment counter!
14462 		 */
14463 		ILM_WALKER_RELE(ill);
14464 		freemsg(mp);
14465 		return (B_TRUE);
14466 	}
14467 	ILM_WALKER_RELE(ill);
14468 done:
14469 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14470 	/*
14471 	 * This assumes the we deliver to all streams for multicast
14472 	 * and broadcast packets.
14473 	 */
14474 	*dstp = INADDR_BROADCAST;
14475 	*ll_multicast = 1;
14476 	return (B_FALSE);
14477 drop_pkt:
14478 	ip2dbg(("ip_rput: drop pkt\n"));
14479 	freemsg(mp);
14480 	return (B_TRUE);
14481 }
14482 
14483 /*
14484  * This function is used to both return an indication of whether or not
14485  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14486  * and in doing so, determine whether or not it is broadcast vs multicast.
14487  * For it to be a broadcast packet, we must have the appropriate mblk_t
14488  * hanging off the ill_t.  If this is either not present or doesn't match
14489  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14490  * to be multicast.  Thus NICs that have no broadcast address (or no
14491  * capability for one, such as point to point links) cannot return as
14492  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14493  * the return values simplifies the current use of the return value of this
14494  * function, which is to pass through the multicast/broadcast characteristic
14495  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14496  * changing the return value to some other symbol demands the appropriate
14497  * "translation" when hpe_flags is set prior to calling hook_run() for
14498  * packet events.
14499  */
14500 int
14501 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14502 {
14503 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14504 	mblk_t *bmp;
14505 
14506 	if (ind->dl_group_address) {
14507 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14508 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14509 		    MBLKL(mb) &&
14510 		    (bmp = ill->ill_bcast_mp) != NULL) {
14511 			dl_unitdata_req_t *dlur;
14512 			uint8_t *bphys_addr;
14513 
14514 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14515 			if (ill->ill_sap_length < 0)
14516 				bphys_addr = (uchar_t *)dlur +
14517 				    dlur->dl_dest_addr_offset;
14518 			else
14519 				bphys_addr = (uchar_t *)dlur +
14520 				    dlur->dl_dest_addr_offset +
14521 				    ill->ill_sap_length;
14522 
14523 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14524 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14525 				return (HPE_BROADCAST);
14526 			}
14527 			return (HPE_MULTICAST);
14528 		}
14529 		return (HPE_MULTICAST);
14530 	}
14531 	return (0);
14532 }
14533 
14534 static boolean_t
14535 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14536     int *ll_multicast, mblk_t **mpp)
14537 {
14538 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14539 	boolean_t must_copy = B_FALSE;
14540 	struct iocblk   *iocp;
14541 	ipha_t		*ipha;
14542 	ip_stack_t	*ipst = ill->ill_ipst;
14543 
14544 #define	rptr    ((uchar_t *)ipha)
14545 
14546 	first_mp = *first_mpp;
14547 	mp = *mpp;
14548 
14549 	ASSERT(first_mp == mp);
14550 
14551 	/*
14552 	 * if db_ref > 1 then copymsg and free original. Packet may be
14553 	 * changed and do not want other entity who has a reference to this
14554 	 * message to trip over the changes. This is a blind change because
14555 	 * trying to catch all places that might change packet is too
14556 	 * difficult (since it may be a module above this one)
14557 	 *
14558 	 * This corresponds to the non-fast path case. We walk down the full
14559 	 * chain in this case, and check the db_ref count of all the dblks,
14560 	 * and do a copymsg if required. It is possible that the db_ref counts
14561 	 * of the data blocks in the mblk chain can be different.
14562 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14563 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14564 	 * 'snoop' is running.
14565 	 */
14566 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14567 		if (mp1->b_datap->db_ref > 1) {
14568 			must_copy = B_TRUE;
14569 			break;
14570 		}
14571 	}
14572 
14573 	if (must_copy) {
14574 		mp1 = copymsg(mp);
14575 		if (mp1 == NULL) {
14576 			for (mp1 = mp; mp1 != NULL;
14577 			    mp1 = mp1->b_cont) {
14578 				mp1->b_next = NULL;
14579 				mp1->b_prev = NULL;
14580 			}
14581 			freemsg(mp);
14582 			if (ill != NULL) {
14583 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14584 			} else {
14585 				BUMP_MIB(&ipst->ips_ip_mib,
14586 				    ipIfStatsInDiscards);
14587 			}
14588 			return (B_TRUE);
14589 		}
14590 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14591 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14592 			/* Copy b_prev - used by ip_mroute_decap */
14593 			to_mp->b_prev = from_mp->b_prev;
14594 			from_mp->b_prev = NULL;
14595 		}
14596 		*first_mpp = first_mp = mp1;
14597 		freemsg(mp);
14598 		mp = mp1;
14599 		*mpp = mp1;
14600 	}
14601 
14602 	ipha = (ipha_t *)mp->b_rptr;
14603 
14604 	/*
14605 	 * previous code has a case for M_DATA.
14606 	 * We want to check how that happens.
14607 	 */
14608 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14609 	switch (first_mp->b_datap->db_type) {
14610 	case M_PROTO:
14611 	case M_PCPROTO:
14612 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14613 		    DL_UNITDATA_IND) {
14614 			/* Go handle anything other than data elsewhere. */
14615 			ip_rput_dlpi(q, mp);
14616 			return (B_TRUE);
14617 		}
14618 
14619 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14620 		/* Ditch the DLPI header. */
14621 		mp1 = mp->b_cont;
14622 		ASSERT(first_mp == mp);
14623 		*first_mpp = mp1;
14624 		freeb(mp);
14625 		*mpp = mp1;
14626 		return (B_FALSE);
14627 	case M_IOCACK:
14628 		ip1dbg(("got iocack "));
14629 		iocp = (struct iocblk *)mp->b_rptr;
14630 		switch (iocp->ioc_cmd) {
14631 		case DL_IOC_HDR_INFO:
14632 			ill = (ill_t *)q->q_ptr;
14633 			ill_fastpath_ack(ill, mp);
14634 			return (B_TRUE);
14635 		case SIOCSTUNPARAM:
14636 		case OSIOCSTUNPARAM:
14637 			/* Go through qwriter_ip */
14638 			break;
14639 		case SIOCGTUNPARAM:
14640 		case OSIOCGTUNPARAM:
14641 			ip_rput_other(NULL, q, mp, NULL);
14642 			return (B_TRUE);
14643 		default:
14644 			putnext(q, mp);
14645 			return (B_TRUE);
14646 		}
14647 		/* FALLTHRU */
14648 	case M_ERROR:
14649 	case M_HANGUP:
14650 		/*
14651 		 * Since this is on the ill stream we unconditionally
14652 		 * bump up the refcount
14653 		 */
14654 		ill_refhold(ill);
14655 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14656 		return (B_TRUE);
14657 	case M_CTL:
14658 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14659 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14660 		    IPHADA_M_CTL)) {
14661 			/*
14662 			 * It's an IPsec accelerated packet.
14663 			 * Make sure that the ill from which we received the
14664 			 * packet has enabled IPsec hardware acceleration.
14665 			 */
14666 			if (!(ill->ill_capabilities &
14667 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14668 				/* IPsec kstats: bean counter */
14669 				freemsg(mp);
14670 				return (B_TRUE);
14671 			}
14672 
14673 			/*
14674 			 * Make mp point to the mblk following the M_CTL,
14675 			 * then process according to type of mp.
14676 			 * After this processing, first_mp will point to
14677 			 * the data-attributes and mp to the pkt following
14678 			 * the M_CTL.
14679 			 */
14680 			mp = first_mp->b_cont;
14681 			if (mp == NULL) {
14682 				freemsg(first_mp);
14683 				return (B_TRUE);
14684 			}
14685 			/*
14686 			 * A Hardware Accelerated packet can only be M_DATA
14687 			 * ESP or AH packet.
14688 			 */
14689 			if (mp->b_datap->db_type != M_DATA) {
14690 				/* non-M_DATA IPsec accelerated packet */
14691 				IPSECHW_DEBUG(IPSECHW_PKT,
14692 				    ("non-M_DATA IPsec accelerated pkt\n"));
14693 				freemsg(first_mp);
14694 				return (B_TRUE);
14695 			}
14696 			ipha = (ipha_t *)mp->b_rptr;
14697 			if (ipha->ipha_protocol != IPPROTO_AH &&
14698 			    ipha->ipha_protocol != IPPROTO_ESP) {
14699 				IPSECHW_DEBUG(IPSECHW_PKT,
14700 				    ("non-M_DATA IPsec accelerated pkt\n"));
14701 				freemsg(first_mp);
14702 				return (B_TRUE);
14703 			}
14704 			*mpp = mp;
14705 			return (B_FALSE);
14706 		}
14707 		putnext(q, mp);
14708 		return (B_TRUE);
14709 	case M_IOCNAK:
14710 		ip1dbg(("got iocnak "));
14711 		iocp = (struct iocblk *)mp->b_rptr;
14712 		switch (iocp->ioc_cmd) {
14713 		case SIOCSTUNPARAM:
14714 		case OSIOCSTUNPARAM:
14715 			/*
14716 			 * Since this is on the ill stream we unconditionally
14717 			 * bump up the refcount
14718 			 */
14719 			ill_refhold(ill);
14720 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14721 			return (B_TRUE);
14722 		case DL_IOC_HDR_INFO:
14723 		case SIOCGTUNPARAM:
14724 		case OSIOCGTUNPARAM:
14725 			ip_rput_other(NULL, q, mp, NULL);
14726 			return (B_TRUE);
14727 		default:
14728 			break;
14729 		}
14730 		/* FALLTHRU */
14731 	default:
14732 		putnext(q, mp);
14733 		return (B_TRUE);
14734 	}
14735 }
14736 
14737 /* Read side put procedure.  Packets coming from the wire arrive here. */
14738 void
14739 ip_rput(queue_t *q, mblk_t *mp)
14740 {
14741 	ill_t	*ill;
14742 	union DL_primitives *dl;
14743 
14744 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14745 
14746 	ill = (ill_t *)q->q_ptr;
14747 
14748 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14749 		/*
14750 		 * If things are opening or closing, only accept high-priority
14751 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14752 		 * created; on close, things hanging off the ill may have been
14753 		 * freed already.)
14754 		 */
14755 		dl = (union DL_primitives *)mp->b_rptr;
14756 		if (DB_TYPE(mp) != M_PCPROTO ||
14757 		    dl->dl_primitive == DL_UNITDATA_IND) {
14758 			/*
14759 			 * SIOC[GS]TUNPARAM ioctls can come here.
14760 			 */
14761 			inet_freemsg(mp);
14762 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14763 			    "ip_rput_end: q %p (%S)", q, "uninit");
14764 			return;
14765 		}
14766 	}
14767 
14768 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14769 	    "ip_rput_end: q %p (%S)", q, "end");
14770 
14771 	ip_input(ill, NULL, mp, NULL);
14772 }
14773 
14774 static mblk_t *
14775 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14776 {
14777 	mblk_t *mp1;
14778 	boolean_t adjusted = B_FALSE;
14779 	ip_stack_t *ipst = ill->ill_ipst;
14780 
14781 	IP_STAT(ipst, ip_db_ref);
14782 	/*
14783 	 * The IP_RECVSLLA option depends on having the
14784 	 * link layer header. First check that:
14785 	 * a> the underlying device is of type ether,
14786 	 * since this option is currently supported only
14787 	 * over ethernet.
14788 	 * b> there is enough room to copy over the link
14789 	 * layer header.
14790 	 *
14791 	 * Once the checks are done, adjust rptr so that
14792 	 * the link layer header will be copied via
14793 	 * copymsg. Note that, IFT_ETHER may be returned
14794 	 * by some non-ethernet drivers but in this case
14795 	 * the second check will fail.
14796 	 */
14797 	if (ill->ill_type == IFT_ETHER &&
14798 	    (mp->b_rptr - mp->b_datap->db_base) >=
14799 	    sizeof (struct ether_header)) {
14800 		mp->b_rptr -= sizeof (struct ether_header);
14801 		adjusted = B_TRUE;
14802 	}
14803 	mp1 = copymsg(mp);
14804 
14805 	if (mp1 == NULL) {
14806 		mp->b_next = NULL;
14807 		/* clear b_prev - used by ip_mroute_decap */
14808 		mp->b_prev = NULL;
14809 		freemsg(mp);
14810 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14811 		return (NULL);
14812 	}
14813 
14814 	if (adjusted) {
14815 		/*
14816 		 * Copy is done. Restore the pointer in
14817 		 * the _new_ mblk
14818 		 */
14819 		mp1->b_rptr += sizeof (struct ether_header);
14820 	}
14821 
14822 	/* Copy b_prev - used by ip_mroute_decap */
14823 	mp1->b_prev = mp->b_prev;
14824 	mp->b_prev = NULL;
14825 
14826 	/* preserve the hardware checksum flags and data, if present */
14827 	if (DB_CKSUMFLAGS(mp) != 0) {
14828 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14829 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14830 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14831 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14832 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14833 	}
14834 
14835 	freemsg(mp);
14836 	return (mp1);
14837 }
14838 
14839 /*
14840  * Direct read side procedure capable of dealing with chains. GLDv3 based
14841  * drivers call this function directly with mblk chains while STREAMS
14842  * read side procedure ip_rput() calls this for single packet with ip_ring
14843  * set to NULL to process one packet at a time.
14844  *
14845  * The ill will always be valid if this function is called directly from
14846  * the driver.
14847  *
14848  * If ip_input() is called from GLDv3:
14849  *
14850  *   - This must be a non-VLAN IP stream.
14851  *   - 'mp' is either an untagged or a special priority-tagged packet.
14852  *   - Any VLAN tag that was in the MAC header has been stripped.
14853  *
14854  * If the IP header in packet is not 32-bit aligned, every message in the
14855  * chain will be aligned before further operations. This is required on SPARC
14856  * platform.
14857  */
14858 /* ARGSUSED */
14859 void
14860 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14861     struct mac_header_info_s *mhip)
14862 {
14863 	ipaddr_t		dst = NULL;
14864 	ipaddr_t		prev_dst;
14865 	ire_t			*ire = NULL;
14866 	ipha_t			*ipha;
14867 	uint_t			pkt_len;
14868 	ssize_t			len;
14869 	uint_t			opt_len;
14870 	int			ll_multicast;
14871 	int			cgtp_flt_pkt;
14872 	queue_t			*q = ill->ill_rq;
14873 	squeue_t		*curr_sqp = NULL;
14874 	mblk_t 			*head = NULL;
14875 	mblk_t			*tail = NULL;
14876 	mblk_t			*first_mp;
14877 	mblk_t 			*mp;
14878 	mblk_t			*dmp;
14879 	int			cnt = 0;
14880 	ip_stack_t		*ipst = ill->ill_ipst;
14881 
14882 	ASSERT(mp_chain != NULL);
14883 	ASSERT(ill != NULL);
14884 
14885 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14886 
14887 #define	rptr	((uchar_t *)ipha)
14888 
14889 	while (mp_chain != NULL) {
14890 		first_mp = mp = mp_chain;
14891 		mp_chain = mp_chain->b_next;
14892 		mp->b_next = NULL;
14893 		ll_multicast = 0;
14894 
14895 		/*
14896 		 * We do ire caching from one iteration to
14897 		 * another. In the event the packet chain contains
14898 		 * all packets from the same dst, this caching saves
14899 		 * an ire_cache_lookup for each of the succeeding
14900 		 * packets in a packet chain.
14901 		 */
14902 		prev_dst = dst;
14903 
14904 		/*
14905 		 * if db_ref > 1 then copymsg and free original. Packet
14906 		 * may be changed and we do not want the other entity
14907 		 * who has a reference to this message to trip over the
14908 		 * changes. This is a blind change because trying to
14909 		 * catch all places that might change the packet is too
14910 		 * difficult.
14911 		 *
14912 		 * This corresponds to the fast path case, where we have
14913 		 * a chain of M_DATA mblks.  We check the db_ref count
14914 		 * of only the 1st data block in the mblk chain. There
14915 		 * doesn't seem to be a reason why a device driver would
14916 		 * send up data with varying db_ref counts in the mblk
14917 		 * chain. In any case the Fast path is a private
14918 		 * interface, and our drivers don't do such a thing.
14919 		 * Given the above assumption, there is no need to walk
14920 		 * down the entire mblk chain (which could have a
14921 		 * potential performance problem)
14922 		 */
14923 
14924 		if (DB_REF(mp) > 1) {
14925 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14926 				continue;
14927 		}
14928 
14929 		/*
14930 		 * Check and align the IP header.
14931 		 */
14932 		first_mp = mp;
14933 		if (DB_TYPE(mp) == M_DATA) {
14934 			dmp = mp;
14935 		} else if (DB_TYPE(mp) == M_PROTO &&
14936 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14937 			dmp = mp->b_cont;
14938 		} else {
14939 			dmp = NULL;
14940 		}
14941 		if (dmp != NULL) {
14942 			/*
14943 			 * IP header ptr not aligned?
14944 			 * OR IP header not complete in first mblk
14945 			 */
14946 			if (!OK_32PTR(dmp->b_rptr) ||
14947 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14948 				if (!ip_check_and_align_header(q, dmp, ipst))
14949 					continue;
14950 			}
14951 		}
14952 
14953 		/*
14954 		 * ip_input fast path
14955 		 */
14956 
14957 		/* mblk type is not M_DATA */
14958 		if (DB_TYPE(mp) != M_DATA) {
14959 			if (ip_rput_process_notdata(q, &first_mp, ill,
14960 			    &ll_multicast, &mp))
14961 				continue;
14962 
14963 			/*
14964 			 * The only way we can get here is if we had a
14965 			 * packet that was either a DL_UNITDATA_IND or
14966 			 * an M_CTL for an IPsec accelerated packet.
14967 			 *
14968 			 * In either case, the first_mp will point to
14969 			 * the leading M_PROTO or M_CTL.
14970 			 */
14971 			ASSERT(first_mp != NULL);
14972 		} else if (mhip != NULL) {
14973 			/*
14974 			 * ll_multicast is set here so that it is ready
14975 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14976 			 * manipulates ll_multicast in the same fashion when
14977 			 * called from ip_rput_process_notdata.
14978 			 */
14979 			switch (mhip->mhi_dsttype) {
14980 			case MAC_ADDRTYPE_MULTICAST :
14981 				ll_multicast = HPE_MULTICAST;
14982 				break;
14983 			case MAC_ADDRTYPE_BROADCAST :
14984 				ll_multicast = HPE_BROADCAST;
14985 				break;
14986 			default :
14987 				break;
14988 			}
14989 		}
14990 
14991 		/* Make sure its an M_DATA and that its aligned */
14992 		ASSERT(DB_TYPE(mp) == M_DATA);
14993 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14994 
14995 		ipha = (ipha_t *)mp->b_rptr;
14996 		len = mp->b_wptr - rptr;
14997 		pkt_len = ntohs(ipha->ipha_length);
14998 
14999 		/*
15000 		 * We must count all incoming packets, even if they end
15001 		 * up being dropped later on.
15002 		 */
15003 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15004 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15005 
15006 		/* multiple mblk or too short */
15007 		len -= pkt_len;
15008 		if (len != 0) {
15009 			/*
15010 			 * Make sure we have data length consistent
15011 			 * with the IP header.
15012 			 */
15013 			if (mp->b_cont == NULL) {
15014 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15015 					BUMP_MIB(ill->ill_ip_mib,
15016 					    ipIfStatsInHdrErrors);
15017 					ip2dbg(("ip_input: drop pkt\n"));
15018 					freemsg(mp);
15019 					continue;
15020 				}
15021 				mp->b_wptr = rptr + pkt_len;
15022 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15023 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15024 					BUMP_MIB(ill->ill_ip_mib,
15025 					    ipIfStatsInHdrErrors);
15026 					ip2dbg(("ip_input: drop pkt\n"));
15027 					freemsg(mp);
15028 					continue;
15029 				}
15030 				(void) adjmsg(mp, -len);
15031 				IP_STAT(ipst, ip_multimblk3);
15032 			}
15033 		}
15034 
15035 		/* Obtain the dst of the current packet */
15036 		dst = ipha->ipha_dst;
15037 
15038 		/*
15039 		 * The following test for loopback is faster than
15040 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15041 		 * operations.
15042 		 * Note that these addresses are always in network byte order
15043 		 */
15044 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15045 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15046 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15047 			freemsg(mp);
15048 			continue;
15049 		}
15050 
15051 		/*
15052 		 * The event for packets being received from a 'physical'
15053 		 * interface is placed after validation of the source and/or
15054 		 * destination address as being local so that packets can be
15055 		 * redirected to loopback addresses using ipnat.
15056 		 */
15057 		DTRACE_PROBE4(ip4__physical__in__start,
15058 		    ill_t *, ill, ill_t *, NULL,
15059 		    ipha_t *, ipha, mblk_t *, first_mp);
15060 
15061 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15062 		    ipst->ips_ipv4firewall_physical_in,
15063 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15064 
15065 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15066 
15067 		if (first_mp == NULL) {
15068 			continue;
15069 		}
15070 		dst = ipha->ipha_dst;
15071 
15072 		/*
15073 		 * Attach any necessary label information to
15074 		 * this packet
15075 		 */
15076 		if (is_system_labeled() &&
15077 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15078 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15079 			freemsg(mp);
15080 			continue;
15081 		}
15082 
15083 		/*
15084 		 * Reuse the cached ire only if the ipha_dst of the previous
15085 		 * packet is the same as the current packet AND it is not
15086 		 * INADDR_ANY.
15087 		 */
15088 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15089 		    (ire != NULL)) {
15090 			ire_refrele(ire);
15091 			ire = NULL;
15092 		}
15093 		opt_len = ipha->ipha_version_and_hdr_length -
15094 		    IP_SIMPLE_HDR_VERSION;
15095 
15096 		/*
15097 		 * Check to see if we can take the fastpath.
15098 		 * That is possible if the following conditions are met
15099 		 *	o Tsol disabled
15100 		 *	o CGTP disabled
15101 		 *	o ipp_action_count is 0
15102 		 *	o no options in the packet
15103 		 *	o not a RSVP packet
15104 		 * 	o not a multicast packet
15105 		 *	o ill not in IP_DHCPINIT_IF mode
15106 		 */
15107 		if (!is_system_labeled() &&
15108 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15109 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15110 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15111 			if (ire == NULL)
15112 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15113 				    ipst);
15114 
15115 			/* incoming packet is for forwarding */
15116 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15117 				ire = ip_fast_forward(ire, dst, ill, mp);
15118 				continue;
15119 			}
15120 			/* incoming packet is for local consumption */
15121 			if (ire->ire_type & IRE_LOCAL)
15122 				goto local;
15123 		}
15124 
15125 		/*
15126 		 * Disable ire caching for anything more complex
15127 		 * than the simple fast path case we checked for above.
15128 		 */
15129 		if (ire != NULL) {
15130 			ire_refrele(ire);
15131 			ire = NULL;
15132 		}
15133 
15134 		/*
15135 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15136 		 * server to unicast DHCP packets to a DHCP client using the
15137 		 * IP address it is offering to the client.  This can be
15138 		 * disabled through the "broadcast bit", but not all DHCP
15139 		 * servers honor that bit.  Therefore, to interoperate with as
15140 		 * many DHCP servers as possible, the DHCP client allows the
15141 		 * server to unicast, but we treat those packets as broadcast
15142 		 * here.  Note that we don't rewrite the packet itself since
15143 		 * (a) that would mess up the checksums and (b) the DHCP
15144 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15145 		 * hand it the packet regardless.
15146 		 */
15147 		if (ill->ill_dhcpinit != 0 &&
15148 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15149 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15150 			udpha_t *udpha;
15151 
15152 			/*
15153 			 * Reload ipha since pullupmsg() can change b_rptr.
15154 			 */
15155 			ipha = (ipha_t *)mp->b_rptr;
15156 			udpha = (udpha_t *)&ipha[1];
15157 
15158 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15159 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15160 				    mblk_t *, mp);
15161 				dst = INADDR_BROADCAST;
15162 			}
15163 		}
15164 
15165 		/* Full-blown slow path */
15166 		if (opt_len != 0) {
15167 			if (len != 0)
15168 				IP_STAT(ipst, ip_multimblk4);
15169 			else
15170 				IP_STAT(ipst, ip_ipoptions);
15171 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15172 			    &dst, ipst))
15173 				continue;
15174 		}
15175 
15176 		/*
15177 		 * Invoke the CGTP (multirouting) filtering module to process
15178 		 * the incoming packet. Packets identified as duplicates
15179 		 * must be discarded. Filtering is active only if the
15180 		 * the ip_cgtp_filter ndd variable is non-zero.
15181 		 */
15182 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15183 		if (ipst->ips_ip_cgtp_filter &&
15184 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15185 			netstackid_t stackid;
15186 
15187 			stackid = ipst->ips_netstack->netstack_stackid;
15188 			cgtp_flt_pkt =
15189 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15190 			    ill->ill_phyint->phyint_ifindex, mp);
15191 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15192 				freemsg(first_mp);
15193 				continue;
15194 			}
15195 		}
15196 
15197 		/*
15198 		 * If rsvpd is running, let RSVP daemon handle its processing
15199 		 * and forwarding of RSVP multicast/unicast packets.
15200 		 * If rsvpd is not running but mrouted is running, RSVP
15201 		 * multicast packets are forwarded as multicast traffic
15202 		 * and RSVP unicast packets are forwarded by unicast router.
15203 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15204 		 * packets are not forwarded, but the unicast packets are
15205 		 * forwarded like unicast traffic.
15206 		 */
15207 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15208 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15209 		    NULL) {
15210 			/* RSVP packet and rsvpd running. Treat as ours */
15211 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15212 			/*
15213 			 * This assumes that we deliver to all streams for
15214 			 * multicast and broadcast packets.
15215 			 * We have to force ll_multicast to 1 to handle the
15216 			 * M_DATA messages passed in from ip_mroute_decap.
15217 			 */
15218 			dst = INADDR_BROADCAST;
15219 			ll_multicast = 1;
15220 		} else if (CLASSD(dst)) {
15221 			/* packet is multicast */
15222 			mp->b_next = NULL;
15223 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15224 			    &ll_multicast, &dst))
15225 				continue;
15226 		}
15227 
15228 		if (ire == NULL) {
15229 			ire = ire_cache_lookup(dst, ALL_ZONES,
15230 			    MBLK_GETLABEL(mp), ipst);
15231 		}
15232 
15233 		if (ire == NULL) {
15234 			/*
15235 			 * No IRE for this destination, so it can't be for us.
15236 			 * Unless we are forwarding, drop the packet.
15237 			 * We have to let source routed packets through
15238 			 * since we don't yet know if they are 'ping -l'
15239 			 * packets i.e. if they will go out over the
15240 			 * same interface as they came in on.
15241 			 */
15242 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15243 			if (ire == NULL)
15244 				continue;
15245 		}
15246 
15247 		/*
15248 		 * Broadcast IRE may indicate either broadcast or
15249 		 * multicast packet
15250 		 */
15251 		if (ire->ire_type == IRE_BROADCAST) {
15252 			/*
15253 			 * Skip broadcast checks if packet is UDP multicast;
15254 			 * we'd rather not enter ip_rput_process_broadcast()
15255 			 * unless the packet is broadcast for real, since
15256 			 * that routine is a no-op for multicast.
15257 			 */
15258 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15259 			    !CLASSD(ipha->ipha_dst)) {
15260 				ire = ip_rput_process_broadcast(&q, mp,
15261 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15262 				    ll_multicast);
15263 				if (ire == NULL)
15264 					continue;
15265 			}
15266 		} else if (ire->ire_stq != NULL) {
15267 			/* fowarding? */
15268 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15269 			    ll_multicast);
15270 			/* ip_rput_process_forward consumed the packet */
15271 			continue;
15272 		}
15273 
15274 local:
15275 		/*
15276 		 * If the queue in the ire is different to the ingress queue
15277 		 * then we need to check to see if we can accept the packet.
15278 		 * Note that for multicast packets and broadcast packets sent
15279 		 * to a broadcast address which is shared between multiple
15280 		 * interfaces we should not do this since we just got a random
15281 		 * broadcast ire.
15282 		 */
15283 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15284 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15285 			    ill)) == NULL) {
15286 				/* Drop packet */
15287 				BUMP_MIB(ill->ill_ip_mib,
15288 				    ipIfStatsForwProhibits);
15289 				freemsg(mp);
15290 				continue;
15291 			}
15292 			if (ire->ire_rfq != NULL)
15293 				q = ire->ire_rfq;
15294 		}
15295 
15296 		switch (ipha->ipha_protocol) {
15297 		case IPPROTO_TCP:
15298 			ASSERT(first_mp == mp);
15299 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15300 			    mp, 0, q, ip_ring)) != NULL) {
15301 				if (curr_sqp == NULL) {
15302 					curr_sqp = GET_SQUEUE(mp);
15303 					ASSERT(cnt == 0);
15304 					cnt++;
15305 					head = tail = mp;
15306 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15307 					ASSERT(tail != NULL);
15308 					cnt++;
15309 					tail->b_next = mp;
15310 					tail = mp;
15311 				} else {
15312 					/*
15313 					 * A different squeue. Send the
15314 					 * chain for the previous squeue on
15315 					 * its way. This shouldn't happen
15316 					 * often unless interrupt binding
15317 					 * changes.
15318 					 */
15319 					IP_STAT(ipst, ip_input_multi_squeue);
15320 					squeue_enter_chain(curr_sqp, head,
15321 					    tail, cnt, SQTAG_IP_INPUT);
15322 					curr_sqp = GET_SQUEUE(mp);
15323 					head = mp;
15324 					tail = mp;
15325 					cnt = 1;
15326 				}
15327 			}
15328 			continue;
15329 		case IPPROTO_UDP:
15330 			ASSERT(first_mp == mp);
15331 			ip_udp_input(q, mp, ipha, ire, ill);
15332 			continue;
15333 		case IPPROTO_SCTP:
15334 			ASSERT(first_mp == mp);
15335 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15336 			    q, dst);
15337 			/* ire has been released by ip_sctp_input */
15338 			ire = NULL;
15339 			continue;
15340 		default:
15341 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15342 			continue;
15343 		}
15344 	}
15345 
15346 	if (ire != NULL)
15347 		ire_refrele(ire);
15348 
15349 	if (head != NULL)
15350 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15351 
15352 	/*
15353 	 * This code is there just to make netperf/ttcp look good.
15354 	 *
15355 	 * Its possible that after being in polling mode (and having cleared
15356 	 * the backlog), squeues have turned the interrupt frequency higher
15357 	 * to improve latency at the expense of more CPU utilization (less
15358 	 * packets per interrupts or more number of interrupts). Workloads
15359 	 * like ttcp/netperf do manage to tickle polling once in a while
15360 	 * but for the remaining time, stay in higher interrupt mode since
15361 	 * their packet arrival rate is pretty uniform and this shows up
15362 	 * as higher CPU utilization. Since people care about CPU utilization
15363 	 * while running netperf/ttcp, turn the interrupt frequency back to
15364 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15365 	 */
15366 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15367 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15368 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15369 			ip_ring->rr_blank(ip_ring->rr_handle,
15370 			    ip_ring->rr_normal_blank_time,
15371 			    ip_ring->rr_normal_pkt_cnt);
15372 		}
15373 		}
15374 
15375 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15376 	    "ip_input_end: q %p (%S)", q, "end");
15377 #undef  rptr
15378 }
15379 
15380 static void
15381 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15382     t_uscalar_t err)
15383 {
15384 	if (dl_err == DL_SYSERR) {
15385 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15386 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15387 		    ill->ill_name, dl_primstr(prim), err);
15388 		return;
15389 	}
15390 
15391 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15392 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15393 	    dl_errstr(dl_err));
15394 }
15395 
15396 /*
15397  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15398  * than DL_UNITDATA_IND messages. If we need to process this message
15399  * exclusively, we call qwriter_ip, in which case we also need to call
15400  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15401  */
15402 void
15403 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15404 {
15405 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15406 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15407 	ill_t		*ill = (ill_t *)q->q_ptr;
15408 	boolean_t	pending;
15409 
15410 	ip1dbg(("ip_rput_dlpi"));
15411 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15412 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15413 		    "%s (0x%x), unix %u\n", ill->ill_name,
15414 		    dl_primstr(dlea->dl_error_primitive),
15415 		    dlea->dl_error_primitive,
15416 		    dl_errstr(dlea->dl_errno),
15417 		    dlea->dl_errno,
15418 		    dlea->dl_unix_errno));
15419 	}
15420 
15421 	/*
15422 	 * If we received an ACK but didn't send a request for it, then it
15423 	 * can't be part of any pending operation; discard up-front.
15424 	 */
15425 	switch (dloa->dl_primitive) {
15426 	case DL_NOTIFY_IND:
15427 		pending = B_TRUE;
15428 		break;
15429 	case DL_ERROR_ACK:
15430 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15431 		break;
15432 	case DL_OK_ACK:
15433 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15434 		break;
15435 	case DL_INFO_ACK:
15436 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15437 		break;
15438 	case DL_BIND_ACK:
15439 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15440 		break;
15441 	case DL_PHYS_ADDR_ACK:
15442 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15443 		break;
15444 	case DL_NOTIFY_ACK:
15445 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15446 		break;
15447 	case DL_CONTROL_ACK:
15448 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15449 		break;
15450 	case DL_CAPABILITY_ACK:
15451 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15452 		break;
15453 	default:
15454 		/* Not a DLPI message we support or were expecting */
15455 		freemsg(mp);
15456 		return;
15457 	}
15458 
15459 	if (!pending) {
15460 		freemsg(mp);
15461 		return;
15462 	}
15463 
15464 	switch (dloa->dl_primitive) {
15465 	case DL_ERROR_ACK:
15466 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15467 			mutex_enter(&ill->ill_lock);
15468 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15469 			cv_signal(&ill->ill_cv);
15470 			mutex_exit(&ill->ill_lock);
15471 		}
15472 		break;
15473 
15474 	case DL_OK_ACK:
15475 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15476 		    dl_primstr((int)dloa->dl_correct_primitive)));
15477 		switch (dloa->dl_correct_primitive) {
15478 		case DL_UNBIND_REQ:
15479 			mutex_enter(&ill->ill_lock);
15480 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15481 			cv_signal(&ill->ill_cv);
15482 			mutex_exit(&ill->ill_lock);
15483 			break;
15484 
15485 		case DL_ENABMULTI_REQ:
15486 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15487 				ill->ill_dlpi_multicast_state = IDS_OK;
15488 			break;
15489 		}
15490 		break;
15491 	default:
15492 		break;
15493 	}
15494 
15495 	/*
15496 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15497 	 * and we need to become writer to continue to process it. If it's not
15498 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15499 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15500 	 * some work as part of the current exclusive operation that actually
15501 	 * is not part of it -- which is wrong, but better than the
15502 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15503 	 * should track which DLPI requests have ACKs that we wait on
15504 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15505 	 *
15506 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15507 	 * Since this is on the ill stream we unconditionally bump up the
15508 	 * refcount without doing ILL_CAN_LOOKUP().
15509 	 */
15510 	ill_refhold(ill);
15511 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15512 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15513 	else
15514 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15515 }
15516 
15517 /*
15518  * Handling of DLPI messages that require exclusive access to the ipsq.
15519  *
15520  * Need to do ill_pending_mp_release on ioctl completion, which could
15521  * happen here. (along with mi_copy_done)
15522  */
15523 /* ARGSUSED */
15524 static void
15525 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15526 {
15527 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15528 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15529 	int		err = 0;
15530 	ill_t		*ill;
15531 	ipif_t		*ipif = NULL;
15532 	mblk_t		*mp1 = NULL;
15533 	conn_t		*connp = NULL;
15534 	t_uscalar_t	paddrreq;
15535 	mblk_t		*mp_hw;
15536 	boolean_t	success;
15537 	boolean_t	ioctl_aborted = B_FALSE;
15538 	boolean_t	log = B_TRUE;
15539 	hook_nic_event_t	*info;
15540 	ip_stack_t		*ipst;
15541 
15542 	ip1dbg(("ip_rput_dlpi_writer .."));
15543 	ill = (ill_t *)q->q_ptr;
15544 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15545 
15546 	ASSERT(IAM_WRITER_ILL(ill));
15547 
15548 	ipst = ill->ill_ipst;
15549 
15550 	/*
15551 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15552 	 * both are null or non-null. However we can assert that only
15553 	 * after grabbing the ipsq_lock. So we don't make any assertion
15554 	 * here and in other places in the code.
15555 	 */
15556 	ipif = ipsq->ipsq_pending_ipif;
15557 	/*
15558 	 * The current ioctl could have been aborted by the user and a new
15559 	 * ioctl to bring up another ill could have started. We could still
15560 	 * get a response from the driver later.
15561 	 */
15562 	if (ipif != NULL && ipif->ipif_ill != ill)
15563 		ioctl_aborted = B_TRUE;
15564 
15565 	switch (dloa->dl_primitive) {
15566 	case DL_ERROR_ACK:
15567 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15568 		    dl_primstr(dlea->dl_error_primitive)));
15569 
15570 		switch (dlea->dl_error_primitive) {
15571 		case DL_PROMISCON_REQ:
15572 		case DL_PROMISCOFF_REQ:
15573 		case DL_DISABMULTI_REQ:
15574 		case DL_UNBIND_REQ:
15575 		case DL_ATTACH_REQ:
15576 		case DL_INFO_REQ:
15577 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15578 			break;
15579 		case DL_NOTIFY_REQ:
15580 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15581 			log = B_FALSE;
15582 			break;
15583 		case DL_PHYS_ADDR_REQ:
15584 			/*
15585 			 * For IPv6 only, there are two additional
15586 			 * phys_addr_req's sent to the driver to get the
15587 			 * IPv6 token and lla. This allows IP to acquire
15588 			 * the hardware address format for a given interface
15589 			 * without having built in knowledge of the hardware
15590 			 * address. ill_phys_addr_pend keeps track of the last
15591 			 * DL_PAR sent so we know which response we are
15592 			 * dealing with. ill_dlpi_done will update
15593 			 * ill_phys_addr_pend when it sends the next req.
15594 			 * We don't complete the IOCTL until all three DL_PARs
15595 			 * have been attempted, so set *_len to 0 and break.
15596 			 */
15597 			paddrreq = ill->ill_phys_addr_pend;
15598 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15599 			if (paddrreq == DL_IPV6_TOKEN) {
15600 				ill->ill_token_length = 0;
15601 				log = B_FALSE;
15602 				break;
15603 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15604 				ill->ill_nd_lla_len = 0;
15605 				log = B_FALSE;
15606 				break;
15607 			}
15608 			/*
15609 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15610 			 * We presumably have an IOCTL hanging out waiting
15611 			 * for completion. Find it and complete the IOCTL
15612 			 * with the error noted.
15613 			 * However, ill_dl_phys was called on an ill queue
15614 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15615 			 * set. But the ioctl is known to be pending on ill_wq.
15616 			 */
15617 			if (!ill->ill_ifname_pending)
15618 				break;
15619 			ill->ill_ifname_pending = 0;
15620 			if (!ioctl_aborted)
15621 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15622 			if (mp1 != NULL) {
15623 				/*
15624 				 * This operation (SIOCSLIFNAME) must have
15625 				 * happened on the ill. Assert there is no conn
15626 				 */
15627 				ASSERT(connp == NULL);
15628 				q = ill->ill_wq;
15629 			}
15630 			break;
15631 		case DL_BIND_REQ:
15632 			ill_dlpi_done(ill, DL_BIND_REQ);
15633 			if (ill->ill_ifname_pending)
15634 				break;
15635 			/*
15636 			 * Something went wrong with the bind.  We presumably
15637 			 * have an IOCTL hanging out waiting for completion.
15638 			 * Find it, take down the interface that was coming
15639 			 * up, and complete the IOCTL with the error noted.
15640 			 */
15641 			if (!ioctl_aborted)
15642 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15643 			if (mp1 != NULL) {
15644 				/*
15645 				 * This operation (SIOCSLIFFLAGS) must have
15646 				 * happened from a conn.
15647 				 */
15648 				ASSERT(connp != NULL);
15649 				q = CONNP_TO_WQ(connp);
15650 				if (ill->ill_move_in_progress) {
15651 					ILL_CLEAR_MOVE(ill);
15652 				}
15653 				(void) ipif_down(ipif, NULL, NULL);
15654 				/* error is set below the switch */
15655 			}
15656 			break;
15657 		case DL_ENABMULTI_REQ:
15658 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15659 
15660 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15661 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15662 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15663 				ipif_t *ipif;
15664 
15665 				printf("ip: joining multicasts failed (%d)"
15666 				    " on %s - will use link layer "
15667 				    "broadcasts for multicast\n",
15668 				    dlea->dl_errno, ill->ill_name);
15669 
15670 				/*
15671 				 * Set up the multicast mapping alone.
15672 				 * writer, so ok to access ill->ill_ipif
15673 				 * without any lock.
15674 				 */
15675 				ipif = ill->ill_ipif;
15676 				mutex_enter(&ill->ill_phyint->phyint_lock);
15677 				ill->ill_phyint->phyint_flags |=
15678 				    PHYI_MULTI_BCAST;
15679 				mutex_exit(&ill->ill_phyint->phyint_lock);
15680 
15681 				if (!ill->ill_isv6) {
15682 					(void) ipif_arp_setup_multicast(ipif,
15683 					    NULL);
15684 				} else {
15685 					(void) ipif_ndp_setup_multicast(ipif,
15686 					    NULL);
15687 				}
15688 			}
15689 			freemsg(mp);	/* Don't want to pass this up */
15690 			return;
15691 
15692 		case DL_CAPABILITY_REQ:
15693 		case DL_CONTROL_REQ:
15694 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15695 			ill->ill_dlpi_capab_state = IDS_FAILED;
15696 			freemsg(mp);
15697 			return;
15698 		}
15699 		/*
15700 		 * Note the error for IOCTL completion (mp1 is set when
15701 		 * ready to complete ioctl). If ill_ifname_pending_err is
15702 		 * set, an error occured during plumbing (ill_ifname_pending),
15703 		 * so we want to report that error.
15704 		 *
15705 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15706 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15707 		 * expected to get errack'd if the driver doesn't support
15708 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15709 		 * if these error conditions are encountered.
15710 		 */
15711 		if (mp1 != NULL) {
15712 			if (ill->ill_ifname_pending_err != 0)  {
15713 				err = ill->ill_ifname_pending_err;
15714 				ill->ill_ifname_pending_err = 0;
15715 			} else {
15716 				err = dlea->dl_unix_errno ?
15717 				    dlea->dl_unix_errno : ENXIO;
15718 			}
15719 		/*
15720 		 * If we're plumbing an interface and an error hasn't already
15721 		 * been saved, set ill_ifname_pending_err to the error passed
15722 		 * up. Ignore the error if log is B_FALSE (see comment above).
15723 		 */
15724 		} else if (log && ill->ill_ifname_pending &&
15725 		    ill->ill_ifname_pending_err == 0) {
15726 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15727 			    dlea->dl_unix_errno : ENXIO;
15728 		}
15729 
15730 		if (log)
15731 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15732 			    dlea->dl_errno, dlea->dl_unix_errno);
15733 		break;
15734 	case DL_CAPABILITY_ACK:
15735 		/* Call a routine to handle this one. */
15736 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15737 		ill_capability_ack(ill, mp);
15738 
15739 		/*
15740 		 * If the ack is due to renegotiation, we will need to send
15741 		 * a new CAPABILITY_REQ to start the renegotiation.
15742 		 */
15743 		if (ill->ill_capab_reneg) {
15744 			ill->ill_capab_reneg = B_FALSE;
15745 			ill_capability_probe(ill);
15746 		}
15747 		break;
15748 	case DL_CONTROL_ACK:
15749 		/* We treat all of these as "fire and forget" */
15750 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15751 		break;
15752 	case DL_INFO_ACK:
15753 		/* Call a routine to handle this one. */
15754 		ill_dlpi_done(ill, DL_INFO_REQ);
15755 		ip_ll_subnet_defaults(ill, mp);
15756 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15757 		return;
15758 	case DL_BIND_ACK:
15759 		/*
15760 		 * We should have an IOCTL waiting on this unless
15761 		 * sent by ill_dl_phys, in which case just return
15762 		 */
15763 		ill_dlpi_done(ill, DL_BIND_REQ);
15764 		if (ill->ill_ifname_pending)
15765 			break;
15766 
15767 		if (!ioctl_aborted)
15768 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15769 		if (mp1 == NULL)
15770 			break;
15771 		/*
15772 		 * Because mp1 was added by ill_dl_up(), and it always
15773 		 * passes a valid connp, connp must be valid here.
15774 		 */
15775 		ASSERT(connp != NULL);
15776 		q = CONNP_TO_WQ(connp);
15777 
15778 		/*
15779 		 * We are exclusive. So nothing can change even after
15780 		 * we get the pending mp. If need be we can put it back
15781 		 * and restart, as in calling ipif_arp_up()  below.
15782 		 */
15783 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15784 
15785 		mutex_enter(&ill->ill_lock);
15786 
15787 		ill->ill_dl_up = 1;
15788 
15789 		if ((info = ill->ill_nic_event_info) != NULL) {
15790 			ip2dbg(("ip_rput_dlpi_writer: unexpected nic event %d "
15791 			    "attached for %s\n", info->hne_event,
15792 			    ill->ill_name));
15793 			if (info->hne_data != NULL)
15794 				kmem_free(info->hne_data, info->hne_datalen);
15795 			kmem_free(info, sizeof (hook_nic_event_t));
15796 		}
15797 
15798 		info = kmem_alloc(sizeof (hook_nic_event_t), KM_NOSLEEP);
15799 		if (info != NULL) {
15800 			info->hne_nic = ill->ill_phyint->phyint_hook_ifindex;
15801 			info->hne_lif = 0;
15802 			info->hne_event = NE_UP;
15803 			info->hne_data = NULL;
15804 			info->hne_datalen = 0;
15805 			info->hne_family = ill->ill_isv6 ?
15806 			    ipst->ips_ipv6_net_data : ipst->ips_ipv4_net_data;
15807 		} else
15808 			ip2dbg(("ip_rput_dlpi_writer: could not attach UP nic "
15809 			    "event information for %s (ENOMEM)\n",
15810 			    ill->ill_name));
15811 
15812 		ill->ill_nic_event_info = info;
15813 
15814 		mutex_exit(&ill->ill_lock);
15815 
15816 		/*
15817 		 * Now bring up the resolver; when that is complete, we'll
15818 		 * create IREs.  Note that we intentionally mirror what
15819 		 * ipif_up() would have done, because we got here by way of
15820 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15821 		 */
15822 		if (ill->ill_isv6) {
15823 			/*
15824 			 * v6 interfaces.
15825 			 * Unlike ARP which has to do another bind
15826 			 * and attach, once we get here we are
15827 			 * done with NDP. Except in the case of
15828 			 * ILLF_XRESOLV, in which case we send an
15829 			 * AR_INTERFACE_UP to the external resolver.
15830 			 * If all goes well, the ioctl will complete
15831 			 * in ip_rput(). If there's an error, we
15832 			 * complete it here.
15833 			 */
15834 			if ((err = ipif_ndp_up(ipif)) == 0) {
15835 				if (ill->ill_flags & ILLF_XRESOLV) {
15836 					mutex_enter(&connp->conn_lock);
15837 					mutex_enter(&ill->ill_lock);
15838 					success = ipsq_pending_mp_add(
15839 					    connp, ipif, q, mp1, 0);
15840 					mutex_exit(&ill->ill_lock);
15841 					mutex_exit(&connp->conn_lock);
15842 					if (success) {
15843 						err = ipif_resolver_up(ipif,
15844 						    Res_act_initial);
15845 						if (err == EINPROGRESS) {
15846 							freemsg(mp);
15847 							return;
15848 						}
15849 						ASSERT(err != 0);
15850 						mp1 = ipsq_pending_mp_get(ipsq,
15851 						    &connp);
15852 						ASSERT(mp1 != NULL);
15853 					} else {
15854 						/* conn has started closing */
15855 						err = EINTR;
15856 					}
15857 				} else { /* Non XRESOLV interface */
15858 					(void) ipif_resolver_up(ipif,
15859 					    Res_act_initial);
15860 					err = ipif_up_done_v6(ipif);
15861 				}
15862 			}
15863 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15864 			/*
15865 			 * ARP and other v4 external resolvers.
15866 			 * Leave the pending mblk intact so that
15867 			 * the ioctl completes in ip_rput().
15868 			 */
15869 			mutex_enter(&connp->conn_lock);
15870 			mutex_enter(&ill->ill_lock);
15871 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15872 			mutex_exit(&ill->ill_lock);
15873 			mutex_exit(&connp->conn_lock);
15874 			if (success) {
15875 				err = ipif_resolver_up(ipif, Res_act_initial);
15876 				if (err == EINPROGRESS) {
15877 					freemsg(mp);
15878 					return;
15879 				}
15880 				ASSERT(err != 0);
15881 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15882 			} else {
15883 				/* The conn has started closing */
15884 				err = EINTR;
15885 			}
15886 		} else {
15887 			/*
15888 			 * This one is complete. Reply to pending ioctl.
15889 			 */
15890 			(void) ipif_resolver_up(ipif, Res_act_initial);
15891 			err = ipif_up_done(ipif);
15892 		}
15893 
15894 		if ((err == 0) && (ill->ill_up_ipifs)) {
15895 			err = ill_up_ipifs(ill, q, mp1);
15896 			if (err == EINPROGRESS) {
15897 				freemsg(mp);
15898 				return;
15899 			}
15900 		}
15901 
15902 		if (ill->ill_up_ipifs) {
15903 			ill_group_cleanup(ill);
15904 		}
15905 
15906 		break;
15907 	case DL_NOTIFY_IND: {
15908 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15909 		ire_t *ire;
15910 		boolean_t need_ire_walk_v4 = B_FALSE;
15911 		boolean_t need_ire_walk_v6 = B_FALSE;
15912 
15913 		switch (notify->dl_notification) {
15914 		case DL_NOTE_PHYS_ADDR:
15915 			err = ill_set_phys_addr(ill, mp);
15916 			break;
15917 
15918 		case DL_NOTE_FASTPATH_FLUSH:
15919 			ill_fastpath_flush(ill);
15920 			break;
15921 
15922 		case DL_NOTE_SDU_SIZE:
15923 			/*
15924 			 * Change the MTU size of the interface, of all
15925 			 * attached ipif's, and of all relevant ire's.  The
15926 			 * new value's a uint32_t at notify->dl_data.
15927 			 * Mtu change Vs. new ire creation - protocol below.
15928 			 *
15929 			 * a Mark the ipif as IPIF_CHANGING.
15930 			 * b Set the new mtu in the ipif.
15931 			 * c Change the ire_max_frag on all affected ires
15932 			 * d Unmark the IPIF_CHANGING
15933 			 *
15934 			 * To see how the protocol works, assume an interface
15935 			 * route is also being added simultaneously by
15936 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15937 			 * the ire. If the ire is created before step a,
15938 			 * it will be cleaned up by step c. If the ire is
15939 			 * created after step d, it will see the new value of
15940 			 * ipif_mtu. Any attempt to create the ire between
15941 			 * steps a to d will fail because of the IPIF_CHANGING
15942 			 * flag. Note that ire_create() is passed a pointer to
15943 			 * the ipif_mtu, and not the value. During ire_add
15944 			 * under the bucket lock, the ire_max_frag of the
15945 			 * new ire being created is set from the ipif/ire from
15946 			 * which it is being derived.
15947 			 */
15948 			mutex_enter(&ill->ill_lock);
15949 			ill->ill_max_frag = (uint_t)notify->dl_data;
15950 
15951 			/*
15952 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15953 			 * leave it alone
15954 			 */
15955 			if (ill->ill_mtu_userspecified) {
15956 				mutex_exit(&ill->ill_lock);
15957 				break;
15958 			}
15959 			ill->ill_max_mtu = ill->ill_max_frag;
15960 			if (ill->ill_isv6) {
15961 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15962 					ill->ill_max_mtu = IPV6_MIN_MTU;
15963 			} else {
15964 				if (ill->ill_max_mtu < IP_MIN_MTU)
15965 					ill->ill_max_mtu = IP_MIN_MTU;
15966 			}
15967 			for (ipif = ill->ill_ipif; ipif != NULL;
15968 			    ipif = ipif->ipif_next) {
15969 				/*
15970 				 * Don't override the mtu if the user
15971 				 * has explicitly set it.
15972 				 */
15973 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15974 					continue;
15975 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15976 				if (ipif->ipif_isv6)
15977 					ire = ipif_to_ire_v6(ipif);
15978 				else
15979 					ire = ipif_to_ire(ipif);
15980 				if (ire != NULL) {
15981 					ire->ire_max_frag = ipif->ipif_mtu;
15982 					ire_refrele(ire);
15983 				}
15984 				if (ipif->ipif_flags & IPIF_UP) {
15985 					if (ill->ill_isv6)
15986 						need_ire_walk_v6 = B_TRUE;
15987 					else
15988 						need_ire_walk_v4 = B_TRUE;
15989 				}
15990 			}
15991 			mutex_exit(&ill->ill_lock);
15992 			if (need_ire_walk_v4)
15993 				ire_walk_v4(ill_mtu_change, (char *)ill,
15994 				    ALL_ZONES, ipst);
15995 			if (need_ire_walk_v6)
15996 				ire_walk_v6(ill_mtu_change, (char *)ill,
15997 				    ALL_ZONES, ipst);
15998 			break;
15999 		case DL_NOTE_LINK_UP:
16000 		case DL_NOTE_LINK_DOWN: {
16001 			/*
16002 			 * We are writer. ill / phyint / ipsq assocs stable.
16003 			 * The RUNNING flag reflects the state of the link.
16004 			 */
16005 			phyint_t *phyint = ill->ill_phyint;
16006 			uint64_t new_phyint_flags;
16007 			boolean_t changed = B_FALSE;
16008 			boolean_t went_up;
16009 
16010 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
16011 			mutex_enter(&phyint->phyint_lock);
16012 			new_phyint_flags = went_up ?
16013 			    phyint->phyint_flags | PHYI_RUNNING :
16014 			    phyint->phyint_flags & ~PHYI_RUNNING;
16015 			if (new_phyint_flags != phyint->phyint_flags) {
16016 				phyint->phyint_flags = new_phyint_flags;
16017 				changed = B_TRUE;
16018 			}
16019 			mutex_exit(&phyint->phyint_lock);
16020 			/*
16021 			 * ill_restart_dad handles the DAD restart and routing
16022 			 * socket notification logic.
16023 			 */
16024 			if (changed) {
16025 				ill_restart_dad(phyint->phyint_illv4, went_up);
16026 				ill_restart_dad(phyint->phyint_illv6, went_up);
16027 			}
16028 			break;
16029 		}
16030 		case DL_NOTE_PROMISC_ON_PHYS:
16031 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16032 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16033 			mutex_enter(&ill->ill_lock);
16034 			ill->ill_promisc_on_phys = B_TRUE;
16035 			mutex_exit(&ill->ill_lock);
16036 			break;
16037 		case DL_NOTE_PROMISC_OFF_PHYS:
16038 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16039 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16040 			mutex_enter(&ill->ill_lock);
16041 			ill->ill_promisc_on_phys = B_FALSE;
16042 			mutex_exit(&ill->ill_lock);
16043 			break;
16044 		case DL_NOTE_CAPAB_RENEG:
16045 			/*
16046 			 * Something changed on the driver side.
16047 			 * It wants us to renegotiate the capabilities
16048 			 * on this ill. One possible cause is the aggregation
16049 			 * interface under us where a port got added or
16050 			 * went away.
16051 			 *
16052 			 * If the capability negotiation is already done
16053 			 * or is in progress, reset the capabilities and
16054 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16055 			 * so that when the ack comes back, we can start
16056 			 * the renegotiation process.
16057 			 *
16058 			 * Note that if ill_capab_reneg is already B_TRUE
16059 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16060 			 * the capability resetting request has been sent
16061 			 * and the renegotiation has not been started yet;
16062 			 * nothing needs to be done in this case.
16063 			 */
16064 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16065 				ill_capability_reset(ill);
16066 				ill->ill_capab_reneg = B_TRUE;
16067 			}
16068 			break;
16069 		default:
16070 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16071 			    "type 0x%x for DL_NOTIFY_IND\n",
16072 			    notify->dl_notification));
16073 			break;
16074 		}
16075 
16076 		/*
16077 		 * As this is an asynchronous operation, we
16078 		 * should not call ill_dlpi_done
16079 		 */
16080 		break;
16081 	}
16082 	case DL_NOTIFY_ACK: {
16083 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16084 
16085 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16086 			ill->ill_note_link = 1;
16087 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16088 		break;
16089 	}
16090 	case DL_PHYS_ADDR_ACK: {
16091 		/*
16092 		 * As part of plumbing the interface via SIOCSLIFNAME,
16093 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16094 		 * whose answers we receive here.  As each answer is received,
16095 		 * we call ill_dlpi_done() to dispatch the next request as
16096 		 * we're processing the current one.  Once all answers have
16097 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16098 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16099 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16100 		 * available, but we know the ioctl is pending on ill_wq.)
16101 		 */
16102 		uint_t paddrlen, paddroff;
16103 
16104 		paddrreq = ill->ill_phys_addr_pend;
16105 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16106 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16107 
16108 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16109 		if (paddrreq == DL_IPV6_TOKEN) {
16110 			/*
16111 			 * bcopy to low-order bits of ill_token
16112 			 *
16113 			 * XXX Temporary hack - currently, all known tokens
16114 			 * are 64 bits, so I'll cheat for the moment.
16115 			 */
16116 			bcopy(mp->b_rptr + paddroff,
16117 			    &ill->ill_token.s6_addr32[2], paddrlen);
16118 			ill->ill_token_length = paddrlen;
16119 			break;
16120 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16121 			ASSERT(ill->ill_nd_lla_mp == NULL);
16122 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16123 			mp = NULL;
16124 			break;
16125 		}
16126 
16127 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16128 		ASSERT(ill->ill_phys_addr_mp == NULL);
16129 		if (!ill->ill_ifname_pending)
16130 			break;
16131 		ill->ill_ifname_pending = 0;
16132 		if (!ioctl_aborted)
16133 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16134 		if (mp1 != NULL) {
16135 			ASSERT(connp == NULL);
16136 			q = ill->ill_wq;
16137 		}
16138 		/*
16139 		 * If any error acks received during the plumbing sequence,
16140 		 * ill_ifname_pending_err will be set. Break out and send up
16141 		 * the error to the pending ioctl.
16142 		 */
16143 		if (ill->ill_ifname_pending_err != 0) {
16144 			err = ill->ill_ifname_pending_err;
16145 			ill->ill_ifname_pending_err = 0;
16146 			break;
16147 		}
16148 
16149 		ill->ill_phys_addr_mp = mp;
16150 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16151 		mp = NULL;
16152 
16153 		/*
16154 		 * If paddrlen is zero, the DLPI provider doesn't support
16155 		 * physical addresses.  The other two tests were historical
16156 		 * workarounds for bugs in our former PPP implementation, but
16157 		 * now other things have grown dependencies on them -- e.g.,
16158 		 * the tun module specifies a dl_addr_length of zero in its
16159 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16160 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16161 		 * but only after careful testing ensures that all dependent
16162 		 * broken DLPI providers have been fixed.
16163 		 */
16164 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16165 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16166 			ill->ill_phys_addr = NULL;
16167 		} else if (paddrlen != ill->ill_phys_addr_length) {
16168 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16169 			    paddrlen, ill->ill_phys_addr_length));
16170 			err = EINVAL;
16171 			break;
16172 		}
16173 
16174 		if (ill->ill_nd_lla_mp == NULL) {
16175 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16176 				err = ENOMEM;
16177 				break;
16178 			}
16179 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16180 		}
16181 
16182 		/*
16183 		 * Set the interface token.  If the zeroth interface address
16184 		 * is unspecified, then set it to the link local address.
16185 		 */
16186 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16187 			(void) ill_setdefaulttoken(ill);
16188 
16189 		ASSERT(ill->ill_ipif->ipif_id == 0);
16190 		if (ipif != NULL &&
16191 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16192 			(void) ipif_setlinklocal(ipif);
16193 		}
16194 		break;
16195 	}
16196 	case DL_OK_ACK:
16197 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16198 		    dl_primstr((int)dloa->dl_correct_primitive),
16199 		    dloa->dl_correct_primitive));
16200 		switch (dloa->dl_correct_primitive) {
16201 		case DL_PROMISCON_REQ:
16202 		case DL_PROMISCOFF_REQ:
16203 		case DL_ENABMULTI_REQ:
16204 		case DL_DISABMULTI_REQ:
16205 		case DL_UNBIND_REQ:
16206 		case DL_ATTACH_REQ:
16207 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16208 			break;
16209 		}
16210 		break;
16211 	default:
16212 		break;
16213 	}
16214 
16215 	freemsg(mp);
16216 	if (mp1 != NULL) {
16217 		/*
16218 		 * The operation must complete without EINPROGRESS
16219 		 * since ipsq_pending_mp_get() has removed the mblk
16220 		 * from ipsq_pending_mp.  Otherwise, the operation
16221 		 * will be stuck forever in the ipsq.
16222 		 */
16223 		ASSERT(err != EINPROGRESS);
16224 
16225 		switch (ipsq->ipsq_current_ioctl) {
16226 		case 0:
16227 			ipsq_current_finish(ipsq);
16228 			break;
16229 
16230 		case SIOCLIFADDIF:
16231 		case SIOCSLIFNAME:
16232 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16233 			break;
16234 
16235 		default:
16236 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16237 			break;
16238 		}
16239 	}
16240 }
16241 
16242 /*
16243  * ip_rput_other is called by ip_rput to handle messages modifying the global
16244  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16245  */
16246 /* ARGSUSED */
16247 void
16248 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16249 {
16250 	ill_t		*ill;
16251 	struct iocblk	*iocp;
16252 	mblk_t		*mp1;
16253 	conn_t		*connp = NULL;
16254 
16255 	ip1dbg(("ip_rput_other "));
16256 	ill = (ill_t *)q->q_ptr;
16257 	/*
16258 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16259 	 * in which case ipsq is NULL.
16260 	 */
16261 	if (ipsq != NULL) {
16262 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16263 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16264 	}
16265 
16266 	switch (mp->b_datap->db_type) {
16267 	case M_ERROR:
16268 	case M_HANGUP:
16269 		/*
16270 		 * The device has a problem.  We force the ILL down.  It can
16271 		 * be brought up again manually using SIOCSIFFLAGS (via
16272 		 * ifconfig or equivalent).
16273 		 */
16274 		ASSERT(ipsq != NULL);
16275 		if (mp->b_rptr < mp->b_wptr)
16276 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16277 		if (ill->ill_error == 0)
16278 			ill->ill_error = ENXIO;
16279 		if (!ill_down_start(q, mp))
16280 			return;
16281 		ipif_all_down_tail(ipsq, q, mp, NULL);
16282 		break;
16283 	case M_IOCACK:
16284 		iocp = (struct iocblk *)mp->b_rptr;
16285 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16286 		switch (iocp->ioc_cmd) {
16287 		case SIOCSTUNPARAM:
16288 		case OSIOCSTUNPARAM:
16289 			ASSERT(ipsq != NULL);
16290 			/*
16291 			 * Finish socket ioctl passed through to tun.
16292 			 * We should have an IOCTL waiting on this.
16293 			 */
16294 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16295 			if (ill->ill_isv6) {
16296 				struct iftun_req *ta;
16297 
16298 				/*
16299 				 * if a source or destination is
16300 				 * being set, try and set the link
16301 				 * local address for the tunnel
16302 				 */
16303 				ta = (struct iftun_req *)mp->b_cont->
16304 				    b_cont->b_rptr;
16305 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16306 					ipif_set_tun_llink(ill, ta);
16307 				}
16308 
16309 			}
16310 			if (mp1 != NULL) {
16311 				/*
16312 				 * Now copy back the b_next/b_prev used by
16313 				 * mi code for the mi_copy* functions.
16314 				 * See ip_sioctl_tunparam() for the reason.
16315 				 * Also protect against missing b_cont.
16316 				 */
16317 				if (mp->b_cont != NULL) {
16318 					mp->b_cont->b_next =
16319 					    mp1->b_cont->b_next;
16320 					mp->b_cont->b_prev =
16321 					    mp1->b_cont->b_prev;
16322 				}
16323 				inet_freemsg(mp1);
16324 				ASSERT(connp != NULL);
16325 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16326 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16327 			} else {
16328 				ASSERT(connp == NULL);
16329 				putnext(q, mp);
16330 			}
16331 			break;
16332 		case SIOCGTUNPARAM:
16333 		case OSIOCGTUNPARAM:
16334 			/*
16335 			 * This is really M_IOCDATA from the tunnel driver.
16336 			 * convert back and complete the ioctl.
16337 			 * We should have an IOCTL waiting on this.
16338 			 */
16339 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16340 			if (mp1) {
16341 				/*
16342 				 * Now copy back the b_next/b_prev used by
16343 				 * mi code for the mi_copy* functions.
16344 				 * See ip_sioctl_tunparam() for the reason.
16345 				 * Also protect against missing b_cont.
16346 				 */
16347 				if (mp->b_cont != NULL) {
16348 					mp->b_cont->b_next =
16349 					    mp1->b_cont->b_next;
16350 					mp->b_cont->b_prev =
16351 					    mp1->b_cont->b_prev;
16352 				}
16353 				inet_freemsg(mp1);
16354 				if (iocp->ioc_error == 0)
16355 					mp->b_datap->db_type = M_IOCDATA;
16356 				ASSERT(connp != NULL);
16357 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16358 				    iocp->ioc_error, COPYOUT, NULL);
16359 			} else {
16360 				ASSERT(connp == NULL);
16361 				putnext(q, mp);
16362 			}
16363 			break;
16364 		default:
16365 			break;
16366 		}
16367 		break;
16368 	case M_IOCNAK:
16369 		iocp = (struct iocblk *)mp->b_rptr;
16370 
16371 		switch (iocp->ioc_cmd) {
16372 		int mode;
16373 
16374 		case DL_IOC_HDR_INFO:
16375 			/*
16376 			 * If this was the first attempt turn of the
16377 			 * fastpath probing.
16378 			 */
16379 			mutex_enter(&ill->ill_lock);
16380 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16381 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16382 				mutex_exit(&ill->ill_lock);
16383 				ill_fastpath_nack(ill);
16384 				ip1dbg(("ip_rput: DLPI fastpath off on "
16385 				    "interface %s\n",
16386 				    ill->ill_name));
16387 			} else {
16388 				mutex_exit(&ill->ill_lock);
16389 			}
16390 			freemsg(mp);
16391 			break;
16392 		case SIOCSTUNPARAM:
16393 		case OSIOCSTUNPARAM:
16394 			ASSERT(ipsq != NULL);
16395 			/*
16396 			 * Finish socket ioctl passed through to tun
16397 			 * We should have an IOCTL waiting on this.
16398 			 */
16399 			/* FALLTHRU */
16400 		case SIOCGTUNPARAM:
16401 		case OSIOCGTUNPARAM:
16402 			/*
16403 			 * This is really M_IOCDATA from the tunnel driver.
16404 			 * convert back and complete the ioctl.
16405 			 * We should have an IOCTL waiting on this.
16406 			 */
16407 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16408 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16409 				mp1 = ill_pending_mp_get(ill, &connp,
16410 				    iocp->ioc_id);
16411 				mode = COPYOUT;
16412 				ipsq = NULL;
16413 			} else {
16414 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16415 				mode = NO_COPYOUT;
16416 			}
16417 			if (mp1 != NULL) {
16418 				/*
16419 				 * Now copy back the b_next/b_prev used by
16420 				 * mi code for the mi_copy* functions.
16421 				 * See ip_sioctl_tunparam() for the reason.
16422 				 * Also protect against missing b_cont.
16423 				 */
16424 				if (mp->b_cont != NULL) {
16425 					mp->b_cont->b_next =
16426 					    mp1->b_cont->b_next;
16427 					mp->b_cont->b_prev =
16428 					    mp1->b_cont->b_prev;
16429 				}
16430 				inet_freemsg(mp1);
16431 				if (iocp->ioc_error == 0)
16432 					iocp->ioc_error = EINVAL;
16433 				ASSERT(connp != NULL);
16434 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16435 				    iocp->ioc_error, mode, ipsq);
16436 			} else {
16437 				ASSERT(connp == NULL);
16438 				putnext(q, mp);
16439 			}
16440 			break;
16441 		default:
16442 			break;
16443 		}
16444 	default:
16445 		break;
16446 	}
16447 }
16448 
16449 /*
16450  * NOTE : This function does not ire_refrele the ire argument passed in.
16451  *
16452  * IPQoS notes
16453  * IP policy is invoked twice for a forwarded packet, once on the read side
16454  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16455  * enabled. An additional parameter, in_ill, has been added for this purpose.
16456  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16457  * because ip_mroute drops this information.
16458  *
16459  */
16460 void
16461 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16462 {
16463 	uint32_t	old_pkt_len;
16464 	uint32_t	pkt_len;
16465 	queue_t	*q;
16466 	uint32_t	sum;
16467 #define	rptr	((uchar_t *)ipha)
16468 	uint32_t	max_frag;
16469 	uint32_t	ill_index;
16470 	ill_t		*out_ill;
16471 	mib2_ipIfStatsEntry_t *mibptr;
16472 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16473 
16474 	/* Get the ill_index of the incoming ILL */
16475 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16476 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16477 
16478 	/* Initiate Read side IPPF processing */
16479 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16480 		ip_process(IPP_FWD_IN, &mp, ill_index);
16481 		if (mp == NULL) {
16482 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16483 			    "during IPPF processing\n"));
16484 			return;
16485 		}
16486 	}
16487 
16488 	/* Adjust the checksum to reflect the ttl decrement. */
16489 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16490 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16491 
16492 	if (ipha->ipha_ttl-- <= 1) {
16493 		if (ip_csum_hdr(ipha)) {
16494 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16495 			goto drop_pkt;
16496 		}
16497 		/*
16498 		 * Note: ire_stq this will be NULL for multicast
16499 		 * datagrams using the long path through arp (the IRE
16500 		 * is not an IRE_CACHE). This should not cause
16501 		 * problems since we don't generate ICMP errors for
16502 		 * multicast packets.
16503 		 */
16504 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16505 		q = ire->ire_stq;
16506 		if (q != NULL) {
16507 			/* Sent by forwarding path, and router is global zone */
16508 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16509 			    GLOBAL_ZONEID, ipst);
16510 		} else
16511 			freemsg(mp);
16512 		return;
16513 	}
16514 
16515 	/*
16516 	 * Don't forward if the interface is down
16517 	 */
16518 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16519 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16520 		ip2dbg(("ip_rput_forward:interface is down\n"));
16521 		goto drop_pkt;
16522 	}
16523 
16524 	/* Get the ill_index of the outgoing ILL */
16525 	out_ill = ire_to_ill(ire);
16526 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16527 
16528 	DTRACE_PROBE4(ip4__forwarding__start,
16529 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16530 
16531 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16532 	    ipst->ips_ipv4firewall_forwarding,
16533 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16534 
16535 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16536 
16537 	if (mp == NULL)
16538 		return;
16539 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16540 
16541 	if (is_system_labeled()) {
16542 		mblk_t *mp1;
16543 
16544 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16545 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16546 			goto drop_pkt;
16547 		}
16548 		/* Size may have changed */
16549 		mp = mp1;
16550 		ipha = (ipha_t *)mp->b_rptr;
16551 		pkt_len = ntohs(ipha->ipha_length);
16552 	}
16553 
16554 	/* Check if there are options to update */
16555 	if (!IS_SIMPLE_IPH(ipha)) {
16556 		if (ip_csum_hdr(ipha)) {
16557 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16558 			goto drop_pkt;
16559 		}
16560 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16561 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16562 			return;
16563 		}
16564 
16565 		ipha->ipha_hdr_checksum = 0;
16566 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16567 	}
16568 	max_frag = ire->ire_max_frag;
16569 	if (pkt_len > max_frag) {
16570 		/*
16571 		 * It needs fragging on its way out.  We haven't
16572 		 * verified the header checksum yet.  Since we
16573 		 * are going to put a surely good checksum in the
16574 		 * outgoing header, we have to make sure that it
16575 		 * was good coming in.
16576 		 */
16577 		if (ip_csum_hdr(ipha)) {
16578 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16579 			goto drop_pkt;
16580 		}
16581 		/* Initiate Write side IPPF processing */
16582 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16583 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16584 			if (mp == NULL) {
16585 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16586 				    " during IPPF processing\n"));
16587 				return;
16588 			}
16589 		}
16590 		/*
16591 		 * Handle labeled packet resizing.
16592 		 *
16593 		 * If we have added a label, inform ip_wput_frag() of its
16594 		 * effect on the MTU for ICMP messages.
16595 		 */
16596 		if (pkt_len > old_pkt_len) {
16597 			uint32_t secopt_size;
16598 
16599 			secopt_size = pkt_len - old_pkt_len;
16600 			if (secopt_size < max_frag)
16601 				max_frag -= secopt_size;
16602 		}
16603 
16604 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16605 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16606 		return;
16607 	}
16608 
16609 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16610 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16611 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16612 	    ipst->ips_ipv4firewall_physical_out,
16613 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16614 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16615 	if (mp == NULL)
16616 		return;
16617 
16618 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16619 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16620 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16621 	/* ip_xmit_v4 always consumes the packet */
16622 	return;
16623 
16624 drop_pkt:;
16625 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16626 	freemsg(mp);
16627 #undef	rptr
16628 }
16629 
16630 void
16631 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16632 {
16633 	ire_t	*ire;
16634 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16635 
16636 	ASSERT(!ipif->ipif_isv6);
16637 	/*
16638 	 * Find an IRE which matches the destination and the outgoing
16639 	 * queue in the cache table. All we need is an IRE_CACHE which
16640 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16641 	 * then it is enough to have some IRE_CACHE in the group.
16642 	 */
16643 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16644 		dst = ipif->ipif_pp_dst_addr;
16645 
16646 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16647 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16648 	if (ire == NULL) {
16649 		/*
16650 		 * Mark this packet to make it be delivered to
16651 		 * ip_rput_forward after the new ire has been
16652 		 * created.
16653 		 */
16654 		mp->b_prev = NULL;
16655 		mp->b_next = mp;
16656 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16657 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16658 	} else {
16659 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16660 		IRE_REFRELE(ire);
16661 	}
16662 }
16663 
16664 /* Update any source route, record route or timestamp options */
16665 static int
16666 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16667 {
16668 	ipoptp_t	opts;
16669 	uchar_t		*opt;
16670 	uint8_t		optval;
16671 	uint8_t		optlen;
16672 	ipaddr_t	dst;
16673 	uint32_t	ts;
16674 	ire_t		*dst_ire = NULL;
16675 	ire_t		*tmp_ire = NULL;
16676 	timestruc_t	now;
16677 
16678 	ip2dbg(("ip_rput_forward_options\n"));
16679 	dst = ipha->ipha_dst;
16680 	for (optval = ipoptp_first(&opts, ipha);
16681 	    optval != IPOPT_EOL;
16682 	    optval = ipoptp_next(&opts)) {
16683 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16684 		opt = opts.ipoptp_cur;
16685 		optlen = opts.ipoptp_len;
16686 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16687 		    optval, opts.ipoptp_len));
16688 		switch (optval) {
16689 			uint32_t off;
16690 		case IPOPT_SSRR:
16691 		case IPOPT_LSRR:
16692 			/* Check if adminstratively disabled */
16693 			if (!ipst->ips_ip_forward_src_routed) {
16694 				if (ire->ire_stq != NULL) {
16695 					/*
16696 					 * Sent by forwarding path, and router
16697 					 * is global zone
16698 					 */
16699 					icmp_unreachable(ire->ire_stq, mp,
16700 					    ICMP_SOURCE_ROUTE_FAILED,
16701 					    GLOBAL_ZONEID, ipst);
16702 				} else {
16703 					ip0dbg(("ip_rput_forward_options: "
16704 					    "unable to send unreach\n"));
16705 					freemsg(mp);
16706 				}
16707 				return (-1);
16708 			}
16709 
16710 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16711 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16712 			if (dst_ire == NULL) {
16713 				/*
16714 				 * Must be partial since ip_rput_options
16715 				 * checked for strict.
16716 				 */
16717 				break;
16718 			}
16719 			off = opt[IPOPT_OFFSET];
16720 			off--;
16721 		redo_srr:
16722 			if (optlen < IP_ADDR_LEN ||
16723 			    off > optlen - IP_ADDR_LEN) {
16724 				/* End of source route */
16725 				ip1dbg((
16726 				    "ip_rput_forward_options: end of SR\n"));
16727 				ire_refrele(dst_ire);
16728 				break;
16729 			}
16730 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16731 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16732 			    IP_ADDR_LEN);
16733 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16734 			    ntohl(dst)));
16735 
16736 			/*
16737 			 * Check if our address is present more than
16738 			 * once as consecutive hops in source route.
16739 			 */
16740 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16741 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16742 			if (tmp_ire != NULL) {
16743 				ire_refrele(tmp_ire);
16744 				off += IP_ADDR_LEN;
16745 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16746 				goto redo_srr;
16747 			}
16748 			ipha->ipha_dst = dst;
16749 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16750 			ire_refrele(dst_ire);
16751 			break;
16752 		case IPOPT_RR:
16753 			off = opt[IPOPT_OFFSET];
16754 			off--;
16755 			if (optlen < IP_ADDR_LEN ||
16756 			    off > optlen - IP_ADDR_LEN) {
16757 				/* No more room - ignore */
16758 				ip1dbg((
16759 				    "ip_rput_forward_options: end of RR\n"));
16760 				break;
16761 			}
16762 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16763 			    IP_ADDR_LEN);
16764 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16765 			break;
16766 		case IPOPT_TS:
16767 			/* Insert timestamp if there is room */
16768 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16769 			case IPOPT_TS_TSONLY:
16770 				off = IPOPT_TS_TIMELEN;
16771 				break;
16772 			case IPOPT_TS_PRESPEC:
16773 			case IPOPT_TS_PRESPEC_RFC791:
16774 				/* Verify that the address matched */
16775 				off = opt[IPOPT_OFFSET] - 1;
16776 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16777 				dst_ire = ire_ctable_lookup(dst, 0,
16778 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16779 				    MATCH_IRE_TYPE, ipst);
16780 				if (dst_ire == NULL) {
16781 					/* Not for us */
16782 					break;
16783 				}
16784 				ire_refrele(dst_ire);
16785 				/* FALLTHRU */
16786 			case IPOPT_TS_TSANDADDR:
16787 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16788 				break;
16789 			default:
16790 				/*
16791 				 * ip_*put_options should have already
16792 				 * dropped this packet.
16793 				 */
16794 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16795 				    "unknown IT - bug in ip_rput_options?\n");
16796 				return (0);	/* Keep "lint" happy */
16797 			}
16798 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16799 				/* Increase overflow counter */
16800 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16801 				opt[IPOPT_POS_OV_FLG] =
16802 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16803 				    (off << 4));
16804 				break;
16805 			}
16806 			off = opt[IPOPT_OFFSET] - 1;
16807 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16808 			case IPOPT_TS_PRESPEC:
16809 			case IPOPT_TS_PRESPEC_RFC791:
16810 			case IPOPT_TS_TSANDADDR:
16811 				bcopy(&ire->ire_src_addr,
16812 				    (char *)opt + off, IP_ADDR_LEN);
16813 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16814 				/* FALLTHRU */
16815 			case IPOPT_TS_TSONLY:
16816 				off = opt[IPOPT_OFFSET] - 1;
16817 				/* Compute # of milliseconds since midnight */
16818 				gethrestime(&now);
16819 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16820 				    now.tv_nsec / (NANOSEC / MILLISEC);
16821 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16822 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16823 				break;
16824 			}
16825 			break;
16826 		}
16827 	}
16828 	return (0);
16829 }
16830 
16831 /*
16832  * This is called after processing at least one of AH/ESP headers.
16833  *
16834  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16835  * the actual, physical interface on which the packet was received,
16836  * but, when ip_strict_dst_multihoming is set to 1, could be the
16837  * interface which had the ipha_dst configured when the packet went
16838  * through ip_rput. The ill_index corresponding to the recv_ill
16839  * is saved in ipsec_in_rill_index
16840  *
16841  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16842  * cannot assume "ire" points to valid data for any IPv6 cases.
16843  */
16844 void
16845 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16846 {
16847 	mblk_t *mp;
16848 	ipaddr_t dst;
16849 	in6_addr_t *v6dstp;
16850 	ipha_t *ipha;
16851 	ip6_t *ip6h;
16852 	ipsec_in_t *ii;
16853 	boolean_t ill_need_rele = B_FALSE;
16854 	boolean_t rill_need_rele = B_FALSE;
16855 	boolean_t ire_need_rele = B_FALSE;
16856 	netstack_t	*ns;
16857 	ip_stack_t	*ipst;
16858 
16859 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16860 	ASSERT(ii->ipsec_in_ill_index != 0);
16861 	ns = ii->ipsec_in_ns;
16862 	ASSERT(ii->ipsec_in_ns != NULL);
16863 	ipst = ns->netstack_ip;
16864 
16865 	mp = ipsec_mp->b_cont;
16866 	ASSERT(mp != NULL);
16867 
16868 
16869 	if (ill == NULL) {
16870 		ASSERT(recv_ill == NULL);
16871 		/*
16872 		 * We need to get the original queue on which ip_rput_local
16873 		 * or ip_rput_data_v6 was called.
16874 		 */
16875 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16876 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16877 		ill_need_rele = B_TRUE;
16878 
16879 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16880 			recv_ill = ill_lookup_on_ifindex(
16881 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16882 			    NULL, NULL, NULL, NULL, ipst);
16883 			rill_need_rele = B_TRUE;
16884 		} else {
16885 			recv_ill = ill;
16886 		}
16887 
16888 		if ((ill == NULL) || (recv_ill == NULL)) {
16889 			ip0dbg(("ip_fanout_proto_again: interface "
16890 			    "disappeared\n"));
16891 			if (ill != NULL)
16892 				ill_refrele(ill);
16893 			if (recv_ill != NULL)
16894 				ill_refrele(recv_ill);
16895 			freemsg(ipsec_mp);
16896 			return;
16897 		}
16898 	}
16899 
16900 	ASSERT(ill != NULL && recv_ill != NULL);
16901 
16902 	if (mp->b_datap->db_type == M_CTL) {
16903 		/*
16904 		 * AH/ESP is returning the ICMP message after
16905 		 * removing their headers. Fanout again till
16906 		 * it gets to the right protocol.
16907 		 */
16908 		if (ii->ipsec_in_v4) {
16909 			icmph_t *icmph;
16910 			int iph_hdr_length;
16911 			int hdr_length;
16912 
16913 			ipha = (ipha_t *)mp->b_rptr;
16914 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16915 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16916 			ipha = (ipha_t *)&icmph[1];
16917 			hdr_length = IPH_HDR_LENGTH(ipha);
16918 			/*
16919 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16920 			 * Reset the type to M_DATA.
16921 			 */
16922 			mp->b_datap->db_type = M_DATA;
16923 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16924 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16925 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16926 		} else {
16927 			icmp6_t *icmp6;
16928 			int hdr_length;
16929 
16930 			ip6h = (ip6_t *)mp->b_rptr;
16931 			/* Don't call hdr_length_v6() unless you have to. */
16932 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16933 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16934 			else
16935 				hdr_length = IPV6_HDR_LEN;
16936 
16937 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16938 			/*
16939 			 * icmp_inbound_error_fanout_v6 may need to do
16940 			 * pullupmsg.  Reset the type to M_DATA.
16941 			 */
16942 			mp->b_datap->db_type = M_DATA;
16943 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16944 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16945 		}
16946 		if (ill_need_rele)
16947 			ill_refrele(ill);
16948 		if (rill_need_rele)
16949 			ill_refrele(recv_ill);
16950 		return;
16951 	}
16952 
16953 	if (ii->ipsec_in_v4) {
16954 		ipha = (ipha_t *)mp->b_rptr;
16955 		dst = ipha->ipha_dst;
16956 		if (CLASSD(dst)) {
16957 			/*
16958 			 * Multicast has to be delivered to all streams.
16959 			 */
16960 			dst = INADDR_BROADCAST;
16961 		}
16962 
16963 		if (ire == NULL) {
16964 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16965 			    MBLK_GETLABEL(mp), ipst);
16966 			if (ire == NULL) {
16967 				if (ill_need_rele)
16968 					ill_refrele(ill);
16969 				if (rill_need_rele)
16970 					ill_refrele(recv_ill);
16971 				ip1dbg(("ip_fanout_proto_again: "
16972 				    "IRE not found"));
16973 				freemsg(ipsec_mp);
16974 				return;
16975 			}
16976 			ire_need_rele = B_TRUE;
16977 		}
16978 
16979 		switch (ipha->ipha_protocol) {
16980 			case IPPROTO_UDP:
16981 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16982 				    recv_ill);
16983 				if (ire_need_rele)
16984 					ire_refrele(ire);
16985 				break;
16986 			case IPPROTO_TCP:
16987 				if (!ire_need_rele)
16988 					IRE_REFHOLD(ire);
16989 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16990 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16991 				IRE_REFRELE(ire);
16992 				if (mp != NULL)
16993 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16994 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16995 				break;
16996 			case IPPROTO_SCTP:
16997 				if (!ire_need_rele)
16998 					IRE_REFHOLD(ire);
16999 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
17000 				    ipsec_mp, 0, ill->ill_rq, dst);
17001 				break;
17002 			default:
17003 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
17004 				    recv_ill, B_FALSE);
17005 				if (ire_need_rele)
17006 					ire_refrele(ire);
17007 				break;
17008 		}
17009 	} else {
17010 		uint32_t rput_flags = 0;
17011 
17012 		ip6h = (ip6_t *)mp->b_rptr;
17013 		v6dstp = &ip6h->ip6_dst;
17014 		/*
17015 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
17016 		 * address.
17017 		 *
17018 		 * Currently, we don't store that state in the IPSEC_IN
17019 		 * message, and we may need to.
17020 		 */
17021 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
17022 		    IP6_IN_LLMCAST : 0);
17023 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
17024 		    NULL, NULL);
17025 	}
17026 	if (ill_need_rele)
17027 		ill_refrele(ill);
17028 	if (rill_need_rele)
17029 		ill_refrele(recv_ill);
17030 }
17031 
17032 /*
17033  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17034  * returns 'true' if there are still fragments left on the queue, in
17035  * which case we restart the timer.
17036  */
17037 void
17038 ill_frag_timer(void *arg)
17039 {
17040 	ill_t	*ill = (ill_t *)arg;
17041 	boolean_t frag_pending;
17042 	ip_stack_t	*ipst = ill->ill_ipst;
17043 
17044 	mutex_enter(&ill->ill_lock);
17045 	ASSERT(!ill->ill_fragtimer_executing);
17046 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17047 		ill->ill_frag_timer_id = 0;
17048 		mutex_exit(&ill->ill_lock);
17049 		return;
17050 	}
17051 	ill->ill_fragtimer_executing = 1;
17052 	mutex_exit(&ill->ill_lock);
17053 
17054 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17055 
17056 	/*
17057 	 * Restart the timer, if we have fragments pending or if someone
17058 	 * wanted us to be scheduled again.
17059 	 */
17060 	mutex_enter(&ill->ill_lock);
17061 	ill->ill_fragtimer_executing = 0;
17062 	ill->ill_frag_timer_id = 0;
17063 	if (frag_pending || ill->ill_fragtimer_needrestart)
17064 		ill_frag_timer_start(ill);
17065 	mutex_exit(&ill->ill_lock);
17066 }
17067 
17068 void
17069 ill_frag_timer_start(ill_t *ill)
17070 {
17071 	ip_stack_t	*ipst = ill->ill_ipst;
17072 
17073 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17074 
17075 	/* If the ill is closing or opening don't proceed */
17076 	if (ill->ill_state_flags & ILL_CONDEMNED)
17077 		return;
17078 
17079 	if (ill->ill_fragtimer_executing) {
17080 		/*
17081 		 * ill_frag_timer is currently executing. Just record the
17082 		 * the fact that we want the timer to be restarted.
17083 		 * ill_frag_timer will post a timeout before it returns,
17084 		 * ensuring it will be called again.
17085 		 */
17086 		ill->ill_fragtimer_needrestart = 1;
17087 		return;
17088 	}
17089 
17090 	if (ill->ill_frag_timer_id == 0) {
17091 		/*
17092 		 * The timer is neither running nor is the timeout handler
17093 		 * executing. Post a timeout so that ill_frag_timer will be
17094 		 * called
17095 		 */
17096 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17097 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17098 		ill->ill_fragtimer_needrestart = 0;
17099 	}
17100 }
17101 
17102 /*
17103  * This routine is needed for loopback when forwarding multicasts.
17104  *
17105  * IPQoS Notes:
17106  * IPPF processing is done in fanout routines.
17107  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17108  * processing for IPsec packets is done when it comes back in clear.
17109  * NOTE : The callers of this function need to do the ire_refrele for the
17110  *	  ire that is being passed in.
17111  */
17112 void
17113 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17114     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17115 {
17116 	ill_t	*ill = (ill_t *)q->q_ptr;
17117 	uint32_t	sum;
17118 	uint32_t	u1;
17119 	uint32_t	u2;
17120 	int		hdr_length;
17121 	boolean_t	mctl_present;
17122 	mblk_t		*first_mp = mp;
17123 	mblk_t		*hada_mp = NULL;
17124 	ipha_t		*inner_ipha;
17125 	ip_stack_t	*ipst;
17126 
17127 	ASSERT(recv_ill != NULL);
17128 	ipst = recv_ill->ill_ipst;
17129 
17130 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17131 	    "ip_rput_locl_start: q %p", q);
17132 
17133 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17134 	ASSERT(ill != NULL);
17135 
17136 
17137 #define	rptr	((uchar_t *)ipha)
17138 #define	iphs	((uint16_t *)ipha)
17139 
17140 	/*
17141 	 * no UDP or TCP packet should come here anymore.
17142 	 */
17143 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17144 	    ipha->ipha_protocol != IPPROTO_UDP);
17145 
17146 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17147 	if (mctl_present &&
17148 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17149 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17150 
17151 		/*
17152 		 * It's an IPsec accelerated packet.
17153 		 * Keep a pointer to the data attributes around until
17154 		 * we allocate the ipsec_info_t.
17155 		 */
17156 		IPSECHW_DEBUG(IPSECHW_PKT,
17157 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17158 		hada_mp = first_mp;
17159 		hada_mp->b_cont = NULL;
17160 		/*
17161 		 * Since it is accelerated, it comes directly from
17162 		 * the ill and the data attributes is followed by
17163 		 * the packet data.
17164 		 */
17165 		ASSERT(mp->b_datap->db_type != M_CTL);
17166 		first_mp = mp;
17167 		mctl_present = B_FALSE;
17168 	}
17169 
17170 	/*
17171 	 * IF M_CTL is not present, then ipsec_in_is_secure
17172 	 * should return B_TRUE. There is a case where loopback
17173 	 * packets has an M_CTL in the front with all the
17174 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17175 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17176 	 * packets never comes here, it is safe to ASSERT the
17177 	 * following.
17178 	 */
17179 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17180 
17181 	/*
17182 	 * Also, we should never have an mctl_present if this is an
17183 	 * ESP-in-UDP packet.
17184 	 */
17185 	ASSERT(!mctl_present || !esp_in_udp_packet);
17186 
17187 
17188 	/* u1 is # words of IP options */
17189 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17190 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17191 
17192 	if (u1 || (!esp_in_udp_packet && !mctl_present)) {
17193 		if (u1) {
17194 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17195 				if (hada_mp != NULL)
17196 					freemsg(hada_mp);
17197 				return;
17198 			}
17199 		} else {
17200 			/* Check the IP header checksum.  */
17201 #define	uph	((uint16_t *)ipha)
17202 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17203 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17204 #undef  uph
17205 			/* finish doing IP checksum */
17206 			sum = (sum & 0xFFFF) + (sum >> 16);
17207 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17208 			if (sum && sum != 0xFFFF) {
17209 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17210 				goto drop_pkt;
17211 			}
17212 		}
17213 	}
17214 
17215 	/*
17216 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17217 	 * might be called more than once for secure packets, count only
17218 	 * the first time.
17219 	 */
17220 	if (!mctl_present) {
17221 		UPDATE_IB_PKT_COUNT(ire);
17222 		ire->ire_last_used_time = lbolt;
17223 	}
17224 
17225 	/* Check for fragmentation offset. */
17226 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17227 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17228 	if (u1) {
17229 		/*
17230 		 * We re-assemble fragments before we do the AH/ESP
17231 		 * processing. Thus, M_CTL should not be present
17232 		 * while we are re-assembling.
17233 		 */
17234 		ASSERT(!mctl_present);
17235 		ASSERT(first_mp == mp);
17236 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17237 			return;
17238 		}
17239 		/*
17240 		 * Make sure that first_mp points back to mp as
17241 		 * the mp we came in with could have changed in
17242 		 * ip_rput_fragment().
17243 		 */
17244 		ipha = (ipha_t *)mp->b_rptr;
17245 		first_mp = mp;
17246 	}
17247 
17248 	/*
17249 	 * Clear hardware checksumming flag as it is currently only
17250 	 * used by TCP and UDP.
17251 	 */
17252 	DB_CKSUMFLAGS(mp) = 0;
17253 
17254 	/* Now we have a complete datagram, destined for this machine. */
17255 	u1 = IPH_HDR_LENGTH(ipha);
17256 	switch (ipha->ipha_protocol) {
17257 	case IPPROTO_ICMP: {
17258 		ire_t		*ire_zone;
17259 		ilm_t		*ilm;
17260 		mblk_t		*mp1;
17261 		zoneid_t	last_zoneid;
17262 
17263 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17264 			ASSERT(ire->ire_type == IRE_BROADCAST);
17265 			/*
17266 			 * In the multicast case, applications may have joined
17267 			 * the group from different zones, so we need to deliver
17268 			 * the packet to each of them. Loop through the
17269 			 * multicast memberships structures (ilm) on the receive
17270 			 * ill and send a copy of the packet up each matching
17271 			 * one. However, we don't do this for multicasts sent on
17272 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17273 			 * they must stay in the sender's zone.
17274 			 *
17275 			 * ilm_add_v6() ensures that ilms in the same zone are
17276 			 * contiguous in the ill_ilm list. We use this property
17277 			 * to avoid sending duplicates needed when two
17278 			 * applications in the same zone join the same group on
17279 			 * different logical interfaces: we ignore the ilm if
17280 			 * its zoneid is the same as the last matching one.
17281 			 * In addition, the sending of the packet for
17282 			 * ire_zoneid is delayed until all of the other ilms
17283 			 * have been exhausted.
17284 			 */
17285 			last_zoneid = -1;
17286 			ILM_WALKER_HOLD(recv_ill);
17287 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17288 			    ilm = ilm->ilm_next) {
17289 				if ((ilm->ilm_flags & ILM_DELETED) ||
17290 				    ipha->ipha_dst != ilm->ilm_addr ||
17291 				    ilm->ilm_zoneid == last_zoneid ||
17292 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17293 				    ilm->ilm_zoneid == ALL_ZONES ||
17294 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17295 					continue;
17296 				mp1 = ip_copymsg(first_mp);
17297 				if (mp1 == NULL)
17298 					continue;
17299 				icmp_inbound(q, mp1, B_TRUE, ill,
17300 				    0, sum, mctl_present, B_TRUE,
17301 				    recv_ill, ilm->ilm_zoneid);
17302 				last_zoneid = ilm->ilm_zoneid;
17303 			}
17304 			ILM_WALKER_RELE(recv_ill);
17305 		} else if (ire->ire_type == IRE_BROADCAST) {
17306 			/*
17307 			 * In the broadcast case, there may be many zones
17308 			 * which need a copy of the packet delivered to them.
17309 			 * There is one IRE_BROADCAST per broadcast address
17310 			 * and per zone; we walk those using a helper function.
17311 			 * In addition, the sending of the packet for ire is
17312 			 * delayed until all of the other ires have been
17313 			 * processed.
17314 			 */
17315 			IRB_REFHOLD(ire->ire_bucket);
17316 			ire_zone = NULL;
17317 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17318 			    ire)) != NULL) {
17319 				mp1 = ip_copymsg(first_mp);
17320 				if (mp1 == NULL)
17321 					continue;
17322 
17323 				UPDATE_IB_PKT_COUNT(ire_zone);
17324 				ire_zone->ire_last_used_time = lbolt;
17325 				icmp_inbound(q, mp1, B_TRUE, ill,
17326 				    0, sum, mctl_present, B_TRUE,
17327 				    recv_ill, ire_zone->ire_zoneid);
17328 			}
17329 			IRB_REFRELE(ire->ire_bucket);
17330 		}
17331 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17332 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17333 		    ire->ire_zoneid);
17334 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17335 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17336 		return;
17337 	}
17338 	case IPPROTO_IGMP:
17339 		/*
17340 		 * If we are not willing to accept IGMP packets in clear,
17341 		 * then check with global policy.
17342 		 */
17343 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17344 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17345 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17346 			if (first_mp == NULL)
17347 				return;
17348 		}
17349 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17350 			freemsg(first_mp);
17351 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17352 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17353 			return;
17354 		}
17355 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17356 			/* Bad packet - discarded by igmp_input */
17357 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17358 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17359 			if (mctl_present)
17360 				freeb(first_mp);
17361 			return;
17362 		}
17363 		/*
17364 		 * igmp_input() may have returned the pulled up message.
17365 		 * So first_mp and ipha need to be reinitialized.
17366 		 */
17367 		ipha = (ipha_t *)mp->b_rptr;
17368 		if (mctl_present)
17369 			first_mp->b_cont = mp;
17370 		else
17371 			first_mp = mp;
17372 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17373 		    connf_head != NULL) {
17374 			/* No user-level listener for IGMP packets */
17375 			goto drop_pkt;
17376 		}
17377 		/* deliver to local raw users */
17378 		break;
17379 	case IPPROTO_PIM:
17380 		/*
17381 		 * If we are not willing to accept PIM packets in clear,
17382 		 * then check with global policy.
17383 		 */
17384 		if (ipst->ips_pim_accept_clear_messages == 0) {
17385 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17386 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17387 			if (first_mp == NULL)
17388 				return;
17389 		}
17390 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17391 			freemsg(first_mp);
17392 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17393 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17394 			return;
17395 		}
17396 		if (pim_input(q, mp, ill) != 0) {
17397 			/* Bad packet - discarded by pim_input */
17398 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17399 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17400 			if (mctl_present)
17401 				freeb(first_mp);
17402 			return;
17403 		}
17404 
17405 		/*
17406 		 * pim_input() may have pulled up the message so ipha needs to
17407 		 * be reinitialized.
17408 		 */
17409 		ipha = (ipha_t *)mp->b_rptr;
17410 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17411 		    connf_head != NULL) {
17412 			/* No user-level listener for PIM packets */
17413 			goto drop_pkt;
17414 		}
17415 		/* deliver to local raw users */
17416 		break;
17417 	case IPPROTO_ENCAP:
17418 		/*
17419 		 * Handle self-encapsulated packets (IP-in-IP where
17420 		 * the inner addresses == the outer addresses).
17421 		 */
17422 		hdr_length = IPH_HDR_LENGTH(ipha);
17423 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17424 		    mp->b_wptr) {
17425 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17426 			    sizeof (ipha_t) - mp->b_rptr)) {
17427 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17428 				freemsg(first_mp);
17429 				return;
17430 			}
17431 			ipha = (ipha_t *)mp->b_rptr;
17432 		}
17433 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17434 		/*
17435 		 * Check the sanity of the inner IP header.
17436 		 */
17437 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17438 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17439 			freemsg(first_mp);
17440 			return;
17441 		}
17442 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17443 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17444 			freemsg(first_mp);
17445 			return;
17446 		}
17447 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17448 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17449 			ipsec_in_t *ii;
17450 
17451 			/*
17452 			 * Self-encapsulated tunnel packet. Remove
17453 			 * the outer IP header and fanout again.
17454 			 * We also need to make sure that the inner
17455 			 * header is pulled up until options.
17456 			 */
17457 			mp->b_rptr = (uchar_t *)inner_ipha;
17458 			ipha = inner_ipha;
17459 			hdr_length = IPH_HDR_LENGTH(ipha);
17460 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17461 				if (!pullupmsg(mp, (uchar_t *)ipha +
17462 				    + hdr_length - mp->b_rptr)) {
17463 					freemsg(first_mp);
17464 					return;
17465 				}
17466 				ipha = (ipha_t *)mp->b_rptr;
17467 			}
17468 			if (!mctl_present) {
17469 				ASSERT(first_mp == mp);
17470 				/*
17471 				 * This means that somebody is sending
17472 				 * Self-encapsualted packets without AH/ESP.
17473 				 * If AH/ESP was present, we would have already
17474 				 * allocated the first_mp.
17475 				 */
17476 				first_mp = ipsec_in_alloc(B_TRUE,
17477 				    ipst->ips_netstack);
17478 				if (first_mp == NULL) {
17479 					ip1dbg(("ip_proto_input: IPSEC_IN "
17480 					    "allocation failure.\n"));
17481 					BUMP_MIB(ill->ill_ip_mib,
17482 					    ipIfStatsInDiscards);
17483 					freemsg(mp);
17484 					return;
17485 				}
17486 				first_mp->b_cont = mp;
17487 			}
17488 			/*
17489 			 * We generally store the ill_index if we need to
17490 			 * do IPsec processing as we lose the ill queue when
17491 			 * we come back. But in this case, we never should
17492 			 * have to store the ill_index here as it should have
17493 			 * been stored previously when we processed the
17494 			 * AH/ESP header in this routine or for non-ipsec
17495 			 * cases, we still have the queue. But for some bad
17496 			 * packets from the wire, we can get to IPsec after
17497 			 * this and we better store the index for that case.
17498 			 */
17499 			ill = (ill_t *)q->q_ptr;
17500 			ii = (ipsec_in_t *)first_mp->b_rptr;
17501 			ii->ipsec_in_ill_index =
17502 			    ill->ill_phyint->phyint_ifindex;
17503 			ii->ipsec_in_rill_index =
17504 			    recv_ill->ill_phyint->phyint_ifindex;
17505 			if (ii->ipsec_in_decaps) {
17506 				/*
17507 				 * This packet is self-encapsulated multiple
17508 				 * times. We don't want to recurse infinitely.
17509 				 * To keep it simple, drop the packet.
17510 				 */
17511 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17512 				freemsg(first_mp);
17513 				return;
17514 			}
17515 			ii->ipsec_in_decaps = B_TRUE;
17516 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17517 			    ire);
17518 			return;
17519 		}
17520 		break;
17521 	case IPPROTO_AH:
17522 	case IPPROTO_ESP: {
17523 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17524 
17525 		/*
17526 		 * Fast path for AH/ESP. If this is the first time
17527 		 * we are sending a datagram to AH/ESP, allocate
17528 		 * a IPSEC_IN message and prepend it. Otherwise,
17529 		 * just fanout.
17530 		 */
17531 
17532 		int ipsec_rc;
17533 		ipsec_in_t *ii;
17534 		netstack_t *ns = ipst->ips_netstack;
17535 
17536 		IP_STAT(ipst, ipsec_proto_ahesp);
17537 		if (!mctl_present) {
17538 			ASSERT(first_mp == mp);
17539 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17540 			if (first_mp == NULL) {
17541 				ip1dbg(("ip_proto_input: IPSEC_IN "
17542 				    "allocation failure.\n"));
17543 				freemsg(hada_mp); /* okay ifnull */
17544 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17545 				freemsg(mp);
17546 				return;
17547 			}
17548 			/*
17549 			 * Store the ill_index so that when we come back
17550 			 * from IPsec we ride on the same queue.
17551 			 */
17552 			ill = (ill_t *)q->q_ptr;
17553 			ii = (ipsec_in_t *)first_mp->b_rptr;
17554 			ii->ipsec_in_ill_index =
17555 			    ill->ill_phyint->phyint_ifindex;
17556 			ii->ipsec_in_rill_index =
17557 			    recv_ill->ill_phyint->phyint_ifindex;
17558 			first_mp->b_cont = mp;
17559 			/*
17560 			 * Cache hardware acceleration info.
17561 			 */
17562 			if (hada_mp != NULL) {
17563 				IPSECHW_DEBUG(IPSECHW_PKT,
17564 				    ("ip_rput_local: caching data attr.\n"));
17565 				ii->ipsec_in_accelerated = B_TRUE;
17566 				ii->ipsec_in_da = hada_mp;
17567 				hada_mp = NULL;
17568 			}
17569 		} else {
17570 			ii = (ipsec_in_t *)first_mp->b_rptr;
17571 		}
17572 
17573 		if (!ipsec_loaded(ipss)) {
17574 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17575 			    ire->ire_zoneid, ipst);
17576 			return;
17577 		}
17578 
17579 		ns = ipst->ips_netstack;
17580 		/* select inbound SA and have IPsec process the pkt */
17581 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17582 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17583 			boolean_t esp_in_udp_sa;
17584 			if (esph == NULL)
17585 				return;
17586 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17587 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17588 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17589 			    IPSA_F_NATT) != 0);
17590 			/*
17591 			 * The following is a fancy, but quick, way of saying:
17592 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17593 			 *    OR
17594 			 * ESP SA and ESP-in-UDP packet --> drop
17595 			 */
17596 			if (esp_in_udp_sa != esp_in_udp_packet) {
17597 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17598 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17599 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17600 				    &ns->netstack_ipsec->ipsec_dropper);
17601 				return;
17602 			}
17603 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17604 			    first_mp, esph);
17605 		} else {
17606 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17607 			if (ah == NULL)
17608 				return;
17609 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17610 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17611 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17612 			    first_mp, ah);
17613 		}
17614 
17615 		switch (ipsec_rc) {
17616 		case IPSEC_STATUS_SUCCESS:
17617 			break;
17618 		case IPSEC_STATUS_FAILED:
17619 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17620 			/* FALLTHRU */
17621 		case IPSEC_STATUS_PENDING:
17622 			return;
17623 		}
17624 		/* we're done with IPsec processing, send it up */
17625 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17626 		return;
17627 	}
17628 	default:
17629 		break;
17630 	}
17631 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17632 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17633 		    ire->ire_zoneid));
17634 		goto drop_pkt;
17635 	}
17636 	/*
17637 	 * Handle protocols with which IP is less intimate.  There
17638 	 * can be more than one stream bound to a particular
17639 	 * protocol.  When this is the case, each one gets a copy
17640 	 * of any incoming packets.
17641 	 */
17642 	ip_fanout_proto(q, first_mp, ill, ipha,
17643 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17644 	    B_TRUE, recv_ill, ire->ire_zoneid);
17645 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17646 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17647 	return;
17648 
17649 drop_pkt:
17650 	freemsg(first_mp);
17651 	if (hada_mp != NULL)
17652 		freeb(hada_mp);
17653 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17654 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17655 #undef	rptr
17656 #undef  iphs
17657 
17658 }
17659 
17660 /*
17661  * Update any source route, record route or timestamp options.
17662  * Check that we are at end of strict source route.
17663  * The options have already been checked for sanity in ip_rput_options().
17664  */
17665 static boolean_t
17666 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17667     ip_stack_t *ipst)
17668 {
17669 	ipoptp_t	opts;
17670 	uchar_t		*opt;
17671 	uint8_t		optval;
17672 	uint8_t		optlen;
17673 	ipaddr_t	dst;
17674 	uint32_t	ts;
17675 	ire_t		*dst_ire;
17676 	timestruc_t	now;
17677 	zoneid_t	zoneid;
17678 	ill_t		*ill;
17679 
17680 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17681 
17682 	ip2dbg(("ip_rput_local_options\n"));
17683 
17684 	for (optval = ipoptp_first(&opts, ipha);
17685 	    optval != IPOPT_EOL;
17686 	    optval = ipoptp_next(&opts)) {
17687 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17688 		opt = opts.ipoptp_cur;
17689 		optlen = opts.ipoptp_len;
17690 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17691 		    optval, optlen));
17692 		switch (optval) {
17693 			uint32_t off;
17694 		case IPOPT_SSRR:
17695 		case IPOPT_LSRR:
17696 			off = opt[IPOPT_OFFSET];
17697 			off--;
17698 			if (optlen < IP_ADDR_LEN ||
17699 			    off > optlen - IP_ADDR_LEN) {
17700 				/* End of source route */
17701 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17702 				break;
17703 			}
17704 			/*
17705 			 * This will only happen if two consecutive entries
17706 			 * in the source route contains our address or if
17707 			 * it is a packet with a loose source route which
17708 			 * reaches us before consuming the whole source route
17709 			 */
17710 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17711 			if (optval == IPOPT_SSRR) {
17712 				goto bad_src_route;
17713 			}
17714 			/*
17715 			 * Hack: instead of dropping the packet truncate the
17716 			 * source route to what has been used by filling the
17717 			 * rest with IPOPT_NOP.
17718 			 */
17719 			opt[IPOPT_OLEN] = (uint8_t)off;
17720 			while (off < optlen) {
17721 				opt[off++] = IPOPT_NOP;
17722 			}
17723 			break;
17724 		case IPOPT_RR:
17725 			off = opt[IPOPT_OFFSET];
17726 			off--;
17727 			if (optlen < IP_ADDR_LEN ||
17728 			    off > optlen - IP_ADDR_LEN) {
17729 				/* No more room - ignore */
17730 				ip1dbg((
17731 				    "ip_rput_local_options: end of RR\n"));
17732 				break;
17733 			}
17734 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17735 			    IP_ADDR_LEN);
17736 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17737 			break;
17738 		case IPOPT_TS:
17739 			/* Insert timestamp if there is romm */
17740 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17741 			case IPOPT_TS_TSONLY:
17742 				off = IPOPT_TS_TIMELEN;
17743 				break;
17744 			case IPOPT_TS_PRESPEC:
17745 			case IPOPT_TS_PRESPEC_RFC791:
17746 				/* Verify that the address matched */
17747 				off = opt[IPOPT_OFFSET] - 1;
17748 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17749 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17750 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17751 				    ipst);
17752 				if (dst_ire == NULL) {
17753 					/* Not for us */
17754 					break;
17755 				}
17756 				ire_refrele(dst_ire);
17757 				/* FALLTHRU */
17758 			case IPOPT_TS_TSANDADDR:
17759 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17760 				break;
17761 			default:
17762 				/*
17763 				 * ip_*put_options should have already
17764 				 * dropped this packet.
17765 				 */
17766 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17767 				    "unknown IT - bug in ip_rput_options?\n");
17768 				return (B_TRUE);	/* Keep "lint" happy */
17769 			}
17770 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17771 				/* Increase overflow counter */
17772 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17773 				opt[IPOPT_POS_OV_FLG] =
17774 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17775 				    (off << 4));
17776 				break;
17777 			}
17778 			off = opt[IPOPT_OFFSET] - 1;
17779 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17780 			case IPOPT_TS_PRESPEC:
17781 			case IPOPT_TS_PRESPEC_RFC791:
17782 			case IPOPT_TS_TSANDADDR:
17783 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17784 				    IP_ADDR_LEN);
17785 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17786 				/* FALLTHRU */
17787 			case IPOPT_TS_TSONLY:
17788 				off = opt[IPOPT_OFFSET] - 1;
17789 				/* Compute # of milliseconds since midnight */
17790 				gethrestime(&now);
17791 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17792 				    now.tv_nsec / (NANOSEC / MILLISEC);
17793 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17794 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17795 				break;
17796 			}
17797 			break;
17798 		}
17799 	}
17800 	return (B_TRUE);
17801 
17802 bad_src_route:
17803 	q = WR(q);
17804 	if (q->q_next != NULL)
17805 		ill = q->q_ptr;
17806 	else
17807 		ill = NULL;
17808 
17809 	/* make sure we clear any indication of a hardware checksum */
17810 	DB_CKSUMFLAGS(mp) = 0;
17811 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17812 	if (zoneid == ALL_ZONES)
17813 		freemsg(mp);
17814 	else
17815 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17816 	return (B_FALSE);
17817 
17818 }
17819 
17820 /*
17821  * Process IP options in an inbound packet.  If an option affects the
17822  * effective destination address, return the next hop address via dstp.
17823  * Returns -1 if something fails in which case an ICMP error has been sent
17824  * and mp freed.
17825  */
17826 static int
17827 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17828     ip_stack_t *ipst)
17829 {
17830 	ipoptp_t	opts;
17831 	uchar_t		*opt;
17832 	uint8_t		optval;
17833 	uint8_t		optlen;
17834 	ipaddr_t	dst;
17835 	intptr_t	code = 0;
17836 	ire_t		*ire = NULL;
17837 	zoneid_t	zoneid;
17838 	ill_t		*ill;
17839 
17840 	ip2dbg(("ip_rput_options\n"));
17841 	dst = ipha->ipha_dst;
17842 	for (optval = ipoptp_first(&opts, ipha);
17843 	    optval != IPOPT_EOL;
17844 	    optval = ipoptp_next(&opts)) {
17845 		opt = opts.ipoptp_cur;
17846 		optlen = opts.ipoptp_len;
17847 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17848 		    optval, optlen));
17849 		/*
17850 		 * Note: we need to verify the checksum before we
17851 		 * modify anything thus this routine only extracts the next
17852 		 * hop dst from any source route.
17853 		 */
17854 		switch (optval) {
17855 			uint32_t off;
17856 		case IPOPT_SSRR:
17857 		case IPOPT_LSRR:
17858 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17859 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17860 			if (ire == NULL) {
17861 				if (optval == IPOPT_SSRR) {
17862 					ip1dbg(("ip_rput_options: not next"
17863 					    " strict source route 0x%x\n",
17864 					    ntohl(dst)));
17865 					code = (char *)&ipha->ipha_dst -
17866 					    (char *)ipha;
17867 					goto param_prob; /* RouterReq's */
17868 				}
17869 				ip2dbg(("ip_rput_options: "
17870 				    "not next source route 0x%x\n",
17871 				    ntohl(dst)));
17872 				break;
17873 			}
17874 			ire_refrele(ire);
17875 
17876 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17877 				ip1dbg((
17878 				    "ip_rput_options: bad option offset\n"));
17879 				code = (char *)&opt[IPOPT_OLEN] -
17880 				    (char *)ipha;
17881 				goto param_prob;
17882 			}
17883 			off = opt[IPOPT_OFFSET];
17884 			off--;
17885 		redo_srr:
17886 			if (optlen < IP_ADDR_LEN ||
17887 			    off > optlen - IP_ADDR_LEN) {
17888 				/* End of source route */
17889 				ip1dbg(("ip_rput_options: end of SR\n"));
17890 				break;
17891 			}
17892 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17893 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17894 			    ntohl(dst)));
17895 
17896 			/*
17897 			 * Check if our address is present more than
17898 			 * once as consecutive hops in source route.
17899 			 * XXX verify per-interface ip_forwarding
17900 			 * for source route?
17901 			 */
17902 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17903 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17904 
17905 			if (ire != NULL) {
17906 				ire_refrele(ire);
17907 				off += IP_ADDR_LEN;
17908 				goto redo_srr;
17909 			}
17910 
17911 			if (dst == htonl(INADDR_LOOPBACK)) {
17912 				ip1dbg(("ip_rput_options: loopback addr in "
17913 				    "source route!\n"));
17914 				goto bad_src_route;
17915 			}
17916 			/*
17917 			 * For strict: verify that dst is directly
17918 			 * reachable.
17919 			 */
17920 			if (optval == IPOPT_SSRR) {
17921 				ire = ire_ftable_lookup(dst, 0, 0,
17922 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17923 				    MBLK_GETLABEL(mp),
17924 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17925 				if (ire == NULL) {
17926 					ip1dbg(("ip_rput_options: SSRR not "
17927 					    "directly reachable: 0x%x\n",
17928 					    ntohl(dst)));
17929 					goto bad_src_route;
17930 				}
17931 				ire_refrele(ire);
17932 			}
17933 			/*
17934 			 * Defer update of the offset and the record route
17935 			 * until the packet is forwarded.
17936 			 */
17937 			break;
17938 		case IPOPT_RR:
17939 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17940 				ip1dbg((
17941 				    "ip_rput_options: bad option offset\n"));
17942 				code = (char *)&opt[IPOPT_OLEN] -
17943 				    (char *)ipha;
17944 				goto param_prob;
17945 			}
17946 			break;
17947 		case IPOPT_TS:
17948 			/*
17949 			 * Verify that length >= 5 and that there is either
17950 			 * room for another timestamp or that the overflow
17951 			 * counter is not maxed out.
17952 			 */
17953 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17954 			if (optlen < IPOPT_MINLEN_IT) {
17955 				goto param_prob;
17956 			}
17957 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17958 				ip1dbg((
17959 				    "ip_rput_options: bad option offset\n"));
17960 				code = (char *)&opt[IPOPT_OFFSET] -
17961 				    (char *)ipha;
17962 				goto param_prob;
17963 			}
17964 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17965 			case IPOPT_TS_TSONLY:
17966 				off = IPOPT_TS_TIMELEN;
17967 				break;
17968 			case IPOPT_TS_TSANDADDR:
17969 			case IPOPT_TS_PRESPEC:
17970 			case IPOPT_TS_PRESPEC_RFC791:
17971 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17972 				break;
17973 			default:
17974 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17975 				    (char *)ipha;
17976 				goto param_prob;
17977 			}
17978 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17979 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17980 				/*
17981 				 * No room and the overflow counter is 15
17982 				 * already.
17983 				 */
17984 				goto param_prob;
17985 			}
17986 			break;
17987 		}
17988 	}
17989 
17990 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17991 		*dstp = dst;
17992 		return (0);
17993 	}
17994 
17995 	ip1dbg(("ip_rput_options: error processing IP options."));
17996 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17997 
17998 param_prob:
17999 	q = WR(q);
18000 	if (q->q_next != NULL)
18001 		ill = q->q_ptr;
18002 	else
18003 		ill = NULL;
18004 
18005 	/* make sure we clear any indication of a hardware checksum */
18006 	DB_CKSUMFLAGS(mp) = 0;
18007 	/* Don't know whether this is for non-global or global/forwarding */
18008 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18009 	if (zoneid == ALL_ZONES)
18010 		freemsg(mp);
18011 	else
18012 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18013 	return (-1);
18014 
18015 bad_src_route:
18016 	q = WR(q);
18017 	if (q->q_next != NULL)
18018 		ill = q->q_ptr;
18019 	else
18020 		ill = NULL;
18021 
18022 	/* make sure we clear any indication of a hardware checksum */
18023 	DB_CKSUMFLAGS(mp) = 0;
18024 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18025 	if (zoneid == ALL_ZONES)
18026 		freemsg(mp);
18027 	else
18028 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18029 	return (-1);
18030 }
18031 
18032 /*
18033  * IP & ICMP info in >=14 msg's ...
18034  *  - ip fixed part (mib2_ip_t)
18035  *  - icmp fixed part (mib2_icmp_t)
18036  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18037  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18038  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18039  *  - ipRouteAttributeTable (ip 102)	labeled routes
18040  *  - ip multicast membership (ip_member_t)
18041  *  - ip multicast source filtering (ip_grpsrc_t)
18042  *  - igmp fixed part (struct igmpstat)
18043  *  - multicast routing stats (struct mrtstat)
18044  *  - multicast routing vifs (array of struct vifctl)
18045  *  - multicast routing routes (array of struct mfcctl)
18046  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18047  *					One per ill plus one generic
18048  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18049  *					One per ill plus one generic
18050  *  - ipv6RouteEntry			all IPv6 IREs
18051  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18052  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18053  *  - ipv6AddrEntry			all IPv6 ipifs
18054  *  - ipv6 multicast membership (ipv6_member_t)
18055  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18056  *
18057  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18058  *
18059  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18060  * already filled in by the caller.
18061  * Return value of 0 indicates that no messages were sent and caller
18062  * should free mpctl.
18063  */
18064 int
18065 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18066 {
18067 	ip_stack_t *ipst;
18068 	sctp_stack_t *sctps;
18069 
18070 	if (q->q_next != NULL) {
18071 		ipst = ILLQ_TO_IPST(q);
18072 	} else {
18073 		ipst = CONNQ_TO_IPST(q);
18074 	}
18075 	ASSERT(ipst != NULL);
18076 	sctps = ipst->ips_netstack->netstack_sctp;
18077 
18078 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18079 		return (0);
18080 	}
18081 
18082 	/*
18083 	 * For the purposes of the (broken) packet shell use
18084 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18085 	 * to make TCP and UDP appear first in the list of mib items.
18086 	 * TBD: We could expand this and use it in netstat so that
18087 	 * the kernel doesn't have to produce large tables (connections,
18088 	 * routes, etc) when netstat only wants the statistics or a particular
18089 	 * table.
18090 	 */
18091 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18092 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18093 			return (1);
18094 		}
18095 	}
18096 
18097 	if (level != MIB2_TCP) {
18098 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18099 			return (1);
18100 		}
18101 	}
18102 
18103 	if (level != MIB2_UDP) {
18104 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18105 			return (1);
18106 		}
18107 	}
18108 
18109 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18110 	    ipst)) == NULL) {
18111 		return (1);
18112 	}
18113 
18114 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18115 		return (1);
18116 	}
18117 
18118 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18119 		return (1);
18120 	}
18121 
18122 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18123 		return (1);
18124 	}
18125 
18126 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18127 		return (1);
18128 	}
18129 
18130 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18131 		return (1);
18132 	}
18133 
18134 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18135 		return (1);
18136 	}
18137 
18138 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18139 		return (1);
18140 	}
18141 
18142 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18143 		return (1);
18144 	}
18145 
18146 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18147 		return (1);
18148 	}
18149 
18150 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18151 		return (1);
18152 	}
18153 
18154 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18155 		return (1);
18156 	}
18157 
18158 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18159 		return (1);
18160 	}
18161 
18162 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18163 		return (1);
18164 	}
18165 
18166 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18167 		return (1);
18168 	}
18169 
18170 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18171 	if (mpctl == NULL) {
18172 		return (1);
18173 	}
18174 
18175 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18176 		return (1);
18177 	}
18178 	freemsg(mpctl);
18179 	return (1);
18180 }
18181 
18182 
18183 /* Get global (legacy) IPv4 statistics */
18184 static mblk_t *
18185 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18186     ip_stack_t *ipst)
18187 {
18188 	mib2_ip_t		old_ip_mib;
18189 	struct opthdr		*optp;
18190 	mblk_t			*mp2ctl;
18191 
18192 	/*
18193 	 * make a copy of the original message
18194 	 */
18195 	mp2ctl = copymsg(mpctl);
18196 
18197 	/* fixed length IP structure... */
18198 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18199 	optp->level = MIB2_IP;
18200 	optp->name = 0;
18201 	SET_MIB(old_ip_mib.ipForwarding,
18202 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18203 	SET_MIB(old_ip_mib.ipDefaultTTL,
18204 	    (uint32_t)ipst->ips_ip_def_ttl);
18205 	SET_MIB(old_ip_mib.ipReasmTimeout,
18206 	    ipst->ips_ip_g_frag_timeout);
18207 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18208 	    sizeof (mib2_ipAddrEntry_t));
18209 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18210 	    sizeof (mib2_ipRouteEntry_t));
18211 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18212 	    sizeof (mib2_ipNetToMediaEntry_t));
18213 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18214 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18215 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18216 	    sizeof (mib2_ipAttributeEntry_t));
18217 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18218 
18219 	/*
18220 	 * Grab the statistics from the new IP MIB
18221 	 */
18222 	SET_MIB(old_ip_mib.ipInReceives,
18223 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18224 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18225 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18226 	SET_MIB(old_ip_mib.ipForwDatagrams,
18227 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18228 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18229 	    ipmib->ipIfStatsInUnknownProtos);
18230 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18231 	SET_MIB(old_ip_mib.ipInDelivers,
18232 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18233 	SET_MIB(old_ip_mib.ipOutRequests,
18234 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18235 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18236 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18237 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18238 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18239 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18240 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18241 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18242 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18243 
18244 	/* ipRoutingDiscards is not being used */
18245 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18246 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18247 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18248 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18249 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18250 	    ipmib->ipIfStatsReasmDuplicates);
18251 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18252 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18253 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18254 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18255 	SET_MIB(old_ip_mib.rawipInOverflows,
18256 	    ipmib->rawipIfStatsInOverflows);
18257 
18258 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18259 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18260 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18261 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18262 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18263 	    ipmib->ipIfStatsOutSwitchIPVersion);
18264 
18265 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18266 	    (int)sizeof (old_ip_mib))) {
18267 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18268 		    (uint_t)sizeof (old_ip_mib)));
18269 	}
18270 
18271 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18272 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18273 	    (int)optp->level, (int)optp->name, (int)optp->len));
18274 	qreply(q, mpctl);
18275 	return (mp2ctl);
18276 }
18277 
18278 /* Per interface IPv4 statistics */
18279 static mblk_t *
18280 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18281 {
18282 	struct opthdr		*optp;
18283 	mblk_t			*mp2ctl;
18284 	ill_t			*ill;
18285 	ill_walk_context_t	ctx;
18286 	mblk_t			*mp_tail = NULL;
18287 	mib2_ipIfStatsEntry_t	global_ip_mib;
18288 
18289 	/*
18290 	 * Make a copy of the original message
18291 	 */
18292 	mp2ctl = copymsg(mpctl);
18293 
18294 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18295 	optp->level = MIB2_IP;
18296 	optp->name = MIB2_IP_TRAFFIC_STATS;
18297 	/* Include "unknown interface" ip_mib */
18298 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18299 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18300 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18301 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18302 	    (ipst->ips_ip_g_forward ? 1 : 2));
18303 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18304 	    (uint32_t)ipst->ips_ip_def_ttl);
18305 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18306 	    sizeof (mib2_ipIfStatsEntry_t));
18307 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18308 	    sizeof (mib2_ipAddrEntry_t));
18309 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18310 	    sizeof (mib2_ipRouteEntry_t));
18311 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18312 	    sizeof (mib2_ipNetToMediaEntry_t));
18313 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18314 	    sizeof (ip_member_t));
18315 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18316 	    sizeof (ip_grpsrc_t));
18317 
18318 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18319 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18320 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18321 		    "failed to allocate %u bytes\n",
18322 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18323 	}
18324 
18325 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18326 
18327 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18328 	ill = ILL_START_WALK_V4(&ctx, ipst);
18329 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18330 		ill->ill_ip_mib->ipIfStatsIfIndex =
18331 		    ill->ill_phyint->phyint_ifindex;
18332 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18333 		    (ipst->ips_ip_g_forward ? 1 : 2));
18334 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18335 		    (uint32_t)ipst->ips_ip_def_ttl);
18336 
18337 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18338 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18339 		    (char *)ill->ill_ip_mib,
18340 		    (int)sizeof (*ill->ill_ip_mib))) {
18341 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18342 			    "failed to allocate %u bytes\n",
18343 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18344 		}
18345 	}
18346 	rw_exit(&ipst->ips_ill_g_lock);
18347 
18348 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18349 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18350 	    "level %d, name %d, len %d\n",
18351 	    (int)optp->level, (int)optp->name, (int)optp->len));
18352 	qreply(q, mpctl);
18353 
18354 	if (mp2ctl == NULL)
18355 		return (NULL);
18356 
18357 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18358 }
18359 
18360 /* Global IPv4 ICMP statistics */
18361 static mblk_t *
18362 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18363 {
18364 	struct opthdr		*optp;
18365 	mblk_t			*mp2ctl;
18366 
18367 	/*
18368 	 * Make a copy of the original message
18369 	 */
18370 	mp2ctl = copymsg(mpctl);
18371 
18372 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18373 	optp->level = MIB2_ICMP;
18374 	optp->name = 0;
18375 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18376 	    (int)sizeof (ipst->ips_icmp_mib))) {
18377 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18378 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18379 	}
18380 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18381 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18382 	    (int)optp->level, (int)optp->name, (int)optp->len));
18383 	qreply(q, mpctl);
18384 	return (mp2ctl);
18385 }
18386 
18387 /* Global IPv4 IGMP statistics */
18388 static mblk_t *
18389 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18390 {
18391 	struct opthdr		*optp;
18392 	mblk_t			*mp2ctl;
18393 
18394 	/*
18395 	 * make a copy of the original message
18396 	 */
18397 	mp2ctl = copymsg(mpctl);
18398 
18399 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18400 	optp->level = EXPER_IGMP;
18401 	optp->name = 0;
18402 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18403 	    (int)sizeof (ipst->ips_igmpstat))) {
18404 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18405 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18406 	}
18407 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18408 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18409 	    (int)optp->level, (int)optp->name, (int)optp->len));
18410 	qreply(q, mpctl);
18411 	return (mp2ctl);
18412 }
18413 
18414 /* Global IPv4 Multicast Routing statistics */
18415 static mblk_t *
18416 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18417 {
18418 	struct opthdr		*optp;
18419 	mblk_t			*mp2ctl;
18420 
18421 	/*
18422 	 * make a copy of the original message
18423 	 */
18424 	mp2ctl = copymsg(mpctl);
18425 
18426 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18427 	optp->level = EXPER_DVMRP;
18428 	optp->name = 0;
18429 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18430 		ip0dbg(("ip_mroute_stats: failed\n"));
18431 	}
18432 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18433 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18434 	    (int)optp->level, (int)optp->name, (int)optp->len));
18435 	qreply(q, mpctl);
18436 	return (mp2ctl);
18437 }
18438 
18439 /* IPv4 address information */
18440 static mblk_t *
18441 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18442 {
18443 	struct opthdr		*optp;
18444 	mblk_t			*mp2ctl;
18445 	mblk_t			*mp_tail = NULL;
18446 	ill_t			*ill;
18447 	ipif_t			*ipif;
18448 	uint_t			bitval;
18449 	mib2_ipAddrEntry_t	mae;
18450 	zoneid_t		zoneid;
18451 	ill_walk_context_t ctx;
18452 
18453 	/*
18454 	 * make a copy of the original message
18455 	 */
18456 	mp2ctl = copymsg(mpctl);
18457 
18458 	/* ipAddrEntryTable */
18459 
18460 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18461 	optp->level = MIB2_IP;
18462 	optp->name = MIB2_IP_ADDR;
18463 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18464 
18465 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18466 	ill = ILL_START_WALK_V4(&ctx, ipst);
18467 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18468 		for (ipif = ill->ill_ipif; ipif != NULL;
18469 		    ipif = ipif->ipif_next) {
18470 			if (ipif->ipif_zoneid != zoneid &&
18471 			    ipif->ipif_zoneid != ALL_ZONES)
18472 				continue;
18473 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18474 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18475 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18476 
18477 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18478 			    OCTET_LENGTH);
18479 			mae.ipAdEntIfIndex.o_length =
18480 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18481 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18482 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18483 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18484 			mae.ipAdEntInfo.ae_subnet_len =
18485 			    ip_mask_to_plen(ipif->ipif_net_mask);
18486 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18487 			for (bitval = 1;
18488 			    bitval &&
18489 			    !(bitval & ipif->ipif_brd_addr);
18490 			    bitval <<= 1)
18491 				noop;
18492 			mae.ipAdEntBcastAddr = bitval;
18493 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18494 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18495 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18496 			mae.ipAdEntInfo.ae_broadcast_addr =
18497 			    ipif->ipif_brd_addr;
18498 			mae.ipAdEntInfo.ae_pp_dst_addr =
18499 			    ipif->ipif_pp_dst_addr;
18500 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18501 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18502 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18503 
18504 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18505 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18506 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18507 				    "allocate %u bytes\n",
18508 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18509 			}
18510 		}
18511 	}
18512 	rw_exit(&ipst->ips_ill_g_lock);
18513 
18514 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18515 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18516 	    (int)optp->level, (int)optp->name, (int)optp->len));
18517 	qreply(q, mpctl);
18518 	return (mp2ctl);
18519 }
18520 
18521 /* IPv6 address information */
18522 static mblk_t *
18523 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18524 {
18525 	struct opthdr		*optp;
18526 	mblk_t			*mp2ctl;
18527 	mblk_t			*mp_tail = NULL;
18528 	ill_t			*ill;
18529 	ipif_t			*ipif;
18530 	mib2_ipv6AddrEntry_t	mae6;
18531 	zoneid_t		zoneid;
18532 	ill_walk_context_t	ctx;
18533 
18534 	/*
18535 	 * make a copy of the original message
18536 	 */
18537 	mp2ctl = copymsg(mpctl);
18538 
18539 	/* ipv6AddrEntryTable */
18540 
18541 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18542 	optp->level = MIB2_IP6;
18543 	optp->name = MIB2_IP6_ADDR;
18544 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18545 
18546 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18547 	ill = ILL_START_WALK_V6(&ctx, ipst);
18548 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18549 		for (ipif = ill->ill_ipif; ipif != NULL;
18550 		    ipif = ipif->ipif_next) {
18551 			if (ipif->ipif_zoneid != zoneid &&
18552 			    ipif->ipif_zoneid != ALL_ZONES)
18553 				continue;
18554 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18555 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18556 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18557 
18558 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18559 			    OCTET_LENGTH);
18560 			mae6.ipv6AddrIfIndex.o_length =
18561 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18562 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18563 			mae6.ipv6AddrPfxLength =
18564 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18565 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18566 			mae6.ipv6AddrInfo.ae_subnet_len =
18567 			    mae6.ipv6AddrPfxLength;
18568 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18569 
18570 			/* Type: stateless(1), stateful(2), unknown(3) */
18571 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18572 				mae6.ipv6AddrType = 1;
18573 			else
18574 				mae6.ipv6AddrType = 2;
18575 			/* Anycast: true(1), false(2) */
18576 			if (ipif->ipif_flags & IPIF_ANYCAST)
18577 				mae6.ipv6AddrAnycastFlag = 1;
18578 			else
18579 				mae6.ipv6AddrAnycastFlag = 2;
18580 
18581 			/*
18582 			 * Address status: preferred(1), deprecated(2),
18583 			 * invalid(3), inaccessible(4), unknown(5)
18584 			 */
18585 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18586 				mae6.ipv6AddrStatus = 3;
18587 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18588 				mae6.ipv6AddrStatus = 2;
18589 			else
18590 				mae6.ipv6AddrStatus = 1;
18591 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18592 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18593 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18594 			    ipif->ipif_v6pp_dst_addr;
18595 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18596 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18597 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18598 			mae6.ipv6AddrIdentifier = ill->ill_token;
18599 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18600 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18601 			mae6.ipv6AddrRetransmitTime =
18602 			    ill->ill_reachable_retrans_time;
18603 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18604 			    (char *)&mae6,
18605 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18606 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18607 				    "allocate %u bytes\n",
18608 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18609 			}
18610 		}
18611 	}
18612 	rw_exit(&ipst->ips_ill_g_lock);
18613 
18614 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18615 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18616 	    (int)optp->level, (int)optp->name, (int)optp->len));
18617 	qreply(q, mpctl);
18618 	return (mp2ctl);
18619 }
18620 
18621 /* IPv4 multicast group membership. */
18622 static mblk_t *
18623 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18624 {
18625 	struct opthdr		*optp;
18626 	mblk_t			*mp2ctl;
18627 	ill_t			*ill;
18628 	ipif_t			*ipif;
18629 	ilm_t			*ilm;
18630 	ip_member_t		ipm;
18631 	mblk_t			*mp_tail = NULL;
18632 	ill_walk_context_t	ctx;
18633 	zoneid_t		zoneid;
18634 
18635 	/*
18636 	 * make a copy of the original message
18637 	 */
18638 	mp2ctl = copymsg(mpctl);
18639 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18640 
18641 	/* ipGroupMember table */
18642 	optp = (struct opthdr *)&mpctl->b_rptr[
18643 	    sizeof (struct T_optmgmt_ack)];
18644 	optp->level = MIB2_IP;
18645 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18646 
18647 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18648 	ill = ILL_START_WALK_V4(&ctx, ipst);
18649 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18650 		ILM_WALKER_HOLD(ill);
18651 		for (ipif = ill->ill_ipif; ipif != NULL;
18652 		    ipif = ipif->ipif_next) {
18653 			if (ipif->ipif_zoneid != zoneid &&
18654 			    ipif->ipif_zoneid != ALL_ZONES)
18655 				continue;	/* not this zone */
18656 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18657 			    OCTET_LENGTH);
18658 			ipm.ipGroupMemberIfIndex.o_length =
18659 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18660 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18661 				ASSERT(ilm->ilm_ipif != NULL);
18662 				ASSERT(ilm->ilm_ill == NULL);
18663 				if (ilm->ilm_ipif != ipif)
18664 					continue;
18665 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18666 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18667 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18668 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18669 				    (char *)&ipm, (int)sizeof (ipm))) {
18670 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18671 					    "failed to allocate %u bytes\n",
18672 					    (uint_t)sizeof (ipm)));
18673 				}
18674 			}
18675 		}
18676 		ILM_WALKER_RELE(ill);
18677 	}
18678 	rw_exit(&ipst->ips_ill_g_lock);
18679 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18680 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18681 	    (int)optp->level, (int)optp->name, (int)optp->len));
18682 	qreply(q, mpctl);
18683 	return (mp2ctl);
18684 }
18685 
18686 /* IPv6 multicast group membership. */
18687 static mblk_t *
18688 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18689 {
18690 	struct opthdr		*optp;
18691 	mblk_t			*mp2ctl;
18692 	ill_t			*ill;
18693 	ilm_t			*ilm;
18694 	ipv6_member_t		ipm6;
18695 	mblk_t			*mp_tail = NULL;
18696 	ill_walk_context_t	ctx;
18697 	zoneid_t		zoneid;
18698 
18699 	/*
18700 	 * make a copy of the original message
18701 	 */
18702 	mp2ctl = copymsg(mpctl);
18703 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18704 
18705 	/* ip6GroupMember table */
18706 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18707 	optp->level = MIB2_IP6;
18708 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18709 
18710 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18711 	ill = ILL_START_WALK_V6(&ctx, ipst);
18712 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18713 		ILM_WALKER_HOLD(ill);
18714 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18715 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18716 			ASSERT(ilm->ilm_ipif == NULL);
18717 			ASSERT(ilm->ilm_ill != NULL);
18718 			if (ilm->ilm_zoneid != zoneid)
18719 				continue;	/* not this zone */
18720 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18721 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18722 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18723 			if (!snmp_append_data2(mpctl->b_cont,
18724 			    &mp_tail,
18725 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18726 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18727 				    "failed to allocate %u bytes\n",
18728 				    (uint_t)sizeof (ipm6)));
18729 			}
18730 		}
18731 		ILM_WALKER_RELE(ill);
18732 	}
18733 	rw_exit(&ipst->ips_ill_g_lock);
18734 
18735 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18736 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18737 	    (int)optp->level, (int)optp->name, (int)optp->len));
18738 	qreply(q, mpctl);
18739 	return (mp2ctl);
18740 }
18741 
18742 /* IP multicast filtered sources */
18743 static mblk_t *
18744 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18745 {
18746 	struct opthdr		*optp;
18747 	mblk_t			*mp2ctl;
18748 	ill_t			*ill;
18749 	ipif_t			*ipif;
18750 	ilm_t			*ilm;
18751 	ip_grpsrc_t		ips;
18752 	mblk_t			*mp_tail = NULL;
18753 	ill_walk_context_t	ctx;
18754 	zoneid_t		zoneid;
18755 	int			i;
18756 	slist_t			*sl;
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 	/* ipGroupSource table */
18765 	optp = (struct opthdr *)&mpctl->b_rptr[
18766 	    sizeof (struct T_optmgmt_ack)];
18767 	optp->level = MIB2_IP;
18768 	optp->name = EXPER_IP_GROUP_SOURCES;
18769 
18770 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18771 	ill = ILL_START_WALK_V4(&ctx, ipst);
18772 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18773 		ILM_WALKER_HOLD(ill);
18774 		for (ipif = ill->ill_ipif; ipif != NULL;
18775 		    ipif = ipif->ipif_next) {
18776 			if (ipif->ipif_zoneid != zoneid)
18777 				continue;	/* not this zone */
18778 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18779 			    OCTET_LENGTH);
18780 			ips.ipGroupSourceIfIndex.o_length =
18781 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18782 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18783 				ASSERT(ilm->ilm_ipif != NULL);
18784 				ASSERT(ilm->ilm_ill == NULL);
18785 				sl = ilm->ilm_filter;
18786 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18787 					continue;
18788 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18789 				for (i = 0; i < sl->sl_numsrc; i++) {
18790 					if (!IN6_IS_ADDR_V4MAPPED(
18791 					    &sl->sl_addr[i]))
18792 						continue;
18793 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18794 					    ips.ipGroupSourceAddress);
18795 					if (snmp_append_data2(mpctl->b_cont,
18796 					    &mp_tail, (char *)&ips,
18797 					    (int)sizeof (ips)) == 0) {
18798 						ip1dbg(("ip_snmp_get_mib2_"
18799 						    "ip_group_src: failed to "
18800 						    "allocate %u bytes\n",
18801 						    (uint_t)sizeof (ips)));
18802 					}
18803 				}
18804 			}
18805 		}
18806 		ILM_WALKER_RELE(ill);
18807 	}
18808 	rw_exit(&ipst->ips_ill_g_lock);
18809 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18810 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18811 	    (int)optp->level, (int)optp->name, (int)optp->len));
18812 	qreply(q, mpctl);
18813 	return (mp2ctl);
18814 }
18815 
18816 /* IPv6 multicast filtered sources. */
18817 static mblk_t *
18818 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18819 {
18820 	struct opthdr		*optp;
18821 	mblk_t			*mp2ctl;
18822 	ill_t			*ill;
18823 	ilm_t			*ilm;
18824 	ipv6_grpsrc_t		ips6;
18825 	mblk_t			*mp_tail = NULL;
18826 	ill_walk_context_t	ctx;
18827 	zoneid_t		zoneid;
18828 	int			i;
18829 	slist_t			*sl;
18830 
18831 	/*
18832 	 * make a copy of the original message
18833 	 */
18834 	mp2ctl = copymsg(mpctl);
18835 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18836 
18837 	/* ip6GroupMember table */
18838 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18839 	optp->level = MIB2_IP6;
18840 	optp->name = EXPER_IP6_GROUP_SOURCES;
18841 
18842 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18843 	ill = ILL_START_WALK_V6(&ctx, ipst);
18844 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18845 		ILM_WALKER_HOLD(ill);
18846 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18847 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18848 			ASSERT(ilm->ilm_ipif == NULL);
18849 			ASSERT(ilm->ilm_ill != NULL);
18850 			sl = ilm->ilm_filter;
18851 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18852 				continue;
18853 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18854 			for (i = 0; i < sl->sl_numsrc; i++) {
18855 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18856 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18857 				    (char *)&ips6, (int)sizeof (ips6))) {
18858 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18859 					    "group_src: failed to allocate "
18860 					    "%u bytes\n",
18861 					    (uint_t)sizeof (ips6)));
18862 				}
18863 			}
18864 		}
18865 		ILM_WALKER_RELE(ill);
18866 	}
18867 	rw_exit(&ipst->ips_ill_g_lock);
18868 
18869 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18870 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18871 	    (int)optp->level, (int)optp->name, (int)optp->len));
18872 	qreply(q, mpctl);
18873 	return (mp2ctl);
18874 }
18875 
18876 /* Multicast routing virtual interface table. */
18877 static mblk_t *
18878 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18879 {
18880 	struct opthdr		*optp;
18881 	mblk_t			*mp2ctl;
18882 
18883 	/*
18884 	 * make a copy of the original message
18885 	 */
18886 	mp2ctl = copymsg(mpctl);
18887 
18888 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18889 	optp->level = EXPER_DVMRP;
18890 	optp->name = EXPER_DVMRP_VIF;
18891 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18892 		ip0dbg(("ip_mroute_vif: failed\n"));
18893 	}
18894 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18895 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18896 	    (int)optp->level, (int)optp->name, (int)optp->len));
18897 	qreply(q, mpctl);
18898 	return (mp2ctl);
18899 }
18900 
18901 /* Multicast routing table. */
18902 static mblk_t *
18903 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18904 {
18905 	struct opthdr		*optp;
18906 	mblk_t			*mp2ctl;
18907 
18908 	/*
18909 	 * make a copy of the original message
18910 	 */
18911 	mp2ctl = copymsg(mpctl);
18912 
18913 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18914 	optp->level = EXPER_DVMRP;
18915 	optp->name = EXPER_DVMRP_MRT;
18916 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18917 		ip0dbg(("ip_mroute_mrt: failed\n"));
18918 	}
18919 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18920 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18921 	    (int)optp->level, (int)optp->name, (int)optp->len));
18922 	qreply(q, mpctl);
18923 	return (mp2ctl);
18924 }
18925 
18926 /*
18927  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18928  * in one IRE walk.
18929  */
18930 static mblk_t *
18931 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18932 {
18933 	struct opthdr	*optp;
18934 	mblk_t		*mp2ctl;	/* Returned */
18935 	mblk_t		*mp3ctl;	/* nettomedia */
18936 	mblk_t		*mp4ctl;	/* routeattrs */
18937 	iproutedata_t	ird;
18938 	zoneid_t	zoneid;
18939 
18940 	/*
18941 	 * make copies of the original message
18942 	 *	- mp2ctl is returned unchanged to the caller for his use
18943 	 *	- mpctl is sent upstream as ipRouteEntryTable
18944 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18945 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18946 	 */
18947 	mp2ctl = copymsg(mpctl);
18948 	mp3ctl = copymsg(mpctl);
18949 	mp4ctl = copymsg(mpctl);
18950 	if (mp3ctl == NULL || mp4ctl == NULL) {
18951 		freemsg(mp4ctl);
18952 		freemsg(mp3ctl);
18953 		freemsg(mp2ctl);
18954 		freemsg(mpctl);
18955 		return (NULL);
18956 	}
18957 
18958 	bzero(&ird, sizeof (ird));
18959 
18960 	ird.ird_route.lp_head = mpctl->b_cont;
18961 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18962 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18963 
18964 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18965 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18966 
18967 	/* ipRouteEntryTable in mpctl */
18968 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18969 	optp->level = MIB2_IP;
18970 	optp->name = MIB2_IP_ROUTE;
18971 	optp->len = msgdsize(ird.ird_route.lp_head);
18972 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18973 	    (int)optp->level, (int)optp->name, (int)optp->len));
18974 	qreply(q, mpctl);
18975 
18976 	/* ipNetToMediaEntryTable in mp3ctl */
18977 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18978 	optp->level = MIB2_IP;
18979 	optp->name = MIB2_IP_MEDIA;
18980 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
18981 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18982 	    (int)optp->level, (int)optp->name, (int)optp->len));
18983 	qreply(q, mp3ctl);
18984 
18985 	/* ipRouteAttributeTable in mp4ctl */
18986 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18987 	optp->level = MIB2_IP;
18988 	optp->name = EXPER_IP_RTATTR;
18989 	optp->len = msgdsize(ird.ird_attrs.lp_head);
18990 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18991 	    (int)optp->level, (int)optp->name, (int)optp->len));
18992 	if (optp->len == 0)
18993 		freemsg(mp4ctl);
18994 	else
18995 		qreply(q, mp4ctl);
18996 
18997 	return (mp2ctl);
18998 }
18999 
19000 /*
19001  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
19002  * ipv6NetToMediaEntryTable in an NDP walk.
19003  */
19004 static mblk_t *
19005 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19006 {
19007 	struct opthdr	*optp;
19008 	mblk_t		*mp2ctl;	/* Returned */
19009 	mblk_t		*mp3ctl;	/* nettomedia */
19010 	mblk_t		*mp4ctl;	/* routeattrs */
19011 	iproutedata_t	ird;
19012 	zoneid_t	zoneid;
19013 
19014 	/*
19015 	 * make copies of the original message
19016 	 *	- mp2ctl is returned unchanged to the caller for his use
19017 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19018 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19019 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19020 	 */
19021 	mp2ctl = copymsg(mpctl);
19022 	mp3ctl = copymsg(mpctl);
19023 	mp4ctl = copymsg(mpctl);
19024 	if (mp3ctl == NULL || mp4ctl == NULL) {
19025 		freemsg(mp4ctl);
19026 		freemsg(mp3ctl);
19027 		freemsg(mp2ctl);
19028 		freemsg(mpctl);
19029 		return (NULL);
19030 	}
19031 
19032 	bzero(&ird, sizeof (ird));
19033 
19034 	ird.ird_route.lp_head = mpctl->b_cont;
19035 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19036 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19037 
19038 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19039 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19040 
19041 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19042 	optp->level = MIB2_IP6;
19043 	optp->name = MIB2_IP6_ROUTE;
19044 	optp->len = msgdsize(ird.ird_route.lp_head);
19045 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19046 	    (int)optp->level, (int)optp->name, (int)optp->len));
19047 	qreply(q, mpctl);
19048 
19049 	/* ipv6NetToMediaEntryTable in mp3ctl */
19050 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19051 
19052 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19053 	optp->level = MIB2_IP6;
19054 	optp->name = MIB2_IP6_MEDIA;
19055 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19056 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19057 	    (int)optp->level, (int)optp->name, (int)optp->len));
19058 	qreply(q, mp3ctl);
19059 
19060 	/* ipv6RouteAttributeTable in mp4ctl */
19061 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19062 	optp->level = MIB2_IP6;
19063 	optp->name = EXPER_IP_RTATTR;
19064 	optp->len = msgdsize(ird.ird_attrs.lp_head);
19065 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19066 	    (int)optp->level, (int)optp->name, (int)optp->len));
19067 	if (optp->len == 0)
19068 		freemsg(mp4ctl);
19069 	else
19070 		qreply(q, mp4ctl);
19071 
19072 	return (mp2ctl);
19073 }
19074 
19075 /*
19076  * IPv6 mib: One per ill
19077  */
19078 static mblk_t *
19079 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19080 {
19081 	struct opthdr		*optp;
19082 	mblk_t			*mp2ctl;
19083 	ill_t			*ill;
19084 	ill_walk_context_t	ctx;
19085 	mblk_t			*mp_tail = NULL;
19086 
19087 	/*
19088 	 * Make a copy of the original message
19089 	 */
19090 	mp2ctl = copymsg(mpctl);
19091 
19092 	/* fixed length IPv6 structure ... */
19093 
19094 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19095 	optp->level = MIB2_IP6;
19096 	optp->name = 0;
19097 	/* Include "unknown interface" ip6_mib */
19098 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19099 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19100 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19101 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19102 	    ipst->ips_ipv6_forward ? 1 : 2);
19103 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19104 	    ipst->ips_ipv6_def_hops);
19105 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19106 	    sizeof (mib2_ipIfStatsEntry_t));
19107 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19108 	    sizeof (mib2_ipv6AddrEntry_t));
19109 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19110 	    sizeof (mib2_ipv6RouteEntry_t));
19111 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19112 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19113 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19114 	    sizeof (ipv6_member_t));
19115 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19116 	    sizeof (ipv6_grpsrc_t));
19117 
19118 	/*
19119 	 * Synchronize 64- and 32-bit counters
19120 	 */
19121 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19122 	    ipIfStatsHCInReceives);
19123 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19124 	    ipIfStatsHCInDelivers);
19125 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19126 	    ipIfStatsHCOutRequests);
19127 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19128 	    ipIfStatsHCOutForwDatagrams);
19129 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19130 	    ipIfStatsHCOutMcastPkts);
19131 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19132 	    ipIfStatsHCInMcastPkts);
19133 
19134 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19135 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19136 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19137 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19138 	}
19139 
19140 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19141 	ill = ILL_START_WALK_V6(&ctx, ipst);
19142 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19143 		ill->ill_ip_mib->ipIfStatsIfIndex =
19144 		    ill->ill_phyint->phyint_ifindex;
19145 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19146 		    ipst->ips_ipv6_forward ? 1 : 2);
19147 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19148 		    ill->ill_max_hops);
19149 
19150 		/*
19151 		 * Synchronize 64- and 32-bit counters
19152 		 */
19153 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19154 		    ipIfStatsHCInReceives);
19155 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19156 		    ipIfStatsHCInDelivers);
19157 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19158 		    ipIfStatsHCOutRequests);
19159 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19160 		    ipIfStatsHCOutForwDatagrams);
19161 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19162 		    ipIfStatsHCOutMcastPkts);
19163 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19164 		    ipIfStatsHCInMcastPkts);
19165 
19166 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19167 		    (char *)ill->ill_ip_mib,
19168 		    (int)sizeof (*ill->ill_ip_mib))) {
19169 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19170 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19171 		}
19172 	}
19173 	rw_exit(&ipst->ips_ill_g_lock);
19174 
19175 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19176 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19177 	    (int)optp->level, (int)optp->name, (int)optp->len));
19178 	qreply(q, mpctl);
19179 	return (mp2ctl);
19180 }
19181 
19182 /*
19183  * ICMPv6 mib: One per ill
19184  */
19185 static mblk_t *
19186 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19187 {
19188 	struct opthdr		*optp;
19189 	mblk_t			*mp2ctl;
19190 	ill_t			*ill;
19191 	ill_walk_context_t	ctx;
19192 	mblk_t			*mp_tail = NULL;
19193 	/*
19194 	 * Make a copy of the original message
19195 	 */
19196 	mp2ctl = copymsg(mpctl);
19197 
19198 	/* fixed length ICMPv6 structure ... */
19199 
19200 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19201 	optp->level = MIB2_ICMP6;
19202 	optp->name = 0;
19203 	/* Include "unknown interface" icmp6_mib */
19204 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19205 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19206 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19207 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19208 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19209 	    (char *)&ipst->ips_icmp6_mib,
19210 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19211 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19212 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19213 	}
19214 
19215 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19216 	ill = ILL_START_WALK_V6(&ctx, ipst);
19217 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19218 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19219 		    ill->ill_phyint->phyint_ifindex;
19220 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19221 		    (char *)ill->ill_icmp6_mib,
19222 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19223 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19224 			    "%u bytes\n",
19225 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19226 		}
19227 	}
19228 	rw_exit(&ipst->ips_ill_g_lock);
19229 
19230 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19231 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19232 	    (int)optp->level, (int)optp->name, (int)optp->len));
19233 	qreply(q, mpctl);
19234 	return (mp2ctl);
19235 }
19236 
19237 /*
19238  * ire_walk routine to create both ipRouteEntryTable and
19239  * ipRouteAttributeTable in one IRE walk
19240  */
19241 static void
19242 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19243 {
19244 	ill_t				*ill;
19245 	ipif_t				*ipif;
19246 	mib2_ipRouteEntry_t		*re;
19247 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19248 	ipaddr_t			gw_addr;
19249 	tsol_ire_gw_secattr_t		*attrp;
19250 	tsol_gc_t			*gc = NULL;
19251 	tsol_gcgrp_t			*gcgrp = NULL;
19252 	uint_t				sacnt = 0;
19253 	int				i;
19254 
19255 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19256 
19257 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19258 		return;
19259 
19260 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19261 		mutex_enter(&attrp->igsa_lock);
19262 		if ((gc = attrp->igsa_gc) != NULL) {
19263 			gcgrp = gc->gc_grp;
19264 			ASSERT(gcgrp != NULL);
19265 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19266 			sacnt = 1;
19267 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19268 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19269 			gc = gcgrp->gcgrp_head;
19270 			sacnt = gcgrp->gcgrp_count;
19271 		}
19272 		mutex_exit(&attrp->igsa_lock);
19273 
19274 		/* do nothing if there's no gc to report */
19275 		if (gc == NULL) {
19276 			ASSERT(sacnt == 0);
19277 			if (gcgrp != NULL) {
19278 				/* we might as well drop the lock now */
19279 				rw_exit(&gcgrp->gcgrp_rwlock);
19280 				gcgrp = NULL;
19281 			}
19282 			attrp = NULL;
19283 		}
19284 
19285 		ASSERT(gc == NULL || (gcgrp != NULL &&
19286 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19287 	}
19288 	ASSERT(sacnt == 0 || gc != NULL);
19289 
19290 	if (sacnt != 0 &&
19291 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19292 		kmem_free(re, sizeof (*re));
19293 		rw_exit(&gcgrp->gcgrp_rwlock);
19294 		return;
19295 	}
19296 
19297 	/*
19298 	 * Return all IRE types for route table... let caller pick and choose
19299 	 */
19300 	re->ipRouteDest = ire->ire_addr;
19301 	ipif = ire->ire_ipif;
19302 	re->ipRouteIfIndex.o_length = 0;
19303 	if (ire->ire_type == IRE_CACHE) {
19304 		ill = (ill_t *)ire->ire_stq->q_ptr;
19305 		re->ipRouteIfIndex.o_length =
19306 		    ill->ill_name_length == 0 ? 0 :
19307 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19308 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19309 		    re->ipRouteIfIndex.o_length);
19310 	} else if (ipif != NULL) {
19311 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19312 		re->ipRouteIfIndex.o_length =
19313 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19314 	}
19315 	re->ipRouteMetric1 = -1;
19316 	re->ipRouteMetric2 = -1;
19317 	re->ipRouteMetric3 = -1;
19318 	re->ipRouteMetric4 = -1;
19319 
19320 	gw_addr = ire->ire_gateway_addr;
19321 
19322 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19323 		re->ipRouteNextHop = ire->ire_src_addr;
19324 	else
19325 		re->ipRouteNextHop = gw_addr;
19326 	/* indirect(4), direct(3), or invalid(2) */
19327 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19328 		re->ipRouteType = 2;
19329 	else
19330 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19331 	re->ipRouteProto = -1;
19332 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19333 	re->ipRouteMask = ire->ire_mask;
19334 	re->ipRouteMetric5 = -1;
19335 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19336 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19337 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19338 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19339 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19340 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19341 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19342 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19343 
19344 	if (ire->ire_flags & RTF_DYNAMIC) {
19345 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19346 	} else {
19347 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19348 	}
19349 
19350 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19351 	    (char *)re, (int)sizeof (*re))) {
19352 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19353 		    (uint_t)sizeof (*re)));
19354 	}
19355 
19356 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19357 		iaeptr->iae_routeidx = ird->ird_idx;
19358 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19359 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19360 	}
19361 
19362 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19363 	    (char *)iae, sacnt * sizeof (*iae))) {
19364 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19365 		    (unsigned)(sacnt * sizeof (*iae))));
19366 	}
19367 
19368 	/* bump route index for next pass */
19369 	ird->ird_idx++;
19370 
19371 	kmem_free(re, sizeof (*re));
19372 	if (sacnt != 0)
19373 		kmem_free(iae, sacnt * sizeof (*iae));
19374 
19375 	if (gcgrp != NULL)
19376 		rw_exit(&gcgrp->gcgrp_rwlock);
19377 }
19378 
19379 /*
19380  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19381  */
19382 static void
19383 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19384 {
19385 	ill_t				*ill;
19386 	ipif_t				*ipif;
19387 	mib2_ipv6RouteEntry_t		*re;
19388 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19389 	in6_addr_t			gw_addr_v6;
19390 	tsol_ire_gw_secattr_t		*attrp;
19391 	tsol_gc_t			*gc = NULL;
19392 	tsol_gcgrp_t			*gcgrp = NULL;
19393 	uint_t				sacnt = 0;
19394 	int				i;
19395 
19396 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19397 
19398 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19399 		return;
19400 
19401 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19402 		mutex_enter(&attrp->igsa_lock);
19403 		if ((gc = attrp->igsa_gc) != NULL) {
19404 			gcgrp = gc->gc_grp;
19405 			ASSERT(gcgrp != NULL);
19406 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19407 			sacnt = 1;
19408 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19409 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19410 			gc = gcgrp->gcgrp_head;
19411 			sacnt = gcgrp->gcgrp_count;
19412 		}
19413 		mutex_exit(&attrp->igsa_lock);
19414 
19415 		/* do nothing if there's no gc to report */
19416 		if (gc == NULL) {
19417 			ASSERT(sacnt == 0);
19418 			if (gcgrp != NULL) {
19419 				/* we might as well drop the lock now */
19420 				rw_exit(&gcgrp->gcgrp_rwlock);
19421 				gcgrp = NULL;
19422 			}
19423 			attrp = NULL;
19424 		}
19425 
19426 		ASSERT(gc == NULL || (gcgrp != NULL &&
19427 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19428 	}
19429 	ASSERT(sacnt == 0 || gc != NULL);
19430 
19431 	if (sacnt != 0 &&
19432 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19433 		kmem_free(re, sizeof (*re));
19434 		rw_exit(&gcgrp->gcgrp_rwlock);
19435 		return;
19436 	}
19437 
19438 	/*
19439 	 * Return all IRE types for route table... let caller pick and choose
19440 	 */
19441 	re->ipv6RouteDest = ire->ire_addr_v6;
19442 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19443 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19444 	re->ipv6RouteIfIndex.o_length = 0;
19445 	ipif = ire->ire_ipif;
19446 	if (ire->ire_type == IRE_CACHE) {
19447 		ill = (ill_t *)ire->ire_stq->q_ptr;
19448 		re->ipv6RouteIfIndex.o_length =
19449 		    ill->ill_name_length == 0 ? 0 :
19450 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19451 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19452 		    re->ipv6RouteIfIndex.o_length);
19453 	} else if (ipif != NULL) {
19454 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19455 		re->ipv6RouteIfIndex.o_length =
19456 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19457 	}
19458 
19459 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19460 
19461 	mutex_enter(&ire->ire_lock);
19462 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19463 	mutex_exit(&ire->ire_lock);
19464 
19465 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19466 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19467 	else
19468 		re->ipv6RouteNextHop = gw_addr_v6;
19469 
19470 	/* remote(4), local(3), or discard(2) */
19471 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19472 		re->ipv6RouteType = 2;
19473 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19474 		re->ipv6RouteType = 3;
19475 	else
19476 		re->ipv6RouteType = 4;
19477 
19478 	re->ipv6RouteProtocol	= -1;
19479 	re->ipv6RoutePolicy	= 0;
19480 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19481 	re->ipv6RouteNextHopRDI	= 0;
19482 	re->ipv6RouteWeight	= 0;
19483 	re->ipv6RouteMetric	= 0;
19484 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19485 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19486 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19487 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19488 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19489 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19490 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19491 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19492 
19493 	if (ire->ire_flags & RTF_DYNAMIC) {
19494 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19495 	} else {
19496 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19497 	}
19498 
19499 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19500 	    (char *)re, (int)sizeof (*re))) {
19501 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19502 		    (uint_t)sizeof (*re)));
19503 	}
19504 
19505 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19506 		iaeptr->iae_routeidx = ird->ird_idx;
19507 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19508 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19509 	}
19510 
19511 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19512 	    (char *)iae, sacnt * sizeof (*iae))) {
19513 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19514 		    (unsigned)(sacnt * sizeof (*iae))));
19515 	}
19516 
19517 	/* bump route index for next pass */
19518 	ird->ird_idx++;
19519 
19520 	kmem_free(re, sizeof (*re));
19521 	if (sacnt != 0)
19522 		kmem_free(iae, sacnt * sizeof (*iae));
19523 
19524 	if (gcgrp != NULL)
19525 		rw_exit(&gcgrp->gcgrp_rwlock);
19526 }
19527 
19528 /*
19529  * ndp_walk routine to create ipv6NetToMediaEntryTable
19530  */
19531 static int
19532 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19533 {
19534 	ill_t				*ill;
19535 	mib2_ipv6NetToMediaEntry_t	ntme;
19536 	dl_unitdata_req_t		*dl;
19537 
19538 	ill = nce->nce_ill;
19539 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19540 		return (0);
19541 
19542 	/*
19543 	 * Neighbor cache entry attached to IRE with on-link
19544 	 * destination.
19545 	 */
19546 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19547 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19548 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19549 	    (nce->nce_res_mp != NULL)) {
19550 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19551 		ntme.ipv6NetToMediaPhysAddress.o_length =
19552 		    dl->dl_dest_addr_length;
19553 	} else {
19554 		ntme.ipv6NetToMediaPhysAddress.o_length =
19555 		    ill->ill_phys_addr_length;
19556 	}
19557 	if (nce->nce_res_mp != NULL) {
19558 		bcopy((char *)nce->nce_res_mp->b_rptr +
19559 		    NCE_LL_ADDR_OFFSET(ill),
19560 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19561 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19562 	} else {
19563 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19564 		    ill->ill_phys_addr_length);
19565 	}
19566 	/*
19567 	 * Note: Returns ND_* states. Should be:
19568 	 * reachable(1), stale(2), delay(3), probe(4),
19569 	 * invalid(5), unknown(6)
19570 	 */
19571 	ntme.ipv6NetToMediaState = nce->nce_state;
19572 	ntme.ipv6NetToMediaLastUpdated = 0;
19573 
19574 	/* other(1), dynamic(2), static(3), local(4) */
19575 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19576 		ntme.ipv6NetToMediaType = 4;
19577 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19578 		ntme.ipv6NetToMediaType = 1;
19579 	} else {
19580 		ntme.ipv6NetToMediaType = 2;
19581 	}
19582 
19583 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19584 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19585 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19586 		    (uint_t)sizeof (ntme)));
19587 	}
19588 	return (0);
19589 }
19590 
19591 /*
19592  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19593  */
19594 /* ARGSUSED */
19595 int
19596 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19597 {
19598 	switch (level) {
19599 	case MIB2_IP:
19600 	case MIB2_ICMP:
19601 		switch (name) {
19602 		default:
19603 			break;
19604 		}
19605 		return (1);
19606 	default:
19607 		return (1);
19608 	}
19609 }
19610 
19611 /*
19612  * When there exists both a 64- and 32-bit counter of a particular type
19613  * (i.e., InReceives), only the 64-bit counters are added.
19614  */
19615 void
19616 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19617 {
19618 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19619 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19620 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19621 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19622 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19623 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19624 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19625 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19626 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19627 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19628 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19629 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19630 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19631 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19632 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19633 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19634 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19635 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19636 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19637 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19638 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19639 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19640 	    o2->ipIfStatsInWrongIPVersion);
19641 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19642 	    o2->ipIfStatsInWrongIPVersion);
19643 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19644 	    o2->ipIfStatsOutSwitchIPVersion);
19645 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19646 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19647 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19648 	    o2->ipIfStatsHCInForwDatagrams);
19649 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19650 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19651 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19652 	    o2->ipIfStatsHCOutForwDatagrams);
19653 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19654 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19655 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19656 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19657 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19658 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19659 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19660 	    o2->ipIfStatsHCOutMcastOctets);
19661 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19662 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19663 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19664 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19665 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19666 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19667 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19668 }
19669 
19670 void
19671 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19672 {
19673 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19674 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19675 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19676 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19677 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19678 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19679 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19680 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19681 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19682 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19683 	    o2->ipv6IfIcmpInRouterSolicits);
19684 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19685 	    o2->ipv6IfIcmpInRouterAdvertisements);
19686 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19687 	    o2->ipv6IfIcmpInNeighborSolicits);
19688 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19689 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19690 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19691 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19692 	    o2->ipv6IfIcmpInGroupMembQueries);
19693 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19694 	    o2->ipv6IfIcmpInGroupMembResponses);
19695 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19696 	    o2->ipv6IfIcmpInGroupMembReductions);
19697 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19698 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19699 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19700 	    o2->ipv6IfIcmpOutDestUnreachs);
19701 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19702 	    o2->ipv6IfIcmpOutAdminProhibs);
19703 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19704 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19705 	    o2->ipv6IfIcmpOutParmProblems);
19706 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19707 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19708 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19709 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19710 	    o2->ipv6IfIcmpOutRouterSolicits);
19711 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19712 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19713 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19714 	    o2->ipv6IfIcmpOutNeighborSolicits);
19715 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19716 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19717 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19718 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19719 	    o2->ipv6IfIcmpOutGroupMembQueries);
19720 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19721 	    o2->ipv6IfIcmpOutGroupMembResponses);
19722 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19723 	    o2->ipv6IfIcmpOutGroupMembReductions);
19724 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19725 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19726 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19727 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19728 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19729 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19730 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19731 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19732 	    o2->ipv6IfIcmpInGroupMembTotal);
19733 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19734 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19735 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19736 	    o2->ipv6IfIcmpInGroupMembBadReports);
19737 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19738 	    o2->ipv6IfIcmpInGroupMembOurReports);
19739 }
19740 
19741 /*
19742  * Called before the options are updated to check if this packet will
19743  * be source routed from here.
19744  * This routine assumes that the options are well formed i.e. that they
19745  * have already been checked.
19746  */
19747 static boolean_t
19748 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19749 {
19750 	ipoptp_t	opts;
19751 	uchar_t		*opt;
19752 	uint8_t		optval;
19753 	uint8_t		optlen;
19754 	ipaddr_t	dst;
19755 	ire_t		*ire;
19756 
19757 	if (IS_SIMPLE_IPH(ipha)) {
19758 		ip2dbg(("not source routed\n"));
19759 		return (B_FALSE);
19760 	}
19761 	dst = ipha->ipha_dst;
19762 	for (optval = ipoptp_first(&opts, ipha);
19763 	    optval != IPOPT_EOL;
19764 	    optval = ipoptp_next(&opts)) {
19765 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19766 		opt = opts.ipoptp_cur;
19767 		optlen = opts.ipoptp_len;
19768 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19769 		    optval, optlen));
19770 		switch (optval) {
19771 			uint32_t off;
19772 		case IPOPT_SSRR:
19773 		case IPOPT_LSRR:
19774 			/*
19775 			 * If dst is one of our addresses and there are some
19776 			 * entries left in the source route return (true).
19777 			 */
19778 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19779 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19780 			if (ire == NULL) {
19781 				ip2dbg(("ip_source_routed: not next"
19782 				    " source route 0x%x\n",
19783 				    ntohl(dst)));
19784 				return (B_FALSE);
19785 			}
19786 			ire_refrele(ire);
19787 			off = opt[IPOPT_OFFSET];
19788 			off--;
19789 			if (optlen < IP_ADDR_LEN ||
19790 			    off > optlen - IP_ADDR_LEN) {
19791 				/* End of source route */
19792 				ip1dbg(("ip_source_routed: end of SR\n"));
19793 				return (B_FALSE);
19794 			}
19795 			return (B_TRUE);
19796 		}
19797 	}
19798 	ip2dbg(("not source routed\n"));
19799 	return (B_FALSE);
19800 }
19801 
19802 /*
19803  * Check if the packet contains any source route.
19804  */
19805 static boolean_t
19806 ip_source_route_included(ipha_t *ipha)
19807 {
19808 	ipoptp_t	opts;
19809 	uint8_t		optval;
19810 
19811 	if (IS_SIMPLE_IPH(ipha))
19812 		return (B_FALSE);
19813 	for (optval = ipoptp_first(&opts, ipha);
19814 	    optval != IPOPT_EOL;
19815 	    optval = ipoptp_next(&opts)) {
19816 		switch (optval) {
19817 		case IPOPT_SSRR:
19818 		case IPOPT_LSRR:
19819 			return (B_TRUE);
19820 		}
19821 	}
19822 	return (B_FALSE);
19823 }
19824 
19825 /*
19826  * Called when the IRE expiration timer fires.
19827  */
19828 void
19829 ip_trash_timer_expire(void *args)
19830 {
19831 	int			flush_flag = 0;
19832 	ire_expire_arg_t	iea;
19833 	ip_stack_t		*ipst = (ip_stack_t *)args;
19834 
19835 	iea.iea_ipst = ipst;	/* No netstack_hold */
19836 
19837 	/*
19838 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19839 	 * This lock makes sure that a new invocation of this function
19840 	 * that occurs due to an almost immediate timer firing will not
19841 	 * progress beyond this point until the current invocation is done
19842 	 */
19843 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19844 	ipst->ips_ip_ire_expire_id = 0;
19845 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19846 
19847 	/* Periodic timer */
19848 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19849 	    ipst->ips_ip_ire_arp_interval) {
19850 		/*
19851 		 * Remove all IRE_CACHE entries since they might
19852 		 * contain arp information.
19853 		 */
19854 		flush_flag |= FLUSH_ARP_TIME;
19855 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19856 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19857 	}
19858 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19859 	    ipst->ips_ip_ire_redir_interval) {
19860 		/* Remove all redirects */
19861 		flush_flag |= FLUSH_REDIRECT_TIME;
19862 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19863 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19864 	}
19865 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19866 	    ipst->ips_ip_ire_pathmtu_interval) {
19867 		/* Increase path mtu */
19868 		flush_flag |= FLUSH_MTU_TIME;
19869 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19870 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19871 	}
19872 
19873 	/*
19874 	 * Optimize for the case when there are no redirects in the
19875 	 * ftable, that is, no need to walk the ftable in that case.
19876 	 */
19877 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19878 		iea.iea_flush_flag = flush_flag;
19879 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19880 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19881 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19882 		    NULL, ALL_ZONES, ipst);
19883 	}
19884 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19885 	    ipst->ips_ip_redirect_cnt > 0) {
19886 		iea.iea_flush_flag = flush_flag;
19887 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19888 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19889 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19890 	}
19891 	if (flush_flag & FLUSH_MTU_TIME) {
19892 		/*
19893 		 * Walk all IPv6 IRE's and update them
19894 		 * Note that ARP and redirect timers are not
19895 		 * needed since NUD handles stale entries.
19896 		 */
19897 		flush_flag = FLUSH_MTU_TIME;
19898 		iea.iea_flush_flag = flush_flag;
19899 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19900 		    ALL_ZONES, ipst);
19901 	}
19902 
19903 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19904 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19905 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19906 
19907 	/*
19908 	 * Hold the lock to serialize timeout calls and prevent
19909 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19910 	 * for the timer to fire and a new invocation of this function
19911 	 * to start before the return value of timeout has been stored
19912 	 * in ip_ire_expire_id by the current invocation.
19913 	 */
19914 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19915 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19916 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19917 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19918 }
19919 
19920 /*
19921  * Called by the memory allocator subsystem directly, when the system
19922  * is running low on memory.
19923  */
19924 /* ARGSUSED */
19925 void
19926 ip_trash_ire_reclaim(void *args)
19927 {
19928 	netstack_handle_t nh;
19929 	netstack_t *ns;
19930 
19931 	netstack_next_init(&nh);
19932 	while ((ns = netstack_next(&nh)) != NULL) {
19933 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19934 		netstack_rele(ns);
19935 	}
19936 	netstack_next_fini(&nh);
19937 }
19938 
19939 static void
19940 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19941 {
19942 	ire_cache_count_t icc;
19943 	ire_cache_reclaim_t icr;
19944 	ncc_cache_count_t ncc;
19945 	nce_cache_reclaim_t ncr;
19946 	uint_t delete_cnt;
19947 	/*
19948 	 * Memory reclaim call back.
19949 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19950 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19951 	 * entries, determine what fraction to free for
19952 	 * each category of IRE_CACHE entries giving absolute priority
19953 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19954 	 * entry will be freed unless all offlink entries are freed).
19955 	 */
19956 	icc.icc_total = 0;
19957 	icc.icc_unused = 0;
19958 	icc.icc_offlink = 0;
19959 	icc.icc_pmtu = 0;
19960 	icc.icc_onlink = 0;
19961 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19962 
19963 	/*
19964 	 * Free NCEs for IPv6 like the onlink ires.
19965 	 */
19966 	ncc.ncc_total = 0;
19967 	ncc.ncc_host = 0;
19968 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19969 
19970 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19971 	    icc.icc_pmtu + icc.icc_onlink);
19972 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19973 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19974 	if (delete_cnt == 0)
19975 		return;
19976 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19977 	/* Always delete all unused offlink entries */
19978 	icr.icr_ipst = ipst;
19979 	icr.icr_unused = 1;
19980 	if (delete_cnt <= icc.icc_unused) {
19981 		/*
19982 		 * Only need to free unused entries.  In other words,
19983 		 * there are enough unused entries to free to meet our
19984 		 * target number of freed ire cache entries.
19985 		 */
19986 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19987 		ncr.ncr_host = 0;
19988 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19989 		/*
19990 		 * Only need to free unused entries, plus a fraction of offlink
19991 		 * entries.  It follows from the first if statement that
19992 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19993 		 */
19994 		delete_cnt -= icc.icc_unused;
19995 		/* Round up # deleted by truncating fraction */
19996 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19997 		icr.icr_pmtu = icr.icr_onlink = 0;
19998 		ncr.ncr_host = 0;
19999 	} else if (delete_cnt <=
20000 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
20001 		/*
20002 		 * Free all unused and offlink entries, plus a fraction of
20003 		 * pmtu entries.  It follows from the previous if statement
20004 		 * that icc_pmtu is non-zero, and that
20005 		 * delete_cnt != icc_unused + icc_offlink.
20006 		 */
20007 		icr.icr_offlink = 1;
20008 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20009 		/* Round up # deleted by truncating fraction */
20010 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20011 		icr.icr_onlink = 0;
20012 		ncr.ncr_host = 0;
20013 	} else {
20014 		/*
20015 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20016 		 * of onlink entries.  If we're here, then we know that
20017 		 * icc_onlink is non-zero, and that
20018 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20019 		 */
20020 		icr.icr_offlink = icr.icr_pmtu = 1;
20021 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20022 		    icc.icc_pmtu;
20023 		/* Round up # deleted by truncating fraction */
20024 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20025 		/* Using the same delete fraction as for onlink IREs */
20026 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20027 	}
20028 #ifdef DEBUG
20029 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20030 	    "fractions %d/%d/%d/%d\n",
20031 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20032 	    icc.icc_unused, icc.icc_offlink,
20033 	    icc.icc_pmtu, icc.icc_onlink,
20034 	    icr.icr_unused, icr.icr_offlink,
20035 	    icr.icr_pmtu, icr.icr_onlink));
20036 #endif
20037 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20038 	if (ncr.ncr_host != 0)
20039 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20040 		    (uchar_t *)&ncr, ipst);
20041 #ifdef DEBUG
20042 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20043 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20044 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20045 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20046 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20047 	    icc.icc_pmtu, icc.icc_onlink));
20048 #endif
20049 }
20050 
20051 /*
20052  * ip_unbind is called when a copy of an unbind request is received from the
20053  * upper level protocol.  We remove this conn from any fanout hash list it is
20054  * on, and zero out the bind information.  No reply is expected up above.
20055  */
20056 mblk_t *
20057 ip_unbind(queue_t *q, mblk_t *mp)
20058 {
20059 	conn_t	*connp = Q_TO_CONN(q);
20060 
20061 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20062 
20063 	if (is_system_labeled() && connp->conn_anon_port) {
20064 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20065 		    connp->conn_mlp_type, connp->conn_ulp,
20066 		    ntohs(connp->conn_lport), B_FALSE);
20067 		connp->conn_anon_port = 0;
20068 	}
20069 	connp->conn_mlp_type = mlptSingle;
20070 
20071 	ipcl_hash_remove(connp);
20072 
20073 	ASSERT(mp->b_cont == NULL);
20074 	/*
20075 	 * Convert mp into a T_OK_ACK
20076 	 */
20077 	mp = mi_tpi_ok_ack_alloc(mp);
20078 
20079 	/*
20080 	 * should not happen in practice... T_OK_ACK is smaller than the
20081 	 * original message.
20082 	 */
20083 	if (mp == NULL)
20084 		return (NULL);
20085 
20086 	return (mp);
20087 }
20088 
20089 /*
20090  * Write side put procedure.  Outbound data, IOCTLs, responses from
20091  * resolvers, etc, come down through here.
20092  *
20093  * arg2 is always a queue_t *.
20094  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20095  * the zoneid.
20096  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20097  */
20098 void
20099 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20100 {
20101 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20102 }
20103 
20104 void
20105 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20106     ip_opt_info_t *infop)
20107 {
20108 	conn_t		*connp = NULL;
20109 	queue_t		*q = (queue_t *)arg2;
20110 	ipha_t		*ipha;
20111 #define	rptr	((uchar_t *)ipha)
20112 	ire_t		*ire = NULL;
20113 	ire_t		*sctp_ire = NULL;
20114 	uint32_t	v_hlen_tos_len;
20115 	ipaddr_t	dst;
20116 	mblk_t		*first_mp = NULL;
20117 	boolean_t	mctl_present;
20118 	ipsec_out_t	*io;
20119 	int		match_flags;
20120 	ill_t		*attach_ill = NULL;
20121 					/* Bind to IPIF_NOFAILOVER ill etc. */
20122 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20123 	ipif_t		*dst_ipif;
20124 	boolean_t	multirt_need_resolve = B_FALSE;
20125 	mblk_t		*copy_mp = NULL;
20126 	int		err;
20127 	zoneid_t	zoneid;
20128 	int	adjust;
20129 	uint16_t iplen;
20130 	boolean_t	need_decref = B_FALSE;
20131 	boolean_t	ignore_dontroute = B_FALSE;
20132 	boolean_t	ignore_nexthop = B_FALSE;
20133 	boolean_t	ip_nexthop = B_FALSE;
20134 	ipaddr_t	nexthop_addr;
20135 	ip_stack_t	*ipst;
20136 
20137 #ifdef	_BIG_ENDIAN
20138 #define	V_HLEN	(v_hlen_tos_len >> 24)
20139 #else
20140 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20141 #endif
20142 
20143 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20144 	    "ip_wput_start: q %p", q);
20145 
20146 	/*
20147 	 * ip_wput fast path
20148 	 */
20149 
20150 	/* is packet from ARP ? */
20151 	if (q->q_next != NULL) {
20152 		zoneid = (zoneid_t)(uintptr_t)arg;
20153 		goto qnext;
20154 	}
20155 
20156 	connp = (conn_t *)arg;
20157 	ASSERT(connp != NULL);
20158 	zoneid = connp->conn_zoneid;
20159 	ipst = connp->conn_netstack->netstack_ip;
20160 
20161 	/* is queue flow controlled? */
20162 	if ((q->q_first != NULL || connp->conn_draining) &&
20163 	    (caller == IP_WPUT)) {
20164 		ASSERT(!need_decref);
20165 		(void) putq(q, mp);
20166 		return;
20167 	}
20168 
20169 	/* Multidata transmit? */
20170 	if (DB_TYPE(mp) == M_MULTIDATA) {
20171 		/*
20172 		 * We should never get here, since all Multidata messages
20173 		 * originating from tcp should have been directed over to
20174 		 * tcp_multisend() in the first place.
20175 		 */
20176 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20177 		freemsg(mp);
20178 		return;
20179 	} else if (DB_TYPE(mp) != M_DATA)
20180 		goto notdata;
20181 
20182 	if (mp->b_flag & MSGHASREF) {
20183 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20184 		mp->b_flag &= ~MSGHASREF;
20185 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20186 		need_decref = B_TRUE;
20187 	}
20188 	ipha = (ipha_t *)mp->b_rptr;
20189 
20190 	/* is IP header non-aligned or mblk smaller than basic IP header */
20191 #ifndef SAFETY_BEFORE_SPEED
20192 	if (!OK_32PTR(rptr) ||
20193 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20194 		goto hdrtoosmall;
20195 #endif
20196 
20197 	ASSERT(OK_32PTR(ipha));
20198 
20199 	/*
20200 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20201 	 * wrong version, we'll catch it again in ip_output_v6.
20202 	 *
20203 	 * Note that this is *only* locally-generated output here, and never
20204 	 * forwarded data, and that we need to deal only with transports that
20205 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20206 	 * label.)
20207 	 */
20208 	if (is_system_labeled() &&
20209 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20210 	    !connp->conn_ulp_labeled) {
20211 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20212 		    connp->conn_mac_exempt, ipst);
20213 		ipha = (ipha_t *)mp->b_rptr;
20214 		if (err != 0) {
20215 			first_mp = mp;
20216 			if (err == EINVAL)
20217 				goto icmp_parameter_problem;
20218 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20219 			goto discard_pkt;
20220 		}
20221 		iplen = ntohs(ipha->ipha_length) + adjust;
20222 		ipha->ipha_length = htons(iplen);
20223 	}
20224 
20225 	ASSERT(infop != NULL);
20226 
20227 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20228 		/*
20229 		 * IP_PKTINFO ancillary option is present.
20230 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20231 		 * allows using address of any zone as the source address.
20232 		 */
20233 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20234 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20235 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20236 		if (ire == NULL)
20237 			goto drop_pkt;
20238 		ire_refrele(ire);
20239 		ire = NULL;
20240 	}
20241 
20242 	/*
20243 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20244 	 * passed in IP_PKTINFO.
20245 	 */
20246 	if (infop->ip_opt_ill_index != 0 &&
20247 	    connp->conn_outgoing_ill == NULL &&
20248 	    connp->conn_nofailover_ill == NULL) {
20249 
20250 		xmit_ill = ill_lookup_on_ifindex(
20251 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20252 		    ipst);
20253 
20254 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20255 			goto drop_pkt;
20256 		/*
20257 		 * check that there is an ipif belonging
20258 		 * to our zone. IPCL_ZONEID is not used because
20259 		 * IP_ALLZONES option is valid only when the ill is
20260 		 * accessible from all zones i.e has a valid ipif in
20261 		 * all zones.
20262 		 */
20263 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20264 			goto drop_pkt;
20265 		}
20266 	}
20267 
20268 	/*
20269 	 * If there is a policy, try to attach an ipsec_out in
20270 	 * the front. At the end, first_mp either points to a
20271 	 * M_DATA message or IPSEC_OUT message linked to a
20272 	 * M_DATA message. We have to do it now as we might
20273 	 * lose the "conn" if we go through ip_newroute.
20274 	 */
20275 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20276 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20277 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20278 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20279 			if (need_decref)
20280 				CONN_DEC_REF(connp);
20281 			return;
20282 		} else {
20283 			ASSERT(mp->b_datap->db_type == M_CTL);
20284 			first_mp = mp;
20285 			mp = mp->b_cont;
20286 			mctl_present = B_TRUE;
20287 		}
20288 	} else {
20289 		first_mp = mp;
20290 		mctl_present = B_FALSE;
20291 	}
20292 
20293 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20294 
20295 	/* is wrong version or IP options present */
20296 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20297 		goto version_hdrlen_check;
20298 	dst = ipha->ipha_dst;
20299 
20300 	if (connp->conn_nofailover_ill != NULL) {
20301 		attach_ill = conn_get_held_ill(connp,
20302 		    &connp->conn_nofailover_ill, &err);
20303 		if (err == ILL_LOOKUP_FAILED) {
20304 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20305 			if (need_decref)
20306 				CONN_DEC_REF(connp);
20307 			freemsg(first_mp);
20308 			return;
20309 		}
20310 	}
20311 
20312 	/* If IP_BOUND_IF has been set, use that ill. */
20313 	if (connp->conn_outgoing_ill != NULL) {
20314 		xmit_ill = conn_get_held_ill(connp,
20315 		    &connp->conn_outgoing_ill, &err);
20316 		if (err == ILL_LOOKUP_FAILED)
20317 			goto drop_pkt;
20318 
20319 		goto send_from_ill;
20320 	}
20321 
20322 	/* is packet multicast? */
20323 	if (CLASSD(dst))
20324 		goto multicast;
20325 
20326 	/*
20327 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20328 	 * takes precedence over conn_dontroute and conn_nexthop_set
20329 	 */
20330 	if (xmit_ill != NULL)
20331 		goto send_from_ill;
20332 
20333 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20334 		/*
20335 		 * If the destination is a broadcast, local, or loopback
20336 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20337 		 * standard path.
20338 		 */
20339 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20340 		if ((ire == NULL) || (ire->ire_type &
20341 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20342 			if (ire != NULL) {
20343 				ire_refrele(ire);
20344 				/* No more access to ire */
20345 				ire = NULL;
20346 			}
20347 			/*
20348 			 * bypass routing checks and go directly to interface.
20349 			 */
20350 			if (connp->conn_dontroute)
20351 				goto dontroute;
20352 
20353 			ASSERT(connp->conn_nexthop_set);
20354 			ip_nexthop = B_TRUE;
20355 			nexthop_addr = connp->conn_nexthop_v4;
20356 			goto send_from_ill;
20357 		}
20358 
20359 		/* Must be a broadcast, a loopback or a local ire */
20360 		ire_refrele(ire);
20361 		/* No more access to ire */
20362 		ire = NULL;
20363 	}
20364 
20365 	if (attach_ill != NULL)
20366 		goto send_from_ill;
20367 
20368 	/*
20369 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20370 	 * this for the tcp global queue and listen end point
20371 	 * as it does not really have a real destination to
20372 	 * talk to.  This is also true for SCTP.
20373 	 */
20374 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20375 	    !connp->conn_fully_bound) {
20376 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20377 		if (ire == NULL)
20378 			goto noirefound;
20379 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20380 		    "ip_wput_end: q %p (%S)", q, "end");
20381 
20382 		/*
20383 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20384 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20385 		 */
20386 		if (ire->ire_flags & RTF_MULTIRT) {
20387 
20388 			/*
20389 			 * Force the TTL of multirouted packets if required.
20390 			 * The TTL of such packets is bounded by the
20391 			 * ip_multirt_ttl ndd variable.
20392 			 */
20393 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20394 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20395 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20396 				    "(was %d), dst 0x%08x\n",
20397 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20398 				    ntohl(ire->ire_addr)));
20399 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20400 			}
20401 			/*
20402 			 * We look at this point if there are pending
20403 			 * unresolved routes. ire_multirt_resolvable()
20404 			 * checks in O(n) that all IRE_OFFSUBNET ire
20405 			 * entries for the packet's destination and
20406 			 * flagged RTF_MULTIRT are currently resolved.
20407 			 * If some remain unresolved, we make a copy
20408 			 * of the current message. It will be used
20409 			 * to initiate additional route resolutions.
20410 			 */
20411 			multirt_need_resolve =
20412 			    ire_multirt_need_resolve(ire->ire_addr,
20413 			    MBLK_GETLABEL(first_mp), ipst);
20414 			ip2dbg(("ip_wput[TCP]: ire %p, "
20415 			    "multirt_need_resolve %d, first_mp %p\n",
20416 			    (void *)ire, multirt_need_resolve,
20417 			    (void *)first_mp));
20418 			if (multirt_need_resolve) {
20419 				copy_mp = copymsg(first_mp);
20420 				if (copy_mp != NULL) {
20421 					MULTIRT_DEBUG_TAG(copy_mp);
20422 				}
20423 			}
20424 		}
20425 
20426 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20427 
20428 		/*
20429 		 * Try to resolve another multiroute if
20430 		 * ire_multirt_need_resolve() deemed it necessary.
20431 		 */
20432 		if (copy_mp != NULL)
20433 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20434 		if (need_decref)
20435 			CONN_DEC_REF(connp);
20436 		return;
20437 	}
20438 
20439 	/*
20440 	 * Access to conn_ire_cache. (protected by conn_lock)
20441 	 *
20442 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20443 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20444 	 * send a packet or two with the IRE_CACHE that is going away.
20445 	 * Access to the ire requires an ire refhold on the ire prior to
20446 	 * its use since an interface unplumb thread may delete the cached
20447 	 * ire and release the refhold at any time.
20448 	 *
20449 	 * Caching an ire in the conn_ire_cache
20450 	 *
20451 	 * o Caching an ire pointer in the conn requires a strict check for
20452 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20453 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20454 	 * in the conn is done after making sure under the bucket lock that the
20455 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20456 	 * caching an ire after the unplumb thread has cleaned up the conn.
20457 	 * If the conn does not send a packet subsequently the unplumb thread
20458 	 * will be hanging waiting for the ire count to drop to zero.
20459 	 *
20460 	 * o We also need to atomically test for a null conn_ire_cache and
20461 	 * set the conn_ire_cache under the the protection of the conn_lock
20462 	 * to avoid races among concurrent threads trying to simultaneously
20463 	 * cache an ire in the conn_ire_cache.
20464 	 */
20465 	mutex_enter(&connp->conn_lock);
20466 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20467 
20468 	if (ire != NULL && ire->ire_addr == dst &&
20469 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20470 
20471 		IRE_REFHOLD(ire);
20472 		mutex_exit(&connp->conn_lock);
20473 
20474 	} else {
20475 		boolean_t cached = B_FALSE;
20476 		connp->conn_ire_cache = NULL;
20477 		mutex_exit(&connp->conn_lock);
20478 		/* Release the old ire */
20479 		if (ire != NULL && sctp_ire == NULL)
20480 			IRE_REFRELE_NOTR(ire);
20481 
20482 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20483 		if (ire == NULL)
20484 			goto noirefound;
20485 		IRE_REFHOLD_NOTR(ire);
20486 
20487 		mutex_enter(&connp->conn_lock);
20488 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20489 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20490 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20491 				if (connp->conn_ulp == IPPROTO_TCP)
20492 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20493 				connp->conn_ire_cache = ire;
20494 				cached = B_TRUE;
20495 			}
20496 			rw_exit(&ire->ire_bucket->irb_lock);
20497 		}
20498 		mutex_exit(&connp->conn_lock);
20499 
20500 		/*
20501 		 * We can continue to use the ire but since it was
20502 		 * not cached, we should drop the extra reference.
20503 		 */
20504 		if (!cached)
20505 			IRE_REFRELE_NOTR(ire);
20506 	}
20507 
20508 
20509 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20510 	    "ip_wput_end: q %p (%S)", q, "end");
20511 
20512 	/*
20513 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20514 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20515 	 */
20516 	if (ire->ire_flags & RTF_MULTIRT) {
20517 
20518 		/*
20519 		 * Force the TTL of multirouted packets if required.
20520 		 * The TTL of such packets is bounded by the
20521 		 * ip_multirt_ttl ndd variable.
20522 		 */
20523 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20524 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20525 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20526 			    "(was %d), dst 0x%08x\n",
20527 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20528 			    ntohl(ire->ire_addr)));
20529 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20530 		}
20531 
20532 		/*
20533 		 * At this point, we check to see if there are any pending
20534 		 * unresolved routes. ire_multirt_resolvable()
20535 		 * checks in O(n) that all IRE_OFFSUBNET ire
20536 		 * entries for the packet's destination and
20537 		 * flagged RTF_MULTIRT are currently resolved.
20538 		 * If some remain unresolved, we make a copy
20539 		 * of the current message. It will be used
20540 		 * to initiate additional route resolutions.
20541 		 */
20542 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20543 		    MBLK_GETLABEL(first_mp), ipst);
20544 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20545 		    "multirt_need_resolve %d, first_mp %p\n",
20546 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20547 		if (multirt_need_resolve) {
20548 			copy_mp = copymsg(first_mp);
20549 			if (copy_mp != NULL) {
20550 				MULTIRT_DEBUG_TAG(copy_mp);
20551 			}
20552 		}
20553 	}
20554 
20555 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20556 
20557 	/*
20558 	 * Try to resolve another multiroute if
20559 	 * ire_multirt_resolvable() deemed it necessary
20560 	 */
20561 	if (copy_mp != NULL)
20562 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20563 	if (need_decref)
20564 		CONN_DEC_REF(connp);
20565 	return;
20566 
20567 qnext:
20568 	/*
20569 	 * Upper Level Protocols pass down complete IP datagrams
20570 	 * as M_DATA messages.	Everything else is a sideshow.
20571 	 *
20572 	 * 1) We could be re-entering ip_wput because of ip_neworute
20573 	 *    in which case we could have a IPSEC_OUT message. We
20574 	 *    need to pass through ip_wput like other datagrams and
20575 	 *    hence cannot branch to ip_wput_nondata.
20576 	 *
20577 	 * 2) ARP, AH, ESP, and other clients who are on the module
20578 	 *    instance of IP stream, give us something to deal with.
20579 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20580 	 *
20581 	 * 3) ICMP replies also could come here.
20582 	 */
20583 	ipst = ILLQ_TO_IPST(q);
20584 
20585 	if (DB_TYPE(mp) != M_DATA) {
20586 notdata:
20587 		if (DB_TYPE(mp) == M_CTL) {
20588 			/*
20589 			 * M_CTL messages are used by ARP, AH and ESP to
20590 			 * communicate with IP. We deal with IPSEC_IN and
20591 			 * IPSEC_OUT here. ip_wput_nondata handles other
20592 			 * cases.
20593 			 */
20594 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20595 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20596 				first_mp = mp->b_cont;
20597 				first_mp->b_flag &= ~MSGHASREF;
20598 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20599 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20600 				CONN_DEC_REF(connp);
20601 				connp = NULL;
20602 			}
20603 			if (ii->ipsec_info_type == IPSEC_IN) {
20604 				/*
20605 				 * Either this message goes back to
20606 				 * IPsec for further processing or to
20607 				 * ULP after policy checks.
20608 				 */
20609 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20610 				return;
20611 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20612 				io = (ipsec_out_t *)ii;
20613 				if (io->ipsec_out_proc_begin) {
20614 					/*
20615 					 * IPsec processing has already started.
20616 					 * Complete it.
20617 					 * IPQoS notes: We don't care what is
20618 					 * in ipsec_out_ill_index since this
20619 					 * won't be processed for IPQoS policies
20620 					 * in ipsec_out_process.
20621 					 */
20622 					ipsec_out_process(q, mp, NULL,
20623 					    io->ipsec_out_ill_index);
20624 					return;
20625 				} else {
20626 					connp = (q->q_next != NULL) ?
20627 					    NULL : Q_TO_CONN(q);
20628 					first_mp = mp;
20629 					mp = mp->b_cont;
20630 					mctl_present = B_TRUE;
20631 				}
20632 				zoneid = io->ipsec_out_zoneid;
20633 				ASSERT(zoneid != ALL_ZONES);
20634 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20635 				/*
20636 				 * It's an IPsec control message requesting
20637 				 * an SADB update to be sent to the IPsec
20638 				 * hardware acceleration capable ills.
20639 				 */
20640 				ipsec_ctl_t *ipsec_ctl =
20641 				    (ipsec_ctl_t *)mp->b_rptr;
20642 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20643 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20644 				mblk_t *cmp = mp->b_cont;
20645 
20646 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20647 				ASSERT(cmp != NULL);
20648 
20649 				freeb(mp);
20650 				ill_ipsec_capab_send_all(satype, cmp, sa,
20651 				    ipst->ips_netstack);
20652 				return;
20653 			} else {
20654 				/*
20655 				 * This must be ARP or special TSOL signaling.
20656 				 */
20657 				ip_wput_nondata(NULL, q, mp, NULL);
20658 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20659 				    "ip_wput_end: q %p (%S)", q, "nondata");
20660 				return;
20661 			}
20662 		} else {
20663 			/*
20664 			 * This must be non-(ARP/AH/ESP) messages.
20665 			 */
20666 			ASSERT(!need_decref);
20667 			ip_wput_nondata(NULL, q, mp, NULL);
20668 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20669 			    "ip_wput_end: q %p (%S)", q, "nondata");
20670 			return;
20671 		}
20672 	} else {
20673 		first_mp = mp;
20674 		mctl_present = B_FALSE;
20675 	}
20676 
20677 	ASSERT(first_mp != NULL);
20678 	/*
20679 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20680 	 * to make sure that this packet goes out on the same interface it
20681 	 * came in. We handle that here.
20682 	 */
20683 	if (mctl_present) {
20684 		uint_t ifindex;
20685 
20686 		io = (ipsec_out_t *)first_mp->b_rptr;
20687 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20688 			/*
20689 			 * We may have lost the conn context if we are
20690 			 * coming here from ip_newroute(). Copy the
20691 			 * nexthop information.
20692 			 */
20693 			if (io->ipsec_out_ip_nexthop) {
20694 				ip_nexthop = B_TRUE;
20695 				nexthop_addr = io->ipsec_out_nexthop_addr;
20696 
20697 				ipha = (ipha_t *)mp->b_rptr;
20698 				dst = ipha->ipha_dst;
20699 				goto send_from_ill;
20700 			} else {
20701 				ASSERT(io->ipsec_out_ill_index != 0);
20702 				ifindex = io->ipsec_out_ill_index;
20703 				attach_ill = ill_lookup_on_ifindex(ifindex,
20704 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20705 				if (attach_ill == NULL) {
20706 					ASSERT(xmit_ill == NULL);
20707 					ip1dbg(("ip_output: bad ifindex for "
20708 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20709 					    ifindex));
20710 					freemsg(first_mp);
20711 					BUMP_MIB(&ipst->ips_ip_mib,
20712 					    ipIfStatsOutDiscards);
20713 					ASSERT(!need_decref);
20714 					return;
20715 				}
20716 			}
20717 		}
20718 	}
20719 
20720 	ASSERT(xmit_ill == NULL);
20721 
20722 	/* We have a complete IP datagram heading outbound. */
20723 	ipha = (ipha_t *)mp->b_rptr;
20724 
20725 #ifndef SPEED_BEFORE_SAFETY
20726 	/*
20727 	 * Make sure we have a full-word aligned message and that at least
20728 	 * a simple IP header is accessible in the first message.  If not,
20729 	 * try a pullup.
20730 	 */
20731 	if (!OK_32PTR(rptr) ||
20732 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH) {
20733 hdrtoosmall:
20734 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20735 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20736 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20737 			if (first_mp == NULL)
20738 				first_mp = mp;
20739 			goto discard_pkt;
20740 		}
20741 
20742 		/* This function assumes that mp points to an IPv4 packet. */
20743 		if (is_system_labeled() && q->q_next == NULL &&
20744 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20745 		    !connp->conn_ulp_labeled) {
20746 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20747 			    &adjust, connp->conn_mac_exempt, ipst);
20748 			ipha = (ipha_t *)mp->b_rptr;
20749 			if (first_mp != NULL)
20750 				first_mp->b_cont = mp;
20751 			if (err != 0) {
20752 				if (first_mp == NULL)
20753 					first_mp = mp;
20754 				if (err == EINVAL)
20755 					goto icmp_parameter_problem;
20756 				ip2dbg(("ip_wput: label check failed (%d)\n",
20757 				    err));
20758 				goto discard_pkt;
20759 			}
20760 			iplen = ntohs(ipha->ipha_length) + adjust;
20761 			ipha->ipha_length = htons(iplen);
20762 		}
20763 
20764 		ipha = (ipha_t *)mp->b_rptr;
20765 		if (first_mp == NULL) {
20766 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20767 			/*
20768 			 * If we got here because of "goto hdrtoosmall"
20769 			 * We need to attach a IPSEC_OUT.
20770 			 */
20771 			if (connp->conn_out_enforce_policy) {
20772 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20773 				    NULL, ipha->ipha_protocol,
20774 				    ipst->ips_netstack)) == NULL)) {
20775 					BUMP_MIB(&ipst->ips_ip_mib,
20776 					    ipIfStatsOutDiscards);
20777 					if (need_decref)
20778 						CONN_DEC_REF(connp);
20779 					return;
20780 				} else {
20781 					ASSERT(mp->b_datap->db_type == M_CTL);
20782 					first_mp = mp;
20783 					mp = mp->b_cont;
20784 					mctl_present = B_TRUE;
20785 				}
20786 			} else {
20787 				first_mp = mp;
20788 				mctl_present = B_FALSE;
20789 			}
20790 		}
20791 	}
20792 #endif
20793 
20794 	/* Most of the code below is written for speed, not readability */
20795 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20796 
20797 	/*
20798 	 * If ip_newroute() fails, we're going to need a full
20799 	 * header for the icmp wraparound.
20800 	 */
20801 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20802 		uint_t	v_hlen;
20803 version_hdrlen_check:
20804 		ASSERT(first_mp != NULL);
20805 		v_hlen = V_HLEN;
20806 		/*
20807 		 * siphon off IPv6 packets coming down from transport
20808 		 * layer modules here.
20809 		 * Note: high-order bit carries NUD reachability confirmation
20810 		 */
20811 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20812 			/*
20813 			 * FIXME: assume that callers of ip_output* call
20814 			 * the right version?
20815 			 */
20816 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20817 			ASSERT(xmit_ill == NULL);
20818 			if (attach_ill != NULL)
20819 				ill_refrele(attach_ill);
20820 			if (need_decref)
20821 				mp->b_flag |= MSGHASREF;
20822 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20823 			return;
20824 		}
20825 
20826 		if ((v_hlen >> 4) != IP_VERSION) {
20827 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20828 			    "ip_wput_end: q %p (%S)", q, "badvers");
20829 			goto discard_pkt;
20830 		}
20831 		/*
20832 		 * Is the header length at least 20 bytes?
20833 		 *
20834 		 * Are there enough bytes accessible in the header?  If
20835 		 * not, try a pullup.
20836 		 */
20837 		v_hlen &= 0xF;
20838 		v_hlen <<= 2;
20839 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20840 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20841 			    "ip_wput_end: q %p (%S)", q, "badlen");
20842 			goto discard_pkt;
20843 		}
20844 		if (v_hlen > (mp->b_wptr - rptr)) {
20845 			if (!pullupmsg(mp, v_hlen)) {
20846 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20847 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20848 				goto discard_pkt;
20849 			}
20850 			ipha = (ipha_t *)mp->b_rptr;
20851 		}
20852 		/*
20853 		 * Move first entry from any source route into ipha_dst and
20854 		 * verify the options
20855 		 */
20856 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20857 		    zoneid, ipst)) {
20858 			ASSERT(xmit_ill == NULL);
20859 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20860 			if (attach_ill != NULL)
20861 				ill_refrele(attach_ill);
20862 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20863 			    "ip_wput_end: q %p (%S)", q, "badopts");
20864 			if (need_decref)
20865 				CONN_DEC_REF(connp);
20866 			return;
20867 		}
20868 	}
20869 	dst = ipha->ipha_dst;
20870 
20871 	/*
20872 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20873 	 * we have to run the packet through ip_newroute which will take
20874 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20875 	 * a resolver, or assigning a default gateway, etc.
20876 	 */
20877 	if (CLASSD(dst)) {
20878 		ipif_t	*ipif;
20879 		uint32_t setsrc = 0;
20880 
20881 multicast:
20882 		ASSERT(first_mp != NULL);
20883 		ip2dbg(("ip_wput: CLASSD\n"));
20884 		if (connp == NULL) {
20885 			/*
20886 			 * Use the first good ipif on the ill.
20887 			 * XXX Should this ever happen? (Appears
20888 			 * to show up with just ppp and no ethernet due
20889 			 * to in.rdisc.)
20890 			 * However, ire_send should be able to
20891 			 * call ip_wput_ire directly.
20892 			 *
20893 			 * XXX Also, this can happen for ICMP and other packets
20894 			 * with multicast source addresses.  Perhaps we should
20895 			 * fix things so that we drop the packet in question,
20896 			 * but for now, just run with it.
20897 			 */
20898 			ill_t *ill = (ill_t *)q->q_ptr;
20899 
20900 			/*
20901 			 * Don't honor attach_if for this case. If ill
20902 			 * is part of the group, ipif could belong to
20903 			 * any ill and we cannot maintain attach_ill
20904 			 * and ipif_ill same anymore and the assert
20905 			 * below would fail.
20906 			 */
20907 			if (mctl_present && io->ipsec_out_attach_if) {
20908 				io->ipsec_out_ill_index = 0;
20909 				io->ipsec_out_attach_if = B_FALSE;
20910 				ASSERT(attach_ill != NULL);
20911 				ill_refrele(attach_ill);
20912 				attach_ill = NULL;
20913 			}
20914 
20915 			ASSERT(attach_ill == NULL);
20916 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20917 			if (ipif == NULL) {
20918 				if (need_decref)
20919 					CONN_DEC_REF(connp);
20920 				freemsg(first_mp);
20921 				return;
20922 			}
20923 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20924 			    ntohl(dst), ill->ill_name));
20925 		} else {
20926 			/*
20927 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20928 			 * and IP_MULTICAST_IF.  The block comment above this
20929 			 * function explains the locking mechanism used here.
20930 			 */
20931 			if (xmit_ill == NULL) {
20932 				xmit_ill = conn_get_held_ill(connp,
20933 				    &connp->conn_outgoing_ill, &err);
20934 				if (err == ILL_LOOKUP_FAILED) {
20935 					ip1dbg(("ip_wput: No ill for "
20936 					    "IP_BOUND_IF\n"));
20937 					BUMP_MIB(&ipst->ips_ip_mib,
20938 					    ipIfStatsOutNoRoutes);
20939 					goto drop_pkt;
20940 				}
20941 			}
20942 
20943 			if (xmit_ill == NULL) {
20944 				ipif = conn_get_held_ipif(connp,
20945 				    &connp->conn_multicast_ipif, &err);
20946 				if (err == IPIF_LOOKUP_FAILED) {
20947 					ip1dbg(("ip_wput: No ipif for "
20948 					    "multicast\n"));
20949 					BUMP_MIB(&ipst->ips_ip_mib,
20950 					    ipIfStatsOutNoRoutes);
20951 					goto drop_pkt;
20952 				}
20953 			}
20954 			if (xmit_ill != NULL) {
20955 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20956 				if (ipif == NULL) {
20957 					ip1dbg(("ip_wput: No ipif for "
20958 					    "xmit_ill\n"));
20959 					BUMP_MIB(&ipst->ips_ip_mib,
20960 					    ipIfStatsOutNoRoutes);
20961 					goto drop_pkt;
20962 				}
20963 			} else if (ipif == NULL || ipif->ipif_isv6) {
20964 				/*
20965 				 * We must do this ipif determination here
20966 				 * else we could pass through ip_newroute
20967 				 * and come back here without the conn context.
20968 				 *
20969 				 * Note: we do late binding i.e. we bind to
20970 				 * the interface when the first packet is sent.
20971 				 * For performance reasons we do not rebind on
20972 				 * each packet but keep the binding until the
20973 				 * next IP_MULTICAST_IF option.
20974 				 *
20975 				 * conn_multicast_{ipif,ill} are shared between
20976 				 * IPv4 and IPv6 and AF_INET6 sockets can
20977 				 * send both IPv4 and IPv6 packets. Hence
20978 				 * we have to check that "isv6" matches above.
20979 				 */
20980 				if (ipif != NULL)
20981 					ipif_refrele(ipif);
20982 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20983 				if (ipif == NULL) {
20984 					ip1dbg(("ip_wput: No ipif for "
20985 					    "multicast\n"));
20986 					BUMP_MIB(&ipst->ips_ip_mib,
20987 					    ipIfStatsOutNoRoutes);
20988 					goto drop_pkt;
20989 				}
20990 				err = conn_set_held_ipif(connp,
20991 				    &connp->conn_multicast_ipif, ipif);
20992 				if (err == IPIF_LOOKUP_FAILED) {
20993 					ipif_refrele(ipif);
20994 					ip1dbg(("ip_wput: No ipif for "
20995 					    "multicast\n"));
20996 					BUMP_MIB(&ipst->ips_ip_mib,
20997 					    ipIfStatsOutNoRoutes);
20998 					goto drop_pkt;
20999 				}
21000 			}
21001 		}
21002 		ASSERT(!ipif->ipif_isv6);
21003 		/*
21004 		 * As we may lose the conn by the time we reach ip_wput_ire,
21005 		 * we copy conn_multicast_loop and conn_dontroute on to an
21006 		 * ipsec_out. In case if this datagram goes out secure,
21007 		 * we need the ill_index also. Copy that also into the
21008 		 * ipsec_out.
21009 		 */
21010 		if (mctl_present) {
21011 			io = (ipsec_out_t *)first_mp->b_rptr;
21012 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21013 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21014 		} else {
21015 			ASSERT(mp == first_mp);
21016 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21017 			    BPRI_HI)) == NULL) {
21018 				ipif_refrele(ipif);
21019 				first_mp = mp;
21020 				goto discard_pkt;
21021 			}
21022 			first_mp->b_datap->db_type = M_CTL;
21023 			first_mp->b_wptr += sizeof (ipsec_info_t);
21024 			/* ipsec_out_secure is B_FALSE now */
21025 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21026 			io = (ipsec_out_t *)first_mp->b_rptr;
21027 			io->ipsec_out_type = IPSEC_OUT;
21028 			io->ipsec_out_len = sizeof (ipsec_out_t);
21029 			io->ipsec_out_use_global_policy = B_TRUE;
21030 			io->ipsec_out_ns = ipst->ips_netstack;
21031 			first_mp->b_cont = mp;
21032 			mctl_present = B_TRUE;
21033 		}
21034 		if (attach_ill != NULL) {
21035 			ASSERT(attach_ill == ipif->ipif_ill);
21036 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21037 
21038 			/*
21039 			 * Check if we need an ire that will not be
21040 			 * looked up by anybody else i.e. HIDDEN.
21041 			 */
21042 			if (ill_is_probeonly(attach_ill)) {
21043 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21044 			}
21045 			io->ipsec_out_ill_index =
21046 			    attach_ill->ill_phyint->phyint_ifindex;
21047 			io->ipsec_out_attach_if = B_TRUE;
21048 		} else {
21049 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21050 			io->ipsec_out_ill_index =
21051 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21052 		}
21053 		if (connp != NULL) {
21054 			io->ipsec_out_multicast_loop =
21055 			    connp->conn_multicast_loop;
21056 			io->ipsec_out_dontroute = connp->conn_dontroute;
21057 			io->ipsec_out_zoneid = connp->conn_zoneid;
21058 		}
21059 		/*
21060 		 * If the application uses IP_MULTICAST_IF with
21061 		 * different logical addresses of the same ILL, we
21062 		 * need to make sure that the soruce address of
21063 		 * the packet matches the logical IP address used
21064 		 * in the option. We do it by initializing ipha_src
21065 		 * here. This should keep IPsec also happy as
21066 		 * when we return from IPsec processing, we don't
21067 		 * have to worry about getting the right address on
21068 		 * the packet. Thus it is sufficient to look for
21069 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21070 		 * MATCH_IRE_IPIF.
21071 		 *
21072 		 * NOTE : We need to do it for non-secure case also as
21073 		 * this might go out secure if there is a global policy
21074 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21075 		 * address, the source should be initialized already and
21076 		 * hence we won't be initializing here.
21077 		 *
21078 		 * As we do not have the ire yet, it is possible that
21079 		 * we set the source address here and then later discover
21080 		 * that the ire implies the source address to be assigned
21081 		 * through the RTF_SETSRC flag.
21082 		 * In that case, the setsrc variable will remind us
21083 		 * that overwritting the source address by the one
21084 		 * of the RTF_SETSRC-flagged ire is allowed.
21085 		 */
21086 		if (ipha->ipha_src == INADDR_ANY &&
21087 		    (connp == NULL || !connp->conn_unspec_src)) {
21088 			ipha->ipha_src = ipif->ipif_src_addr;
21089 			setsrc = RTF_SETSRC;
21090 		}
21091 		/*
21092 		 * Find an IRE which matches the destination and the outgoing
21093 		 * queue (i.e. the outgoing interface.)
21094 		 * For loopback use a unicast IP address for
21095 		 * the ire lookup.
21096 		 */
21097 		if (IS_LOOPBACK(ipif->ipif_ill))
21098 			dst = ipif->ipif_lcl_addr;
21099 
21100 		/*
21101 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21102 		 * We don't need to lookup ire in ctable as the packet
21103 		 * needs to be sent to the destination through the specified
21104 		 * ill irrespective of ires in the cache table.
21105 		 */
21106 		ire = NULL;
21107 		if (xmit_ill == NULL) {
21108 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21109 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21110 		}
21111 
21112 		/*
21113 		 * refrele attach_ill as its not needed anymore.
21114 		 */
21115 		if (attach_ill != NULL) {
21116 			ill_refrele(attach_ill);
21117 			attach_ill = NULL;
21118 		}
21119 
21120 		if (ire == NULL) {
21121 			/*
21122 			 * Multicast loopback and multicast forwarding is
21123 			 * done in ip_wput_ire.
21124 			 *
21125 			 * Mark this packet to make it be delivered to
21126 			 * ip_wput_ire after the new ire has been
21127 			 * created.
21128 			 *
21129 			 * The call to ip_newroute_ipif takes into account
21130 			 * the setsrc reminder. In any case, we take care
21131 			 * of the RTF_MULTIRT flag.
21132 			 */
21133 			mp->b_prev = mp->b_next = NULL;
21134 			if (xmit_ill == NULL ||
21135 			    xmit_ill->ill_ipif_up_count > 0) {
21136 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21137 				    setsrc | RTF_MULTIRT, zoneid, infop);
21138 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21139 				    "ip_wput_end: q %p (%S)", q, "noire");
21140 			} else {
21141 				freemsg(first_mp);
21142 			}
21143 			ipif_refrele(ipif);
21144 			if (xmit_ill != NULL)
21145 				ill_refrele(xmit_ill);
21146 			if (need_decref)
21147 				CONN_DEC_REF(connp);
21148 			return;
21149 		}
21150 
21151 		ipif_refrele(ipif);
21152 		ipif = NULL;
21153 		ASSERT(xmit_ill == NULL);
21154 
21155 		/*
21156 		 * Honor the RTF_SETSRC flag for multicast packets,
21157 		 * if allowed by the setsrc reminder.
21158 		 */
21159 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21160 			ipha->ipha_src = ire->ire_src_addr;
21161 		}
21162 
21163 		/*
21164 		 * Unconditionally force the TTL to 1 for
21165 		 * multirouted multicast packets:
21166 		 * multirouted multicast should not cross
21167 		 * multicast routers.
21168 		 */
21169 		if (ire->ire_flags & RTF_MULTIRT) {
21170 			if (ipha->ipha_ttl > 1) {
21171 				ip2dbg(("ip_wput: forcing multicast "
21172 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21173 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21174 				ipha->ipha_ttl = 1;
21175 			}
21176 		}
21177 	} else {
21178 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21179 		if ((ire != NULL) && (ire->ire_type &
21180 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21181 			ignore_dontroute = B_TRUE;
21182 			ignore_nexthop = B_TRUE;
21183 		}
21184 		if (ire != NULL) {
21185 			ire_refrele(ire);
21186 			ire = NULL;
21187 		}
21188 		/*
21189 		 * Guard against coming in from arp in which case conn is NULL.
21190 		 * Also guard against non M_DATA with dontroute set but
21191 		 * destined to local, loopback or broadcast addresses.
21192 		 */
21193 		if (connp != NULL && connp->conn_dontroute &&
21194 		    !ignore_dontroute) {
21195 dontroute:
21196 			/*
21197 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21198 			 * routing protocols from seeing false direct
21199 			 * connectivity.
21200 			 */
21201 			ipha->ipha_ttl = 1;
21202 
21203 			/* If suitable ipif not found, drop packet */
21204 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21205 			if (dst_ipif == NULL) {
21206 noroute:
21207 				ip1dbg(("ip_wput: no route for dst using"
21208 				    " SO_DONTROUTE\n"));
21209 				BUMP_MIB(&ipst->ips_ip_mib,
21210 				    ipIfStatsOutNoRoutes);
21211 				mp->b_prev = mp->b_next = NULL;
21212 				if (first_mp == NULL)
21213 					first_mp = mp;
21214 				goto drop_pkt;
21215 			} else {
21216 				/*
21217 				 * If suitable ipif has been found, set
21218 				 * xmit_ill to the corresponding
21219 				 * ipif_ill because we'll be using the
21220 				 * send_from_ill logic below.
21221 				 */
21222 				ASSERT(xmit_ill == NULL);
21223 				xmit_ill = dst_ipif->ipif_ill;
21224 				mutex_enter(&xmit_ill->ill_lock);
21225 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21226 					mutex_exit(&xmit_ill->ill_lock);
21227 					xmit_ill = NULL;
21228 					ipif_refrele(dst_ipif);
21229 					goto noroute;
21230 				}
21231 				ill_refhold_locked(xmit_ill);
21232 				mutex_exit(&xmit_ill->ill_lock);
21233 				ipif_refrele(dst_ipif);
21234 			}
21235 		}
21236 		/*
21237 		 * If we are bound to IPIF_NOFAILOVER address, look for
21238 		 * an IRE_CACHE matching the ill.
21239 		 */
21240 send_from_ill:
21241 		if (attach_ill != NULL) {
21242 			ipif_t	*attach_ipif;
21243 
21244 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21245 
21246 			/*
21247 			 * Check if we need an ire that will not be
21248 			 * looked up by anybody else i.e. HIDDEN.
21249 			 */
21250 			if (ill_is_probeonly(attach_ill)) {
21251 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21252 			}
21253 
21254 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21255 			if (attach_ipif == NULL) {
21256 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21257 				goto discard_pkt;
21258 			}
21259 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21260 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21261 			ipif_refrele(attach_ipif);
21262 		} else if (xmit_ill != NULL) {
21263 			ipif_t *ipif;
21264 
21265 			/*
21266 			 * Mark this packet as originated locally
21267 			 */
21268 			mp->b_prev = mp->b_next = NULL;
21269 
21270 			/*
21271 			 * Could be SO_DONTROUTE case also.
21272 			 * Verify that at least one ipif is up on the ill.
21273 			 */
21274 			if (xmit_ill->ill_ipif_up_count == 0) {
21275 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21276 				    xmit_ill->ill_name));
21277 				goto drop_pkt;
21278 			}
21279 
21280 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21281 			if (ipif == NULL) {
21282 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21283 				    xmit_ill->ill_name));
21284 				goto drop_pkt;
21285 			}
21286 
21287 			/*
21288 			 * Look for a ire that is part of the group,
21289 			 * if found use it else call ip_newroute_ipif.
21290 			 * IPCL_ZONEID is not used for matching because
21291 			 * IP_ALLZONES option is valid only when the
21292 			 * ill is accessible from all zones i.e has a
21293 			 * valid ipif in all zones.
21294 			 */
21295 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21296 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21297 			    MBLK_GETLABEL(mp), match_flags, ipst);
21298 			/*
21299 			 * If an ire exists use it or else create
21300 			 * an ire but don't add it to the cache.
21301 			 * Adding an ire may cause issues with
21302 			 * asymmetric routing.
21303 			 * In case of multiroute always act as if
21304 			 * ire does not exist.
21305 			 */
21306 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21307 				if (ire != NULL)
21308 					ire_refrele(ire);
21309 				ip_newroute_ipif(q, first_mp, ipif,
21310 				    dst, connp, 0, zoneid, infop);
21311 				ipif_refrele(ipif);
21312 				ip1dbg(("ip_output: xmit_ill via %s\n",
21313 				    xmit_ill->ill_name));
21314 				ill_refrele(xmit_ill);
21315 				if (need_decref)
21316 					CONN_DEC_REF(connp);
21317 				return;
21318 			}
21319 			ipif_refrele(ipif);
21320 		} else if (ip_nexthop || (connp != NULL &&
21321 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21322 			if (!ip_nexthop) {
21323 				ip_nexthop = B_TRUE;
21324 				nexthop_addr = connp->conn_nexthop_v4;
21325 			}
21326 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21327 			    MATCH_IRE_GW;
21328 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21329 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21330 		} else {
21331 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21332 			    ipst);
21333 		}
21334 		if (!ire) {
21335 			/*
21336 			 * Make sure we don't load spread if this
21337 			 * is IPIF_NOFAILOVER case.
21338 			 */
21339 			if ((attach_ill != NULL) ||
21340 			    (ip_nexthop && !ignore_nexthop)) {
21341 				if (mctl_present) {
21342 					io = (ipsec_out_t *)first_mp->b_rptr;
21343 					ASSERT(first_mp->b_datap->db_type ==
21344 					    M_CTL);
21345 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21346 				} else {
21347 					ASSERT(mp == first_mp);
21348 					first_mp = allocb(
21349 					    sizeof (ipsec_info_t), BPRI_HI);
21350 					if (first_mp == NULL) {
21351 						first_mp = mp;
21352 						goto discard_pkt;
21353 					}
21354 					first_mp->b_datap->db_type = M_CTL;
21355 					first_mp->b_wptr +=
21356 					    sizeof (ipsec_info_t);
21357 					/* ipsec_out_secure is B_FALSE now */
21358 					bzero(first_mp->b_rptr,
21359 					    sizeof (ipsec_info_t));
21360 					io = (ipsec_out_t *)first_mp->b_rptr;
21361 					io->ipsec_out_type = IPSEC_OUT;
21362 					io->ipsec_out_len =
21363 					    sizeof (ipsec_out_t);
21364 					io->ipsec_out_use_global_policy =
21365 					    B_TRUE;
21366 					io->ipsec_out_ns = ipst->ips_netstack;
21367 					first_mp->b_cont = mp;
21368 					mctl_present = B_TRUE;
21369 				}
21370 				if (attach_ill != NULL) {
21371 					io->ipsec_out_ill_index = attach_ill->
21372 					    ill_phyint->phyint_ifindex;
21373 					io->ipsec_out_attach_if = B_TRUE;
21374 				} else {
21375 					io->ipsec_out_ip_nexthop = ip_nexthop;
21376 					io->ipsec_out_nexthop_addr =
21377 					    nexthop_addr;
21378 				}
21379 			}
21380 noirefound:
21381 			/*
21382 			 * Mark this packet as having originated on
21383 			 * this machine.  This will be noted in
21384 			 * ire_add_then_send, which needs to know
21385 			 * whether to run it back through ip_wput or
21386 			 * ip_rput following successful resolution.
21387 			 */
21388 			mp->b_prev = NULL;
21389 			mp->b_next = NULL;
21390 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21391 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21392 			    "ip_wput_end: q %p (%S)", q, "newroute");
21393 			if (attach_ill != NULL)
21394 				ill_refrele(attach_ill);
21395 			if (xmit_ill != NULL)
21396 				ill_refrele(xmit_ill);
21397 			if (need_decref)
21398 				CONN_DEC_REF(connp);
21399 			return;
21400 		}
21401 	}
21402 
21403 	/* We now know where we are going with it. */
21404 
21405 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21406 	    "ip_wput_end: q %p (%S)", q, "end");
21407 
21408 	/*
21409 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21410 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21411 	 */
21412 	if (ire->ire_flags & RTF_MULTIRT) {
21413 		/*
21414 		 * Force the TTL of multirouted packets if required.
21415 		 * The TTL of such packets is bounded by the
21416 		 * ip_multirt_ttl ndd variable.
21417 		 */
21418 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21419 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21420 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21421 			    "(was %d), dst 0x%08x\n",
21422 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21423 			    ntohl(ire->ire_addr)));
21424 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21425 		}
21426 		/*
21427 		 * At this point, we check to see if there are any pending
21428 		 * unresolved routes. ire_multirt_resolvable()
21429 		 * checks in O(n) that all IRE_OFFSUBNET ire
21430 		 * entries for the packet's destination and
21431 		 * flagged RTF_MULTIRT are currently resolved.
21432 		 * If some remain unresolved, we make a copy
21433 		 * of the current message. It will be used
21434 		 * to initiate additional route resolutions.
21435 		 */
21436 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21437 		    MBLK_GETLABEL(first_mp), ipst);
21438 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21439 		    "multirt_need_resolve %d, first_mp %p\n",
21440 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21441 		if (multirt_need_resolve) {
21442 			copy_mp = copymsg(first_mp);
21443 			if (copy_mp != NULL) {
21444 				MULTIRT_DEBUG_TAG(copy_mp);
21445 			}
21446 		}
21447 	}
21448 
21449 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21450 	/*
21451 	 * Try to resolve another multiroute if
21452 	 * ire_multirt_resolvable() deemed it necessary.
21453 	 * At this point, we need to distinguish
21454 	 * multicasts from other packets. For multicasts,
21455 	 * we call ip_newroute_ipif() and request that both
21456 	 * multirouting and setsrc flags are checked.
21457 	 */
21458 	if (copy_mp != NULL) {
21459 		if (CLASSD(dst)) {
21460 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21461 			if (ipif) {
21462 				ASSERT(infop->ip_opt_ill_index == 0);
21463 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21464 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21465 				ipif_refrele(ipif);
21466 			} else {
21467 				MULTIRT_DEBUG_UNTAG(copy_mp);
21468 				freemsg(copy_mp);
21469 				copy_mp = NULL;
21470 			}
21471 		} else {
21472 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21473 		}
21474 	}
21475 	if (attach_ill != NULL)
21476 		ill_refrele(attach_ill);
21477 	if (xmit_ill != NULL)
21478 		ill_refrele(xmit_ill);
21479 	if (need_decref)
21480 		CONN_DEC_REF(connp);
21481 	return;
21482 
21483 icmp_parameter_problem:
21484 	/* could not have originated externally */
21485 	ASSERT(mp->b_prev == NULL);
21486 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21487 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21488 		/* it's the IP header length that's in trouble */
21489 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21490 		first_mp = NULL;
21491 	}
21492 
21493 discard_pkt:
21494 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21495 drop_pkt:
21496 	ip1dbg(("ip_wput: dropped packet\n"));
21497 	if (ire != NULL)
21498 		ire_refrele(ire);
21499 	if (need_decref)
21500 		CONN_DEC_REF(connp);
21501 	freemsg(first_mp);
21502 	if (attach_ill != NULL)
21503 		ill_refrele(attach_ill);
21504 	if (xmit_ill != NULL)
21505 		ill_refrele(xmit_ill);
21506 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21507 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21508 }
21509 
21510 /*
21511  * If this is a conn_t queue, then we pass in the conn. This includes the
21512  * zoneid.
21513  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21514  * in which case we use the global zoneid since those are all part of
21515  * the global zone.
21516  */
21517 void
21518 ip_wput(queue_t *q, mblk_t *mp)
21519 {
21520 	if (CONN_Q(q))
21521 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21522 	else
21523 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21524 }
21525 
21526 /*
21527  *
21528  * The following rules must be observed when accessing any ipif or ill
21529  * that has been cached in the conn. Typically conn_nofailover_ill,
21530  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21531  *
21532  * Access: The ipif or ill pointed to from the conn can be accessed under
21533  * the protection of the conn_lock or after it has been refheld under the
21534  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21535  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21536  * The reason for this is that a concurrent unplumb could actually be
21537  * cleaning up these cached pointers by walking the conns and might have
21538  * finished cleaning up the conn in question. The macros check that an
21539  * unplumb has not yet started on the ipif or ill.
21540  *
21541  * Caching: An ipif or ill pointer may be cached in the conn only after
21542  * making sure that an unplumb has not started. So the caching is done
21543  * while holding both the conn_lock and the ill_lock and after using the
21544  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21545  * flag before starting the cleanup of conns.
21546  *
21547  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21548  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21549  * or a reference to the ipif or a reference to an ire that references the
21550  * ipif. An ipif does not change its ill except for failover/failback. Since
21551  * failover/failback happens only after bringing down the ipif and making sure
21552  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21553  * the above holds.
21554  */
21555 ipif_t *
21556 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21557 {
21558 	ipif_t	*ipif;
21559 	ill_t	*ill;
21560 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21561 
21562 	*err = 0;
21563 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21564 	mutex_enter(&connp->conn_lock);
21565 	ipif = *ipifp;
21566 	if (ipif != NULL) {
21567 		ill = ipif->ipif_ill;
21568 		mutex_enter(&ill->ill_lock);
21569 		if (IPIF_CAN_LOOKUP(ipif)) {
21570 			ipif_refhold_locked(ipif);
21571 			mutex_exit(&ill->ill_lock);
21572 			mutex_exit(&connp->conn_lock);
21573 			rw_exit(&ipst->ips_ill_g_lock);
21574 			return (ipif);
21575 		} else {
21576 			*err = IPIF_LOOKUP_FAILED;
21577 		}
21578 		mutex_exit(&ill->ill_lock);
21579 	}
21580 	mutex_exit(&connp->conn_lock);
21581 	rw_exit(&ipst->ips_ill_g_lock);
21582 	return (NULL);
21583 }
21584 
21585 ill_t *
21586 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21587 {
21588 	ill_t	*ill;
21589 
21590 	*err = 0;
21591 	mutex_enter(&connp->conn_lock);
21592 	ill = *illp;
21593 	if (ill != NULL) {
21594 		mutex_enter(&ill->ill_lock);
21595 		if (ILL_CAN_LOOKUP(ill)) {
21596 			ill_refhold_locked(ill);
21597 			mutex_exit(&ill->ill_lock);
21598 			mutex_exit(&connp->conn_lock);
21599 			return (ill);
21600 		} else {
21601 			*err = ILL_LOOKUP_FAILED;
21602 		}
21603 		mutex_exit(&ill->ill_lock);
21604 	}
21605 	mutex_exit(&connp->conn_lock);
21606 	return (NULL);
21607 }
21608 
21609 static int
21610 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21611 {
21612 	ill_t	*ill;
21613 
21614 	ill = ipif->ipif_ill;
21615 	mutex_enter(&connp->conn_lock);
21616 	mutex_enter(&ill->ill_lock);
21617 	if (IPIF_CAN_LOOKUP(ipif)) {
21618 		*ipifp = ipif;
21619 		mutex_exit(&ill->ill_lock);
21620 		mutex_exit(&connp->conn_lock);
21621 		return (0);
21622 	}
21623 	mutex_exit(&ill->ill_lock);
21624 	mutex_exit(&connp->conn_lock);
21625 	return (IPIF_LOOKUP_FAILED);
21626 }
21627 
21628 /*
21629  * This is called if the outbound datagram needs fragmentation.
21630  *
21631  * NOTE : This function does not ire_refrele the ire argument passed in.
21632  */
21633 static void
21634 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21635     ip_stack_t *ipst)
21636 {
21637 	ipha_t		*ipha;
21638 	mblk_t		*mp;
21639 	uint32_t	v_hlen_tos_len;
21640 	uint32_t	max_frag;
21641 	uint32_t	frag_flag;
21642 	boolean_t	dont_use;
21643 
21644 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21645 		mp = ipsec_mp->b_cont;
21646 	} else {
21647 		mp = ipsec_mp;
21648 	}
21649 
21650 	ipha = (ipha_t *)mp->b_rptr;
21651 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21652 
21653 #ifdef	_BIG_ENDIAN
21654 #define	V_HLEN	(v_hlen_tos_len >> 24)
21655 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21656 #else
21657 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21658 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21659 #endif
21660 
21661 #ifndef SPEED_BEFORE_SAFETY
21662 	/*
21663 	 * Check that ipha_length is consistent with
21664 	 * the mblk length
21665 	 */
21666 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21667 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21668 		    LENGTH, msgdsize(mp)));
21669 		freemsg(ipsec_mp);
21670 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21671 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21672 		    "packet length mismatch");
21673 		return;
21674 	}
21675 #endif
21676 	/*
21677 	 * Don't use frag_flag if pre-built packet or source
21678 	 * routed or if multicast (since multicast packets do not solicit
21679 	 * ICMP "packet too big" messages). Get the values of
21680 	 * max_frag and frag_flag atomically by acquiring the
21681 	 * ire_lock.
21682 	 */
21683 	mutex_enter(&ire->ire_lock);
21684 	max_frag = ire->ire_max_frag;
21685 	frag_flag = ire->ire_frag_flag;
21686 	mutex_exit(&ire->ire_lock);
21687 
21688 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21689 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21690 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21691 
21692 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21693 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21694 }
21695 
21696 /*
21697  * Used for deciding the MSS size for the upper layer. Thus
21698  * we need to check the outbound policy values in the conn.
21699  */
21700 int
21701 conn_ipsec_length(conn_t *connp)
21702 {
21703 	ipsec_latch_t *ipl;
21704 
21705 	ipl = connp->conn_latch;
21706 	if (ipl == NULL)
21707 		return (0);
21708 
21709 	if (ipl->ipl_out_policy == NULL)
21710 		return (0);
21711 
21712 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21713 }
21714 
21715 /*
21716  * Returns an estimate of the IPsec headers size. This is used if
21717  * we don't want to call into IPsec to get the exact size.
21718  */
21719 int
21720 ipsec_out_extra_length(mblk_t *ipsec_mp)
21721 {
21722 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21723 	ipsec_action_t *a;
21724 
21725 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21726 	if (!io->ipsec_out_secure)
21727 		return (0);
21728 
21729 	a = io->ipsec_out_act;
21730 
21731 	if (a == NULL) {
21732 		ASSERT(io->ipsec_out_policy != NULL);
21733 		a = io->ipsec_out_policy->ipsp_act;
21734 	}
21735 	ASSERT(a != NULL);
21736 
21737 	return (a->ipa_ovhd);
21738 }
21739 
21740 /*
21741  * Returns an estimate of the IPsec headers size. This is used if
21742  * we don't want to call into IPsec to get the exact size.
21743  */
21744 int
21745 ipsec_in_extra_length(mblk_t *ipsec_mp)
21746 {
21747 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21748 	ipsec_action_t *a;
21749 
21750 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21751 
21752 	a = ii->ipsec_in_action;
21753 	return (a == NULL ? 0 : a->ipa_ovhd);
21754 }
21755 
21756 /*
21757  * If there are any source route options, return the true final
21758  * destination. Otherwise, return the destination.
21759  */
21760 ipaddr_t
21761 ip_get_dst(ipha_t *ipha)
21762 {
21763 	ipoptp_t	opts;
21764 	uchar_t		*opt;
21765 	uint8_t		optval;
21766 	uint8_t		optlen;
21767 	ipaddr_t	dst;
21768 	uint32_t off;
21769 
21770 	dst = ipha->ipha_dst;
21771 
21772 	if (IS_SIMPLE_IPH(ipha))
21773 		return (dst);
21774 
21775 	for (optval = ipoptp_first(&opts, ipha);
21776 	    optval != IPOPT_EOL;
21777 	    optval = ipoptp_next(&opts)) {
21778 		opt = opts.ipoptp_cur;
21779 		optlen = opts.ipoptp_len;
21780 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21781 		switch (optval) {
21782 		case IPOPT_SSRR:
21783 		case IPOPT_LSRR:
21784 			off = opt[IPOPT_OFFSET];
21785 			/*
21786 			 * If one of the conditions is true, it means
21787 			 * end of options and dst already has the right
21788 			 * value.
21789 			 */
21790 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21791 				off = optlen - IP_ADDR_LEN;
21792 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21793 			}
21794 			return (dst);
21795 		default:
21796 			break;
21797 		}
21798 	}
21799 
21800 	return (dst);
21801 }
21802 
21803 mblk_t *
21804 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21805     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21806 {
21807 	ipsec_out_t	*io;
21808 	mblk_t		*first_mp;
21809 	boolean_t policy_present;
21810 	ip_stack_t	*ipst;
21811 	ipsec_stack_t	*ipss;
21812 
21813 	ASSERT(ire != NULL);
21814 	ipst = ire->ire_ipst;
21815 	ipss = ipst->ips_netstack->netstack_ipsec;
21816 
21817 	first_mp = mp;
21818 	if (mp->b_datap->db_type == M_CTL) {
21819 		io = (ipsec_out_t *)first_mp->b_rptr;
21820 		/*
21821 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21822 		 *
21823 		 * 1) There is per-socket policy (including cached global
21824 		 *    policy) or a policy on the IP-in-IP tunnel.
21825 		 * 2) There is no per-socket policy, but it is
21826 		 *    a multicast packet that needs to go out
21827 		 *    on a specific interface. This is the case
21828 		 *    where (ip_wput and ip_wput_multicast) attaches
21829 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21830 		 *
21831 		 * In case (2) we check with global policy to
21832 		 * see if there is a match and set the ill_index
21833 		 * appropriately so that we can lookup the ire
21834 		 * properly in ip_wput_ipsec_out.
21835 		 */
21836 
21837 		/*
21838 		 * ipsec_out_use_global_policy is set to B_FALSE
21839 		 * in ipsec_in_to_out(). Refer to that function for
21840 		 * details.
21841 		 */
21842 		if ((io->ipsec_out_latch == NULL) &&
21843 		    (io->ipsec_out_use_global_policy)) {
21844 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21845 			    ire, connp, unspec_src, zoneid));
21846 		}
21847 		if (!io->ipsec_out_secure) {
21848 			/*
21849 			 * If this is not a secure packet, drop
21850 			 * the IPSEC_OUT mp and treat it as a clear
21851 			 * packet. This happens when we are sending
21852 			 * a ICMP reply back to a clear packet. See
21853 			 * ipsec_in_to_out() for details.
21854 			 */
21855 			mp = first_mp->b_cont;
21856 			freeb(first_mp);
21857 		}
21858 		return (mp);
21859 	}
21860 	/*
21861 	 * See whether we need to attach a global policy here. We
21862 	 * don't depend on the conn (as it could be null) for deciding
21863 	 * what policy this datagram should go through because it
21864 	 * should have happened in ip_wput if there was some
21865 	 * policy. This normally happens for connections which are not
21866 	 * fully bound preventing us from caching policies in
21867 	 * ip_bind. Packets coming from the TCP listener/global queue
21868 	 * - which are non-hard_bound - could also be affected by
21869 	 * applying policy here.
21870 	 *
21871 	 * If this packet is coming from tcp global queue or listener,
21872 	 * we will be applying policy here.  This may not be *right*
21873 	 * if these packets are coming from the detached connection as
21874 	 * it could have gone in clear before. This happens only if a
21875 	 * TCP connection started when there is no policy and somebody
21876 	 * added policy before it became detached. Thus packets of the
21877 	 * detached connection could go out secure and the other end
21878 	 * would drop it because it will be expecting in clear. The
21879 	 * converse is not true i.e if somebody starts a TCP
21880 	 * connection and deletes the policy, all the packets will
21881 	 * still go out with the policy that existed before deleting
21882 	 * because ip_unbind sends up policy information which is used
21883 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21884 	 * TCP to attach a dummy IPSEC_OUT and set
21885 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21886 	 * affect performance for normal cases, we are not doing it.
21887 	 * Thus, set policy before starting any TCP connections.
21888 	 *
21889 	 * NOTE - We might apply policy even for a hard bound connection
21890 	 * - for which we cached policy in ip_bind - if somebody added
21891 	 * global policy after we inherited the policy in ip_bind.
21892 	 * This means that the packets that were going out in clear
21893 	 * previously would start going secure and hence get dropped
21894 	 * on the other side. To fix this, TCP attaches a dummy
21895 	 * ipsec_out and make sure that we don't apply global policy.
21896 	 */
21897 	if (ipha != NULL)
21898 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21899 	else
21900 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21901 	if (!policy_present)
21902 		return (mp);
21903 
21904 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21905 	    zoneid));
21906 }
21907 
21908 ire_t *
21909 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21910 {
21911 	ipaddr_t addr;
21912 	ire_t *save_ire;
21913 	irb_t *irb;
21914 	ill_group_t *illgrp;
21915 	int	err;
21916 
21917 	save_ire = ire;
21918 	addr = ire->ire_addr;
21919 
21920 	ASSERT(ire->ire_type == IRE_BROADCAST);
21921 
21922 	illgrp = connp->conn_outgoing_ill->ill_group;
21923 	if (illgrp == NULL) {
21924 		*conn_outgoing_ill = conn_get_held_ill(connp,
21925 		    &connp->conn_outgoing_ill, &err);
21926 		if (err == ILL_LOOKUP_FAILED) {
21927 			ire_refrele(save_ire);
21928 			return (NULL);
21929 		}
21930 		return (save_ire);
21931 	}
21932 	/*
21933 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21934 	 * If it is part of the group, we need to send on the ire
21935 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21936 	 * to this group. This is okay as IP_BOUND_IF really means
21937 	 * any ill in the group. We depend on the fact that the
21938 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21939 	 * if such an ire exists. This is possible only if you have
21940 	 * at least one ill in the group that has not failed.
21941 	 *
21942 	 * First get to the ire that matches the address and group.
21943 	 *
21944 	 * We don't look for an ire with a matching zoneid because a given zone
21945 	 * won't always have broadcast ires on all ills in the group.
21946 	 */
21947 	irb = ire->ire_bucket;
21948 	rw_enter(&irb->irb_lock, RW_READER);
21949 	if (ire->ire_marks & IRE_MARK_NORECV) {
21950 		/*
21951 		 * If the current zone only has an ire broadcast for this
21952 		 * address marked NORECV, the ire we want is ahead in the
21953 		 * bucket, so we look it up deliberately ignoring the zoneid.
21954 		 */
21955 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21956 			if (ire->ire_addr != addr)
21957 				continue;
21958 			/* skip over deleted ires */
21959 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21960 				continue;
21961 		}
21962 	}
21963 	while (ire != NULL) {
21964 		/*
21965 		 * If a new interface is coming up, we could end up
21966 		 * seeing the loopback ire and the non-loopback ire
21967 		 * may not have been added yet. So check for ire_stq
21968 		 */
21969 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21970 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21971 			break;
21972 		}
21973 		ire = ire->ire_next;
21974 	}
21975 	if (ire != NULL && ire->ire_addr == addr &&
21976 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21977 		IRE_REFHOLD(ire);
21978 		rw_exit(&irb->irb_lock);
21979 		ire_refrele(save_ire);
21980 		*conn_outgoing_ill = ire_to_ill(ire);
21981 		/*
21982 		 * Refhold the ill to make the conn_outgoing_ill
21983 		 * independent of the ire. ip_wput_ire goes in a loop
21984 		 * and may refrele the ire. Since we have an ire at this
21985 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21986 		 */
21987 		ill_refhold(*conn_outgoing_ill);
21988 		return (ire);
21989 	}
21990 	rw_exit(&irb->irb_lock);
21991 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21992 	/*
21993 	 * If we can't find a suitable ire, return the original ire.
21994 	 */
21995 	return (save_ire);
21996 }
21997 
21998 /*
21999  * This function does the ire_refrele of the ire passed in as the
22000  * argument. As this function looks up more ires i.e broadcast ires,
22001  * it needs to REFRELE them. Currently, for simplicity we don't
22002  * differentiate the one passed in and looked up here. We always
22003  * REFRELE.
22004  * IPQoS Notes:
22005  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
22006  * IPsec packets are done in ipsec_out_process.
22007  *
22008  */
22009 void
22010 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22011     zoneid_t zoneid)
22012 {
22013 	ipha_t		*ipha;
22014 #define	rptr	((uchar_t *)ipha)
22015 	queue_t		*stq;
22016 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22017 	uint32_t	v_hlen_tos_len;
22018 	uint32_t	ttl_protocol;
22019 	ipaddr_t	src;
22020 	ipaddr_t	dst;
22021 	uint32_t	cksum;
22022 	ipaddr_t	orig_src;
22023 	ire_t		*ire1;
22024 	mblk_t		*next_mp;
22025 	uint_t		hlen;
22026 	uint16_t	*up;
22027 	uint32_t	max_frag = ire->ire_max_frag;
22028 	ill_t		*ill = ire_to_ill(ire);
22029 	int		clusterwide;
22030 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22031 	int		ipsec_len;
22032 	mblk_t		*first_mp;
22033 	ipsec_out_t	*io;
22034 	boolean_t	conn_dontroute;		/* conn value for multicast */
22035 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22036 	boolean_t	multicast_forward;	/* Should we forward ? */
22037 	boolean_t	unspec_src;
22038 	ill_t		*conn_outgoing_ill = NULL;
22039 	ill_t		*ire_ill;
22040 	ill_t		*ire1_ill;
22041 	ill_t		*out_ill;
22042 	uint32_t 	ill_index = 0;
22043 	boolean_t	multirt_send = B_FALSE;
22044 	int		err;
22045 	ipxmit_state_t	pktxmit_state;
22046 	ip_stack_t	*ipst = ire->ire_ipst;
22047 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22048 
22049 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22050 	    "ip_wput_ire_start: q %p", q);
22051 
22052 	multicast_forward = B_FALSE;
22053 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22054 
22055 	if (ire->ire_flags & RTF_MULTIRT) {
22056 		/*
22057 		 * Multirouting case. The bucket where ire is stored
22058 		 * probably holds other RTF_MULTIRT flagged ire
22059 		 * to the destination. In this call to ip_wput_ire,
22060 		 * we attempt to send the packet through all
22061 		 * those ires. Thus, we first ensure that ire is the
22062 		 * first RTF_MULTIRT ire in the bucket,
22063 		 * before walking the ire list.
22064 		 */
22065 		ire_t *first_ire;
22066 		irb_t *irb = ire->ire_bucket;
22067 		ASSERT(irb != NULL);
22068 
22069 		/* Make sure we do not omit any multiroute ire. */
22070 		IRB_REFHOLD(irb);
22071 		for (first_ire = irb->irb_ire;
22072 		    first_ire != NULL;
22073 		    first_ire = first_ire->ire_next) {
22074 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22075 			    (first_ire->ire_addr == ire->ire_addr) &&
22076 			    !(first_ire->ire_marks &
22077 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22078 				break;
22079 			}
22080 		}
22081 
22082 		if ((first_ire != NULL) && (first_ire != ire)) {
22083 			IRE_REFHOLD(first_ire);
22084 			ire_refrele(ire);
22085 			ire = first_ire;
22086 			ill = ire_to_ill(ire);
22087 		}
22088 		IRB_REFRELE(irb);
22089 	}
22090 
22091 	/*
22092 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22093 	 * for performance we don't grab the mutexs in the fastpath
22094 	 */
22095 	if ((connp != NULL) &&
22096 	    (ire->ire_type == IRE_BROADCAST) &&
22097 	    ((connp->conn_nofailover_ill != NULL) ||
22098 	    (connp->conn_outgoing_ill != NULL))) {
22099 		/*
22100 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22101 		 * option. So, see if this endpoint is bound to a
22102 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22103 		 * that if the interface is failed, we will still send
22104 		 * the packet on the same ill which is what we want.
22105 		 */
22106 		conn_outgoing_ill = conn_get_held_ill(connp,
22107 		    &connp->conn_nofailover_ill, &err);
22108 		if (err == ILL_LOOKUP_FAILED) {
22109 			ire_refrele(ire);
22110 			freemsg(mp);
22111 			return;
22112 		}
22113 		if (conn_outgoing_ill == NULL) {
22114 			/*
22115 			 * Choose a good ill in the group to send the
22116 			 * packets on.
22117 			 */
22118 			ire = conn_set_outgoing_ill(connp, ire,
22119 			    &conn_outgoing_ill);
22120 			if (ire == NULL) {
22121 				freemsg(mp);
22122 				return;
22123 			}
22124 		}
22125 	}
22126 
22127 	if (mp->b_datap->db_type != M_CTL) {
22128 		ipha = (ipha_t *)mp->b_rptr;
22129 	} else {
22130 		io = (ipsec_out_t *)mp->b_rptr;
22131 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22132 		ASSERT(zoneid == io->ipsec_out_zoneid);
22133 		ASSERT(zoneid != ALL_ZONES);
22134 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22135 		dst = ipha->ipha_dst;
22136 		/*
22137 		 * For the multicast case, ipsec_out carries conn_dontroute and
22138 		 * conn_multicast_loop as conn may not be available here. We
22139 		 * need this for multicast loopback and forwarding which is done
22140 		 * later in the code.
22141 		 */
22142 		if (CLASSD(dst)) {
22143 			conn_dontroute = io->ipsec_out_dontroute;
22144 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22145 			/*
22146 			 * If conn_dontroute is not set or conn_multicast_loop
22147 			 * is set, we need to do forwarding/loopback. For
22148 			 * datagrams from ip_wput_multicast, conn_dontroute is
22149 			 * set to B_TRUE and conn_multicast_loop is set to
22150 			 * B_FALSE so that we neither do forwarding nor
22151 			 * loopback.
22152 			 */
22153 			if (!conn_dontroute || conn_multicast_loop)
22154 				multicast_forward = B_TRUE;
22155 		}
22156 	}
22157 
22158 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22159 	    ire->ire_zoneid != ALL_ZONES) {
22160 		/*
22161 		 * When a zone sends a packet to another zone, we try to deliver
22162 		 * the packet under the same conditions as if the destination
22163 		 * was a real node on the network. To do so, we look for a
22164 		 * matching route in the forwarding table.
22165 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22166 		 * ip_newroute() does.
22167 		 * Note that IRE_LOCAL are special, since they are used
22168 		 * when the zoneid doesn't match in some cases. This means that
22169 		 * we need to handle ipha_src differently since ire_src_addr
22170 		 * belongs to the receiving zone instead of the sending zone.
22171 		 * When ip_restrict_interzone_loopback is set, then
22172 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22173 		 * for loopback between zones when the logical "Ethernet" would
22174 		 * have looped them back.
22175 		 */
22176 		ire_t *src_ire;
22177 
22178 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22179 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22180 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22181 		if (src_ire != NULL &&
22182 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22183 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22184 		    ire_local_same_ill_group(ire, src_ire))) {
22185 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22186 				ipha->ipha_src = src_ire->ire_src_addr;
22187 			ire_refrele(src_ire);
22188 		} else {
22189 			ire_refrele(ire);
22190 			if (conn_outgoing_ill != NULL)
22191 				ill_refrele(conn_outgoing_ill);
22192 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22193 			if (src_ire != NULL) {
22194 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22195 					ire_refrele(src_ire);
22196 					freemsg(mp);
22197 					return;
22198 				}
22199 				ire_refrele(src_ire);
22200 			}
22201 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22202 				/* Failed */
22203 				freemsg(mp);
22204 				return;
22205 			}
22206 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22207 			    ipst);
22208 			return;
22209 		}
22210 	}
22211 
22212 	if (mp->b_datap->db_type == M_CTL ||
22213 	    ipss->ipsec_outbound_v4_policy_present) {
22214 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22215 		    unspec_src, zoneid);
22216 		if (mp == NULL) {
22217 			ire_refrele(ire);
22218 			if (conn_outgoing_ill != NULL)
22219 				ill_refrele(conn_outgoing_ill);
22220 			return;
22221 		}
22222 	}
22223 
22224 	first_mp = mp;
22225 	ipsec_len = 0;
22226 
22227 	if (first_mp->b_datap->db_type == M_CTL) {
22228 		io = (ipsec_out_t *)first_mp->b_rptr;
22229 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22230 		mp = first_mp->b_cont;
22231 		ipsec_len = ipsec_out_extra_length(first_mp);
22232 		ASSERT(ipsec_len >= 0);
22233 		/* We already picked up the zoneid from the M_CTL above */
22234 		ASSERT(zoneid == io->ipsec_out_zoneid);
22235 		ASSERT(zoneid != ALL_ZONES);
22236 
22237 		/*
22238 		 * Drop M_CTL here if IPsec processing is not needed.
22239 		 * (Non-IPsec use of M_CTL extracted any information it
22240 		 * needed above).
22241 		 */
22242 		if (ipsec_len == 0) {
22243 			freeb(first_mp);
22244 			first_mp = mp;
22245 		}
22246 	}
22247 
22248 	/*
22249 	 * Fast path for ip_wput_ire
22250 	 */
22251 
22252 	ipha = (ipha_t *)mp->b_rptr;
22253 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22254 	dst = ipha->ipha_dst;
22255 
22256 	/*
22257 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22258 	 * if the socket is a SOCK_RAW type. The transport checksum should
22259 	 * be provided in the pre-built packet, so we don't need to compute it.
22260 	 * Also, other application set flags, like DF, should not be altered.
22261 	 * Other transport MUST pass down zero.
22262 	 */
22263 	ip_hdr_included = ipha->ipha_ident;
22264 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22265 
22266 	if (CLASSD(dst)) {
22267 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22268 		    ntohl(dst),
22269 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22270 		    ntohl(ire->ire_addr)));
22271 	}
22272 
22273 /* Macros to extract header fields from data already in registers */
22274 #ifdef	_BIG_ENDIAN
22275 #define	V_HLEN	(v_hlen_tos_len >> 24)
22276 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22277 #define	PROTO	(ttl_protocol & 0xFF)
22278 #else
22279 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22280 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22281 #define	PROTO	(ttl_protocol >> 8)
22282 #endif
22283 
22284 
22285 	orig_src = src = ipha->ipha_src;
22286 	/* (The loop back to "another" is explained down below.) */
22287 another:;
22288 	/*
22289 	 * Assign an ident value for this packet.  We assign idents on
22290 	 * a per destination basis out of the IRE.  There could be
22291 	 * other threads targeting the same destination, so we have to
22292 	 * arrange for a atomic increment.  Note that we use a 32-bit
22293 	 * atomic add because it has better performance than its
22294 	 * 16-bit sibling.
22295 	 *
22296 	 * If running in cluster mode and if the source address
22297 	 * belongs to a replicated service then vector through
22298 	 * cl_inet_ipident vector to allocate ip identifier
22299 	 * NOTE: This is a contract private interface with the
22300 	 * clustering group.
22301 	 */
22302 	clusterwide = 0;
22303 	if (cl_inet_ipident) {
22304 		ASSERT(cl_inet_isclusterwide);
22305 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22306 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22307 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22308 			    AF_INET, (uint8_t *)(uintptr_t)src,
22309 			    (uint8_t *)(uintptr_t)dst);
22310 			clusterwide = 1;
22311 		}
22312 	}
22313 	if (!clusterwide) {
22314 		ipha->ipha_ident =
22315 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22316 	}
22317 
22318 #ifndef _BIG_ENDIAN
22319 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22320 #endif
22321 
22322 	/*
22323 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22324 	 * This is needed to obey conn_unspec_src when packets go through
22325 	 * ip_newroute + arp.
22326 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22327 	 */
22328 	if (src == INADDR_ANY && !unspec_src) {
22329 		/*
22330 		 * Assign the appropriate source address from the IRE if none
22331 		 * was specified.
22332 		 */
22333 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22334 
22335 		/*
22336 		 * With IP multipathing, broadcast packets are sent on the ire
22337 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22338 		 * the group. However, this ire might not be in the same zone so
22339 		 * we can't always use its source address. We look for a
22340 		 * broadcast ire in the same group and in the right zone.
22341 		 */
22342 		if (ire->ire_type == IRE_BROADCAST &&
22343 		    ire->ire_zoneid != zoneid) {
22344 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22345 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22346 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22347 			if (src_ire != NULL) {
22348 				src = src_ire->ire_src_addr;
22349 				ire_refrele(src_ire);
22350 			} else {
22351 				ire_refrele(ire);
22352 				if (conn_outgoing_ill != NULL)
22353 					ill_refrele(conn_outgoing_ill);
22354 				freemsg(first_mp);
22355 				if (ill != NULL) {
22356 					BUMP_MIB(ill->ill_ip_mib,
22357 					    ipIfStatsOutDiscards);
22358 				} else {
22359 					BUMP_MIB(&ipst->ips_ip_mib,
22360 					    ipIfStatsOutDiscards);
22361 				}
22362 				return;
22363 			}
22364 		} else {
22365 			src = ire->ire_src_addr;
22366 		}
22367 
22368 		if (connp == NULL) {
22369 			ip1dbg(("ip_wput_ire: no connp and no src "
22370 			    "address for dst 0x%x, using src 0x%x\n",
22371 			    ntohl(dst),
22372 			    ntohl(src)));
22373 		}
22374 		ipha->ipha_src = src;
22375 	}
22376 	stq = ire->ire_stq;
22377 
22378 	/*
22379 	 * We only allow ire chains for broadcasts since there will
22380 	 * be multiple IRE_CACHE entries for the same multicast
22381 	 * address (one per ipif).
22382 	 */
22383 	next_mp = NULL;
22384 
22385 	/* broadcast packet */
22386 	if (ire->ire_type == IRE_BROADCAST)
22387 		goto broadcast;
22388 
22389 	/* loopback ? */
22390 	if (stq == NULL)
22391 		goto nullstq;
22392 
22393 	/* The ill_index for outbound ILL */
22394 	ill_index = Q_TO_INDEX(stq);
22395 
22396 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22397 	ttl_protocol = ((uint16_t *)ipha)[4];
22398 
22399 	/* pseudo checksum (do it in parts for IP header checksum) */
22400 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22401 
22402 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22403 		queue_t *dev_q = stq->q_next;
22404 
22405 		/* flow controlled */
22406 		if ((dev_q->q_next || dev_q->q_first) &&
22407 		    !canput(dev_q))
22408 			goto blocked;
22409 		if ((PROTO == IPPROTO_UDP) &&
22410 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22411 			hlen = (V_HLEN & 0xF) << 2;
22412 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22413 			if (*up != 0) {
22414 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22415 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22416 				/* Software checksum? */
22417 				if (DB_CKSUMFLAGS(mp) == 0) {
22418 					IP_STAT(ipst, ip_out_sw_cksum);
22419 					IP_STAT_UPDATE(ipst,
22420 					    ip_udp_out_sw_cksum_bytes,
22421 					    LENGTH - hlen);
22422 				}
22423 			}
22424 		}
22425 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22426 		hlen = (V_HLEN & 0xF) << 2;
22427 		if (PROTO == IPPROTO_TCP) {
22428 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22429 			/*
22430 			 * The packet header is processed once and for all, even
22431 			 * in the multirouting case. We disable hardware
22432 			 * checksum if the packet is multirouted, as it will be
22433 			 * replicated via several interfaces, and not all of
22434 			 * them may have this capability.
22435 			 */
22436 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22437 			    LENGTH, max_frag, ipsec_len, cksum);
22438 			/* Software checksum? */
22439 			if (DB_CKSUMFLAGS(mp) == 0) {
22440 				IP_STAT(ipst, ip_out_sw_cksum);
22441 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22442 				    LENGTH - hlen);
22443 			}
22444 		} else {
22445 			sctp_hdr_t	*sctph;
22446 
22447 			ASSERT(PROTO == IPPROTO_SCTP);
22448 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22449 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22450 			/*
22451 			 * Zero out the checksum field to ensure proper
22452 			 * checksum calculation.
22453 			 */
22454 			sctph->sh_chksum = 0;
22455 #ifdef	DEBUG
22456 			if (!skip_sctp_cksum)
22457 #endif
22458 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22459 		}
22460 	}
22461 
22462 	/*
22463 	 * If this is a multicast packet and originated from ip_wput
22464 	 * we need to do loopback and forwarding checks. If it comes
22465 	 * from ip_wput_multicast, we SHOULD not do this.
22466 	 */
22467 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22468 
22469 	/* checksum */
22470 	cksum += ttl_protocol;
22471 
22472 	/* fragment the packet */
22473 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22474 		goto fragmentit;
22475 	/*
22476 	 * Don't use frag_flag if packet is pre-built or source
22477 	 * routed or if multicast (since multicast packets do
22478 	 * not solicit ICMP "packet too big" messages).
22479 	 */
22480 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22481 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22482 	    !ip_source_route_included(ipha)) &&
22483 	    !CLASSD(ipha->ipha_dst))
22484 		ipha->ipha_fragment_offset_and_flags |=
22485 		    htons(ire->ire_frag_flag);
22486 
22487 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22488 		/* calculate IP header checksum */
22489 		cksum += ipha->ipha_ident;
22490 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22491 		cksum += ipha->ipha_fragment_offset_and_flags;
22492 
22493 		/* IP options present */
22494 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22495 		if (hlen)
22496 			goto checksumoptions;
22497 
22498 		/* calculate hdr checksum */
22499 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22500 		cksum = ~(cksum + (cksum >> 16));
22501 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22502 	}
22503 	if (ipsec_len != 0) {
22504 		/*
22505 		 * We will do the rest of the processing after
22506 		 * we come back from IPsec in ip_wput_ipsec_out().
22507 		 */
22508 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22509 
22510 		io = (ipsec_out_t *)first_mp->b_rptr;
22511 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22512 		    ill_phyint->phyint_ifindex;
22513 
22514 		ipsec_out_process(q, first_mp, ire, ill_index);
22515 		ire_refrele(ire);
22516 		if (conn_outgoing_ill != NULL)
22517 			ill_refrele(conn_outgoing_ill);
22518 		return;
22519 	}
22520 
22521 	/*
22522 	 * In most cases, the emission loop below is entered only
22523 	 * once. Only in the case where the ire holds the
22524 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22525 	 * flagged ires in the bucket, and send the packet
22526 	 * through all crossed RTF_MULTIRT routes.
22527 	 */
22528 	if (ire->ire_flags & RTF_MULTIRT) {
22529 		multirt_send = B_TRUE;
22530 	}
22531 	do {
22532 		if (multirt_send) {
22533 			irb_t *irb;
22534 			/*
22535 			 * We are in a multiple send case, need to get
22536 			 * the next ire and make a duplicate of the packet.
22537 			 * ire1 holds here the next ire to process in the
22538 			 * bucket. If multirouting is expected,
22539 			 * any non-RTF_MULTIRT ire that has the
22540 			 * right destination address is ignored.
22541 			 */
22542 			irb = ire->ire_bucket;
22543 			ASSERT(irb != NULL);
22544 
22545 			IRB_REFHOLD(irb);
22546 			for (ire1 = ire->ire_next;
22547 			    ire1 != NULL;
22548 			    ire1 = ire1->ire_next) {
22549 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22550 					continue;
22551 				if (ire1->ire_addr != ire->ire_addr)
22552 					continue;
22553 				if (ire1->ire_marks &
22554 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22555 					continue;
22556 
22557 				/* Got one */
22558 				IRE_REFHOLD(ire1);
22559 				break;
22560 			}
22561 			IRB_REFRELE(irb);
22562 
22563 			if (ire1 != NULL) {
22564 				next_mp = copyb(mp);
22565 				if ((next_mp == NULL) ||
22566 				    ((mp->b_cont != NULL) &&
22567 				    ((next_mp->b_cont =
22568 				    dupmsg(mp->b_cont)) == NULL))) {
22569 					freemsg(next_mp);
22570 					next_mp = NULL;
22571 					ire_refrele(ire1);
22572 					ire1 = NULL;
22573 				}
22574 			}
22575 
22576 			/* Last multiroute ire; don't loop anymore. */
22577 			if (ire1 == NULL) {
22578 				multirt_send = B_FALSE;
22579 			}
22580 		}
22581 
22582 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22583 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22584 		    mblk_t *, mp);
22585 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22586 		    ipst->ips_ipv4firewall_physical_out,
22587 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22588 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22589 		if (mp == NULL)
22590 			goto release_ire_and_ill;
22591 
22592 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22593 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22594 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22595 		if ((pktxmit_state == SEND_FAILED) ||
22596 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22597 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22598 			    "- packet dropped\n"));
22599 release_ire_and_ill:
22600 			ire_refrele(ire);
22601 			if (next_mp != NULL) {
22602 				freemsg(next_mp);
22603 				ire_refrele(ire1);
22604 			}
22605 			if (conn_outgoing_ill != NULL)
22606 				ill_refrele(conn_outgoing_ill);
22607 			return;
22608 		}
22609 
22610 		if (CLASSD(dst)) {
22611 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22612 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22613 			    LENGTH);
22614 		}
22615 
22616 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22617 		    "ip_wput_ire_end: q %p (%S)",
22618 		    q, "last copy out");
22619 		IRE_REFRELE(ire);
22620 
22621 		if (multirt_send) {
22622 			ASSERT(ire1);
22623 			/*
22624 			 * Proceed with the next RTF_MULTIRT ire,
22625 			 * Also set up the send-to queue accordingly.
22626 			 */
22627 			ire = ire1;
22628 			ire1 = NULL;
22629 			stq = ire->ire_stq;
22630 			mp = next_mp;
22631 			next_mp = NULL;
22632 			ipha = (ipha_t *)mp->b_rptr;
22633 			ill_index = Q_TO_INDEX(stq);
22634 			ill = (ill_t *)stq->q_ptr;
22635 		}
22636 	} while (multirt_send);
22637 	if (conn_outgoing_ill != NULL)
22638 		ill_refrele(conn_outgoing_ill);
22639 	return;
22640 
22641 	/*
22642 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22643 	 */
22644 broadcast:
22645 	{
22646 		/*
22647 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22648 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22649 		 * can be overridden stack-wide through the ip_broadcast_ttl
22650 		 * ndd tunable, or on a per-connection basis through the
22651 		 * IP_BROADCAST_TTL socket option.
22652 		 *
22653 		 * In the event that we are replying to incoming ICMP packets,
22654 		 * connp could be NULL.
22655 		 */
22656 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22657 		if (connp != NULL) {
22658 			if (connp->conn_dontroute)
22659 				ipha->ipha_ttl = 1;
22660 			else if (connp->conn_broadcast_ttl != 0)
22661 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22662 		}
22663 
22664 		/*
22665 		 * Note that we are not doing a IRB_REFHOLD here.
22666 		 * Actually we don't care if the list changes i.e
22667 		 * if somebody deletes an IRE from the list while
22668 		 * we drop the lock, the next time we come around
22669 		 * ire_next will be NULL and hence we won't send
22670 		 * out multiple copies which is fine.
22671 		 */
22672 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22673 		ire1 = ire->ire_next;
22674 		if (conn_outgoing_ill != NULL) {
22675 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22676 				ASSERT(ire1 == ire->ire_next);
22677 				if (ire1 != NULL && ire1->ire_addr == dst) {
22678 					ire_refrele(ire);
22679 					ire = ire1;
22680 					IRE_REFHOLD(ire);
22681 					ire1 = ire->ire_next;
22682 					continue;
22683 				}
22684 				rw_exit(&ire->ire_bucket->irb_lock);
22685 				/* Did not find a matching ill */
22686 				ip1dbg(("ip_wput_ire: broadcast with no "
22687 				    "matching IP_BOUND_IF ill %s dst %x\n",
22688 				    conn_outgoing_ill->ill_name, dst));
22689 				freemsg(first_mp);
22690 				if (ire != NULL)
22691 					ire_refrele(ire);
22692 				ill_refrele(conn_outgoing_ill);
22693 				return;
22694 			}
22695 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22696 			/*
22697 			 * If the next IRE has the same address and is not one
22698 			 * of the two copies that we need to send, try to see
22699 			 * whether this copy should be sent at all. This
22700 			 * assumes that we insert loopbacks first and then
22701 			 * non-loopbacks. This is acheived by inserting the
22702 			 * loopback always before non-loopback.
22703 			 * This is used to send a single copy of a broadcast
22704 			 * packet out all physical interfaces that have an
22705 			 * matching IRE_BROADCAST while also looping
22706 			 * back one copy (to ip_wput_local) for each
22707 			 * matching physical interface. However, we avoid
22708 			 * sending packets out different logical that match by
22709 			 * having ipif_up/ipif_down supress duplicate
22710 			 * IRE_BROADCASTS.
22711 			 *
22712 			 * This feature is currently used to get broadcasts
22713 			 * sent to multiple interfaces, when the broadcast
22714 			 * address being used applies to multiple interfaces.
22715 			 * For example, a whole net broadcast will be
22716 			 * replicated on every connected subnet of
22717 			 * the target net.
22718 			 *
22719 			 * Each zone has its own set of IRE_BROADCASTs, so that
22720 			 * we're able to distribute inbound packets to multiple
22721 			 * zones who share a broadcast address. We avoid looping
22722 			 * back outbound packets in different zones but on the
22723 			 * same ill, as the application would see duplicates.
22724 			 *
22725 			 * If the interfaces are part of the same group,
22726 			 * we would want to send only one copy out for
22727 			 * whole group.
22728 			 *
22729 			 * This logic assumes that ire_add_v4() groups the
22730 			 * IRE_BROADCAST entries so that those with the same
22731 			 * ire_addr and ill_group are kept together.
22732 			 */
22733 			ire_ill = ire->ire_ipif->ipif_ill;
22734 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22735 				if (ire_ill->ill_group != NULL &&
22736 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22737 					/*
22738 					 * If the current zone only has an ire
22739 					 * broadcast for this address marked
22740 					 * NORECV, the ire we want is ahead in
22741 					 * the bucket, so we look it up
22742 					 * deliberately ignoring the zoneid.
22743 					 */
22744 					for (ire1 = ire->ire_bucket->irb_ire;
22745 					    ire1 != NULL;
22746 					    ire1 = ire1->ire_next) {
22747 						ire1_ill =
22748 						    ire1->ire_ipif->ipif_ill;
22749 						if (ire1->ire_addr != dst)
22750 							continue;
22751 						/* skip over the current ire */
22752 						if (ire1 == ire)
22753 							continue;
22754 						/* skip over deleted ires */
22755 						if (ire1->ire_marks &
22756 						    IRE_MARK_CONDEMNED)
22757 							continue;
22758 						/*
22759 						 * non-loopback ire in our
22760 						 * group: use it for the next
22761 						 * pass in the loop
22762 						 */
22763 						if (ire1->ire_stq != NULL &&
22764 						    ire1_ill->ill_group ==
22765 						    ire_ill->ill_group)
22766 							break;
22767 					}
22768 				}
22769 			} else {
22770 				while (ire1 != NULL && ire1->ire_addr == dst) {
22771 					ire1_ill = ire1->ire_ipif->ipif_ill;
22772 					/*
22773 					 * We can have two broadcast ires on the
22774 					 * same ill in different zones; here
22775 					 * we'll send a copy of the packet on
22776 					 * each ill and the fanout code will
22777 					 * call conn_wantpacket() to check that
22778 					 * the zone has the broadcast address
22779 					 * configured on the ill. If the two
22780 					 * ires are in the same group we only
22781 					 * send one copy up.
22782 					 */
22783 					if (ire1_ill != ire_ill &&
22784 					    (ire1_ill->ill_group == NULL ||
22785 					    ire_ill->ill_group == NULL ||
22786 					    ire1_ill->ill_group !=
22787 					    ire_ill->ill_group)) {
22788 						break;
22789 					}
22790 					ire1 = ire1->ire_next;
22791 				}
22792 			}
22793 		}
22794 		ASSERT(multirt_send == B_FALSE);
22795 		if (ire1 != NULL && ire1->ire_addr == dst) {
22796 			if ((ire->ire_flags & RTF_MULTIRT) &&
22797 			    (ire1->ire_flags & RTF_MULTIRT)) {
22798 				/*
22799 				 * We are in the multirouting case.
22800 				 * The message must be sent at least
22801 				 * on both ires. These ires have been
22802 				 * inserted AFTER the standard ones
22803 				 * in ip_rt_add(). There are thus no
22804 				 * other ire entries for the destination
22805 				 * address in the rest of the bucket
22806 				 * that do not have the RTF_MULTIRT
22807 				 * flag. We don't process a copy
22808 				 * of the message here. This will be
22809 				 * done in the final sending loop.
22810 				 */
22811 				multirt_send = B_TRUE;
22812 			} else {
22813 				next_mp = ip_copymsg(first_mp);
22814 				if (next_mp != NULL)
22815 					IRE_REFHOLD(ire1);
22816 			}
22817 		}
22818 		rw_exit(&ire->ire_bucket->irb_lock);
22819 	}
22820 
22821 	if (stq) {
22822 		/*
22823 		 * A non-NULL send-to queue means this packet is going
22824 		 * out of this machine.
22825 		 */
22826 		out_ill = (ill_t *)stq->q_ptr;
22827 
22828 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22829 		ttl_protocol = ((uint16_t *)ipha)[4];
22830 		/*
22831 		 * We accumulate the pseudo header checksum in cksum.
22832 		 * This is pretty hairy code, so watch close.  One
22833 		 * thing to keep in mind is that UDP and TCP have
22834 		 * stored their respective datagram lengths in their
22835 		 * checksum fields.  This lines things up real nice.
22836 		 */
22837 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22838 		    (src >> 16) + (src & 0xFFFF);
22839 		/*
22840 		 * We assume the udp checksum field contains the
22841 		 * length, so to compute the pseudo header checksum,
22842 		 * all we need is the protocol number and src/dst.
22843 		 */
22844 		/* Provide the checksums for UDP and TCP. */
22845 		if ((PROTO == IPPROTO_TCP) &&
22846 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22847 			/* hlen gets the number of uchar_ts in the IP header */
22848 			hlen = (V_HLEN & 0xF) << 2;
22849 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22850 			IP_STAT(ipst, ip_out_sw_cksum);
22851 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22852 			    LENGTH - hlen);
22853 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22854 		} else if (PROTO == IPPROTO_SCTP &&
22855 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22856 			sctp_hdr_t	*sctph;
22857 
22858 			hlen = (V_HLEN & 0xF) << 2;
22859 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22860 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22861 			sctph->sh_chksum = 0;
22862 #ifdef	DEBUG
22863 			if (!skip_sctp_cksum)
22864 #endif
22865 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22866 		} else {
22867 			queue_t *dev_q = stq->q_next;
22868 
22869 			if ((dev_q->q_next || dev_q->q_first) &&
22870 			    !canput(dev_q)) {
22871 blocked:
22872 				ipha->ipha_ident = ip_hdr_included;
22873 				/*
22874 				 * If we don't have a conn to apply
22875 				 * backpressure, free the message.
22876 				 * In the ire_send path, we don't know
22877 				 * the position to requeue the packet. Rather
22878 				 * than reorder packets, we just drop this
22879 				 * packet.
22880 				 */
22881 				if (ipst->ips_ip_output_queue &&
22882 				    connp != NULL &&
22883 				    caller != IRE_SEND) {
22884 					if (caller == IP_WSRV) {
22885 						connp->conn_did_putbq = 1;
22886 						(void) putbq(connp->conn_wq,
22887 						    first_mp);
22888 						conn_drain_insert(connp);
22889 						/*
22890 						 * This is the service thread,
22891 						 * and the queue is already
22892 						 * noenabled. The check for
22893 						 * canput and the putbq is not
22894 						 * atomic. So we need to check
22895 						 * again.
22896 						 */
22897 						if (canput(stq->q_next))
22898 							connp->conn_did_putbq
22899 							    = 0;
22900 						IP_STAT(ipst, ip_conn_flputbq);
22901 					} else {
22902 						/*
22903 						 * We are not the service proc.
22904 						 * ip_wsrv will be scheduled or
22905 						 * is already running.
22906 						 */
22907 						(void) putq(connp->conn_wq,
22908 						    first_mp);
22909 					}
22910 				} else {
22911 					out_ill = (ill_t *)stq->q_ptr;
22912 					BUMP_MIB(out_ill->ill_ip_mib,
22913 					    ipIfStatsOutDiscards);
22914 					freemsg(first_mp);
22915 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22916 					    "ip_wput_ire_end: q %p (%S)",
22917 					    q, "discard");
22918 				}
22919 				ire_refrele(ire);
22920 				if (next_mp) {
22921 					ire_refrele(ire1);
22922 					freemsg(next_mp);
22923 				}
22924 				if (conn_outgoing_ill != NULL)
22925 					ill_refrele(conn_outgoing_ill);
22926 				return;
22927 			}
22928 			if ((PROTO == IPPROTO_UDP) &&
22929 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22930 				/*
22931 				 * hlen gets the number of uchar_ts in the
22932 				 * IP header
22933 				 */
22934 				hlen = (V_HLEN & 0xF) << 2;
22935 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22936 				max_frag = ire->ire_max_frag;
22937 				if (*up != 0) {
22938 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22939 					    up, PROTO, hlen, LENGTH, max_frag,
22940 					    ipsec_len, cksum);
22941 					/* Software checksum? */
22942 					if (DB_CKSUMFLAGS(mp) == 0) {
22943 						IP_STAT(ipst, ip_out_sw_cksum);
22944 						IP_STAT_UPDATE(ipst,
22945 						    ip_udp_out_sw_cksum_bytes,
22946 						    LENGTH - hlen);
22947 					}
22948 				}
22949 			}
22950 		}
22951 		/*
22952 		 * Need to do this even when fragmenting. The local
22953 		 * loopback can be done without computing checksums
22954 		 * but forwarding out other interface must be done
22955 		 * after the IP checksum (and ULP checksums) have been
22956 		 * computed.
22957 		 *
22958 		 * NOTE : multicast_forward is set only if this packet
22959 		 * originated from ip_wput. For packets originating from
22960 		 * ip_wput_multicast, it is not set.
22961 		 */
22962 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22963 multi_loopback:
22964 			ip2dbg(("ip_wput: multicast, loop %d\n",
22965 			    conn_multicast_loop));
22966 
22967 			/*  Forget header checksum offload */
22968 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22969 
22970 			/*
22971 			 * Local loopback of multicasts?  Check the
22972 			 * ill.
22973 			 *
22974 			 * Note that the loopback function will not come
22975 			 * in through ip_rput - it will only do the
22976 			 * client fanout thus we need to do an mforward
22977 			 * as well.  The is different from the BSD
22978 			 * logic.
22979 			 */
22980 			if (ill != NULL) {
22981 				ilm_t	*ilm;
22982 
22983 				ILM_WALKER_HOLD(ill);
22984 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22985 				    ALL_ZONES);
22986 				ILM_WALKER_RELE(ill);
22987 				if (ilm != NULL) {
22988 					/*
22989 					 * Pass along the virtual output q.
22990 					 * ip_wput_local() will distribute the
22991 					 * packet to all the matching zones,
22992 					 * except the sending zone when
22993 					 * IP_MULTICAST_LOOP is false.
22994 					 */
22995 					ip_multicast_loopback(q, ill, first_mp,
22996 					    conn_multicast_loop ? 0 :
22997 					    IP_FF_NO_MCAST_LOOP, zoneid);
22998 				}
22999 			}
23000 			if (ipha->ipha_ttl == 0) {
23001 				/*
23002 				 * 0 => only to this host i.e. we are
23003 				 * done. We are also done if this was the
23004 				 * loopback interface since it is sufficient
23005 				 * to loopback one copy of a multicast packet.
23006 				 */
23007 				freemsg(first_mp);
23008 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23009 				    "ip_wput_ire_end: q %p (%S)",
23010 				    q, "loopback");
23011 				ire_refrele(ire);
23012 				if (conn_outgoing_ill != NULL)
23013 					ill_refrele(conn_outgoing_ill);
23014 				return;
23015 			}
23016 			/*
23017 			 * ILLF_MULTICAST is checked in ip_newroute
23018 			 * i.e. we don't need to check it here since
23019 			 * all IRE_CACHEs come from ip_newroute.
23020 			 * For multicast traffic, SO_DONTROUTE is interpreted
23021 			 * to mean only send the packet out the interface
23022 			 * (optionally specified with IP_MULTICAST_IF)
23023 			 * and do not forward it out additional interfaces.
23024 			 * RSVP and the rsvp daemon is an example of a
23025 			 * protocol and user level process that
23026 			 * handles it's own routing. Hence, it uses the
23027 			 * SO_DONTROUTE option to accomplish this.
23028 			 */
23029 
23030 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23031 			    ill != NULL) {
23032 				/* Unconditionally redo the checksum */
23033 				ipha->ipha_hdr_checksum = 0;
23034 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23035 
23036 				/*
23037 				 * If this needs to go out secure, we need
23038 				 * to wait till we finish the IPsec
23039 				 * processing.
23040 				 */
23041 				if (ipsec_len == 0 &&
23042 				    ip_mforward(ill, ipha, mp)) {
23043 					freemsg(first_mp);
23044 					ip1dbg(("ip_wput: mforward failed\n"));
23045 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23046 					    "ip_wput_ire_end: q %p (%S)",
23047 					    q, "mforward failed");
23048 					ire_refrele(ire);
23049 					if (conn_outgoing_ill != NULL)
23050 						ill_refrele(conn_outgoing_ill);
23051 					return;
23052 				}
23053 			}
23054 		}
23055 		max_frag = ire->ire_max_frag;
23056 		cksum += ttl_protocol;
23057 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23058 			/* No fragmentation required for this one. */
23059 			/*
23060 			 * Don't use frag_flag if packet is pre-built or source
23061 			 * routed or if multicast (since multicast packets do
23062 			 * not solicit ICMP "packet too big" messages).
23063 			 */
23064 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23065 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23066 			    !ip_source_route_included(ipha)) &&
23067 			    !CLASSD(ipha->ipha_dst))
23068 				ipha->ipha_fragment_offset_and_flags |=
23069 				    htons(ire->ire_frag_flag);
23070 
23071 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23072 				/* Complete the IP header checksum. */
23073 				cksum += ipha->ipha_ident;
23074 				cksum += (v_hlen_tos_len >> 16)+
23075 				    (v_hlen_tos_len & 0xFFFF);
23076 				cksum += ipha->ipha_fragment_offset_and_flags;
23077 				hlen = (V_HLEN & 0xF) -
23078 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23079 				if (hlen) {
23080 checksumoptions:
23081 					/*
23082 					 * Account for the IP Options in the IP
23083 					 * header checksum.
23084 					 */
23085 					up = (uint16_t *)(rptr+
23086 					    IP_SIMPLE_HDR_LENGTH);
23087 					do {
23088 						cksum += up[0];
23089 						cksum += up[1];
23090 						up += 2;
23091 					} while (--hlen);
23092 				}
23093 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23094 				cksum = ~(cksum + (cksum >> 16));
23095 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23096 			}
23097 			if (ipsec_len != 0) {
23098 				ipsec_out_process(q, first_mp, ire, ill_index);
23099 				if (!next_mp) {
23100 					ire_refrele(ire);
23101 					if (conn_outgoing_ill != NULL)
23102 						ill_refrele(conn_outgoing_ill);
23103 					return;
23104 				}
23105 				goto next;
23106 			}
23107 
23108 			/*
23109 			 * multirt_send has already been handled
23110 			 * for broadcast, but not yet for multicast
23111 			 * or IP options.
23112 			 */
23113 			if (next_mp == NULL) {
23114 				if (ire->ire_flags & RTF_MULTIRT) {
23115 					multirt_send = B_TRUE;
23116 				}
23117 			}
23118 
23119 			/*
23120 			 * In most cases, the emission loop below is
23121 			 * entered only once. Only in the case where
23122 			 * the ire holds the RTF_MULTIRT flag, do we loop
23123 			 * to process all RTF_MULTIRT ires in the bucket,
23124 			 * and send the packet through all crossed
23125 			 * RTF_MULTIRT routes.
23126 			 */
23127 			do {
23128 				if (multirt_send) {
23129 					irb_t *irb;
23130 
23131 					irb = ire->ire_bucket;
23132 					ASSERT(irb != NULL);
23133 					/*
23134 					 * We are in a multiple send case,
23135 					 * need to get the next IRE and make
23136 					 * a duplicate of the packet.
23137 					 */
23138 					IRB_REFHOLD(irb);
23139 					for (ire1 = ire->ire_next;
23140 					    ire1 != NULL;
23141 					    ire1 = ire1->ire_next) {
23142 						if (!(ire1->ire_flags &
23143 						    RTF_MULTIRT)) {
23144 							continue;
23145 						}
23146 						if (ire1->ire_addr !=
23147 						    ire->ire_addr) {
23148 							continue;
23149 						}
23150 						if (ire1->ire_marks &
23151 						    (IRE_MARK_CONDEMNED|
23152 						    IRE_MARK_HIDDEN)) {
23153 							continue;
23154 						}
23155 
23156 						/* Got one */
23157 						IRE_REFHOLD(ire1);
23158 						break;
23159 					}
23160 					IRB_REFRELE(irb);
23161 
23162 					if (ire1 != NULL) {
23163 						next_mp = copyb(mp);
23164 						if ((next_mp == NULL) ||
23165 						    ((mp->b_cont != NULL) &&
23166 						    ((next_mp->b_cont =
23167 						    dupmsg(mp->b_cont))
23168 						    == NULL))) {
23169 							freemsg(next_mp);
23170 							next_mp = NULL;
23171 							ire_refrele(ire1);
23172 							ire1 = NULL;
23173 						}
23174 					}
23175 
23176 					/*
23177 					 * Last multiroute ire; don't loop
23178 					 * anymore. The emission is over
23179 					 * and next_mp is NULL.
23180 					 */
23181 					if (ire1 == NULL) {
23182 						multirt_send = B_FALSE;
23183 					}
23184 				}
23185 
23186 				out_ill = ire_to_ill(ire);
23187 				DTRACE_PROBE4(ip4__physical__out__start,
23188 				    ill_t *, NULL,
23189 				    ill_t *, out_ill,
23190 				    ipha_t *, ipha, mblk_t *, mp);
23191 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23192 				    ipst->ips_ipv4firewall_physical_out,
23193 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23194 				DTRACE_PROBE1(ip4__physical__out__end,
23195 				    mblk_t *, mp);
23196 				if (mp == NULL)
23197 					goto release_ire_and_ill_2;
23198 
23199 				ASSERT(ipsec_len == 0);
23200 				mp->b_prev =
23201 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23202 				DTRACE_PROBE2(ip__xmit__2,
23203 				    mblk_t *, mp, ire_t *, ire);
23204 				pktxmit_state = ip_xmit_v4(mp, ire,
23205 				    NULL, B_TRUE);
23206 				if ((pktxmit_state == SEND_FAILED) ||
23207 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23208 release_ire_and_ill_2:
23209 					if (next_mp) {
23210 						freemsg(next_mp);
23211 						ire_refrele(ire1);
23212 					}
23213 					ire_refrele(ire);
23214 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23215 					    "ip_wput_ire_end: q %p (%S)",
23216 					    q, "discard MDATA");
23217 					if (conn_outgoing_ill != NULL)
23218 						ill_refrele(conn_outgoing_ill);
23219 					return;
23220 				}
23221 
23222 				if (CLASSD(dst)) {
23223 					BUMP_MIB(out_ill->ill_ip_mib,
23224 					    ipIfStatsHCOutMcastPkts);
23225 					UPDATE_MIB(out_ill->ill_ip_mib,
23226 					    ipIfStatsHCOutMcastOctets,
23227 					    LENGTH);
23228 				} else if (ire->ire_type == IRE_BROADCAST) {
23229 					BUMP_MIB(out_ill->ill_ip_mib,
23230 					    ipIfStatsHCOutBcastPkts);
23231 				}
23232 
23233 				if (multirt_send) {
23234 					/*
23235 					 * We are in a multiple send case,
23236 					 * need to re-enter the sending loop
23237 					 * using the next ire.
23238 					 */
23239 					ire_refrele(ire);
23240 					ire = ire1;
23241 					stq = ire->ire_stq;
23242 					mp = next_mp;
23243 					next_mp = NULL;
23244 					ipha = (ipha_t *)mp->b_rptr;
23245 					ill_index = Q_TO_INDEX(stq);
23246 				}
23247 			} while (multirt_send);
23248 
23249 			if (!next_mp) {
23250 				/*
23251 				 * Last copy going out (the ultra-common
23252 				 * case).  Note that we intentionally replicate
23253 				 * the putnext rather than calling it before
23254 				 * the next_mp check in hopes of a little
23255 				 * tail-call action out of the compiler.
23256 				 */
23257 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23258 				    "ip_wput_ire_end: q %p (%S)",
23259 				    q, "last copy out(1)");
23260 				ire_refrele(ire);
23261 				if (conn_outgoing_ill != NULL)
23262 					ill_refrele(conn_outgoing_ill);
23263 				return;
23264 			}
23265 			/* More copies going out below. */
23266 		} else {
23267 			int offset;
23268 fragmentit:
23269 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23270 			/*
23271 			 * If this would generate a icmp_frag_needed message,
23272 			 * we need to handle it before we do the IPsec
23273 			 * processing. Otherwise, we need to strip the IPsec
23274 			 * headers before we send up the message to the ULPs
23275 			 * which becomes messy and difficult.
23276 			 */
23277 			if (ipsec_len != 0) {
23278 				if ((max_frag < (unsigned int)(LENGTH +
23279 				    ipsec_len)) && (offset & IPH_DF)) {
23280 					out_ill = (ill_t *)stq->q_ptr;
23281 					BUMP_MIB(out_ill->ill_ip_mib,
23282 					    ipIfStatsOutFragFails);
23283 					BUMP_MIB(out_ill->ill_ip_mib,
23284 					    ipIfStatsOutFragReqds);
23285 					ipha->ipha_hdr_checksum = 0;
23286 					ipha->ipha_hdr_checksum =
23287 					    (uint16_t)ip_csum_hdr(ipha);
23288 					icmp_frag_needed(ire->ire_stq, first_mp,
23289 					    max_frag, zoneid, ipst);
23290 					if (!next_mp) {
23291 						ire_refrele(ire);
23292 						if (conn_outgoing_ill != NULL) {
23293 							ill_refrele(
23294 							    conn_outgoing_ill);
23295 						}
23296 						return;
23297 					}
23298 				} else {
23299 					/*
23300 					 * This won't cause a icmp_frag_needed
23301 					 * message. to be generated. Send it on
23302 					 * the wire. Note that this could still
23303 					 * cause fragmentation and all we
23304 					 * do is the generation of the message
23305 					 * to the ULP if needed before IPsec.
23306 					 */
23307 					if (!next_mp) {
23308 						ipsec_out_process(q, first_mp,
23309 						    ire, ill_index);
23310 						TRACE_2(TR_FAC_IP,
23311 						    TR_IP_WPUT_IRE_END,
23312 						    "ip_wput_ire_end: q %p "
23313 						    "(%S)", q,
23314 						    "last ipsec_out_process");
23315 						ire_refrele(ire);
23316 						if (conn_outgoing_ill != NULL) {
23317 							ill_refrele(
23318 							    conn_outgoing_ill);
23319 						}
23320 						return;
23321 					}
23322 					ipsec_out_process(q, first_mp,
23323 					    ire, ill_index);
23324 				}
23325 			} else {
23326 				/*
23327 				 * Initiate IPPF processing. For
23328 				 * fragmentable packets we finish
23329 				 * all QOS packet processing before
23330 				 * calling:
23331 				 * ip_wput_ire_fragmentit->ip_wput_frag
23332 				 */
23333 
23334 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23335 					ip_process(IPP_LOCAL_OUT, &mp,
23336 					    ill_index);
23337 					if (mp == NULL) {
23338 						out_ill = (ill_t *)stq->q_ptr;
23339 						BUMP_MIB(out_ill->ill_ip_mib,
23340 						    ipIfStatsOutDiscards);
23341 						if (next_mp != NULL) {
23342 							freemsg(next_mp);
23343 							ire_refrele(ire1);
23344 						}
23345 						ire_refrele(ire);
23346 						TRACE_2(TR_FAC_IP,
23347 						    TR_IP_WPUT_IRE_END,
23348 						    "ip_wput_ire: q %p (%S)",
23349 						    q, "discard MDATA");
23350 						if (conn_outgoing_ill != NULL) {
23351 							ill_refrele(
23352 							    conn_outgoing_ill);
23353 						}
23354 						return;
23355 					}
23356 				}
23357 				if (!next_mp) {
23358 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23359 					    "ip_wput_ire_end: q %p (%S)",
23360 					    q, "last fragmentation");
23361 					ip_wput_ire_fragmentit(mp, ire,
23362 					    zoneid, ipst);
23363 					ire_refrele(ire);
23364 					if (conn_outgoing_ill != NULL)
23365 						ill_refrele(conn_outgoing_ill);
23366 					return;
23367 				}
23368 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23369 			}
23370 		}
23371 	} else {
23372 nullstq:
23373 		/* A NULL stq means the destination address is local. */
23374 		UPDATE_OB_PKT_COUNT(ire);
23375 		ire->ire_last_used_time = lbolt;
23376 		ASSERT(ire->ire_ipif != NULL);
23377 		if (!next_mp) {
23378 			/*
23379 			 * Is there an "in" and "out" for traffic local
23380 			 * to a host (loopback)?  The code in Solaris doesn't
23381 			 * explicitly draw a line in its code for in vs out,
23382 			 * so we've had to draw a line in the sand: ip_wput_ire
23383 			 * is considered to be the "output" side and
23384 			 * ip_wput_local to be the "input" side.
23385 			 */
23386 			out_ill = ire_to_ill(ire);
23387 
23388 			DTRACE_PROBE4(ip4__loopback__out__start,
23389 			    ill_t *, NULL, ill_t *, out_ill,
23390 			    ipha_t *, ipha, mblk_t *, first_mp);
23391 
23392 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23393 			    ipst->ips_ipv4firewall_loopback_out,
23394 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23395 
23396 			DTRACE_PROBE1(ip4__loopback__out_end,
23397 			    mblk_t *, first_mp);
23398 
23399 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23400 			    "ip_wput_ire_end: q %p (%S)",
23401 			    q, "local address");
23402 
23403 			if (first_mp != NULL)
23404 				ip_wput_local(q, out_ill, ipha,
23405 				    first_mp, ire, 0, ire->ire_zoneid);
23406 			ire_refrele(ire);
23407 			if (conn_outgoing_ill != NULL)
23408 				ill_refrele(conn_outgoing_ill);
23409 			return;
23410 		}
23411 
23412 		out_ill = ire_to_ill(ire);
23413 
23414 		DTRACE_PROBE4(ip4__loopback__out__start,
23415 		    ill_t *, NULL, ill_t *, out_ill,
23416 		    ipha_t *, ipha, mblk_t *, first_mp);
23417 
23418 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23419 		    ipst->ips_ipv4firewall_loopback_out,
23420 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23421 
23422 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23423 
23424 		if (first_mp != NULL)
23425 			ip_wput_local(q, out_ill, ipha,
23426 			    first_mp, ire, 0, ire->ire_zoneid);
23427 	}
23428 next:
23429 	/*
23430 	 * More copies going out to additional interfaces.
23431 	 * ire1 has already been held. We don't need the
23432 	 * "ire" anymore.
23433 	 */
23434 	ire_refrele(ire);
23435 	ire = ire1;
23436 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23437 	mp = next_mp;
23438 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23439 	ill = ire_to_ill(ire);
23440 	first_mp = mp;
23441 	if (ipsec_len != 0) {
23442 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23443 		mp = mp->b_cont;
23444 	}
23445 	dst = ire->ire_addr;
23446 	ipha = (ipha_t *)mp->b_rptr;
23447 	/*
23448 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23449 	 * Restore ipha_ident "no checksum" flag.
23450 	 */
23451 	src = orig_src;
23452 	ipha->ipha_ident = ip_hdr_included;
23453 	goto another;
23454 
23455 #undef	rptr
23456 #undef	Q_TO_INDEX
23457 }
23458 
23459 /*
23460  * Routine to allocate a message that is used to notify the ULP about MDT.
23461  * The caller may provide a pointer to the link-layer MDT capabilities,
23462  * or NULL if MDT is to be disabled on the stream.
23463  */
23464 mblk_t *
23465 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23466 {
23467 	mblk_t *mp;
23468 	ip_mdt_info_t *mdti;
23469 	ill_mdt_capab_t *idst;
23470 
23471 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23472 		DB_TYPE(mp) = M_CTL;
23473 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23474 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23475 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23476 		idst = &(mdti->mdt_capab);
23477 
23478 		/*
23479 		 * If the caller provides us with the capability, copy
23480 		 * it over into our notification message; otherwise
23481 		 * we zero out the capability portion.
23482 		 */
23483 		if (isrc != NULL)
23484 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23485 		else
23486 			bzero((caddr_t)idst, sizeof (*idst));
23487 	}
23488 	return (mp);
23489 }
23490 
23491 /*
23492  * Routine which determines whether MDT can be enabled on the destination
23493  * IRE and IPC combination, and if so, allocates and returns the MDT
23494  * notification mblk that may be used by ULP.  We also check if we need to
23495  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23496  * MDT usage in the past have been lifted.  This gets called during IP
23497  * and ULP binding.
23498  */
23499 mblk_t *
23500 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23501     ill_mdt_capab_t *mdt_cap)
23502 {
23503 	mblk_t *mp;
23504 	boolean_t rc = B_FALSE;
23505 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23506 
23507 	ASSERT(dst_ire != NULL);
23508 	ASSERT(connp != NULL);
23509 	ASSERT(mdt_cap != NULL);
23510 
23511 	/*
23512 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23513 	 * Multidata, which is handled in tcp_multisend().  This
23514 	 * is the reason why we do all these checks here, to ensure
23515 	 * that we don't enable Multidata for the cases which we
23516 	 * can't handle at the moment.
23517 	 */
23518 	do {
23519 		/* Only do TCP at the moment */
23520 		if (connp->conn_ulp != IPPROTO_TCP)
23521 			break;
23522 
23523 		/*
23524 		 * IPsec outbound policy present?  Note that we get here
23525 		 * after calling ipsec_conn_cache_policy() where the global
23526 		 * policy checking is performed.  conn_latch will be
23527 		 * non-NULL as long as there's a policy defined,
23528 		 * i.e. conn_out_enforce_policy may be NULL in such case
23529 		 * when the connection is non-secure, and hence we check
23530 		 * further if the latch refers to an outbound policy.
23531 		 */
23532 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23533 			break;
23534 
23535 		/* CGTP (multiroute) is enabled? */
23536 		if (dst_ire->ire_flags & RTF_MULTIRT)
23537 			break;
23538 
23539 		/* Outbound IPQoS enabled? */
23540 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23541 			/*
23542 			 * In this case, we disable MDT for this and all
23543 			 * future connections going over the interface.
23544 			 */
23545 			mdt_cap->ill_mdt_on = 0;
23546 			break;
23547 		}
23548 
23549 		/* socket option(s) present? */
23550 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23551 			break;
23552 
23553 		rc = B_TRUE;
23554 	/* CONSTCOND */
23555 	} while (0);
23556 
23557 	/* Remember the result */
23558 	connp->conn_mdt_ok = rc;
23559 
23560 	if (!rc)
23561 		return (NULL);
23562 	else if (!mdt_cap->ill_mdt_on) {
23563 		/*
23564 		 * If MDT has been previously turned off in the past, and we
23565 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23566 		 * then enable it for this interface.
23567 		 */
23568 		mdt_cap->ill_mdt_on = 1;
23569 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23570 		    "interface %s\n", ill_name));
23571 	}
23572 
23573 	/* Allocate the MDT info mblk */
23574 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23575 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23576 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23577 		return (NULL);
23578 	}
23579 	return (mp);
23580 }
23581 
23582 /*
23583  * Routine to allocate a message that is used to notify the ULP about LSO.
23584  * The caller may provide a pointer to the link-layer LSO capabilities,
23585  * or NULL if LSO is to be disabled on the stream.
23586  */
23587 mblk_t *
23588 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23589 {
23590 	mblk_t *mp;
23591 	ip_lso_info_t *lsoi;
23592 	ill_lso_capab_t *idst;
23593 
23594 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23595 		DB_TYPE(mp) = M_CTL;
23596 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23597 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23598 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23599 		idst = &(lsoi->lso_capab);
23600 
23601 		/*
23602 		 * If the caller provides us with the capability, copy
23603 		 * it over into our notification message; otherwise
23604 		 * we zero out the capability portion.
23605 		 */
23606 		if (isrc != NULL)
23607 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23608 		else
23609 			bzero((caddr_t)idst, sizeof (*idst));
23610 	}
23611 	return (mp);
23612 }
23613 
23614 /*
23615  * Routine which determines whether LSO can be enabled on the destination
23616  * IRE and IPC combination, and if so, allocates and returns the LSO
23617  * notification mblk that may be used by ULP.  We also check if we need to
23618  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23619  * LSO usage in the past have been lifted.  This gets called during IP
23620  * and ULP binding.
23621  */
23622 mblk_t *
23623 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23624     ill_lso_capab_t *lso_cap)
23625 {
23626 	mblk_t *mp;
23627 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23628 
23629 	ASSERT(dst_ire != NULL);
23630 	ASSERT(connp != NULL);
23631 	ASSERT(lso_cap != NULL);
23632 
23633 	connp->conn_lso_ok = B_TRUE;
23634 
23635 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23636 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23637 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23638 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23639 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23640 		connp->conn_lso_ok = B_FALSE;
23641 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23642 			/*
23643 			 * Disable LSO for this and all future connections going
23644 			 * over the interface.
23645 			 */
23646 			lso_cap->ill_lso_on = 0;
23647 		}
23648 	}
23649 
23650 	if (!connp->conn_lso_ok)
23651 		return (NULL);
23652 	else if (!lso_cap->ill_lso_on) {
23653 		/*
23654 		 * If LSO has been previously turned off in the past, and we
23655 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23656 		 * then enable it for this interface.
23657 		 */
23658 		lso_cap->ill_lso_on = 1;
23659 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23660 		    ill_name));
23661 	}
23662 
23663 	/* Allocate the LSO info mblk */
23664 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23665 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23666 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23667 
23668 	return (mp);
23669 }
23670 
23671 /*
23672  * Create destination address attribute, and fill it with the physical
23673  * destination address and SAP taken from the template DL_UNITDATA_REQ
23674  * message block.
23675  */
23676 boolean_t
23677 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23678 {
23679 	dl_unitdata_req_t *dlurp;
23680 	pattr_t *pa;
23681 	pattrinfo_t pa_info;
23682 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23683 	uint_t das_len, das_off;
23684 
23685 	ASSERT(dlmp != NULL);
23686 
23687 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23688 	das_len = dlurp->dl_dest_addr_length;
23689 	das_off = dlurp->dl_dest_addr_offset;
23690 
23691 	pa_info.type = PATTR_DSTADDRSAP;
23692 	pa_info.len = sizeof (**das) + das_len - 1;
23693 
23694 	/* create and associate the attribute */
23695 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23696 	if (pa != NULL) {
23697 		ASSERT(*das != NULL);
23698 		(*das)->addr_is_group = 0;
23699 		(*das)->addr_len = (uint8_t)das_len;
23700 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23701 	}
23702 
23703 	return (pa != NULL);
23704 }
23705 
23706 /*
23707  * Create hardware checksum attribute and fill it with the values passed.
23708  */
23709 boolean_t
23710 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23711     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23712 {
23713 	pattr_t *pa;
23714 	pattrinfo_t pa_info;
23715 
23716 	ASSERT(mmd != NULL);
23717 
23718 	pa_info.type = PATTR_HCKSUM;
23719 	pa_info.len = sizeof (pattr_hcksum_t);
23720 
23721 	/* create and associate the attribute */
23722 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23723 	if (pa != NULL) {
23724 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23725 
23726 		hck->hcksum_start_offset = start_offset;
23727 		hck->hcksum_stuff_offset = stuff_offset;
23728 		hck->hcksum_end_offset = end_offset;
23729 		hck->hcksum_flags = flags;
23730 	}
23731 	return (pa != NULL);
23732 }
23733 
23734 /*
23735  * Create zerocopy attribute and fill it with the specified flags
23736  */
23737 boolean_t
23738 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23739 {
23740 	pattr_t *pa;
23741 	pattrinfo_t pa_info;
23742 
23743 	ASSERT(mmd != NULL);
23744 	pa_info.type = PATTR_ZCOPY;
23745 	pa_info.len = sizeof (pattr_zcopy_t);
23746 
23747 	/* create and associate the attribute */
23748 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23749 	if (pa != NULL) {
23750 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23751 
23752 		zcopy->zcopy_flags = flags;
23753 	}
23754 	return (pa != NULL);
23755 }
23756 
23757 /*
23758  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23759  * block chain. We could rewrite to handle arbitrary message block chains but
23760  * that would make the code complicated and slow. Right now there three
23761  * restrictions:
23762  *
23763  *   1. The first message block must contain the complete IP header and
23764  *	at least 1 byte of payload data.
23765  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23766  *	so that we can use a single Multidata message.
23767  *   3. No frag must be distributed over two or more message blocks so
23768  *	that we don't need more than two packet descriptors per frag.
23769  *
23770  * The above restrictions allow us to support userland applications (which
23771  * will send down a single message block) and NFS over UDP (which will
23772  * send down a chain of at most three message blocks).
23773  *
23774  * We also don't use MDT for payloads with less than or equal to
23775  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23776  */
23777 boolean_t
23778 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23779 {
23780 	int	blocks;
23781 	ssize_t	total, missing, size;
23782 
23783 	ASSERT(mp != NULL);
23784 	ASSERT(hdr_len > 0);
23785 
23786 	size = MBLKL(mp) - hdr_len;
23787 	if (size <= 0)
23788 		return (B_FALSE);
23789 
23790 	/* The first mblk contains the header and some payload. */
23791 	blocks = 1;
23792 	total = size;
23793 	size %= len;
23794 	missing = (size == 0) ? 0 : (len - size);
23795 	mp = mp->b_cont;
23796 
23797 	while (mp != NULL) {
23798 		/*
23799 		 * Give up if we encounter a zero length message block.
23800 		 * In practice, this should rarely happen and therefore
23801 		 * not worth the trouble of freeing and re-linking the
23802 		 * mblk from the chain to handle such case.
23803 		 */
23804 		if ((size = MBLKL(mp)) == 0)
23805 			return (B_FALSE);
23806 
23807 		/* Too many payload buffers for a single Multidata message? */
23808 		if (++blocks > MULTIDATA_MAX_PBUFS)
23809 			return (B_FALSE);
23810 
23811 		total += size;
23812 		/* Is a frag distributed over two or more message blocks? */
23813 		if (missing > size)
23814 			return (B_FALSE);
23815 		size -= missing;
23816 
23817 		size %= len;
23818 		missing = (size == 0) ? 0 : (len - size);
23819 
23820 		mp = mp->b_cont;
23821 	}
23822 
23823 	return (total > ip_wput_frag_mdt_min);
23824 }
23825 
23826 /*
23827  * Outbound IPv4 fragmentation routine using MDT.
23828  */
23829 static void
23830 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23831     uint32_t frag_flag, int offset)
23832 {
23833 	ipha_t		*ipha_orig;
23834 	int		i1, ip_data_end;
23835 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23836 	mblk_t		*hdr_mp, *md_mp = NULL;
23837 	unsigned char	*hdr_ptr, *pld_ptr;
23838 	multidata_t	*mmd;
23839 	ip_pdescinfo_t	pdi;
23840 	ill_t		*ill;
23841 	ip_stack_t	*ipst = ire->ire_ipst;
23842 
23843 	ASSERT(DB_TYPE(mp) == M_DATA);
23844 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23845 
23846 	ill = ire_to_ill(ire);
23847 	ASSERT(ill != NULL);
23848 
23849 	ipha_orig = (ipha_t *)mp->b_rptr;
23850 	mp->b_rptr += sizeof (ipha_t);
23851 
23852 	/* Calculate how many packets we will send out */
23853 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23854 	pkts = (i1 + len - 1) / len;
23855 	ASSERT(pkts > 1);
23856 
23857 	/* Allocate a message block which will hold all the IP Headers. */
23858 	wroff = ipst->ips_ip_wroff_extra;
23859 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23860 
23861 	i1 = pkts * hdr_chunk_len;
23862 	/*
23863 	 * Create the header buffer, Multidata and destination address
23864 	 * and SAP attribute that should be associated with it.
23865 	 */
23866 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23867 	    ((hdr_mp->b_wptr += i1),
23868 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23869 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23870 		freemsg(mp);
23871 		if (md_mp == NULL) {
23872 			freemsg(hdr_mp);
23873 		} else {
23874 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23875 			freemsg(md_mp);
23876 		}
23877 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23878 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23879 		return;
23880 	}
23881 	IP_STAT(ipst, ip_frag_mdt_allocd);
23882 
23883 	/*
23884 	 * Add a payload buffer to the Multidata; this operation must not
23885 	 * fail, or otherwise our logic in this routine is broken.  There
23886 	 * is no memory allocation done by the routine, so any returned
23887 	 * failure simply tells us that we've done something wrong.
23888 	 *
23889 	 * A failure tells us that either we're adding the same payload
23890 	 * buffer more than once, or we're trying to add more buffers than
23891 	 * allowed.  None of the above cases should happen, and we panic
23892 	 * because either there's horrible heap corruption, and/or
23893 	 * programming mistake.
23894 	 */
23895 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23896 		goto pbuf_panic;
23897 
23898 	hdr_ptr = hdr_mp->b_rptr;
23899 	pld_ptr = mp->b_rptr;
23900 
23901 	/* Establish the ending byte offset, based on the starting offset. */
23902 	offset <<= 3;
23903 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23904 	    IP_SIMPLE_HDR_LENGTH;
23905 
23906 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23907 
23908 	while (pld_ptr < mp->b_wptr) {
23909 		ipha_t		*ipha;
23910 		uint16_t	offset_and_flags;
23911 		uint16_t	ip_len;
23912 		int		error;
23913 
23914 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23915 		ipha = (ipha_t *)(hdr_ptr + wroff);
23916 		ASSERT(OK_32PTR(ipha));
23917 		*ipha = *ipha_orig;
23918 
23919 		if (ip_data_end - offset > len) {
23920 			offset_and_flags = IPH_MF;
23921 		} else {
23922 			/*
23923 			 * Last frag. Set len to the length of this last piece.
23924 			 */
23925 			len = ip_data_end - offset;
23926 			/* A frag of a frag might have IPH_MF non-zero */
23927 			offset_and_flags =
23928 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23929 			    IPH_MF;
23930 		}
23931 		offset_and_flags |= (uint16_t)(offset >> 3);
23932 		offset_and_flags |= (uint16_t)frag_flag;
23933 		/* Store the offset and flags in the IP header. */
23934 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23935 
23936 		/* Store the length in the IP header. */
23937 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23938 		ipha->ipha_length = htons(ip_len);
23939 
23940 		/*
23941 		 * Set the IP header checksum.  Note that mp is just
23942 		 * the header, so this is easy to pass to ip_csum.
23943 		 */
23944 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23945 
23946 		/*
23947 		 * Record offset and size of header and data of the next packet
23948 		 * in the multidata message.
23949 		 */
23950 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23951 		PDESC_PLD_INIT(&pdi);
23952 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23953 		ASSERT(i1 > 0);
23954 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23955 		if (i1 == len) {
23956 			pld_ptr += len;
23957 		} else {
23958 			i1 = len - i1;
23959 			mp = mp->b_cont;
23960 			ASSERT(mp != NULL);
23961 			ASSERT(MBLKL(mp) >= i1);
23962 			/*
23963 			 * Attach the next payload message block to the
23964 			 * multidata message.
23965 			 */
23966 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23967 				goto pbuf_panic;
23968 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23969 			pld_ptr = mp->b_rptr + i1;
23970 		}
23971 
23972 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23973 		    KM_NOSLEEP)) == NULL) {
23974 			/*
23975 			 * Any failure other than ENOMEM indicates that we
23976 			 * have passed in invalid pdesc info or parameters
23977 			 * to mmd_addpdesc, which must not happen.
23978 			 *
23979 			 * EINVAL is a result of failure on boundary checks
23980 			 * against the pdesc info contents.  It should not
23981 			 * happen, and we panic because either there's
23982 			 * horrible heap corruption, and/or programming
23983 			 * mistake.
23984 			 */
23985 			if (error != ENOMEM) {
23986 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23987 				    "pdesc logic error detected for "
23988 				    "mmd %p pinfo %p (%d)\n",
23989 				    (void *)mmd, (void *)&pdi, error);
23990 				/* NOTREACHED */
23991 			}
23992 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23993 			/* Free unattached payload message blocks as well */
23994 			md_mp->b_cont = mp->b_cont;
23995 			goto free_mmd;
23996 		}
23997 
23998 		/* Advance fragment offset. */
23999 		offset += len;
24000 
24001 		/* Advance to location for next header in the buffer. */
24002 		hdr_ptr += hdr_chunk_len;
24003 
24004 		/* Did we reach the next payload message block? */
24005 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24006 			mp = mp->b_cont;
24007 			/*
24008 			 * Attach the next message block with payload
24009 			 * data to the multidata message.
24010 			 */
24011 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24012 				goto pbuf_panic;
24013 			pld_ptr = mp->b_rptr;
24014 		}
24015 	}
24016 
24017 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24018 	ASSERT(mp->b_wptr == pld_ptr);
24019 
24020 	/* Update IP statistics */
24021 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24022 
24023 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24024 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24025 
24026 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24027 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24028 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24029 
24030 	if (pkt_type == OB_PKT) {
24031 		ire->ire_ob_pkt_count += pkts;
24032 		if (ire->ire_ipif != NULL)
24033 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24034 	} else {
24035 		/* The type is IB_PKT in the forwarding path. */
24036 		ire->ire_ib_pkt_count += pkts;
24037 		ASSERT(!IRE_IS_LOCAL(ire));
24038 		if (ire->ire_type & IRE_BROADCAST) {
24039 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24040 		} else {
24041 			UPDATE_MIB(ill->ill_ip_mib,
24042 			    ipIfStatsHCOutForwDatagrams, pkts);
24043 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24044 		}
24045 	}
24046 	ire->ire_last_used_time = lbolt;
24047 	/* Send it down */
24048 	putnext(ire->ire_stq, md_mp);
24049 	return;
24050 
24051 pbuf_panic:
24052 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24053 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24054 	    pbuf_idx);
24055 	/* NOTREACHED */
24056 }
24057 
24058 /*
24059  * Outbound IP fragmentation routine.
24060  *
24061  * NOTE : This routine does not ire_refrele the ire that is passed in
24062  * as the argument.
24063  */
24064 static void
24065 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24066     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24067 {
24068 	int		i1;
24069 	mblk_t		*ll_hdr_mp;
24070 	int 		ll_hdr_len;
24071 	int		hdr_len;
24072 	mblk_t		*hdr_mp;
24073 	ipha_t		*ipha;
24074 	int		ip_data_end;
24075 	int		len;
24076 	mblk_t		*mp = mp_orig, *mp1;
24077 	int		offset;
24078 	queue_t		*q;
24079 	uint32_t	v_hlen_tos_len;
24080 	mblk_t		*first_mp;
24081 	boolean_t	mctl_present;
24082 	ill_t		*ill;
24083 	ill_t		*out_ill;
24084 	mblk_t		*xmit_mp;
24085 	mblk_t		*carve_mp;
24086 	ire_t		*ire1 = NULL;
24087 	ire_t		*save_ire = NULL;
24088 	mblk_t  	*next_mp = NULL;
24089 	boolean_t	last_frag = B_FALSE;
24090 	boolean_t	multirt_send = B_FALSE;
24091 	ire_t		*first_ire = NULL;
24092 	irb_t		*irb = NULL;
24093 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24094 
24095 	ill = ire_to_ill(ire);
24096 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24097 
24098 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24099 
24100 	if (max_frag == 0) {
24101 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24102 		    " -  dropping packet\n"));
24103 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24104 		freemsg(mp);
24105 		return;
24106 	}
24107 
24108 	/*
24109 	 * IPsec does not allow hw accelerated packets to be fragmented
24110 	 * This check is made in ip_wput_ipsec_out prior to coming here
24111 	 * via ip_wput_ire_fragmentit.
24112 	 *
24113 	 * If at this point we have an ire whose ARP request has not
24114 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24115 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24116 	 * This packet and all fragmentable packets for this ire will
24117 	 * continue to get dropped while ire_nce->nce_state remains in
24118 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24119 	 * ND_REACHABLE, all subsquent large packets for this ire will
24120 	 * get fragemented and sent out by this function.
24121 	 */
24122 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24123 		/* If nce_state is ND_INITIAL, trigger ARP query */
24124 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24125 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24126 		    " -  dropping packet\n"));
24127 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24128 		freemsg(mp);
24129 		return;
24130 	}
24131 
24132 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24133 	    "ip_wput_frag_start:");
24134 
24135 	if (mp->b_datap->db_type == M_CTL) {
24136 		first_mp = mp;
24137 		mp_orig = mp = mp->b_cont;
24138 		mctl_present = B_TRUE;
24139 	} else {
24140 		first_mp = mp;
24141 		mctl_present = B_FALSE;
24142 	}
24143 
24144 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24145 	ipha = (ipha_t *)mp->b_rptr;
24146 
24147 	/*
24148 	 * If the Don't Fragment flag is on, generate an ICMP destination
24149 	 * unreachable, fragmentation needed.
24150 	 */
24151 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24152 	if (offset & IPH_DF) {
24153 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24154 		if (is_system_labeled()) {
24155 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24156 			    ire->ire_max_frag - max_frag, AF_INET);
24157 		}
24158 		/*
24159 		 * Need to compute hdr checksum if called from ip_wput_ire.
24160 		 * Note that ip_rput_forward verifies the checksum before
24161 		 * calling this routine so in that case this is a noop.
24162 		 */
24163 		ipha->ipha_hdr_checksum = 0;
24164 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24165 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24166 		    ipst);
24167 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24168 		    "ip_wput_frag_end:(%S)",
24169 		    "don't fragment");
24170 		return;
24171 	}
24172 	/*
24173 	 * Labeled systems adjust max_frag if they add a label
24174 	 * to send the correct path mtu.  We need the real mtu since we
24175 	 * are fragmenting the packet after label adjustment.
24176 	 */
24177 	if (is_system_labeled())
24178 		max_frag = ire->ire_max_frag;
24179 	if (mctl_present)
24180 		freeb(first_mp);
24181 	/*
24182 	 * Establish the starting offset.  May not be zero if we are fragging
24183 	 * a fragment that is being forwarded.
24184 	 */
24185 	offset = offset & IPH_OFFSET;
24186 
24187 	/* TODO why is this test needed? */
24188 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24189 	if (((max_frag - LENGTH) & ~7) < 8) {
24190 		/* TODO: notify ulp somehow */
24191 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24192 		freemsg(mp);
24193 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24194 		    "ip_wput_frag_end:(%S)",
24195 		    "len < 8");
24196 		return;
24197 	}
24198 
24199 	hdr_len = (V_HLEN & 0xF) << 2;
24200 
24201 	ipha->ipha_hdr_checksum = 0;
24202 
24203 	/*
24204 	 * Establish the number of bytes maximum per frag, after putting
24205 	 * in the header.
24206 	 */
24207 	len = (max_frag - hdr_len) & ~7;
24208 
24209 	/* Check if we can use MDT to send out the frags. */
24210 	ASSERT(!IRE_IS_LOCAL(ire));
24211 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24212 	    ipst->ips_ip_multidata_outbound &&
24213 	    !(ire->ire_flags & RTF_MULTIRT) &&
24214 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24215 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24216 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24217 		ASSERT(ill->ill_mdt_capab != NULL);
24218 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24219 			/*
24220 			 * If MDT has been previously turned off in the past,
24221 			 * and we currently can do MDT (due to IPQoS policy
24222 			 * removal, etc.) then enable it for this interface.
24223 			 */
24224 			ill->ill_mdt_capab->ill_mdt_on = 1;
24225 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24226 			    ill->ill_name));
24227 		}
24228 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24229 		    offset);
24230 		return;
24231 	}
24232 
24233 	/* Get a copy of the header for the trailing frags */
24234 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24235 	if (!hdr_mp) {
24236 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24237 		freemsg(mp);
24238 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24239 		    "ip_wput_frag_end:(%S)",
24240 		    "couldn't copy hdr");
24241 		return;
24242 	}
24243 	if (DB_CRED(mp) != NULL)
24244 		mblk_setcred(hdr_mp, DB_CRED(mp));
24245 
24246 	/* Store the starting offset, with the MoreFrags flag. */
24247 	i1 = offset | IPH_MF | frag_flag;
24248 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24249 
24250 	/* Establish the ending byte offset, based on the starting offset. */
24251 	offset <<= 3;
24252 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24253 
24254 	/* Store the length of the first fragment in the IP header. */
24255 	i1 = len + hdr_len;
24256 	ASSERT(i1 <= IP_MAXPACKET);
24257 	ipha->ipha_length = htons((uint16_t)i1);
24258 
24259 	/*
24260 	 * Compute the IP header checksum for the first frag.  We have to
24261 	 * watch out that we stop at the end of the header.
24262 	 */
24263 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24264 
24265 	/*
24266 	 * Now carve off the first frag.  Note that this will include the
24267 	 * original IP header.
24268 	 */
24269 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24270 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24271 		freeb(hdr_mp);
24272 		freemsg(mp_orig);
24273 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24274 		    "ip_wput_frag_end:(%S)",
24275 		    "couldn't carve first");
24276 		return;
24277 	}
24278 
24279 	/*
24280 	 * Multirouting case. Each fragment is replicated
24281 	 * via all non-condemned RTF_MULTIRT routes
24282 	 * currently resolved.
24283 	 * We ensure that first_ire is the first RTF_MULTIRT
24284 	 * ire in the bucket.
24285 	 */
24286 	if (ire->ire_flags & RTF_MULTIRT) {
24287 		irb = ire->ire_bucket;
24288 		ASSERT(irb != NULL);
24289 
24290 		multirt_send = B_TRUE;
24291 
24292 		/* Make sure we do not omit any multiroute ire. */
24293 		IRB_REFHOLD(irb);
24294 		for (first_ire = irb->irb_ire;
24295 		    first_ire != NULL;
24296 		    first_ire = first_ire->ire_next) {
24297 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24298 			    (first_ire->ire_addr == ire->ire_addr) &&
24299 			    !(first_ire->ire_marks &
24300 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24301 				break;
24302 			}
24303 		}
24304 
24305 		if (first_ire != NULL) {
24306 			if (first_ire != ire) {
24307 				IRE_REFHOLD(first_ire);
24308 				/*
24309 				 * Do not release the ire passed in
24310 				 * as the argument.
24311 				 */
24312 				ire = first_ire;
24313 			} else {
24314 				first_ire = NULL;
24315 			}
24316 		}
24317 		IRB_REFRELE(irb);
24318 
24319 		/*
24320 		 * Save the first ire; we will need to restore it
24321 		 * for the trailing frags.
24322 		 * We REFHOLD save_ire, as each iterated ire will be
24323 		 * REFRELEd.
24324 		 */
24325 		save_ire = ire;
24326 		IRE_REFHOLD(save_ire);
24327 	}
24328 
24329 	/*
24330 	 * First fragment emission loop.
24331 	 * In most cases, the emission loop below is entered only
24332 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24333 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24334 	 * bucket, and send the fragment through all crossed
24335 	 * RTF_MULTIRT routes.
24336 	 */
24337 	do {
24338 		if (ire->ire_flags & RTF_MULTIRT) {
24339 			/*
24340 			 * We are in a multiple send case, need to get
24341 			 * the next ire and make a copy of the packet.
24342 			 * ire1 holds here the next ire to process in the
24343 			 * bucket. If multirouting is expected,
24344 			 * any non-RTF_MULTIRT ire that has the
24345 			 * right destination address is ignored.
24346 			 *
24347 			 * We have to take into account the MTU of
24348 			 * each walked ire. max_frag is set by the
24349 			 * the caller and generally refers to
24350 			 * the primary ire entry. Here we ensure that
24351 			 * no route with a lower MTU will be used, as
24352 			 * fragments are carved once for all ires,
24353 			 * then replicated.
24354 			 */
24355 			ASSERT(irb != NULL);
24356 			IRB_REFHOLD(irb);
24357 			for (ire1 = ire->ire_next;
24358 			    ire1 != NULL;
24359 			    ire1 = ire1->ire_next) {
24360 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24361 					continue;
24362 				if (ire1->ire_addr != ire->ire_addr)
24363 					continue;
24364 				if (ire1->ire_marks &
24365 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24366 					continue;
24367 				/*
24368 				 * Ensure we do not exceed the MTU
24369 				 * of the next route.
24370 				 */
24371 				if (ire1->ire_max_frag < max_frag) {
24372 					ip_multirt_bad_mtu(ire1, max_frag);
24373 					continue;
24374 				}
24375 
24376 				/* Got one. */
24377 				IRE_REFHOLD(ire1);
24378 				break;
24379 			}
24380 			IRB_REFRELE(irb);
24381 
24382 			if (ire1 != NULL) {
24383 				next_mp = copyb(mp);
24384 				if ((next_mp == NULL) ||
24385 				    ((mp->b_cont != NULL) &&
24386 				    ((next_mp->b_cont =
24387 				    dupmsg(mp->b_cont)) == NULL))) {
24388 					freemsg(next_mp);
24389 					next_mp = NULL;
24390 					ire_refrele(ire1);
24391 					ire1 = NULL;
24392 				}
24393 			}
24394 
24395 			/* Last multiroute ire; don't loop anymore. */
24396 			if (ire1 == NULL) {
24397 				multirt_send = B_FALSE;
24398 			}
24399 		}
24400 
24401 		ll_hdr_len = 0;
24402 		LOCK_IRE_FP_MP(ire);
24403 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24404 		if (ll_hdr_mp != NULL) {
24405 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24406 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24407 		} else {
24408 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24409 		}
24410 
24411 		/* If there is a transmit header, get a copy for this frag. */
24412 		/*
24413 		 * TODO: should check db_ref before calling ip_carve_mp since
24414 		 * it might give us a dup.
24415 		 */
24416 		if (!ll_hdr_mp) {
24417 			/* No xmit header. */
24418 			xmit_mp = mp;
24419 
24420 		/* We have a link-layer header that can fit in our mblk. */
24421 		} else if (mp->b_datap->db_ref == 1 &&
24422 		    ll_hdr_len != 0 &&
24423 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24424 			/* M_DATA fastpath */
24425 			mp->b_rptr -= ll_hdr_len;
24426 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24427 			xmit_mp = mp;
24428 
24429 		/* Corner case if copyb has failed */
24430 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24431 			UNLOCK_IRE_FP_MP(ire);
24432 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24433 			freeb(hdr_mp);
24434 			freemsg(mp);
24435 			freemsg(mp_orig);
24436 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24437 			    "ip_wput_frag_end:(%S)",
24438 			    "discard");
24439 
24440 			if (multirt_send) {
24441 				ASSERT(ire1);
24442 				ASSERT(next_mp);
24443 
24444 				freemsg(next_mp);
24445 				ire_refrele(ire1);
24446 			}
24447 			if (save_ire != NULL)
24448 				IRE_REFRELE(save_ire);
24449 
24450 			if (first_ire != NULL)
24451 				ire_refrele(first_ire);
24452 			return;
24453 
24454 		/*
24455 		 * Case of res_mp OR the fastpath mp can't fit
24456 		 * in the mblk
24457 		 */
24458 		} else {
24459 			xmit_mp->b_cont = mp;
24460 			if (DB_CRED(mp) != NULL)
24461 				mblk_setcred(xmit_mp, DB_CRED(mp));
24462 			/*
24463 			 * Get priority marking, if any.
24464 			 * We propagate the CoS marking from the
24465 			 * original packet that went to QoS processing
24466 			 * in ip_wput_ire to the newly carved mp.
24467 			 */
24468 			if (DB_TYPE(xmit_mp) == M_DATA)
24469 				xmit_mp->b_band = mp->b_band;
24470 		}
24471 		UNLOCK_IRE_FP_MP(ire);
24472 
24473 		q = ire->ire_stq;
24474 		out_ill = (ill_t *)q->q_ptr;
24475 
24476 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24477 
24478 		DTRACE_PROBE4(ip4__physical__out__start,
24479 		    ill_t *, NULL, ill_t *, out_ill,
24480 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24481 
24482 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24483 		    ipst->ips_ipv4firewall_physical_out,
24484 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24485 
24486 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24487 
24488 		if (xmit_mp != NULL) {
24489 			putnext(q, xmit_mp);
24490 
24491 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24492 			UPDATE_MIB(out_ill->ill_ip_mib,
24493 			    ipIfStatsHCOutOctets, i1);
24494 
24495 			if (pkt_type != OB_PKT) {
24496 				/*
24497 				 * Update the packet count and MIB stats
24498 				 * of trailing RTF_MULTIRT ires.
24499 				 */
24500 				UPDATE_OB_PKT_COUNT(ire);
24501 				BUMP_MIB(out_ill->ill_ip_mib,
24502 				    ipIfStatsOutFragReqds);
24503 			}
24504 		}
24505 
24506 		if (multirt_send) {
24507 			/*
24508 			 * We are in a multiple send case; look for
24509 			 * the next ire and re-enter the loop.
24510 			 */
24511 			ASSERT(ire1);
24512 			ASSERT(next_mp);
24513 			/* REFRELE the current ire before looping */
24514 			ire_refrele(ire);
24515 			ire = ire1;
24516 			ire1 = NULL;
24517 			mp = next_mp;
24518 			next_mp = NULL;
24519 		}
24520 	} while (multirt_send);
24521 
24522 	ASSERT(ire1 == NULL);
24523 
24524 	/* Restore the original ire; we need it for the trailing frags */
24525 	if (save_ire != NULL) {
24526 		/* REFRELE the last iterated ire */
24527 		ire_refrele(ire);
24528 		/* save_ire has been REFHOLDed */
24529 		ire = save_ire;
24530 		save_ire = NULL;
24531 		q = ire->ire_stq;
24532 	}
24533 
24534 	if (pkt_type == OB_PKT) {
24535 		UPDATE_OB_PKT_COUNT(ire);
24536 	} else {
24537 		out_ill = (ill_t *)q->q_ptr;
24538 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24539 		UPDATE_IB_PKT_COUNT(ire);
24540 	}
24541 
24542 	/* Advance the offset to the second frag starting point. */
24543 	offset += len;
24544 	/*
24545 	 * Update hdr_len from the copied header - there might be less options
24546 	 * in the later fragments.
24547 	 */
24548 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24549 	/* Loop until done. */
24550 	for (;;) {
24551 		uint16_t	offset_and_flags;
24552 		uint16_t	ip_len;
24553 
24554 		if (ip_data_end - offset > len) {
24555 			/*
24556 			 * Carve off the appropriate amount from the original
24557 			 * datagram.
24558 			 */
24559 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24560 				mp = NULL;
24561 				break;
24562 			}
24563 			/*
24564 			 * More frags after this one.  Get another copy
24565 			 * of the header.
24566 			 */
24567 			if (carve_mp->b_datap->db_ref == 1 &&
24568 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24569 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24570 				/* Inline IP header */
24571 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24572 				    hdr_mp->b_rptr;
24573 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24574 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24575 				mp = carve_mp;
24576 			} else {
24577 				if (!(mp = copyb(hdr_mp))) {
24578 					freemsg(carve_mp);
24579 					break;
24580 				}
24581 				/* Get priority marking, if any. */
24582 				mp->b_band = carve_mp->b_band;
24583 				mp->b_cont = carve_mp;
24584 			}
24585 			ipha = (ipha_t *)mp->b_rptr;
24586 			offset_and_flags = IPH_MF;
24587 		} else {
24588 			/*
24589 			 * Last frag.  Consume the header. Set len to
24590 			 * the length of this last piece.
24591 			 */
24592 			len = ip_data_end - offset;
24593 
24594 			/*
24595 			 * Carve off the appropriate amount from the original
24596 			 * datagram.
24597 			 */
24598 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24599 				mp = NULL;
24600 				break;
24601 			}
24602 			if (carve_mp->b_datap->db_ref == 1 &&
24603 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24604 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24605 				/* Inline IP header */
24606 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24607 				    hdr_mp->b_rptr;
24608 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24609 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24610 				mp = carve_mp;
24611 				freeb(hdr_mp);
24612 				hdr_mp = mp;
24613 			} else {
24614 				mp = hdr_mp;
24615 				/* Get priority marking, if any. */
24616 				mp->b_band = carve_mp->b_band;
24617 				mp->b_cont = carve_mp;
24618 			}
24619 			ipha = (ipha_t *)mp->b_rptr;
24620 			/* A frag of a frag might have IPH_MF non-zero */
24621 			offset_and_flags =
24622 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24623 			    IPH_MF;
24624 		}
24625 		offset_and_flags |= (uint16_t)(offset >> 3);
24626 		offset_and_flags |= (uint16_t)frag_flag;
24627 		/* Store the offset and flags in the IP header. */
24628 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24629 
24630 		/* Store the length in the IP header. */
24631 		ip_len = (uint16_t)(len + hdr_len);
24632 		ipha->ipha_length = htons(ip_len);
24633 
24634 		/*
24635 		 * Set the IP header checksum.	Note that mp is just
24636 		 * the header, so this is easy to pass to ip_csum.
24637 		 */
24638 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24639 
24640 		/* Attach a transmit header, if any, and ship it. */
24641 		if (pkt_type == OB_PKT) {
24642 			UPDATE_OB_PKT_COUNT(ire);
24643 		} else {
24644 			out_ill = (ill_t *)q->q_ptr;
24645 			BUMP_MIB(out_ill->ill_ip_mib,
24646 			    ipIfStatsHCOutForwDatagrams);
24647 			UPDATE_IB_PKT_COUNT(ire);
24648 		}
24649 
24650 		if (ire->ire_flags & RTF_MULTIRT) {
24651 			irb = ire->ire_bucket;
24652 			ASSERT(irb != NULL);
24653 
24654 			multirt_send = B_TRUE;
24655 
24656 			/*
24657 			 * Save the original ire; we will need to restore it
24658 			 * for the tailing frags.
24659 			 */
24660 			save_ire = ire;
24661 			IRE_REFHOLD(save_ire);
24662 		}
24663 		/*
24664 		 * Emission loop for this fragment, similar
24665 		 * to what is done for the first fragment.
24666 		 */
24667 		do {
24668 			if (multirt_send) {
24669 				/*
24670 				 * We are in a multiple send case, need to get
24671 				 * the next ire and make a copy of the packet.
24672 				 */
24673 				ASSERT(irb != NULL);
24674 				IRB_REFHOLD(irb);
24675 				for (ire1 = ire->ire_next;
24676 				    ire1 != NULL;
24677 				    ire1 = ire1->ire_next) {
24678 					if (!(ire1->ire_flags & RTF_MULTIRT))
24679 						continue;
24680 					if (ire1->ire_addr != ire->ire_addr)
24681 						continue;
24682 					if (ire1->ire_marks &
24683 					    (IRE_MARK_CONDEMNED|
24684 					    IRE_MARK_HIDDEN)) {
24685 						continue;
24686 					}
24687 					/*
24688 					 * Ensure we do not exceed the MTU
24689 					 * of the next route.
24690 					 */
24691 					if (ire1->ire_max_frag < max_frag) {
24692 						ip_multirt_bad_mtu(ire1,
24693 						    max_frag);
24694 						continue;
24695 					}
24696 
24697 					/* Got one. */
24698 					IRE_REFHOLD(ire1);
24699 					break;
24700 				}
24701 				IRB_REFRELE(irb);
24702 
24703 				if (ire1 != NULL) {
24704 					next_mp = copyb(mp);
24705 					if ((next_mp == NULL) ||
24706 					    ((mp->b_cont != NULL) &&
24707 					    ((next_mp->b_cont =
24708 					    dupmsg(mp->b_cont)) == NULL))) {
24709 						freemsg(next_mp);
24710 						next_mp = NULL;
24711 						ire_refrele(ire1);
24712 						ire1 = NULL;
24713 					}
24714 				}
24715 
24716 				/* Last multiroute ire; don't loop anymore. */
24717 				if (ire1 == NULL) {
24718 					multirt_send = B_FALSE;
24719 				}
24720 			}
24721 
24722 			/* Update transmit header */
24723 			ll_hdr_len = 0;
24724 			LOCK_IRE_FP_MP(ire);
24725 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24726 			if (ll_hdr_mp != NULL) {
24727 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24728 				ll_hdr_len = MBLKL(ll_hdr_mp);
24729 			} else {
24730 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24731 			}
24732 
24733 			if (!ll_hdr_mp) {
24734 				xmit_mp = mp;
24735 
24736 			/*
24737 			 * We have link-layer header that can fit in
24738 			 * our mblk.
24739 			 */
24740 			} else if (mp->b_datap->db_ref == 1 &&
24741 			    ll_hdr_len != 0 &&
24742 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24743 				/* M_DATA fastpath */
24744 				mp->b_rptr -= ll_hdr_len;
24745 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24746 				    ll_hdr_len);
24747 				xmit_mp = mp;
24748 
24749 			/*
24750 			 * Case of res_mp OR the fastpath mp can't fit
24751 			 * in the mblk
24752 			 */
24753 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24754 				xmit_mp->b_cont = mp;
24755 				if (DB_CRED(mp) != NULL)
24756 					mblk_setcred(xmit_mp, DB_CRED(mp));
24757 				/* Get priority marking, if any. */
24758 				if (DB_TYPE(xmit_mp) == M_DATA)
24759 					xmit_mp->b_band = mp->b_band;
24760 
24761 			/* Corner case if copyb failed */
24762 			} else {
24763 				/*
24764 				 * Exit both the replication and
24765 				 * fragmentation loops.
24766 				 */
24767 				UNLOCK_IRE_FP_MP(ire);
24768 				goto drop_pkt;
24769 			}
24770 			UNLOCK_IRE_FP_MP(ire);
24771 
24772 			mp1 = mp;
24773 			out_ill = (ill_t *)q->q_ptr;
24774 
24775 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24776 
24777 			DTRACE_PROBE4(ip4__physical__out__start,
24778 			    ill_t *, NULL, ill_t *, out_ill,
24779 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24780 
24781 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24782 			    ipst->ips_ipv4firewall_physical_out,
24783 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24784 
24785 			DTRACE_PROBE1(ip4__physical__out__end,
24786 			    mblk_t *, xmit_mp);
24787 
24788 			if (mp != mp1 && hdr_mp == mp1)
24789 				hdr_mp = mp;
24790 			if (mp != mp1 && mp_orig == mp1)
24791 				mp_orig = mp;
24792 
24793 			if (xmit_mp != NULL) {
24794 				putnext(q, xmit_mp);
24795 
24796 				BUMP_MIB(out_ill->ill_ip_mib,
24797 				    ipIfStatsHCOutTransmits);
24798 				UPDATE_MIB(out_ill->ill_ip_mib,
24799 				    ipIfStatsHCOutOctets, ip_len);
24800 
24801 				if (pkt_type != OB_PKT) {
24802 					/*
24803 					 * Update the packet count of trailing
24804 					 * RTF_MULTIRT ires.
24805 					 */
24806 					UPDATE_OB_PKT_COUNT(ire);
24807 				}
24808 			}
24809 
24810 			/* All done if we just consumed the hdr_mp. */
24811 			if (mp == hdr_mp) {
24812 				last_frag = B_TRUE;
24813 				BUMP_MIB(out_ill->ill_ip_mib,
24814 				    ipIfStatsOutFragOKs);
24815 			}
24816 
24817 			if (multirt_send) {
24818 				/*
24819 				 * We are in a multiple send case; look for
24820 				 * the next ire and re-enter the loop.
24821 				 */
24822 				ASSERT(ire1);
24823 				ASSERT(next_mp);
24824 				/* REFRELE the current ire before looping */
24825 				ire_refrele(ire);
24826 				ire = ire1;
24827 				ire1 = NULL;
24828 				q = ire->ire_stq;
24829 				mp = next_mp;
24830 				next_mp = NULL;
24831 			}
24832 		} while (multirt_send);
24833 		/*
24834 		 * Restore the original ire; we need it for the
24835 		 * trailing frags
24836 		 */
24837 		if (save_ire != NULL) {
24838 			ASSERT(ire1 == NULL);
24839 			/* REFRELE the last iterated ire */
24840 			ire_refrele(ire);
24841 			/* save_ire has been REFHOLDed */
24842 			ire = save_ire;
24843 			q = ire->ire_stq;
24844 			save_ire = NULL;
24845 		}
24846 
24847 		if (last_frag) {
24848 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24849 			    "ip_wput_frag_end:(%S)",
24850 			    "consumed hdr_mp");
24851 
24852 			if (first_ire != NULL)
24853 				ire_refrele(first_ire);
24854 			return;
24855 		}
24856 		/* Otherwise, advance and loop. */
24857 		offset += len;
24858 	}
24859 
24860 drop_pkt:
24861 	/* Clean up following allocation failure. */
24862 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24863 	freemsg(mp);
24864 	if (mp != hdr_mp)
24865 		freeb(hdr_mp);
24866 	if (mp != mp_orig)
24867 		freemsg(mp_orig);
24868 
24869 	if (save_ire != NULL)
24870 		IRE_REFRELE(save_ire);
24871 	if (first_ire != NULL)
24872 		ire_refrele(first_ire);
24873 
24874 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24875 	    "ip_wput_frag_end:(%S)",
24876 	    "end--alloc failure");
24877 }
24878 
24879 /*
24880  * Copy the header plus those options which have the copy bit set
24881  */
24882 static mblk_t *
24883 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24884 {
24885 	mblk_t	*mp;
24886 	uchar_t	*up;
24887 
24888 	/*
24889 	 * Quick check if we need to look for options without the copy bit
24890 	 * set
24891 	 */
24892 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24893 	if (!mp)
24894 		return (mp);
24895 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24896 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24897 		bcopy(rptr, mp->b_rptr, hdr_len);
24898 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24899 		return (mp);
24900 	}
24901 	up  = mp->b_rptr;
24902 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24903 	up += IP_SIMPLE_HDR_LENGTH;
24904 	rptr += IP_SIMPLE_HDR_LENGTH;
24905 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24906 	while (hdr_len > 0) {
24907 		uint32_t optval;
24908 		uint32_t optlen;
24909 
24910 		optval = *rptr;
24911 		if (optval == IPOPT_EOL)
24912 			break;
24913 		if (optval == IPOPT_NOP)
24914 			optlen = 1;
24915 		else
24916 			optlen = rptr[1];
24917 		if (optval & IPOPT_COPY) {
24918 			bcopy(rptr, up, optlen);
24919 			up += optlen;
24920 		}
24921 		rptr += optlen;
24922 		hdr_len -= optlen;
24923 	}
24924 	/*
24925 	 * Make sure that we drop an even number of words by filling
24926 	 * with EOL to the next word boundary.
24927 	 */
24928 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24929 	    hdr_len & 0x3; hdr_len++)
24930 		*up++ = IPOPT_EOL;
24931 	mp->b_wptr = up;
24932 	/* Update header length */
24933 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24934 	return (mp);
24935 }
24936 
24937 /*
24938  * Delivery to local recipients including fanout to multiple recipients.
24939  * Does not do checksumming of UDP/TCP.
24940  * Note: q should be the read side queue for either the ill or conn.
24941  * Note: rq should be the read side q for the lower (ill) stream.
24942  * We don't send packets to IPPF processing, thus the last argument
24943  * to all the fanout calls are B_FALSE.
24944  */
24945 void
24946 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24947     int fanout_flags, zoneid_t zoneid)
24948 {
24949 	uint32_t	protocol;
24950 	mblk_t		*first_mp;
24951 	boolean_t	mctl_present;
24952 	int		ire_type;
24953 #define	rptr	((uchar_t *)ipha)
24954 	ip_stack_t	*ipst = ill->ill_ipst;
24955 
24956 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24957 	    "ip_wput_local_start: q %p", q);
24958 
24959 	if (ire != NULL) {
24960 		ire_type = ire->ire_type;
24961 	} else {
24962 		/*
24963 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24964 		 * packet is not multicast, we can't tell the ire type.
24965 		 */
24966 		ASSERT(CLASSD(ipha->ipha_dst));
24967 		ire_type = IRE_BROADCAST;
24968 	}
24969 
24970 	first_mp = mp;
24971 	if (first_mp->b_datap->db_type == M_CTL) {
24972 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24973 		if (!io->ipsec_out_secure) {
24974 			/*
24975 			 * This ipsec_out_t was allocated in ip_wput
24976 			 * for multicast packets to store the ill_index.
24977 			 * As this is being delivered locally, we don't
24978 			 * need this anymore.
24979 			 */
24980 			mp = first_mp->b_cont;
24981 			freeb(first_mp);
24982 			first_mp = mp;
24983 			mctl_present = B_FALSE;
24984 		} else {
24985 			/*
24986 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24987 			 * security properties for the looped-back packet.
24988 			 */
24989 			mctl_present = B_TRUE;
24990 			mp = first_mp->b_cont;
24991 			ASSERT(mp != NULL);
24992 			ipsec_out_to_in(first_mp);
24993 		}
24994 	} else {
24995 		mctl_present = B_FALSE;
24996 	}
24997 
24998 	DTRACE_PROBE4(ip4__loopback__in__start,
24999 	    ill_t *, ill, ill_t *, NULL,
25000 	    ipha_t *, ipha, mblk_t *, first_mp);
25001 
25002 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25003 	    ipst->ips_ipv4firewall_loopback_in,
25004 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25005 
25006 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25007 
25008 	if (first_mp == NULL)
25009 		return;
25010 
25011 	ipst->ips_loopback_packets++;
25012 
25013 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25014 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25015 	if (!IS_SIMPLE_IPH(ipha)) {
25016 		ip_wput_local_options(ipha, ipst);
25017 	}
25018 
25019 	protocol = ipha->ipha_protocol;
25020 	switch (protocol) {
25021 	case IPPROTO_ICMP: {
25022 		ire_t		*ire_zone;
25023 		ilm_t		*ilm;
25024 		mblk_t		*mp1;
25025 		zoneid_t	last_zoneid;
25026 
25027 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25028 			ASSERT(ire_type == IRE_BROADCAST);
25029 			/*
25030 			 * In the multicast case, applications may have joined
25031 			 * the group from different zones, so we need to deliver
25032 			 * the packet to each of them. Loop through the
25033 			 * multicast memberships structures (ilm) on the receive
25034 			 * ill and send a copy of the packet up each matching
25035 			 * one. However, we don't do this for multicasts sent on
25036 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25037 			 * they must stay in the sender's zone.
25038 			 *
25039 			 * ilm_add_v6() ensures that ilms in the same zone are
25040 			 * contiguous in the ill_ilm list. We use this property
25041 			 * to avoid sending duplicates needed when two
25042 			 * applications in the same zone join the same group on
25043 			 * different logical interfaces: we ignore the ilm if
25044 			 * it's zoneid is the same as the last matching one.
25045 			 * In addition, the sending of the packet for
25046 			 * ire_zoneid is delayed until all of the other ilms
25047 			 * have been exhausted.
25048 			 */
25049 			last_zoneid = -1;
25050 			ILM_WALKER_HOLD(ill);
25051 			for (ilm = ill->ill_ilm; ilm != NULL;
25052 			    ilm = ilm->ilm_next) {
25053 				if ((ilm->ilm_flags & ILM_DELETED) ||
25054 				    ipha->ipha_dst != ilm->ilm_addr ||
25055 				    ilm->ilm_zoneid == last_zoneid ||
25056 				    ilm->ilm_zoneid == zoneid ||
25057 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25058 					continue;
25059 				mp1 = ip_copymsg(first_mp);
25060 				if (mp1 == NULL)
25061 					continue;
25062 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25063 				    mctl_present, B_FALSE, ill,
25064 				    ilm->ilm_zoneid);
25065 				last_zoneid = ilm->ilm_zoneid;
25066 			}
25067 			ILM_WALKER_RELE(ill);
25068 			/*
25069 			 * Loopback case: the sending endpoint has
25070 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25071 			 * dispatch the multicast packet to the sending zone.
25072 			 */
25073 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25074 				freemsg(first_mp);
25075 				return;
25076 			}
25077 		} else if (ire_type == IRE_BROADCAST) {
25078 			/*
25079 			 * In the broadcast case, there may be many zones
25080 			 * which need a copy of the packet delivered to them.
25081 			 * There is one IRE_BROADCAST per broadcast address
25082 			 * and per zone; we walk those using a helper function.
25083 			 * In addition, the sending of the packet for zoneid is
25084 			 * delayed until all of the other ires have been
25085 			 * processed.
25086 			 */
25087 			IRB_REFHOLD(ire->ire_bucket);
25088 			ire_zone = NULL;
25089 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25090 			    ire)) != NULL) {
25091 				mp1 = ip_copymsg(first_mp);
25092 				if (mp1 == NULL)
25093 					continue;
25094 
25095 				UPDATE_IB_PKT_COUNT(ire_zone);
25096 				ire_zone->ire_last_used_time = lbolt;
25097 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25098 				    mctl_present, B_FALSE, ill,
25099 				    ire_zone->ire_zoneid);
25100 			}
25101 			IRB_REFRELE(ire->ire_bucket);
25102 		}
25103 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25104 		    0, mctl_present, B_FALSE, ill, zoneid);
25105 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25106 		    "ip_wput_local_end: q %p (%S)",
25107 		    q, "icmp");
25108 		return;
25109 	}
25110 	case IPPROTO_IGMP:
25111 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25112 			/* Bad packet - discarded by igmp_input */
25113 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25114 			    "ip_wput_local_end: q %p (%S)",
25115 			    q, "igmp_input--bad packet");
25116 			if (mctl_present)
25117 				freeb(first_mp);
25118 			return;
25119 		}
25120 		/*
25121 		 * igmp_input() may have returned the pulled up message.
25122 		 * So first_mp and ipha need to be reinitialized.
25123 		 */
25124 		ipha = (ipha_t *)mp->b_rptr;
25125 		if (mctl_present)
25126 			first_mp->b_cont = mp;
25127 		else
25128 			first_mp = mp;
25129 		/* deliver to local raw users */
25130 		break;
25131 	case IPPROTO_ENCAP:
25132 		/*
25133 		 * This case is covered by either ip_fanout_proto, or by
25134 		 * the above security processing for self-tunneled packets.
25135 		 */
25136 		break;
25137 	case IPPROTO_UDP: {
25138 		uint16_t	*up;
25139 		uint32_t	ports;
25140 
25141 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25142 		    UDP_PORTS_OFFSET);
25143 		/* Force a 'valid' checksum. */
25144 		up[3] = 0;
25145 
25146 		ports = *(uint32_t *)up;
25147 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25148 		    (ire_type == IRE_BROADCAST),
25149 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25150 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25151 		    ill, zoneid);
25152 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25153 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25154 		return;
25155 	}
25156 	case IPPROTO_TCP: {
25157 
25158 		/*
25159 		 * For TCP, discard broadcast packets.
25160 		 */
25161 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25162 			freemsg(first_mp);
25163 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25164 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25165 			return;
25166 		}
25167 
25168 		if (mp->b_datap->db_type == M_DATA) {
25169 			/*
25170 			 * M_DATA mblk, so init mblk (chain) for no struio().
25171 			 */
25172 			mblk_t	*mp1 = mp;
25173 
25174 			do {
25175 				mp1->b_datap->db_struioflag = 0;
25176 			} while ((mp1 = mp1->b_cont) != NULL);
25177 		}
25178 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25179 		    <= mp->b_wptr);
25180 		ip_fanout_tcp(q, first_mp, ill, ipha,
25181 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25182 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25183 		    mctl_present, B_FALSE, zoneid);
25184 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25185 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25186 		return;
25187 	}
25188 	case IPPROTO_SCTP:
25189 	{
25190 		uint32_t	ports;
25191 
25192 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25193 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25194 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25195 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25196 		return;
25197 	}
25198 
25199 	default:
25200 		break;
25201 	}
25202 	/*
25203 	 * Find a client for some other protocol.  We give
25204 	 * copies to multiple clients, if more than one is
25205 	 * bound.
25206 	 */
25207 	ip_fanout_proto(q, first_mp, ill, ipha,
25208 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25209 	    mctl_present, B_FALSE, ill, zoneid);
25210 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25211 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25212 #undef	rptr
25213 }
25214 
25215 /*
25216  * Update any source route, record route, or timestamp options.
25217  * Check that we are at end of strict source route.
25218  * The options have been sanity checked by ip_wput_options().
25219  */
25220 static void
25221 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25222 {
25223 	ipoptp_t	opts;
25224 	uchar_t		*opt;
25225 	uint8_t		optval;
25226 	uint8_t		optlen;
25227 	ipaddr_t	dst;
25228 	uint32_t	ts;
25229 	ire_t		*ire;
25230 	timestruc_t	now;
25231 
25232 	ip2dbg(("ip_wput_local_options\n"));
25233 	for (optval = ipoptp_first(&opts, ipha);
25234 	    optval != IPOPT_EOL;
25235 	    optval = ipoptp_next(&opts)) {
25236 		opt = opts.ipoptp_cur;
25237 		optlen = opts.ipoptp_len;
25238 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25239 		switch (optval) {
25240 			uint32_t off;
25241 		case IPOPT_SSRR:
25242 		case IPOPT_LSRR:
25243 			off = opt[IPOPT_OFFSET];
25244 			off--;
25245 			if (optlen < IP_ADDR_LEN ||
25246 			    off > optlen - IP_ADDR_LEN) {
25247 				/* End of source route */
25248 				break;
25249 			}
25250 			/*
25251 			 * This will only happen if two consecutive entries
25252 			 * in the source route contains our address or if
25253 			 * it is a packet with a loose source route which
25254 			 * reaches us before consuming the whole source route
25255 			 */
25256 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25257 			if (optval == IPOPT_SSRR) {
25258 				return;
25259 			}
25260 			/*
25261 			 * Hack: instead of dropping the packet truncate the
25262 			 * source route to what has been used by filling the
25263 			 * rest with IPOPT_NOP.
25264 			 */
25265 			opt[IPOPT_OLEN] = (uint8_t)off;
25266 			while (off < optlen) {
25267 				opt[off++] = IPOPT_NOP;
25268 			}
25269 			break;
25270 		case IPOPT_RR:
25271 			off = opt[IPOPT_OFFSET];
25272 			off--;
25273 			if (optlen < IP_ADDR_LEN ||
25274 			    off > optlen - IP_ADDR_LEN) {
25275 				/* No more room - ignore */
25276 				ip1dbg((
25277 				    "ip_wput_forward_options: end of RR\n"));
25278 				break;
25279 			}
25280 			dst = htonl(INADDR_LOOPBACK);
25281 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25282 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25283 			break;
25284 		case IPOPT_TS:
25285 			/* Insert timestamp if there is romm */
25286 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25287 			case IPOPT_TS_TSONLY:
25288 				off = IPOPT_TS_TIMELEN;
25289 				break;
25290 			case IPOPT_TS_PRESPEC:
25291 			case IPOPT_TS_PRESPEC_RFC791:
25292 				/* Verify that the address matched */
25293 				off = opt[IPOPT_OFFSET] - 1;
25294 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25295 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25296 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25297 				    ipst);
25298 				if (ire == NULL) {
25299 					/* Not for us */
25300 					break;
25301 				}
25302 				ire_refrele(ire);
25303 				/* FALLTHRU */
25304 			case IPOPT_TS_TSANDADDR:
25305 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25306 				break;
25307 			default:
25308 				/*
25309 				 * ip_*put_options should have already
25310 				 * dropped this packet.
25311 				 */
25312 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25313 				    "unknown IT - bug in ip_wput_options?\n");
25314 				return;	/* Keep "lint" happy */
25315 			}
25316 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25317 				/* Increase overflow counter */
25318 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25319 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25320 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25321 				    (off << 4);
25322 				break;
25323 			}
25324 			off = opt[IPOPT_OFFSET] - 1;
25325 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25326 			case IPOPT_TS_PRESPEC:
25327 			case IPOPT_TS_PRESPEC_RFC791:
25328 			case IPOPT_TS_TSANDADDR:
25329 				dst = htonl(INADDR_LOOPBACK);
25330 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25331 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25332 				/* FALLTHRU */
25333 			case IPOPT_TS_TSONLY:
25334 				off = opt[IPOPT_OFFSET] - 1;
25335 				/* Compute # of milliseconds since midnight */
25336 				gethrestime(&now);
25337 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25338 				    now.tv_nsec / (NANOSEC / MILLISEC);
25339 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25340 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25341 				break;
25342 			}
25343 			break;
25344 		}
25345 	}
25346 }
25347 
25348 /*
25349  * Send out a multicast packet on interface ipif.
25350  * The sender does not have an conn.
25351  * Caller verifies that this isn't a PHYI_LOOPBACK.
25352  */
25353 void
25354 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25355 {
25356 	ipha_t	*ipha;
25357 	ire_t	*ire;
25358 	ipaddr_t	dst;
25359 	mblk_t		*first_mp;
25360 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25361 
25362 	/* igmp_sendpkt always allocates a ipsec_out_t */
25363 	ASSERT(mp->b_datap->db_type == M_CTL);
25364 	ASSERT(!ipif->ipif_isv6);
25365 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25366 
25367 	first_mp = mp;
25368 	mp = first_mp->b_cont;
25369 	ASSERT(mp->b_datap->db_type == M_DATA);
25370 	ipha = (ipha_t *)mp->b_rptr;
25371 
25372 	/*
25373 	 * Find an IRE which matches the destination and the outgoing
25374 	 * queue (i.e. the outgoing interface.)
25375 	 */
25376 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25377 		dst = ipif->ipif_pp_dst_addr;
25378 	else
25379 		dst = ipha->ipha_dst;
25380 	/*
25381 	 * The source address has already been initialized by the
25382 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25383 	 * be sufficient rather than MATCH_IRE_IPIF.
25384 	 *
25385 	 * This function is used for sending IGMP packets. We need
25386 	 * to make sure that we send the packet out of the interface
25387 	 * (ipif->ipif_ill) where we joined the group. This is to
25388 	 * prevent from switches doing IGMP snooping to send us multicast
25389 	 * packets for a given group on the interface we have joined.
25390 	 * If we can't find an ire, igmp_sendpkt has already initialized
25391 	 * ipsec_out_attach_if so that this will not be load spread in
25392 	 * ip_newroute_ipif.
25393 	 */
25394 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25395 	    MATCH_IRE_ILL, ipst);
25396 	if (!ire) {
25397 		/*
25398 		 * Mark this packet to make it be delivered to
25399 		 * ip_wput_ire after the new ire has been
25400 		 * created.
25401 		 */
25402 		mp->b_prev = NULL;
25403 		mp->b_next = NULL;
25404 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25405 		    zoneid, &zero_info);
25406 		return;
25407 	}
25408 
25409 	/*
25410 	 * Honor the RTF_SETSRC flag; this is the only case
25411 	 * where we force this addr whatever the current src addr is,
25412 	 * because this address is set by igmp_sendpkt(), and
25413 	 * cannot be specified by any user.
25414 	 */
25415 	if (ire->ire_flags & RTF_SETSRC) {
25416 		ipha->ipha_src = ire->ire_src_addr;
25417 	}
25418 
25419 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25420 }
25421 
25422 /*
25423  * NOTE : This function does not ire_refrele the ire argument passed in.
25424  *
25425  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25426  * failure. The nce_fp_mp can vanish any time in the case of
25427  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25428  * the ire_lock to access the nce_fp_mp in this case.
25429  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25430  * prepending a fastpath message IPQoS processing must precede it, we also set
25431  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25432  * (IPQoS might have set the b_band for CoS marking).
25433  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25434  * must follow it so that IPQoS can mark the dl_priority field for CoS
25435  * marking, if needed.
25436  */
25437 static mblk_t *
25438 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25439 {
25440 	uint_t	hlen;
25441 	ipha_t *ipha;
25442 	mblk_t *mp1;
25443 	boolean_t qos_done = B_FALSE;
25444 	uchar_t	*ll_hdr;
25445 	ip_stack_t	*ipst = ire->ire_ipst;
25446 
25447 #define	rptr	((uchar_t *)ipha)
25448 
25449 	ipha = (ipha_t *)mp->b_rptr;
25450 	hlen = 0;
25451 	LOCK_IRE_FP_MP(ire);
25452 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25453 		ASSERT(DB_TYPE(mp1) == M_DATA);
25454 		/* Initiate IPPF processing */
25455 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25456 			UNLOCK_IRE_FP_MP(ire);
25457 			ip_process(proc, &mp, ill_index);
25458 			if (mp == NULL)
25459 				return (NULL);
25460 
25461 			ipha = (ipha_t *)mp->b_rptr;
25462 			LOCK_IRE_FP_MP(ire);
25463 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25464 				qos_done = B_TRUE;
25465 				goto no_fp_mp;
25466 			}
25467 			ASSERT(DB_TYPE(mp1) == M_DATA);
25468 		}
25469 		hlen = MBLKL(mp1);
25470 		/*
25471 		 * Check if we have enough room to prepend fastpath
25472 		 * header
25473 		 */
25474 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25475 			ll_hdr = rptr - hlen;
25476 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25477 			/*
25478 			 * Set the b_rptr to the start of the link layer
25479 			 * header
25480 			 */
25481 			mp->b_rptr = ll_hdr;
25482 			mp1 = mp;
25483 		} else {
25484 			mp1 = copyb(mp1);
25485 			if (mp1 == NULL)
25486 				goto unlock_err;
25487 			mp1->b_band = mp->b_band;
25488 			mp1->b_cont = mp;
25489 			/*
25490 			 * certain system generated traffic may not
25491 			 * have cred/label in ip header block. This
25492 			 * is true even for a labeled system. But for
25493 			 * labeled traffic, inherit the label in the
25494 			 * new header.
25495 			 */
25496 			if (DB_CRED(mp) != NULL)
25497 				mblk_setcred(mp1, DB_CRED(mp));
25498 			/*
25499 			 * XXX disable ICK_VALID and compute checksum
25500 			 * here; can happen if nce_fp_mp changes and
25501 			 * it can't be copied now due to insufficient
25502 			 * space. (unlikely, fp mp can change, but it
25503 			 * does not increase in length)
25504 			 */
25505 		}
25506 		UNLOCK_IRE_FP_MP(ire);
25507 	} else {
25508 no_fp_mp:
25509 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25510 		if (mp1 == NULL) {
25511 unlock_err:
25512 			UNLOCK_IRE_FP_MP(ire);
25513 			freemsg(mp);
25514 			return (NULL);
25515 		}
25516 		UNLOCK_IRE_FP_MP(ire);
25517 		mp1->b_cont = mp;
25518 		/*
25519 		 * certain system generated traffic may not
25520 		 * have cred/label in ip header block. This
25521 		 * is true even for a labeled system. But for
25522 		 * labeled traffic, inherit the label in the
25523 		 * new header.
25524 		 */
25525 		if (DB_CRED(mp) != NULL)
25526 			mblk_setcred(mp1, DB_CRED(mp));
25527 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25528 			ip_process(proc, &mp1, ill_index);
25529 			if (mp1 == NULL)
25530 				return (NULL);
25531 		}
25532 	}
25533 	return (mp1);
25534 #undef rptr
25535 }
25536 
25537 /*
25538  * Finish the outbound IPsec processing for an IPv6 packet. This function
25539  * is called from ipsec_out_process() if the IPsec packet was processed
25540  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25541  * asynchronously.
25542  */
25543 void
25544 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25545     ire_t *ire_arg)
25546 {
25547 	in6_addr_t *v6dstp;
25548 	ire_t *ire;
25549 	mblk_t *mp;
25550 	ip6_t *ip6h1;
25551 	uint_t	ill_index;
25552 	ipsec_out_t *io;
25553 	boolean_t attach_if, hwaccel;
25554 	uint32_t flags = IP6_NO_IPPOLICY;
25555 	int match_flags;
25556 	zoneid_t zoneid;
25557 	boolean_t ill_need_rele = B_FALSE;
25558 	boolean_t ire_need_rele = B_FALSE;
25559 	ip_stack_t	*ipst;
25560 
25561 	mp = ipsec_mp->b_cont;
25562 	ip6h1 = (ip6_t *)mp->b_rptr;
25563 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25564 	ASSERT(io->ipsec_out_ns != NULL);
25565 	ipst = io->ipsec_out_ns->netstack_ip;
25566 	ill_index = io->ipsec_out_ill_index;
25567 	if (io->ipsec_out_reachable) {
25568 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25569 	}
25570 	attach_if = io->ipsec_out_attach_if;
25571 	hwaccel = io->ipsec_out_accelerated;
25572 	zoneid = io->ipsec_out_zoneid;
25573 	ASSERT(zoneid != ALL_ZONES);
25574 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25575 	/* Multicast addresses should have non-zero ill_index. */
25576 	v6dstp = &ip6h->ip6_dst;
25577 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25578 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25579 	ASSERT(!attach_if || ill_index != 0);
25580 	if (ill_index != 0) {
25581 		if (ill == NULL) {
25582 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25583 			    B_TRUE, ipst);
25584 
25585 			/* Failure case frees things for us. */
25586 			if (ill == NULL)
25587 				return;
25588 
25589 			ill_need_rele = B_TRUE;
25590 		}
25591 		/*
25592 		 * If this packet needs to go out on a particular interface
25593 		 * honor it.
25594 		 */
25595 		if (attach_if) {
25596 			match_flags = MATCH_IRE_ILL;
25597 
25598 			/*
25599 			 * Check if we need an ire that will not be
25600 			 * looked up by anybody else i.e. HIDDEN.
25601 			 */
25602 			if (ill_is_probeonly(ill)) {
25603 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25604 			}
25605 		}
25606 	}
25607 	ASSERT(mp != NULL);
25608 
25609 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25610 		boolean_t unspec_src;
25611 		ipif_t	*ipif;
25612 
25613 		/*
25614 		 * Use the ill_index to get the right ill.
25615 		 */
25616 		unspec_src = io->ipsec_out_unspec_src;
25617 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25618 		if (ipif == NULL) {
25619 			if (ill_need_rele)
25620 				ill_refrele(ill);
25621 			freemsg(ipsec_mp);
25622 			return;
25623 		}
25624 
25625 		if (ire_arg != NULL) {
25626 			ire = ire_arg;
25627 		} else {
25628 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25629 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25630 			ire_need_rele = B_TRUE;
25631 		}
25632 		if (ire != NULL) {
25633 			ipif_refrele(ipif);
25634 			/*
25635 			 * XXX Do the multicast forwarding now, as the IPsec
25636 			 * processing has been done.
25637 			 */
25638 			goto send;
25639 		}
25640 
25641 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25642 		mp->b_prev = NULL;
25643 		mp->b_next = NULL;
25644 
25645 		/*
25646 		 * If the IPsec packet was processed asynchronously,
25647 		 * drop it now.
25648 		 */
25649 		if (q == NULL) {
25650 			if (ill_need_rele)
25651 				ill_refrele(ill);
25652 			freemsg(ipsec_mp);
25653 			return;
25654 		}
25655 
25656 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25657 		    unspec_src, zoneid);
25658 		ipif_refrele(ipif);
25659 	} else {
25660 		if (attach_if) {
25661 			ipif_t	*ipif;
25662 
25663 			ipif = ipif_get_next_ipif(NULL, ill);
25664 			if (ipif == NULL) {
25665 				if (ill_need_rele)
25666 					ill_refrele(ill);
25667 				freemsg(ipsec_mp);
25668 				return;
25669 			}
25670 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25671 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25672 			ire_need_rele = B_TRUE;
25673 			ipif_refrele(ipif);
25674 		} else {
25675 			if (ire_arg != NULL) {
25676 				ire = ire_arg;
25677 			} else {
25678 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25679 				    ipst);
25680 				ire_need_rele = B_TRUE;
25681 			}
25682 		}
25683 		if (ire != NULL)
25684 			goto send;
25685 		/*
25686 		 * ire disappeared underneath.
25687 		 *
25688 		 * What we need to do here is the ip_newroute
25689 		 * logic to get the ire without doing the IPsec
25690 		 * processing. Follow the same old path. But this
25691 		 * time, ip_wput or ire_add_then_send will call us
25692 		 * directly as all the IPsec operations are done.
25693 		 */
25694 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25695 		mp->b_prev = NULL;
25696 		mp->b_next = NULL;
25697 
25698 		/*
25699 		 * If the IPsec packet was processed asynchronously,
25700 		 * drop it now.
25701 		 */
25702 		if (q == NULL) {
25703 			if (ill_need_rele)
25704 				ill_refrele(ill);
25705 			freemsg(ipsec_mp);
25706 			return;
25707 		}
25708 
25709 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25710 		    zoneid, ipst);
25711 	}
25712 	if (ill != NULL && ill_need_rele)
25713 		ill_refrele(ill);
25714 	return;
25715 send:
25716 	if (ill != NULL && ill_need_rele)
25717 		ill_refrele(ill);
25718 
25719 	/* Local delivery */
25720 	if (ire->ire_stq == NULL) {
25721 		ill_t	*out_ill;
25722 		ASSERT(q != NULL);
25723 
25724 		/* PFHooks: LOOPBACK_OUT */
25725 		out_ill = ire_to_ill(ire);
25726 
25727 		DTRACE_PROBE4(ip6__loopback__out__start,
25728 		    ill_t *, NULL, ill_t *, out_ill,
25729 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25730 
25731 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25732 		    ipst->ips_ipv6firewall_loopback_out,
25733 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25734 
25735 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25736 
25737 		if (ipsec_mp != NULL)
25738 			ip_wput_local_v6(RD(q), out_ill,
25739 			    ip6h, ipsec_mp, ire, 0);
25740 		if (ire_need_rele)
25741 			ire_refrele(ire);
25742 		return;
25743 	}
25744 	/*
25745 	 * Everything is done. Send it out on the wire.
25746 	 * We force the insertion of a fragment header using the
25747 	 * IPH_FRAG_HDR flag in two cases:
25748 	 * - after reception of an ICMPv6 "packet too big" message
25749 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25750 	 * - for multirouted IPv6 packets, so that the receiver can
25751 	 *   discard duplicates according to their fragment identifier
25752 	 */
25753 	/* XXX fix flow control problems. */
25754 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25755 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25756 		if (hwaccel) {
25757 			/*
25758 			 * hardware acceleration does not handle these
25759 			 * "slow path" cases.
25760 			 */
25761 			/* IPsec KSTATS: should bump bean counter here. */
25762 			if (ire_need_rele)
25763 				ire_refrele(ire);
25764 			freemsg(ipsec_mp);
25765 			return;
25766 		}
25767 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25768 		    (mp->b_cont ? msgdsize(mp) :
25769 		    mp->b_wptr - (uchar_t *)ip6h)) {
25770 			/* IPsec KSTATS: should bump bean counter here. */
25771 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25772 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25773 			    msgdsize(mp)));
25774 			if (ire_need_rele)
25775 				ire_refrele(ire);
25776 			freemsg(ipsec_mp);
25777 			return;
25778 		}
25779 		ASSERT(mp->b_prev == NULL);
25780 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25781 		    ntohs(ip6h->ip6_plen) +
25782 		    IPV6_HDR_LEN, ire->ire_max_frag));
25783 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25784 		    ire->ire_max_frag);
25785 	} else {
25786 		UPDATE_OB_PKT_COUNT(ire);
25787 		ire->ire_last_used_time = lbolt;
25788 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25789 	}
25790 	if (ire_need_rele)
25791 		ire_refrele(ire);
25792 	freeb(ipsec_mp);
25793 }
25794 
25795 void
25796 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25797 {
25798 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25799 	da_ipsec_t *hada;	/* data attributes */
25800 	ill_t *ill = (ill_t *)q->q_ptr;
25801 
25802 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25803 
25804 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25805 		/* IPsec KSTATS: Bump lose counter here! */
25806 		freemsg(mp);
25807 		return;
25808 	}
25809 
25810 	/*
25811 	 * It's an IPsec packet that must be
25812 	 * accelerated by the Provider, and the
25813 	 * outbound ill is IPsec acceleration capable.
25814 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25815 	 * to the ill.
25816 	 * IPsec KSTATS: should bump packet counter here.
25817 	 */
25818 
25819 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25820 	if (hada_mp == NULL) {
25821 		/* IPsec KSTATS: should bump packet counter here. */
25822 		freemsg(mp);
25823 		return;
25824 	}
25825 
25826 	hada_mp->b_datap->db_type = M_CTL;
25827 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25828 	hada_mp->b_cont = mp;
25829 
25830 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25831 	bzero(hada, sizeof (da_ipsec_t));
25832 	hada->da_type = IPHADA_M_CTL;
25833 
25834 	putnext(q, hada_mp);
25835 }
25836 
25837 /*
25838  * Finish the outbound IPsec processing. This function is called from
25839  * ipsec_out_process() if the IPsec packet was processed
25840  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25841  * asynchronously.
25842  */
25843 void
25844 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25845     ire_t *ire_arg)
25846 {
25847 	uint32_t v_hlen_tos_len;
25848 	ipaddr_t	dst;
25849 	ipif_t	*ipif = NULL;
25850 	ire_t *ire;
25851 	ire_t *ire1 = NULL;
25852 	mblk_t *next_mp = NULL;
25853 	uint32_t max_frag;
25854 	boolean_t multirt_send = B_FALSE;
25855 	mblk_t *mp;
25856 	ipha_t *ipha1;
25857 	uint_t	ill_index;
25858 	ipsec_out_t *io;
25859 	boolean_t attach_if;
25860 	int match_flags;
25861 	irb_t *irb = NULL;
25862 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25863 	zoneid_t zoneid;
25864 	ipxmit_state_t	pktxmit_state;
25865 	ip_stack_t	*ipst;
25866 
25867 #ifdef	_BIG_ENDIAN
25868 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25869 #else
25870 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25871 #endif
25872 
25873 	mp = ipsec_mp->b_cont;
25874 	ipha1 = (ipha_t *)mp->b_rptr;
25875 	ASSERT(mp != NULL);
25876 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25877 	dst = ipha->ipha_dst;
25878 
25879 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25880 	ill_index = io->ipsec_out_ill_index;
25881 	attach_if = io->ipsec_out_attach_if;
25882 	zoneid = io->ipsec_out_zoneid;
25883 	ASSERT(zoneid != ALL_ZONES);
25884 	ipst = io->ipsec_out_ns->netstack_ip;
25885 	ASSERT(io->ipsec_out_ns != NULL);
25886 
25887 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25888 	if (ill_index != 0) {
25889 		if (ill == NULL) {
25890 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25891 			    ill_index, B_FALSE, ipst);
25892 
25893 			/* Failure case frees things for us. */
25894 			if (ill == NULL)
25895 				return;
25896 
25897 			ill_need_rele = B_TRUE;
25898 		}
25899 		/*
25900 		 * If this packet needs to go out on a particular interface
25901 		 * honor it.
25902 		 */
25903 		if (attach_if) {
25904 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25905 
25906 			/*
25907 			 * Check if we need an ire that will not be
25908 			 * looked up by anybody else i.e. HIDDEN.
25909 			 */
25910 			if (ill_is_probeonly(ill)) {
25911 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25912 			}
25913 		}
25914 	}
25915 
25916 	if (CLASSD(dst)) {
25917 		boolean_t conn_dontroute;
25918 		/*
25919 		 * Use the ill_index to get the right ipif.
25920 		 */
25921 		conn_dontroute = io->ipsec_out_dontroute;
25922 		if (ill_index == 0)
25923 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25924 		else
25925 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25926 		if (ipif == NULL) {
25927 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25928 			    " multicast\n"));
25929 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25930 			freemsg(ipsec_mp);
25931 			goto done;
25932 		}
25933 		/*
25934 		 * ipha_src has already been intialized with the
25935 		 * value of the ipif in ip_wput. All we need now is
25936 		 * an ire to send this downstream.
25937 		 */
25938 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25939 		    MBLK_GETLABEL(mp), match_flags, ipst);
25940 		if (ire != NULL) {
25941 			ill_t *ill1;
25942 			/*
25943 			 * Do the multicast forwarding now, as the IPsec
25944 			 * processing has been done.
25945 			 */
25946 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25947 			    (ill1 = ire_to_ill(ire))) {
25948 				if (ip_mforward(ill1, ipha, mp)) {
25949 					freemsg(ipsec_mp);
25950 					ip1dbg(("ip_wput_ipsec_out: mforward "
25951 					    "failed\n"));
25952 					ire_refrele(ire);
25953 					goto done;
25954 				}
25955 			}
25956 			goto send;
25957 		}
25958 
25959 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25960 		mp->b_prev = NULL;
25961 		mp->b_next = NULL;
25962 
25963 		/*
25964 		 * If the IPsec packet was processed asynchronously,
25965 		 * drop it now.
25966 		 */
25967 		if (q == NULL) {
25968 			freemsg(ipsec_mp);
25969 			goto done;
25970 		}
25971 
25972 		/*
25973 		 * We may be using a wrong ipif to create the ire.
25974 		 * But it is okay as the source address is assigned
25975 		 * for the packet already. Next outbound packet would
25976 		 * create the IRE with the right IPIF in ip_wput.
25977 		 *
25978 		 * Also handle RTF_MULTIRT routes.
25979 		 */
25980 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25981 		    zoneid, &zero_info);
25982 	} else {
25983 		if (attach_if) {
25984 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25985 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25986 		} else {
25987 			if (ire_arg != NULL) {
25988 				ire = ire_arg;
25989 				ire_need_rele = B_FALSE;
25990 			} else {
25991 				ire = ire_cache_lookup(dst, zoneid,
25992 				    MBLK_GETLABEL(mp), ipst);
25993 			}
25994 		}
25995 		if (ire != NULL) {
25996 			goto send;
25997 		}
25998 
25999 		/*
26000 		 * ire disappeared underneath.
26001 		 *
26002 		 * What we need to do here is the ip_newroute
26003 		 * logic to get the ire without doing the IPsec
26004 		 * processing. Follow the same old path. But this
26005 		 * time, ip_wput or ire_add_then_put will call us
26006 		 * directly as all the IPsec operations are done.
26007 		 */
26008 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26009 		mp->b_prev = NULL;
26010 		mp->b_next = NULL;
26011 
26012 		/*
26013 		 * If the IPsec packet was processed asynchronously,
26014 		 * drop it now.
26015 		 */
26016 		if (q == NULL) {
26017 			freemsg(ipsec_mp);
26018 			goto done;
26019 		}
26020 
26021 		/*
26022 		 * Since we're going through ip_newroute() again, we
26023 		 * need to make sure we don't:
26024 		 *
26025 		 *	1.) Trigger the ASSERT() with the ipha_ident
26026 		 *	    overloading.
26027 		 *	2.) Redo transport-layer checksumming, since we've
26028 		 *	    already done all that to get this far.
26029 		 *
26030 		 * The easiest way not do either of the above is to set
26031 		 * the ipha_ident field to IP_HDR_INCLUDED.
26032 		 */
26033 		ipha->ipha_ident = IP_HDR_INCLUDED;
26034 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26035 		    zoneid, ipst);
26036 	}
26037 	goto done;
26038 send:
26039 	if (ire->ire_stq == NULL) {
26040 		ill_t	*out_ill;
26041 		/*
26042 		 * Loopbacks go through ip_wput_local except for one case.
26043 		 * We come here if we generate a icmp_frag_needed message
26044 		 * after IPsec processing is over. When this function calls
26045 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26046 		 * icmp_frag_needed. The message generated comes back here
26047 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26048 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26049 		 * source address as it is usually set in ip_wput_ire. As
26050 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26051 		 * and we end up here. We can't enter ip_wput_ire once the
26052 		 * IPsec processing is over and hence we need to do it here.
26053 		 */
26054 		ASSERT(q != NULL);
26055 		UPDATE_OB_PKT_COUNT(ire);
26056 		ire->ire_last_used_time = lbolt;
26057 		if (ipha->ipha_src == 0)
26058 			ipha->ipha_src = ire->ire_src_addr;
26059 
26060 		/* PFHooks: LOOPBACK_OUT */
26061 		out_ill = ire_to_ill(ire);
26062 
26063 		DTRACE_PROBE4(ip4__loopback__out__start,
26064 		    ill_t *, NULL, ill_t *, out_ill,
26065 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26066 
26067 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26068 		    ipst->ips_ipv4firewall_loopback_out,
26069 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26070 
26071 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26072 
26073 		if (ipsec_mp != NULL)
26074 			ip_wput_local(RD(q), out_ill,
26075 			    ipha, ipsec_mp, ire, 0, zoneid);
26076 		if (ire_need_rele)
26077 			ire_refrele(ire);
26078 		goto done;
26079 	}
26080 
26081 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26082 		/*
26083 		 * We are through with IPsec processing.
26084 		 * Fragment this and send it on the wire.
26085 		 */
26086 		if (io->ipsec_out_accelerated) {
26087 			/*
26088 			 * The packet has been accelerated but must
26089 			 * be fragmented. This should not happen
26090 			 * since AH and ESP must not accelerate
26091 			 * packets that need fragmentation, however
26092 			 * the configuration could have changed
26093 			 * since the AH or ESP processing.
26094 			 * Drop packet.
26095 			 * IPsec KSTATS: bump bean counter here.
26096 			 */
26097 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26098 			    "fragmented accelerated packet!\n"));
26099 			freemsg(ipsec_mp);
26100 		} else {
26101 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26102 		}
26103 		if (ire_need_rele)
26104 			ire_refrele(ire);
26105 		goto done;
26106 	}
26107 
26108 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26109 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26110 	    (void *)ire->ire_ipif, (void *)ipif));
26111 
26112 	/*
26113 	 * Multiroute the secured packet, unless IPsec really
26114 	 * requires the packet to go out only through a particular
26115 	 * interface.
26116 	 */
26117 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26118 		ire_t *first_ire;
26119 		irb = ire->ire_bucket;
26120 		ASSERT(irb != NULL);
26121 		/*
26122 		 * This ire has been looked up as the one that
26123 		 * goes through the given ipif;
26124 		 * make sure we do not omit any other multiroute ire
26125 		 * that may be present in the bucket before this one.
26126 		 */
26127 		IRB_REFHOLD(irb);
26128 		for (first_ire = irb->irb_ire;
26129 		    first_ire != NULL;
26130 		    first_ire = first_ire->ire_next) {
26131 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26132 			    (first_ire->ire_addr == ire->ire_addr) &&
26133 			    !(first_ire->ire_marks &
26134 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26135 				break;
26136 			}
26137 		}
26138 
26139 		if ((first_ire != NULL) && (first_ire != ire)) {
26140 			/*
26141 			 * Don't change the ire if the packet must
26142 			 * be fragmented if sent via this new one.
26143 			 */
26144 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26145 				IRE_REFHOLD(first_ire);
26146 				if (ire_need_rele)
26147 					ire_refrele(ire);
26148 				else
26149 					ire_need_rele = B_TRUE;
26150 				ire = first_ire;
26151 			}
26152 		}
26153 		IRB_REFRELE(irb);
26154 
26155 		multirt_send = B_TRUE;
26156 		max_frag = ire->ire_max_frag;
26157 	} else {
26158 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26159 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26160 			    "flag, attach_if %d\n", attach_if));
26161 		}
26162 	}
26163 
26164 	/*
26165 	 * In most cases, the emission loop below is entered only once.
26166 	 * Only in the case where the ire holds the RTF_MULTIRT
26167 	 * flag, we loop to process all RTF_MULTIRT ires in the
26168 	 * bucket, and send the packet through all crossed
26169 	 * RTF_MULTIRT routes.
26170 	 */
26171 	do {
26172 		if (multirt_send) {
26173 			/*
26174 			 * ire1 holds here the next ire to process in the
26175 			 * bucket. If multirouting is expected,
26176 			 * any non-RTF_MULTIRT ire that has the
26177 			 * right destination address is ignored.
26178 			 */
26179 			ASSERT(irb != NULL);
26180 			IRB_REFHOLD(irb);
26181 			for (ire1 = ire->ire_next;
26182 			    ire1 != NULL;
26183 			    ire1 = ire1->ire_next) {
26184 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26185 					continue;
26186 				if (ire1->ire_addr != ire->ire_addr)
26187 					continue;
26188 				if (ire1->ire_marks &
26189 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26190 					continue;
26191 				/* No loopback here */
26192 				if (ire1->ire_stq == NULL)
26193 					continue;
26194 				/*
26195 				 * Ensure we do not exceed the MTU
26196 				 * of the next route.
26197 				 */
26198 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26199 					ip_multirt_bad_mtu(ire1, max_frag);
26200 					continue;
26201 				}
26202 
26203 				IRE_REFHOLD(ire1);
26204 				break;
26205 			}
26206 			IRB_REFRELE(irb);
26207 			if (ire1 != NULL) {
26208 				/*
26209 				 * We are in a multiple send case, need to
26210 				 * make a copy of the packet.
26211 				 */
26212 				next_mp = copymsg(ipsec_mp);
26213 				if (next_mp == NULL) {
26214 					ire_refrele(ire1);
26215 					ire1 = NULL;
26216 				}
26217 			}
26218 		}
26219 		/*
26220 		 * Everything is done. Send it out on the wire
26221 		 *
26222 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26223 		 * either send it on the wire or, in the case of
26224 		 * HW acceleration, call ipsec_hw_putnext.
26225 		 */
26226 		if (ire->ire_nce &&
26227 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26228 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26229 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26230 			/*
26231 			 * If ire's link-layer is unresolved (this
26232 			 * would only happen if the incomplete ire
26233 			 * was added to cachetable via forwarding path)
26234 			 * don't bother going to ip_xmit_v4. Just drop the
26235 			 * packet.
26236 			 * There is a slight risk here, in that, if we
26237 			 * have the forwarding path create an incomplete
26238 			 * IRE, then until the IRE is completed, any
26239 			 * transmitted IPsec packets will be dropped
26240 			 * instead of being queued waiting for resolution.
26241 			 *
26242 			 * But the likelihood of a forwarding packet and a wput
26243 			 * packet sending to the same dst at the same time
26244 			 * and there not yet be an ARP entry for it is small.
26245 			 * Furthermore, if this actually happens, it might
26246 			 * be likely that wput would generate multiple
26247 			 * packets (and forwarding would also have a train
26248 			 * of packets) for that destination. If this is
26249 			 * the case, some of them would have been dropped
26250 			 * anyway, since ARP only queues a few packets while
26251 			 * waiting for resolution
26252 			 *
26253 			 * NOTE: We should really call ip_xmit_v4,
26254 			 * and let it queue the packet and send the
26255 			 * ARP query and have ARP come back thus:
26256 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26257 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26258 			 * hw accel work. But it's too complex to get
26259 			 * the IPsec hw  acceleration approach to fit
26260 			 * well with ip_xmit_v4 doing ARP without
26261 			 * doing IPsec simplification. For now, we just
26262 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26263 			 * that we can continue with the send on the next
26264 			 * attempt.
26265 			 *
26266 			 * XXX THis should be revisited, when
26267 			 * the IPsec/IP interaction is cleaned up
26268 			 */
26269 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26270 			    " - dropping packet\n"));
26271 			freemsg(ipsec_mp);
26272 			/*
26273 			 * Call ip_xmit_v4() to trigger ARP query
26274 			 * in case the nce_state is ND_INITIAL
26275 			 */
26276 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26277 			goto drop_pkt;
26278 		}
26279 
26280 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26281 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26282 		    mblk_t *, ipsec_mp);
26283 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26284 		    ipst->ips_ipv4firewall_physical_out, NULL,
26285 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26286 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26287 		if (ipsec_mp == NULL)
26288 			goto drop_pkt;
26289 
26290 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26291 		pktxmit_state = ip_xmit_v4(mp, ire,
26292 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26293 
26294 		if ((pktxmit_state ==  SEND_FAILED) ||
26295 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26296 
26297 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26298 drop_pkt:
26299 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26300 			    ipIfStatsOutDiscards);
26301 			if (ire_need_rele)
26302 				ire_refrele(ire);
26303 			if (ire1 != NULL) {
26304 				ire_refrele(ire1);
26305 				freemsg(next_mp);
26306 			}
26307 			goto done;
26308 		}
26309 
26310 		freeb(ipsec_mp);
26311 		if (ire_need_rele)
26312 			ire_refrele(ire);
26313 
26314 		if (ire1 != NULL) {
26315 			ire = ire1;
26316 			ire_need_rele = B_TRUE;
26317 			ASSERT(next_mp);
26318 			ipsec_mp = next_mp;
26319 			mp = ipsec_mp->b_cont;
26320 			ire1 = NULL;
26321 			next_mp = NULL;
26322 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26323 		} else {
26324 			multirt_send = B_FALSE;
26325 		}
26326 	} while (multirt_send);
26327 done:
26328 	if (ill != NULL && ill_need_rele)
26329 		ill_refrele(ill);
26330 	if (ipif != NULL)
26331 		ipif_refrele(ipif);
26332 }
26333 
26334 /*
26335  * Get the ill corresponding to the specified ire, and compare its
26336  * capabilities with the protocol and algorithms specified by the
26337  * the SA obtained from ipsec_out. If they match, annotate the
26338  * ipsec_out structure to indicate that the packet needs acceleration.
26339  *
26340  *
26341  * A packet is eligible for outbound hardware acceleration if the
26342  * following conditions are satisfied:
26343  *
26344  * 1. the packet will not be fragmented
26345  * 2. the provider supports the algorithm
26346  * 3. there is no pending control message being exchanged
26347  * 4. snoop is not attached
26348  * 5. the destination address is not a broadcast or multicast address.
26349  *
26350  * Rationale:
26351  *	- Hardware drivers do not support fragmentation with
26352  *	  the current interface.
26353  *	- snoop, multicast, and broadcast may result in exposure of
26354  *	  a cleartext datagram.
26355  * We check all five of these conditions here.
26356  *
26357  * XXX would like to nuke "ire_t *" parameter here; problem is that
26358  * IRE is only way to figure out if a v4 address is a broadcast and
26359  * thus ineligible for acceleration...
26360  */
26361 static void
26362 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26363 {
26364 	ipsec_out_t *io;
26365 	mblk_t *data_mp;
26366 	uint_t plen, overhead;
26367 	ip_stack_t	*ipst;
26368 
26369 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26370 		return;
26371 
26372 	if (ill == NULL)
26373 		return;
26374 	ipst = ill->ill_ipst;
26375 	/*
26376 	 * Destination address is a broadcast or multicast.  Punt.
26377 	 */
26378 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26379 	    IRE_LOCAL)))
26380 		return;
26381 
26382 	data_mp = ipsec_mp->b_cont;
26383 
26384 	if (ill->ill_isv6) {
26385 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26386 
26387 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26388 			return;
26389 
26390 		plen = ip6h->ip6_plen;
26391 	} else {
26392 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26393 
26394 		if (CLASSD(ipha->ipha_dst))
26395 			return;
26396 
26397 		plen = ipha->ipha_length;
26398 	}
26399 	/*
26400 	 * Is there a pending DLPI control message being exchanged
26401 	 * between IP/IPsec and the DLS Provider? If there is, it
26402 	 * could be a SADB update, and the state of the DLS Provider
26403 	 * SADB might not be in sync with the SADB maintained by
26404 	 * IPsec. To avoid dropping packets or using the wrong keying
26405 	 * material, we do not accelerate this packet.
26406 	 */
26407 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26408 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26409 		    "ill_dlpi_pending! don't accelerate packet\n"));
26410 		return;
26411 	}
26412 
26413 	/*
26414 	 * Is the Provider in promiscous mode? If it does, we don't
26415 	 * accelerate the packet since it will bounce back up to the
26416 	 * listeners in the clear.
26417 	 */
26418 	if (ill->ill_promisc_on_phys) {
26419 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26420 		    "ill in promiscous mode, don't accelerate packet\n"));
26421 		return;
26422 	}
26423 
26424 	/*
26425 	 * Will the packet require fragmentation?
26426 	 */
26427 
26428 	/*
26429 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26430 	 * as is used elsewhere.
26431 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26432 	 *	+ 2-byte trailer
26433 	 */
26434 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26435 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26436 
26437 	if ((plen + overhead) > ill->ill_max_mtu)
26438 		return;
26439 
26440 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26441 
26442 	/*
26443 	 * Can the ill accelerate this IPsec protocol and algorithm
26444 	 * specified by the SA?
26445 	 */
26446 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26447 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26448 		return;
26449 	}
26450 
26451 	/*
26452 	 * Tell AH or ESP that the outbound ill is capable of
26453 	 * accelerating this packet.
26454 	 */
26455 	io->ipsec_out_is_capab_ill = B_TRUE;
26456 }
26457 
26458 /*
26459  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26460  *
26461  * If this function returns B_TRUE, the requested SA's have been filled
26462  * into the ipsec_out_*_sa pointers.
26463  *
26464  * If the function returns B_FALSE, the packet has been "consumed", most
26465  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26466  *
26467  * The SA references created by the protocol-specific "select"
26468  * function will be released when the ipsec_mp is freed, thanks to the
26469  * ipsec_out_free destructor -- see spd.c.
26470  */
26471 static boolean_t
26472 ipsec_out_select_sa(mblk_t *ipsec_mp)
26473 {
26474 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26475 	ipsec_out_t *io;
26476 	ipsec_policy_t *pp;
26477 	ipsec_action_t *ap;
26478 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26479 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26480 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26481 
26482 	if (!io->ipsec_out_secure) {
26483 		/*
26484 		 * We came here by mistake.
26485 		 * Don't bother with ipsec processing
26486 		 * We should "discourage" this path in the future.
26487 		 */
26488 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26489 		return (B_FALSE);
26490 	}
26491 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26492 	ASSERT((io->ipsec_out_policy != NULL) ||
26493 	    (io->ipsec_out_act != NULL));
26494 
26495 	ASSERT(io->ipsec_out_failed == B_FALSE);
26496 
26497 	/*
26498 	 * IPsec processing has started.
26499 	 */
26500 	io->ipsec_out_proc_begin = B_TRUE;
26501 	ap = io->ipsec_out_act;
26502 	if (ap == NULL) {
26503 		pp = io->ipsec_out_policy;
26504 		ASSERT(pp != NULL);
26505 		ap = pp->ipsp_act;
26506 		ASSERT(ap != NULL);
26507 	}
26508 
26509 	/*
26510 	 * We have an action.  now, let's select SA's.
26511 	 * (In the future, we can cache this in the conn_t..)
26512 	 */
26513 	if (ap->ipa_want_esp) {
26514 		if (io->ipsec_out_esp_sa == NULL) {
26515 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26516 			    IPPROTO_ESP);
26517 		}
26518 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26519 	}
26520 
26521 	if (ap->ipa_want_ah) {
26522 		if (io->ipsec_out_ah_sa == NULL) {
26523 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26524 			    IPPROTO_AH);
26525 		}
26526 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26527 		/*
26528 		 * The ESP and AH processing order needs to be preserved
26529 		 * when both protocols are required (ESP should be applied
26530 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26531 		 * when both ESP and AH are required, and an AH ACQUIRE
26532 		 * is needed.
26533 		 */
26534 		if (ap->ipa_want_esp && need_ah_acquire)
26535 			need_esp_acquire = B_TRUE;
26536 	}
26537 
26538 	/*
26539 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26540 	 * Release SAs that got referenced, but will not be used until we
26541 	 * acquire _all_ of the SAs we need.
26542 	 */
26543 	if (need_ah_acquire || need_esp_acquire) {
26544 		if (io->ipsec_out_ah_sa != NULL) {
26545 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26546 			io->ipsec_out_ah_sa = NULL;
26547 		}
26548 		if (io->ipsec_out_esp_sa != NULL) {
26549 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26550 			io->ipsec_out_esp_sa = NULL;
26551 		}
26552 
26553 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26554 		return (B_FALSE);
26555 	}
26556 
26557 	return (B_TRUE);
26558 }
26559 
26560 /*
26561  * Process an IPSEC_OUT message and see what you can
26562  * do with it.
26563  * IPQoS Notes:
26564  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26565  * IPsec.
26566  * XXX would like to nuke ire_t.
26567  * XXX ill_index better be "real"
26568  */
26569 void
26570 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26571 {
26572 	ipsec_out_t *io;
26573 	ipsec_policy_t *pp;
26574 	ipsec_action_t *ap;
26575 	ipha_t *ipha;
26576 	ip6_t *ip6h;
26577 	mblk_t *mp;
26578 	ill_t *ill;
26579 	zoneid_t zoneid;
26580 	ipsec_status_t ipsec_rc;
26581 	boolean_t ill_need_rele = B_FALSE;
26582 	ip_stack_t	*ipst;
26583 	ipsec_stack_t	*ipss;
26584 
26585 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26586 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26587 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26588 	ipst = io->ipsec_out_ns->netstack_ip;
26589 	mp = ipsec_mp->b_cont;
26590 
26591 	/*
26592 	 * Initiate IPPF processing. We do it here to account for packets
26593 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26594 	 * We can check for ipsec_out_proc_begin even for such packets, as
26595 	 * they will always be false (asserted below).
26596 	 */
26597 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26598 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26599 		    io->ipsec_out_ill_index : ill_index);
26600 		if (mp == NULL) {
26601 			ip2dbg(("ipsec_out_process: packet dropped "\
26602 			    "during IPPF processing\n"));
26603 			freeb(ipsec_mp);
26604 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26605 			return;
26606 		}
26607 	}
26608 
26609 	if (!io->ipsec_out_secure) {
26610 		/*
26611 		 * We came here by mistake.
26612 		 * Don't bother with ipsec processing
26613 		 * Should "discourage" this path in the future.
26614 		 */
26615 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26616 		goto done;
26617 	}
26618 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26619 	ASSERT((io->ipsec_out_policy != NULL) ||
26620 	    (io->ipsec_out_act != NULL));
26621 	ASSERT(io->ipsec_out_failed == B_FALSE);
26622 
26623 	ipss = ipst->ips_netstack->netstack_ipsec;
26624 	if (!ipsec_loaded(ipss)) {
26625 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26626 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26627 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26628 		} else {
26629 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26630 		}
26631 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26632 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26633 		    &ipss->ipsec_dropper);
26634 		return;
26635 	}
26636 
26637 	/*
26638 	 * IPsec processing has started.
26639 	 */
26640 	io->ipsec_out_proc_begin = B_TRUE;
26641 	ap = io->ipsec_out_act;
26642 	if (ap == NULL) {
26643 		pp = io->ipsec_out_policy;
26644 		ASSERT(pp != NULL);
26645 		ap = pp->ipsp_act;
26646 		ASSERT(ap != NULL);
26647 	}
26648 
26649 	/*
26650 	 * Save the outbound ill index. When the packet comes back
26651 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26652 	 * before sending it the accelerated packet.
26653 	 */
26654 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26655 		int ifindex;
26656 		ill = ire_to_ill(ire);
26657 		ifindex = ill->ill_phyint->phyint_ifindex;
26658 		io->ipsec_out_capab_ill_index = ifindex;
26659 	}
26660 
26661 	/*
26662 	 * The order of processing is first insert a IP header if needed.
26663 	 * Then insert the ESP header and then the AH header.
26664 	 */
26665 	if ((io->ipsec_out_se_done == B_FALSE) &&
26666 	    (ap->ipa_want_se)) {
26667 		/*
26668 		 * First get the outer IP header before sending
26669 		 * it to ESP.
26670 		 */
26671 		ipha_t *oipha, *iipha;
26672 		mblk_t *outer_mp, *inner_mp;
26673 
26674 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26675 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26676 			    "ipsec_out_process: "
26677 			    "Self-Encapsulation failed: Out of memory\n");
26678 			freemsg(ipsec_mp);
26679 			if (ill != NULL) {
26680 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26681 			} else {
26682 				BUMP_MIB(&ipst->ips_ip_mib,
26683 				    ipIfStatsOutDiscards);
26684 			}
26685 			return;
26686 		}
26687 		inner_mp = ipsec_mp->b_cont;
26688 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26689 		oipha = (ipha_t *)outer_mp->b_rptr;
26690 		iipha = (ipha_t *)inner_mp->b_rptr;
26691 		*oipha = *iipha;
26692 		outer_mp->b_wptr += sizeof (ipha_t);
26693 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26694 		    sizeof (ipha_t));
26695 		oipha->ipha_protocol = IPPROTO_ENCAP;
26696 		oipha->ipha_version_and_hdr_length =
26697 		    IP_SIMPLE_HDR_VERSION;
26698 		oipha->ipha_hdr_checksum = 0;
26699 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26700 		outer_mp->b_cont = inner_mp;
26701 		ipsec_mp->b_cont = outer_mp;
26702 
26703 		io->ipsec_out_se_done = B_TRUE;
26704 		io->ipsec_out_tunnel = B_TRUE;
26705 	}
26706 
26707 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26708 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26709 	    !ipsec_out_select_sa(ipsec_mp))
26710 		return;
26711 
26712 	/*
26713 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26714 	 * to do the heavy lifting.
26715 	 */
26716 	zoneid = io->ipsec_out_zoneid;
26717 	ASSERT(zoneid != ALL_ZONES);
26718 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26719 		ASSERT(io->ipsec_out_esp_sa != NULL);
26720 		io->ipsec_out_esp_done = B_TRUE;
26721 		/*
26722 		 * Note that since hw accel can only apply one transform,
26723 		 * not two, we skip hw accel for ESP if we also have AH
26724 		 * This is an design limitation of the interface
26725 		 * which should be revisited.
26726 		 */
26727 		ASSERT(ire != NULL);
26728 		if (io->ipsec_out_ah_sa == NULL) {
26729 			ill = (ill_t *)ire->ire_stq->q_ptr;
26730 			ipsec_out_is_accelerated(ipsec_mp,
26731 			    io->ipsec_out_esp_sa, ill, ire);
26732 		}
26733 
26734 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26735 		switch (ipsec_rc) {
26736 		case IPSEC_STATUS_SUCCESS:
26737 			break;
26738 		case IPSEC_STATUS_FAILED:
26739 			if (ill != NULL) {
26740 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26741 			} else {
26742 				BUMP_MIB(&ipst->ips_ip_mib,
26743 				    ipIfStatsOutDiscards);
26744 			}
26745 			/* FALLTHRU */
26746 		case IPSEC_STATUS_PENDING:
26747 			return;
26748 		}
26749 	}
26750 
26751 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26752 		ASSERT(io->ipsec_out_ah_sa != NULL);
26753 		io->ipsec_out_ah_done = B_TRUE;
26754 		if (ire == NULL) {
26755 			int idx = io->ipsec_out_capab_ill_index;
26756 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26757 			    NULL, NULL, NULL, NULL, ipst);
26758 			ill_need_rele = B_TRUE;
26759 		} else {
26760 			ill = (ill_t *)ire->ire_stq->q_ptr;
26761 		}
26762 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26763 		    ire);
26764 
26765 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26766 		switch (ipsec_rc) {
26767 		case IPSEC_STATUS_SUCCESS:
26768 			break;
26769 		case IPSEC_STATUS_FAILED:
26770 			if (ill != NULL) {
26771 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26772 			} else {
26773 				BUMP_MIB(&ipst->ips_ip_mib,
26774 				    ipIfStatsOutDiscards);
26775 			}
26776 			/* FALLTHRU */
26777 		case IPSEC_STATUS_PENDING:
26778 			if (ill != NULL && ill_need_rele)
26779 				ill_refrele(ill);
26780 			return;
26781 		}
26782 	}
26783 	/*
26784 	 * We are done with IPsec processing. Send it over
26785 	 * the wire.
26786 	 */
26787 done:
26788 	mp = ipsec_mp->b_cont;
26789 	ipha = (ipha_t *)mp->b_rptr;
26790 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26791 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26792 	} else {
26793 		ip6h = (ip6_t *)ipha;
26794 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26795 	}
26796 	if (ill != NULL && ill_need_rele)
26797 		ill_refrele(ill);
26798 }
26799 
26800 /* ARGSUSED */
26801 void
26802 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26803 {
26804 	opt_restart_t	*or;
26805 	int	err;
26806 	conn_t	*connp;
26807 
26808 	ASSERT(CONN_Q(q));
26809 	connp = Q_TO_CONN(q);
26810 
26811 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26812 	or = (opt_restart_t *)first_mp->b_rptr;
26813 	/*
26814 	 * We don't need to pass any credentials here since this is just
26815 	 * a restart. The credentials are passed in when svr4_optcom_req
26816 	 * is called the first time (from ip_wput_nondata).
26817 	 */
26818 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26819 		err = svr4_optcom_req(q, first_mp, NULL,
26820 		    &ip_opt_obj, B_FALSE);
26821 	} else {
26822 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26823 		err = tpi_optcom_req(q, first_mp, NULL,
26824 		    &ip_opt_obj, B_FALSE);
26825 	}
26826 	if (err != EINPROGRESS) {
26827 		/* operation is done */
26828 		CONN_OPER_PENDING_DONE(connp);
26829 	}
26830 }
26831 
26832 /*
26833  * ioctls that go through a down/up sequence may need to wait for the down
26834  * to complete. This involves waiting for the ire and ipif refcnts to go down
26835  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26836  */
26837 /* ARGSUSED */
26838 void
26839 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26840 {
26841 	struct iocblk *iocp;
26842 	mblk_t *mp1;
26843 	ip_ioctl_cmd_t *ipip;
26844 	int err;
26845 	sin_t	*sin;
26846 	struct lifreq *lifr;
26847 	struct ifreq *ifr;
26848 
26849 	iocp = (struct iocblk *)mp->b_rptr;
26850 	ASSERT(ipsq != NULL);
26851 	/* Existence of mp1 verified in ip_wput_nondata */
26852 	mp1 = mp->b_cont->b_cont;
26853 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26854 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26855 		/*
26856 		 * Special case where ipsq_current_ipif is not set:
26857 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26858 		 * ill could also have become part of a ipmp group in the
26859 		 * process, we are here as were not able to complete the
26860 		 * operation in ipif_set_values because we could not become
26861 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26862 		 * will not be set so we need to set it.
26863 		 */
26864 		ill_t *ill = q->q_ptr;
26865 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26866 	}
26867 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26868 
26869 	if (ipip->ipi_cmd_type == IF_CMD) {
26870 		/* This a old style SIOC[GS]IF* command */
26871 		ifr = (struct ifreq *)mp1->b_rptr;
26872 		sin = (sin_t *)&ifr->ifr_addr;
26873 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26874 		/* This a new style SIOC[GS]LIF* command */
26875 		lifr = (struct lifreq *)mp1->b_rptr;
26876 		sin = (sin_t *)&lifr->lifr_addr;
26877 	} else {
26878 		sin = NULL;
26879 	}
26880 
26881 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26882 	    ipip, mp1->b_rptr);
26883 
26884 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26885 }
26886 
26887 /*
26888  * ioctl processing
26889  *
26890  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26891  * the ioctl command in the ioctl tables, determines the copyin data size
26892  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26893  *
26894  * ioctl processing then continues when the M_IOCDATA makes its way down to
26895  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26896  * associated 'conn' is refheld till the end of the ioctl and the general
26897  * ioctl processing function ip_process_ioctl() is called to extract the
26898  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26899  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26900  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26901  * is used to extract the ioctl's arguments.
26902  *
26903  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26904  * so goes thru the serialization primitive ipsq_try_enter. Then the
26905  * appropriate function to handle the ioctl is called based on the entry in
26906  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26907  * which also refreleases the 'conn' that was refheld at the start of the
26908  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26909  *
26910  * Many exclusive ioctls go thru an internal down up sequence as part of
26911  * the operation. For example an attempt to change the IP address of an
26912  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26913  * does all the cleanup such as deleting all ires that use this address.
26914  * Then we need to wait till all references to the interface go away.
26915  */
26916 void
26917 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26918 {
26919 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26920 	ip_ioctl_cmd_t *ipip = arg;
26921 	ip_extract_func_t *extract_funcp;
26922 	cmd_info_t ci;
26923 	int err;
26924 	boolean_t entered_ipsq = B_FALSE;
26925 
26926 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26927 
26928 	if (ipip == NULL)
26929 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26930 
26931 	/*
26932 	 * SIOCLIFADDIF needs to go thru a special path since the
26933 	 * ill may not exist yet. This happens in the case of lo0
26934 	 * which is created using this ioctl.
26935 	 */
26936 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26937 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26938 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26939 		return;
26940 	}
26941 
26942 	ci.ci_ipif = NULL;
26943 	if (ipip->ipi_cmd_type == MISC_CMD) {
26944 		/*
26945 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26946 		 */
26947 		if (ipip->ipi_cmd == IF_UNITSEL) {
26948 			/* ioctl comes down the ill */
26949 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26950 			ipif_refhold(ci.ci_ipif);
26951 		}
26952 		err = 0;
26953 		ci.ci_sin = NULL;
26954 		ci.ci_sin6 = NULL;
26955 		ci.ci_lifr = NULL;
26956 	} else {
26957 		switch (ipip->ipi_cmd_type) {
26958 		case IF_CMD:
26959 		case LIF_CMD:
26960 			extract_funcp = ip_extract_lifreq;
26961 			break;
26962 
26963 		case ARP_CMD:
26964 		case XARP_CMD:
26965 			extract_funcp = ip_extract_arpreq;
26966 			break;
26967 
26968 		case TUN_CMD:
26969 			extract_funcp = ip_extract_tunreq;
26970 			break;
26971 
26972 		case MSFILT_CMD:
26973 			extract_funcp = ip_extract_msfilter;
26974 			break;
26975 
26976 		default:
26977 			ASSERT(0);
26978 		}
26979 
26980 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26981 		if (err != 0) {
26982 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26983 			return;
26984 		}
26985 
26986 		/*
26987 		 * All of the extraction functions return a refheld ipif.
26988 		 */
26989 		ASSERT(ci.ci_ipif != NULL);
26990 	}
26991 
26992 	/*
26993 	 * If ipsq is non-null, we are already being called exclusively
26994 	 */
26995 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26996 	if (!(ipip->ipi_flags & IPI_WR)) {
26997 		/*
26998 		 * A return value of EINPROGRESS means the ioctl is
26999 		 * either queued and waiting for some reason or has
27000 		 * already completed.
27001 		 */
27002 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27003 		    ci.ci_lifr);
27004 		if (ci.ci_ipif != NULL)
27005 			ipif_refrele(ci.ci_ipif);
27006 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27007 		return;
27008 	}
27009 
27010 	ASSERT(ci.ci_ipif != NULL);
27011 
27012 	if (ipsq == NULL) {
27013 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27014 		    ip_process_ioctl, NEW_OP, B_TRUE);
27015 		entered_ipsq = B_TRUE;
27016 	}
27017 	/*
27018 	 * Release the ipif so that ipif_down and friends that wait for
27019 	 * references to go away are not misled about the current ipif_refcnt
27020 	 * values. We are writer so we can access the ipif even after releasing
27021 	 * the ipif.
27022 	 */
27023 	ipif_refrele(ci.ci_ipif);
27024 	if (ipsq == NULL)
27025 		return;
27026 
27027 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27028 
27029 	/*
27030 	 * For most set ioctls that come here, this serves as a single point
27031 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27032 	 * be any new references to the ipif. This helps functions that go
27033 	 * through this path and end up trying to wait for the refcnts
27034 	 * associated with the ipif to go down to zero. Some exceptions are
27035 	 * Failover, Failback, and Groupname commands that operate on more than
27036 	 * just the ci.ci_ipif. These commands internally determine the
27037 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27038 	 * flags on that set. Another exception is the Removeif command that
27039 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27040 	 * ipif to operate on.
27041 	 */
27042 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27043 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27044 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27045 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27046 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27047 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27048 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27049 
27050 	/*
27051 	 * A return value of EINPROGRESS means the ioctl is
27052 	 * either queued and waiting for some reason or has
27053 	 * already completed.
27054 	 */
27055 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27056 
27057 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27058 
27059 	if (entered_ipsq)
27060 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27061 }
27062 
27063 /*
27064  * Complete the ioctl. Typically ioctls use the mi package and need to
27065  * do mi_copyout/mi_copy_done.
27066  */
27067 void
27068 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27069 {
27070 	conn_t	*connp = NULL;
27071 
27072 	if (err == EINPROGRESS)
27073 		return;
27074 
27075 	if (CONN_Q(q)) {
27076 		connp = Q_TO_CONN(q);
27077 		ASSERT(connp->conn_ref >= 2);
27078 	}
27079 
27080 	switch (mode) {
27081 	case COPYOUT:
27082 		if (err == 0)
27083 			mi_copyout(q, mp);
27084 		else
27085 			mi_copy_done(q, mp, err);
27086 		break;
27087 
27088 	case NO_COPYOUT:
27089 		mi_copy_done(q, mp, err);
27090 		break;
27091 
27092 	default:
27093 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27094 		break;
27095 	}
27096 
27097 	/*
27098 	 * The refhold placed at the start of the ioctl is released here.
27099 	 */
27100 	if (connp != NULL)
27101 		CONN_OPER_PENDING_DONE(connp);
27102 
27103 	if (ipsq != NULL)
27104 		ipsq_current_finish(ipsq);
27105 }
27106 
27107 /*
27108  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27109  */
27110 /* ARGSUSED */
27111 void
27112 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27113 {
27114 	conn_t *connp = arg;
27115 	tcp_t	*tcp;
27116 
27117 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27118 	tcp = connp->conn_tcp;
27119 
27120 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27121 		freemsg(mp);
27122 	else
27123 		tcp_rput_other(tcp, mp);
27124 	CONN_OPER_PENDING_DONE(connp);
27125 }
27126 
27127 /* Called from ip_wput for all non data messages */
27128 /* ARGSUSED */
27129 void
27130 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27131 {
27132 	mblk_t		*mp1;
27133 	ire_t		*ire, *fake_ire;
27134 	ill_t		*ill;
27135 	struct iocblk	*iocp;
27136 	ip_ioctl_cmd_t	*ipip;
27137 	cred_t		*cr;
27138 	conn_t		*connp;
27139 	int		err;
27140 	nce_t		*nce;
27141 	ipif_t		*ipif;
27142 	ip_stack_t	*ipst;
27143 	char		*proto_str;
27144 
27145 	if (CONN_Q(q)) {
27146 		connp = Q_TO_CONN(q);
27147 		ipst = connp->conn_netstack->netstack_ip;
27148 	} else {
27149 		connp = NULL;
27150 		ipst = ILLQ_TO_IPST(q);
27151 	}
27152 
27153 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27154 
27155 	switch (DB_TYPE(mp)) {
27156 	case M_IOCTL:
27157 		/*
27158 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27159 		 * will arrange to copy in associated control structures.
27160 		 */
27161 		ip_sioctl_copyin_setup(q, mp);
27162 		return;
27163 	case M_IOCDATA:
27164 		/*
27165 		 * Ensure that this is associated with one of our trans-
27166 		 * parent ioctls.  If it's not ours, discard it if we're
27167 		 * running as a driver, or pass it on if we're a module.
27168 		 */
27169 		iocp = (struct iocblk *)mp->b_rptr;
27170 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27171 		if (ipip == NULL) {
27172 			if (q->q_next == NULL) {
27173 				goto nak;
27174 			} else {
27175 				putnext(q, mp);
27176 			}
27177 			return;
27178 		}
27179 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27180 			/*
27181 			 * the ioctl is one we recognise, but is not
27182 			 * consumed by IP as a module, pass M_IOCDATA
27183 			 * for processing downstream, but only for
27184 			 * common Streams ioctls.
27185 			 */
27186 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27187 				putnext(q, mp);
27188 				return;
27189 			} else {
27190 				goto nak;
27191 			}
27192 		}
27193 
27194 		/* IOCTL continuation following copyin or copyout. */
27195 		if (mi_copy_state(q, mp, NULL) == -1) {
27196 			/*
27197 			 * The copy operation failed.  mi_copy_state already
27198 			 * cleaned up, so we're out of here.
27199 			 */
27200 			return;
27201 		}
27202 		/*
27203 		 * If we just completed a copy in, we become writer and
27204 		 * continue processing in ip_sioctl_copyin_done.  If it
27205 		 * was a copy out, we call mi_copyout again.  If there is
27206 		 * nothing more to copy out, it will complete the IOCTL.
27207 		 */
27208 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27209 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27210 				mi_copy_done(q, mp, EPROTO);
27211 				return;
27212 			}
27213 			/*
27214 			 * Check for cases that need more copying.  A return
27215 			 * value of 0 means a second copyin has been started,
27216 			 * so we return; a return value of 1 means no more
27217 			 * copying is needed, so we continue.
27218 			 */
27219 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27220 			    MI_COPY_COUNT(mp) == 1) {
27221 				if (ip_copyin_msfilter(q, mp) == 0)
27222 					return;
27223 			}
27224 			/*
27225 			 * Refhold the conn, till the ioctl completes. This is
27226 			 * needed in case the ioctl ends up in the pending mp
27227 			 * list. Every mp in the ill_pending_mp list and
27228 			 * the ipsq_pending_mp must have a refhold on the conn
27229 			 * to resume processing. The refhold is released when
27230 			 * the ioctl completes. (normally or abnormally)
27231 			 * In all cases ip_ioctl_finish is called to finish
27232 			 * the ioctl.
27233 			 */
27234 			if (connp != NULL) {
27235 				/* This is not a reentry */
27236 				ASSERT(ipsq == NULL);
27237 				CONN_INC_REF(connp);
27238 			} else {
27239 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27240 					mi_copy_done(q, mp, EINVAL);
27241 					return;
27242 				}
27243 			}
27244 
27245 			ip_process_ioctl(ipsq, q, mp, ipip);
27246 
27247 		} else {
27248 			mi_copyout(q, mp);
27249 		}
27250 		return;
27251 nak:
27252 		iocp->ioc_error = EINVAL;
27253 		mp->b_datap->db_type = M_IOCNAK;
27254 		iocp->ioc_count = 0;
27255 		qreply(q, mp);
27256 		return;
27257 
27258 	case M_IOCNAK:
27259 		/*
27260 		 * The only way we could get here is if a resolver didn't like
27261 		 * an IOCTL we sent it.	 This shouldn't happen.
27262 		 */
27263 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27264 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27265 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27266 		freemsg(mp);
27267 		return;
27268 	case M_IOCACK:
27269 		/* /dev/ip shouldn't see this */
27270 		if (CONN_Q(q))
27271 			goto nak;
27272 
27273 		/* Finish socket ioctls passed through to ARP. */
27274 		ip_sioctl_iocack(q, mp);
27275 		return;
27276 	case M_FLUSH:
27277 		if (*mp->b_rptr & FLUSHW)
27278 			flushq(q, FLUSHALL);
27279 		if (q->q_next) {
27280 			putnext(q, mp);
27281 			return;
27282 		}
27283 		if (*mp->b_rptr & FLUSHR) {
27284 			*mp->b_rptr &= ~FLUSHW;
27285 			qreply(q, mp);
27286 			return;
27287 		}
27288 		freemsg(mp);
27289 		return;
27290 	case IRE_DB_REQ_TYPE:
27291 		if (connp == NULL) {
27292 			proto_str = "IRE_DB_REQ_TYPE";
27293 			goto protonak;
27294 		}
27295 		/* An Upper Level Protocol wants a copy of an IRE. */
27296 		ip_ire_req(q, mp);
27297 		return;
27298 	case M_CTL:
27299 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27300 			break;
27301 
27302 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27303 		    TUN_HELLO) {
27304 			ASSERT(connp != NULL);
27305 			connp->conn_flags |= IPCL_IPTUN;
27306 			freeb(mp);
27307 			return;
27308 		}
27309 
27310 		/* M_CTL messages are used by ARP to tell us things. */
27311 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27312 			break;
27313 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27314 		case AR_ENTRY_SQUERY:
27315 			ip_wput_ctl(q, mp);
27316 			return;
27317 		case AR_CLIENT_NOTIFY:
27318 			ip_arp_news(q, mp);
27319 			return;
27320 		case AR_DLPIOP_DONE:
27321 			ASSERT(q->q_next != NULL);
27322 			ill = (ill_t *)q->q_ptr;
27323 			/* qwriter_ip releases the refhold */
27324 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27325 			ill_refhold(ill);
27326 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27327 			return;
27328 		case AR_ARP_CLOSING:
27329 			/*
27330 			 * ARP (above us) is closing. If no ARP bringup is
27331 			 * currently pending, ack the message so that ARP
27332 			 * can complete its close. Also mark ill_arp_closing
27333 			 * so that new ARP bringups will fail. If any
27334 			 * ARP bringup is currently in progress, we will
27335 			 * ack this when the current ARP bringup completes.
27336 			 */
27337 			ASSERT(q->q_next != NULL);
27338 			ill = (ill_t *)q->q_ptr;
27339 			mutex_enter(&ill->ill_lock);
27340 			ill->ill_arp_closing = 1;
27341 			if (!ill->ill_arp_bringup_pending) {
27342 				mutex_exit(&ill->ill_lock);
27343 				qreply(q, mp);
27344 			} else {
27345 				mutex_exit(&ill->ill_lock);
27346 				freemsg(mp);
27347 			}
27348 			return;
27349 		case AR_ARP_EXTEND:
27350 			/*
27351 			 * The ARP module above us is capable of duplicate
27352 			 * address detection.  Old ATM drivers will not send
27353 			 * this message.
27354 			 */
27355 			ASSERT(q->q_next != NULL);
27356 			ill = (ill_t *)q->q_ptr;
27357 			ill->ill_arp_extend = B_TRUE;
27358 			freemsg(mp);
27359 			return;
27360 		default:
27361 			break;
27362 		}
27363 		break;
27364 	case M_PROTO:
27365 	case M_PCPROTO:
27366 		/*
27367 		 * The only PROTO messages we expect are ULP binds and
27368 		 * copies of option negotiation acknowledgements.
27369 		 */
27370 		switch (((union T_primitives *)mp->b_rptr)->type) {
27371 		case O_T_BIND_REQ:
27372 		case T_BIND_REQ: {
27373 			/* Request can get queued in bind */
27374 			if (connp == NULL) {
27375 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27376 				goto protonak;
27377 			}
27378 			/*
27379 			 * The transports except SCTP call ip_bind_{v4,v6}()
27380 			 * directly instead of a a putnext. SCTP doesn't
27381 			 * generate any T_BIND_REQ since it has its own
27382 			 * fanout data structures. However, ESP and AH
27383 			 * come in for regular binds; all other cases are
27384 			 * bind retries.
27385 			 */
27386 			ASSERT(!IPCL_IS_SCTP(connp));
27387 
27388 			/* Don't increment refcnt if this is a re-entry */
27389 			if (ipsq == NULL)
27390 				CONN_INC_REF(connp);
27391 
27392 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27393 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27394 			if (mp == NULL)
27395 				return;
27396 			if (IPCL_IS_TCP(connp)) {
27397 				/*
27398 				 * In the case of TCP endpoint we
27399 				 * come here only for bind retries
27400 				 */
27401 				ASSERT(ipsq != NULL);
27402 				CONN_INC_REF(connp);
27403 				squeue_fill(connp->conn_sqp, mp,
27404 				    ip_resume_tcp_bind, connp,
27405 				    SQTAG_BIND_RETRY);
27406 			} else if (IPCL_IS_UDP(connp)) {
27407 				/*
27408 				 * In the case of UDP endpoint we
27409 				 * come here only for bind retries
27410 				 */
27411 				ASSERT(ipsq != NULL);
27412 				udp_resume_bind(connp, mp);
27413 			} else if (IPCL_IS_RAWIP(connp)) {
27414 				/*
27415 				 * In the case of RAWIP endpoint we
27416 				 * come here only for bind retries
27417 				 */
27418 				ASSERT(ipsq != NULL);
27419 				rawip_resume_bind(connp, mp);
27420 			} else {
27421 				/* The case of AH and ESP */
27422 				qreply(q, mp);
27423 				CONN_OPER_PENDING_DONE(connp);
27424 			}
27425 			return;
27426 		}
27427 		case T_SVR4_OPTMGMT_REQ:
27428 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27429 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27430 
27431 			if (connp == NULL) {
27432 				proto_str = "T_SVR4_OPTMGMT_REQ";
27433 				goto protonak;
27434 			}
27435 
27436 			if (!snmpcom_req(q, mp, ip_snmp_set,
27437 			    ip_snmp_get, cr)) {
27438 				/*
27439 				 * Call svr4_optcom_req so that it can
27440 				 * generate the ack. We don't come here
27441 				 * if this operation is being restarted.
27442 				 * ip_restart_optmgmt will drop the conn ref.
27443 				 * In the case of ipsec option after the ipsec
27444 				 * load is complete conn_restart_ipsec_waiter
27445 				 * drops the conn ref.
27446 				 */
27447 				ASSERT(ipsq == NULL);
27448 				CONN_INC_REF(connp);
27449 				if (ip_check_for_ipsec_opt(q, mp))
27450 					return;
27451 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27452 				    B_FALSE);
27453 				if (err != EINPROGRESS) {
27454 					/* Operation is done */
27455 					CONN_OPER_PENDING_DONE(connp);
27456 				}
27457 			}
27458 			return;
27459 		case T_OPTMGMT_REQ:
27460 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27461 			/*
27462 			 * Note: No snmpcom_req support through new
27463 			 * T_OPTMGMT_REQ.
27464 			 * Call tpi_optcom_req so that it can
27465 			 * generate the ack.
27466 			 */
27467 			if (connp == NULL) {
27468 				proto_str = "T_OPTMGMT_REQ";
27469 				goto protonak;
27470 			}
27471 
27472 			ASSERT(ipsq == NULL);
27473 			/*
27474 			 * We don't come here for restart. ip_restart_optmgmt
27475 			 * will drop the conn ref. In the case of ipsec option
27476 			 * after the ipsec load is complete
27477 			 * conn_restart_ipsec_waiter drops the conn ref.
27478 			 */
27479 			CONN_INC_REF(connp);
27480 			if (ip_check_for_ipsec_opt(q, mp))
27481 				return;
27482 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27483 			if (err != EINPROGRESS) {
27484 				/* Operation is done */
27485 				CONN_OPER_PENDING_DONE(connp);
27486 			}
27487 			return;
27488 		case T_UNBIND_REQ:
27489 			if (connp == NULL) {
27490 				proto_str = "T_UNBIND_REQ";
27491 				goto protonak;
27492 			}
27493 			mp = ip_unbind(q, mp);
27494 			qreply(q, mp);
27495 			return;
27496 		default:
27497 			/*
27498 			 * Have to drop any DLPI messages coming down from
27499 			 * arp (such as an info_req which would cause ip
27500 			 * to receive an extra info_ack if it was passed
27501 			 * through.
27502 			 */
27503 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27504 			    (int)*(uint_t *)mp->b_rptr));
27505 			freemsg(mp);
27506 			return;
27507 		}
27508 		/* NOTREACHED */
27509 	case IRE_DB_TYPE: {
27510 		nce_t		*nce;
27511 		ill_t		*ill;
27512 		in6_addr_t	gw_addr_v6;
27513 
27514 
27515 		/*
27516 		 * This is a response back from a resolver.  It
27517 		 * consists of a message chain containing:
27518 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27519 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27520 		 * The LL_HDR_MBLK is the DLPI header to use to get
27521 		 * the attached packet, and subsequent ones for the
27522 		 * same destination, transmitted.
27523 		 */
27524 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27525 			break;
27526 		/*
27527 		 * First, check to make sure the resolution succeeded.
27528 		 * If it failed, the second mblk will be empty.
27529 		 * If it is, free the chain, dropping the packet.
27530 		 * (We must ire_delete the ire; that frees the ire mblk)
27531 		 * We're doing this now to support PVCs for ATM; it's
27532 		 * a partial xresolv implementation. When we fully implement
27533 		 * xresolv interfaces, instead of freeing everything here
27534 		 * we'll initiate neighbor discovery.
27535 		 *
27536 		 * For v4 (ARP and other external resolvers) the resolver
27537 		 * frees the message, so no check is needed. This check
27538 		 * is required, though, for a full xresolve implementation.
27539 		 * Including this code here now both shows how external
27540 		 * resolvers can NACK a resolution request using an
27541 		 * existing design that has no specific provisions for NACKs,
27542 		 * and also takes into account that the current non-ARP
27543 		 * external resolver has been coded to use this method of
27544 		 * NACKing for all IPv6 (xresolv) cases,
27545 		 * whether our xresolv implementation is complete or not.
27546 		 *
27547 		 */
27548 		ire = (ire_t *)mp->b_rptr;
27549 		ill = ire_to_ill(ire);
27550 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27551 		if (mp1->b_rptr == mp1->b_wptr) {
27552 			if (ire->ire_ipversion == IPV6_VERSION) {
27553 				/*
27554 				 * XRESOLV interface.
27555 				 */
27556 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27557 				mutex_enter(&ire->ire_lock);
27558 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27559 				mutex_exit(&ire->ire_lock);
27560 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27561 					nce = ndp_lookup_v6(ill,
27562 					    &ire->ire_addr_v6, B_FALSE);
27563 				} else {
27564 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27565 					    B_FALSE);
27566 				}
27567 				if (nce != NULL) {
27568 					nce_resolv_failed(nce);
27569 					ndp_delete(nce);
27570 					NCE_REFRELE(nce);
27571 				}
27572 			}
27573 			mp->b_cont = NULL;
27574 			freemsg(mp1);		/* frees the pkt as well */
27575 			ASSERT(ire->ire_nce == NULL);
27576 			ire_delete((ire_t *)mp->b_rptr);
27577 			return;
27578 		}
27579 
27580 		/*
27581 		 * Split them into IRE_MBLK and pkt and feed it into
27582 		 * ire_add_then_send. Then in ire_add_then_send
27583 		 * the IRE will be added, and then the packet will be
27584 		 * run back through ip_wput. This time it will make
27585 		 * it to the wire.
27586 		 */
27587 		mp->b_cont = NULL;
27588 		mp = mp1->b_cont;		/* now, mp points to pkt */
27589 		mp1->b_cont = NULL;
27590 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27591 		if (ire->ire_ipversion == IPV6_VERSION) {
27592 			/*
27593 			 * XRESOLV interface. Find the nce and put a copy
27594 			 * of the dl_unitdata_req in nce_res_mp
27595 			 */
27596 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27597 			mutex_enter(&ire->ire_lock);
27598 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27599 			mutex_exit(&ire->ire_lock);
27600 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27601 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27602 				    B_FALSE);
27603 			} else {
27604 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27605 			}
27606 			if (nce != NULL) {
27607 				/*
27608 				 * We have to protect nce_res_mp here
27609 				 * from being accessed by other threads
27610 				 * while we change the mblk pointer.
27611 				 * Other functions will also lock the nce when
27612 				 * accessing nce_res_mp.
27613 				 *
27614 				 * The reason we change the mblk pointer
27615 				 * here rather than copying the resolved address
27616 				 * into the template is that, unlike with
27617 				 * ethernet, we have no guarantee that the
27618 				 * resolved address length will be
27619 				 * smaller than or equal to the lla length
27620 				 * with which the template was allocated,
27621 				 * (for ethernet, they're equal)
27622 				 * so we have to use the actual resolved
27623 				 * address mblk - which holds the real
27624 				 * dl_unitdata_req with the resolved address.
27625 				 *
27626 				 * Doing this is the same behavior as was
27627 				 * previously used in the v4 ARP case.
27628 				 */
27629 				mutex_enter(&nce->nce_lock);
27630 				if (nce->nce_res_mp != NULL)
27631 					freemsg(nce->nce_res_mp);
27632 				nce->nce_res_mp = mp1;
27633 				mutex_exit(&nce->nce_lock);
27634 				/*
27635 				 * We do a fastpath probe here because
27636 				 * we have resolved the address without
27637 				 * using Neighbor Discovery.
27638 				 * In the non-XRESOLV v6 case, the fastpath
27639 				 * probe is done right after neighbor
27640 				 * discovery completes.
27641 				 */
27642 				if (nce->nce_res_mp != NULL) {
27643 					int res;
27644 					nce_fastpath_list_add(nce);
27645 					res = ill_fastpath_probe(ill,
27646 					    nce->nce_res_mp);
27647 					if (res != 0 && res != EAGAIN)
27648 						nce_fastpath_list_delete(nce);
27649 				}
27650 
27651 				ire_add_then_send(q, ire, mp);
27652 				/*
27653 				 * Now we have to clean out any packets
27654 				 * that may have been queued on the nce
27655 				 * while it was waiting for address resolution
27656 				 * to complete.
27657 				 */
27658 				mutex_enter(&nce->nce_lock);
27659 				mp1 = nce->nce_qd_mp;
27660 				nce->nce_qd_mp = NULL;
27661 				mutex_exit(&nce->nce_lock);
27662 				while (mp1 != NULL) {
27663 					mblk_t *nxt_mp;
27664 					queue_t *fwdq = NULL;
27665 					ill_t   *inbound_ill;
27666 					uint_t ifindex;
27667 
27668 					nxt_mp = mp1->b_next;
27669 					mp1->b_next = NULL;
27670 					/*
27671 					 * Retrieve ifindex stored in
27672 					 * ip_rput_data_v6()
27673 					 */
27674 					ifindex =
27675 					    (uint_t)(uintptr_t)mp1->b_prev;
27676 					inbound_ill =
27677 					    ill_lookup_on_ifindex(ifindex,
27678 					    B_TRUE, NULL, NULL, NULL,
27679 					    NULL, ipst);
27680 					mp1->b_prev = NULL;
27681 					if (inbound_ill != NULL)
27682 						fwdq = inbound_ill->ill_rq;
27683 
27684 					if (fwdq != NULL) {
27685 						put(fwdq, mp1);
27686 						ill_refrele(inbound_ill);
27687 					} else
27688 						put(WR(ill->ill_rq), mp1);
27689 					mp1 = nxt_mp;
27690 				}
27691 				NCE_REFRELE(nce);
27692 			} else {	/* nce is NULL; clean up */
27693 				ire_delete(ire);
27694 				freemsg(mp);
27695 				freemsg(mp1);
27696 				return;
27697 			}
27698 		} else {
27699 			nce_t *arpce;
27700 			/*
27701 			 * Link layer resolution succeeded. Recompute the
27702 			 * ire_nce.
27703 			 */
27704 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27705 			if ((arpce = ndp_lookup_v4(ill,
27706 			    (ire->ire_gateway_addr != INADDR_ANY ?
27707 			    &ire->ire_gateway_addr : &ire->ire_addr),
27708 			    B_FALSE)) == NULL) {
27709 				freeb(ire->ire_mp);
27710 				freeb(mp1);
27711 				freemsg(mp);
27712 				return;
27713 			}
27714 			mutex_enter(&arpce->nce_lock);
27715 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27716 			if (arpce->nce_state == ND_REACHABLE) {
27717 				/*
27718 				 * Someone resolved this before us;
27719 				 * cleanup the res_mp. Since ire has
27720 				 * not been added yet, the call to ire_add_v4
27721 				 * from ire_add_then_send (when a dup is
27722 				 * detected) will clean up the ire.
27723 				 */
27724 				freeb(mp1);
27725 			} else {
27726 				ASSERT(arpce->nce_res_mp == NULL);
27727 				arpce->nce_res_mp = mp1;
27728 				arpce->nce_state = ND_REACHABLE;
27729 			}
27730 			mutex_exit(&arpce->nce_lock);
27731 			if (ire->ire_marks & IRE_MARK_NOADD) {
27732 				/*
27733 				 * this ire will not be added to the ire
27734 				 * cache table, so we can set the ire_nce
27735 				 * here, as there are no atomicity constraints.
27736 				 */
27737 				ire->ire_nce = arpce;
27738 				/*
27739 				 * We are associating this nce with the ire
27740 				 * so change the nce ref taken in
27741 				 * ndp_lookup_v4() from
27742 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27743 				 */
27744 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27745 			} else {
27746 				NCE_REFRELE(arpce);
27747 			}
27748 			ire_add_then_send(q, ire, mp);
27749 		}
27750 		return;	/* All is well, the packet has been sent. */
27751 	}
27752 	case IRE_ARPRESOLVE_TYPE: {
27753 
27754 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27755 			break;
27756 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27757 		mp->b_cont = NULL;
27758 		/*
27759 		 * First, check to make sure the resolution succeeded.
27760 		 * If it failed, the second mblk will be empty.
27761 		 */
27762 		if (mp1->b_rptr == mp1->b_wptr) {
27763 			/* cleanup  the incomplete ire, free queued packets */
27764 			freemsg(mp); /* fake ire */
27765 			freeb(mp1);  /* dl_unitdata response */
27766 			return;
27767 		}
27768 
27769 		/*
27770 		 * update any incomplete nce_t found. we lookup the ctable
27771 		 * and find the nce from the ire->ire_nce because we need
27772 		 * to pass the ire to ip_xmit_v4 later, and can find both
27773 		 * ire and nce in one lookup from the ctable.
27774 		 */
27775 		fake_ire = (ire_t *)mp->b_rptr;
27776 		/*
27777 		 * By the time we come back here from ARP
27778 		 * the logical outgoing interface  of the incomplete ire
27779 		 * we added in ire_forward could have disappeared,
27780 		 * causing the incomplete ire to also have
27781 		 * dissapeared. So we need to retreive the
27782 		 * proper ipif for the ire  before looking
27783 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27784 		 */
27785 		ill = q->q_ptr;
27786 
27787 		/* Get the outgoing ipif */
27788 		mutex_enter(&ill->ill_lock);
27789 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27790 			mutex_exit(&ill->ill_lock);
27791 			freemsg(mp); /* fake ire */
27792 			freeb(mp1);  /* dl_unitdata response */
27793 			return;
27794 		}
27795 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27796 
27797 		if (ipif == NULL) {
27798 			mutex_exit(&ill->ill_lock);
27799 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27800 			freemsg(mp);
27801 			freeb(mp1);
27802 			return;
27803 		}
27804 		ipif_refhold_locked(ipif);
27805 		mutex_exit(&ill->ill_lock);
27806 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27807 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27808 		    ipif, fake_ire->ire_zoneid, NULL,
27809 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY), ipst);
27810 		ipif_refrele(ipif);
27811 		if (ire == NULL) {
27812 			/*
27813 			 * no ire was found; check if there is an nce
27814 			 * for this lookup; if it has no ire's pointing at it
27815 			 * cleanup.
27816 			 */
27817 			if ((nce = ndp_lookup_v4(ill,
27818 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27819 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27820 			    B_FALSE)) != NULL) {
27821 				/*
27822 				 * cleanup:
27823 				 * We check for refcnt 2 (one for the nce
27824 				 * hash list + 1 for the ref taken by
27825 				 * ndp_lookup_v4) to check that there are
27826 				 * no ire's pointing at the nce.
27827 				 */
27828 				if (nce->nce_refcnt == 2)
27829 					ndp_delete(nce);
27830 				NCE_REFRELE(nce);
27831 			}
27832 			freeb(mp1);  /* dl_unitdata response */
27833 			freemsg(mp); /* fake ire */
27834 			return;
27835 		}
27836 		nce = ire->ire_nce;
27837 		DTRACE_PROBE2(ire__arpresolve__type,
27838 		    ire_t *, ire, nce_t *, nce);
27839 		ASSERT(nce->nce_state != ND_INITIAL);
27840 		mutex_enter(&nce->nce_lock);
27841 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27842 		if (nce->nce_state == ND_REACHABLE) {
27843 			/*
27844 			 * Someone resolved this before us;
27845 			 * our response is not needed any more.
27846 			 */
27847 			mutex_exit(&nce->nce_lock);
27848 			freeb(mp1);  /* dl_unitdata response */
27849 		} else {
27850 			ASSERT(nce->nce_res_mp == NULL);
27851 			nce->nce_res_mp = mp1;
27852 			nce->nce_state = ND_REACHABLE;
27853 			mutex_exit(&nce->nce_lock);
27854 			nce_fastpath(nce);
27855 		}
27856 		/*
27857 		 * The cached nce_t has been updated to be reachable;
27858 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27859 		 */
27860 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27861 		freemsg(mp);
27862 		/*
27863 		 * send out queued packets.
27864 		 */
27865 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27866 
27867 		IRE_REFRELE(ire);
27868 		return;
27869 	}
27870 	default:
27871 		break;
27872 	}
27873 	if (q->q_next) {
27874 		putnext(q, mp);
27875 	} else
27876 		freemsg(mp);
27877 	return;
27878 
27879 protonak:
27880 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27881 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27882 		qreply(q, mp);
27883 }
27884 
27885 /*
27886  * Process IP options in an outbound packet.  Modify the destination if there
27887  * is a source route option.
27888  * Returns non-zero if something fails in which case an ICMP error has been
27889  * sent and mp freed.
27890  */
27891 static int
27892 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27893     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27894 {
27895 	ipoptp_t	opts;
27896 	uchar_t		*opt;
27897 	uint8_t		optval;
27898 	uint8_t		optlen;
27899 	ipaddr_t	dst;
27900 	intptr_t	code = 0;
27901 	mblk_t		*mp;
27902 	ire_t		*ire = NULL;
27903 
27904 	ip2dbg(("ip_wput_options\n"));
27905 	mp = ipsec_mp;
27906 	if (mctl_present) {
27907 		mp = ipsec_mp->b_cont;
27908 	}
27909 
27910 	dst = ipha->ipha_dst;
27911 	for (optval = ipoptp_first(&opts, ipha);
27912 	    optval != IPOPT_EOL;
27913 	    optval = ipoptp_next(&opts)) {
27914 		opt = opts.ipoptp_cur;
27915 		optlen = opts.ipoptp_len;
27916 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27917 		    optval, optlen));
27918 		switch (optval) {
27919 			uint32_t off;
27920 		case IPOPT_SSRR:
27921 		case IPOPT_LSRR:
27922 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27923 				ip1dbg((
27924 				    "ip_wput_options: bad option offset\n"));
27925 				code = (char *)&opt[IPOPT_OLEN] -
27926 				    (char *)ipha;
27927 				goto param_prob;
27928 			}
27929 			off = opt[IPOPT_OFFSET];
27930 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27931 			    ntohl(dst)));
27932 			/*
27933 			 * For strict: verify that dst is directly
27934 			 * reachable.
27935 			 */
27936 			if (optval == IPOPT_SSRR) {
27937 				ire = ire_ftable_lookup(dst, 0, 0,
27938 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27939 				    MBLK_GETLABEL(mp),
27940 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27941 				if (ire == NULL) {
27942 					ip1dbg(("ip_wput_options: SSRR not"
27943 					    " directly reachable: 0x%x\n",
27944 					    ntohl(dst)));
27945 					goto bad_src_route;
27946 				}
27947 				ire_refrele(ire);
27948 			}
27949 			break;
27950 		case IPOPT_RR:
27951 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27952 				ip1dbg((
27953 				    "ip_wput_options: bad option offset\n"));
27954 				code = (char *)&opt[IPOPT_OLEN] -
27955 				    (char *)ipha;
27956 				goto param_prob;
27957 			}
27958 			break;
27959 		case IPOPT_TS:
27960 			/*
27961 			 * Verify that length >=5 and that there is either
27962 			 * room for another timestamp or that the overflow
27963 			 * counter is not maxed out.
27964 			 */
27965 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27966 			if (optlen < IPOPT_MINLEN_IT) {
27967 				goto param_prob;
27968 			}
27969 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27970 				ip1dbg((
27971 				    "ip_wput_options: bad option offset\n"));
27972 				code = (char *)&opt[IPOPT_OFFSET] -
27973 				    (char *)ipha;
27974 				goto param_prob;
27975 			}
27976 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27977 			case IPOPT_TS_TSONLY:
27978 				off = IPOPT_TS_TIMELEN;
27979 				break;
27980 			case IPOPT_TS_TSANDADDR:
27981 			case IPOPT_TS_PRESPEC:
27982 			case IPOPT_TS_PRESPEC_RFC791:
27983 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27984 				break;
27985 			default:
27986 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27987 				    (char *)ipha;
27988 				goto param_prob;
27989 			}
27990 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27991 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27992 				/*
27993 				 * No room and the overflow counter is 15
27994 				 * already.
27995 				 */
27996 				goto param_prob;
27997 			}
27998 			break;
27999 		}
28000 	}
28001 
28002 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28003 		return (0);
28004 
28005 	ip1dbg(("ip_wput_options: error processing IP options."));
28006 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28007 
28008 param_prob:
28009 	/*
28010 	 * Since ip_wput() isn't close to finished, we fill
28011 	 * in enough of the header for credible error reporting.
28012 	 */
28013 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28014 		/* Failed */
28015 		freemsg(ipsec_mp);
28016 		return (-1);
28017 	}
28018 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28019 	return (-1);
28020 
28021 bad_src_route:
28022 	/*
28023 	 * Since ip_wput() isn't close to finished, we fill
28024 	 * in enough of the header for credible error reporting.
28025 	 */
28026 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28027 		/* Failed */
28028 		freemsg(ipsec_mp);
28029 		return (-1);
28030 	}
28031 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28032 	return (-1);
28033 }
28034 
28035 /*
28036  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28037  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28038  * thru /etc/system.
28039  */
28040 #define	CONN_MAXDRAINCNT	64
28041 
28042 static void
28043 conn_drain_init(ip_stack_t *ipst)
28044 {
28045 	int i;
28046 
28047 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28048 
28049 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28050 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28051 		/*
28052 		 * Default value of the number of drainers is the
28053 		 * number of cpus, subject to maximum of 8 drainers.
28054 		 */
28055 		if (boot_max_ncpus != -1)
28056 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28057 		else
28058 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28059 	}
28060 
28061 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28062 	    sizeof (idl_t), KM_SLEEP);
28063 
28064 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28065 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28066 		    MUTEX_DEFAULT, NULL);
28067 	}
28068 }
28069 
28070 static void
28071 conn_drain_fini(ip_stack_t *ipst)
28072 {
28073 	int i;
28074 
28075 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28076 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28077 	kmem_free(ipst->ips_conn_drain_list,
28078 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28079 	ipst->ips_conn_drain_list = NULL;
28080 }
28081 
28082 /*
28083  * Note: For an overview of how flowcontrol is handled in IP please see the
28084  * IP Flowcontrol notes at the top of this file.
28085  *
28086  * Flow control has blocked us from proceeding. Insert the given conn in one
28087  * of the conn drain lists. These conn wq's will be qenabled later on when
28088  * STREAMS flow control does a backenable. conn_walk_drain will enable
28089  * the first conn in each of these drain lists. Each of these qenabled conns
28090  * in turn enables the next in the list, after it runs, or when it closes,
28091  * thus sustaining the drain process.
28092  *
28093  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28094  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28095  * running at any time, on a given conn, since there can be only 1 service proc
28096  * running on a queue at any time.
28097  */
28098 void
28099 conn_drain_insert(conn_t *connp)
28100 {
28101 	idl_t	*idl;
28102 	uint_t	index;
28103 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28104 
28105 	mutex_enter(&connp->conn_lock);
28106 	if (connp->conn_state_flags & CONN_CLOSING) {
28107 		/*
28108 		 * The conn is closing as a result of which CONN_CLOSING
28109 		 * is set. Return.
28110 		 */
28111 		mutex_exit(&connp->conn_lock);
28112 		return;
28113 	} else if (connp->conn_idl == NULL) {
28114 		/*
28115 		 * Assign the next drain list round robin. We dont' use
28116 		 * a lock, and thus it may not be strictly round robin.
28117 		 * Atomicity of load/stores is enough to make sure that
28118 		 * conn_drain_list_index is always within bounds.
28119 		 */
28120 		index = ipst->ips_conn_drain_list_index;
28121 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28122 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28123 		index++;
28124 		if (index == ipst->ips_conn_drain_list_cnt)
28125 			index = 0;
28126 		ipst->ips_conn_drain_list_index = index;
28127 	}
28128 	mutex_exit(&connp->conn_lock);
28129 
28130 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28131 	if ((connp->conn_drain_prev != NULL) ||
28132 	    (connp->conn_state_flags & CONN_CLOSING)) {
28133 		/*
28134 		 * The conn is already in the drain list, OR
28135 		 * the conn is closing. We need to check again for
28136 		 * the closing case again since close can happen
28137 		 * after we drop the conn_lock, and before we
28138 		 * acquire the CONN_DRAIN_LIST_LOCK.
28139 		 */
28140 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28141 		return;
28142 	} else {
28143 		idl = connp->conn_idl;
28144 	}
28145 
28146 	/*
28147 	 * The conn is not in the drain list. Insert it at the
28148 	 * tail of the drain list. The drain list is circular
28149 	 * and doubly linked. idl_conn points to the 1st element
28150 	 * in the list.
28151 	 */
28152 	if (idl->idl_conn == NULL) {
28153 		idl->idl_conn = connp;
28154 		connp->conn_drain_next = connp;
28155 		connp->conn_drain_prev = connp;
28156 	} else {
28157 		conn_t *head = idl->idl_conn;
28158 
28159 		connp->conn_drain_next = head;
28160 		connp->conn_drain_prev = head->conn_drain_prev;
28161 		head->conn_drain_prev->conn_drain_next = connp;
28162 		head->conn_drain_prev = connp;
28163 	}
28164 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28165 }
28166 
28167 /*
28168  * This conn is closing, and we are called from ip_close. OR
28169  * This conn has been serviced by ip_wsrv, and we need to do the tail
28170  * processing.
28171  * If this conn is part of the drain list, we may need to sustain the drain
28172  * process by qenabling the next conn in the drain list. We may also need to
28173  * remove this conn from the list, if it is done.
28174  */
28175 static void
28176 conn_drain_tail(conn_t *connp, boolean_t closing)
28177 {
28178 	idl_t *idl;
28179 
28180 	/*
28181 	 * connp->conn_idl is stable at this point, and no lock is needed
28182 	 * to check it. If we are called from ip_close, close has already
28183 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28184 	 * called us only because conn_idl is non-null. If we are called thru
28185 	 * service, conn_idl could be null, but it cannot change because
28186 	 * service is single-threaded per queue, and there cannot be another
28187 	 * instance of service trying to call conn_drain_insert on this conn
28188 	 * now.
28189 	 */
28190 	ASSERT(!closing || (connp->conn_idl != NULL));
28191 
28192 	/*
28193 	 * If connp->conn_idl is null, the conn has not been inserted into any
28194 	 * drain list even once since creation of the conn. Just return.
28195 	 */
28196 	if (connp->conn_idl == NULL)
28197 		return;
28198 
28199 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28200 
28201 	if (connp->conn_drain_prev == NULL) {
28202 		/* This conn is currently not in the drain list.  */
28203 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28204 		return;
28205 	}
28206 	idl = connp->conn_idl;
28207 	if (idl->idl_conn_draining == connp) {
28208 		/*
28209 		 * This conn is the current drainer. If this is the last conn
28210 		 * in the drain list, we need to do more checks, in the 'if'
28211 		 * below. Otherwwise we need to just qenable the next conn,
28212 		 * to sustain the draining, and is handled in the 'else'
28213 		 * below.
28214 		 */
28215 		if (connp->conn_drain_next == idl->idl_conn) {
28216 			/*
28217 			 * This conn is the last in this list. This round
28218 			 * of draining is complete. If idl_repeat is set,
28219 			 * it means another flow enabling has happened from
28220 			 * the driver/streams and we need to another round
28221 			 * of draining.
28222 			 * If there are more than 2 conns in the drain list,
28223 			 * do a left rotate by 1, so that all conns except the
28224 			 * conn at the head move towards the head by 1, and the
28225 			 * the conn at the head goes to the tail. This attempts
28226 			 * a more even share for all queues that are being
28227 			 * drained.
28228 			 */
28229 			if ((connp->conn_drain_next != connp) &&
28230 			    (idl->idl_conn->conn_drain_next != connp)) {
28231 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28232 			}
28233 			if (idl->idl_repeat) {
28234 				qenable(idl->idl_conn->conn_wq);
28235 				idl->idl_conn_draining = idl->idl_conn;
28236 				idl->idl_repeat = 0;
28237 			} else {
28238 				idl->idl_conn_draining = NULL;
28239 			}
28240 		} else {
28241 			/*
28242 			 * If the next queue that we are now qenable'ing,
28243 			 * is closing, it will remove itself from this list
28244 			 * and qenable the subsequent queue in ip_close().
28245 			 * Serialization is acheived thru idl_lock.
28246 			 */
28247 			qenable(connp->conn_drain_next->conn_wq);
28248 			idl->idl_conn_draining = connp->conn_drain_next;
28249 		}
28250 	}
28251 	if (!connp->conn_did_putbq || closing) {
28252 		/*
28253 		 * Remove ourself from the drain list, if we did not do
28254 		 * a putbq, or if the conn is closing.
28255 		 * Note: It is possible that q->q_first is non-null. It means
28256 		 * that these messages landed after we did a enableok() in
28257 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28258 		 * service them.
28259 		 */
28260 		if (connp->conn_drain_next == connp) {
28261 			/* Singleton in the list */
28262 			ASSERT(connp->conn_drain_prev == connp);
28263 			idl->idl_conn = NULL;
28264 			idl->idl_conn_draining = NULL;
28265 		} else {
28266 			connp->conn_drain_prev->conn_drain_next =
28267 			    connp->conn_drain_next;
28268 			connp->conn_drain_next->conn_drain_prev =
28269 			    connp->conn_drain_prev;
28270 			if (idl->idl_conn == connp)
28271 				idl->idl_conn = connp->conn_drain_next;
28272 			ASSERT(idl->idl_conn_draining != connp);
28273 
28274 		}
28275 		connp->conn_drain_next = NULL;
28276 		connp->conn_drain_prev = NULL;
28277 	}
28278 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28279 }
28280 
28281 /*
28282  * Write service routine. Shared perimeter entry point.
28283  * ip_wsrv can be called in any of the following ways.
28284  * 1. The device queue's messages has fallen below the low water mark
28285  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28286  *    the drain lists and backenable the first conn in each list.
28287  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28288  *    qenabled non-tcp upper layers. We start dequeing messages and call
28289  *    ip_wput for each message.
28290  */
28291 
28292 void
28293 ip_wsrv(queue_t *q)
28294 {
28295 	conn_t	*connp;
28296 	ill_t	*ill;
28297 	mblk_t	*mp;
28298 
28299 	if (q->q_next) {
28300 		ill = (ill_t *)q->q_ptr;
28301 		if (ill->ill_state_flags == 0) {
28302 			/*
28303 			 * The device flow control has opened up.
28304 			 * Walk through conn drain lists and qenable the
28305 			 * first conn in each list. This makes sense only
28306 			 * if the stream is fully plumbed and setup.
28307 			 * Hence the if check above.
28308 			 */
28309 			ip1dbg(("ip_wsrv: walking\n"));
28310 			conn_walk_drain(ill->ill_ipst);
28311 		}
28312 		return;
28313 	}
28314 
28315 	connp = Q_TO_CONN(q);
28316 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28317 
28318 	/*
28319 	 * 1. Set conn_draining flag to signal that service is active.
28320 	 *
28321 	 * 2. ip_output determines whether it has been called from service,
28322 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28323 	 *    has been called from service.
28324 	 *
28325 	 * 3. Message ordering is preserved by the following logic.
28326 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28327 	 *    the message at the tail, if conn_draining is set (i.e. service
28328 	 *    is running) or if q->q_first is non-null.
28329 	 *
28330 	 *    ii. If ip_output is called from service, and if ip_output cannot
28331 	 *    putnext due to flow control, it does a putbq.
28332 	 *
28333 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28334 	 *    (causing an infinite loop).
28335 	 */
28336 	ASSERT(!connp->conn_did_putbq);
28337 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28338 		connp->conn_draining = 1;
28339 		noenable(q);
28340 		while ((mp = getq(q)) != NULL) {
28341 			ASSERT(CONN_Q(q));
28342 
28343 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28344 			if (connp->conn_did_putbq) {
28345 				/* ip_wput did a putbq */
28346 				break;
28347 			}
28348 		}
28349 		/*
28350 		 * At this point, a thread coming down from top, calling
28351 		 * ip_wput, may end up queueing the message. We have not yet
28352 		 * enabled the queue, so ip_wsrv won't be called again.
28353 		 * To avoid this race, check q->q_first again (in the loop)
28354 		 * If the other thread queued the message before we call
28355 		 * enableok(), we will catch it in the q->q_first check.
28356 		 * If the other thread queues the message after we call
28357 		 * enableok(), ip_wsrv will be called again by STREAMS.
28358 		 */
28359 		connp->conn_draining = 0;
28360 		enableok(q);
28361 	}
28362 
28363 	/* Enable the next conn for draining */
28364 	conn_drain_tail(connp, B_FALSE);
28365 
28366 	connp->conn_did_putbq = 0;
28367 }
28368 
28369 /*
28370  * Walk the list of all conn's calling the function provided with the
28371  * specified argument for each.	 Note that this only walks conn's that
28372  * have been bound.
28373  * Applies to both IPv4 and IPv6.
28374  */
28375 static void
28376 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28377 {
28378 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28379 	    ipst->ips_ipcl_udp_fanout_size,
28380 	    func, arg, zoneid);
28381 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28382 	    ipst->ips_ipcl_conn_fanout_size,
28383 	    func, arg, zoneid);
28384 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28385 	    ipst->ips_ipcl_bind_fanout_size,
28386 	    func, arg, zoneid);
28387 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28388 	    IPPROTO_MAX, func, arg, zoneid);
28389 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28390 	    IPPROTO_MAX, func, arg, zoneid);
28391 }
28392 
28393 /*
28394  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28395  * of conns that need to be drained, check if drain is already in progress.
28396  * If so set the idl_repeat bit, indicating that the last conn in the list
28397  * needs to reinitiate the drain once again, for the list. If drain is not
28398  * in progress for the list, initiate the draining, by qenabling the 1st
28399  * conn in the list. The drain is self-sustaining, each qenabled conn will
28400  * in turn qenable the next conn, when it is done/blocked/closing.
28401  */
28402 static void
28403 conn_walk_drain(ip_stack_t *ipst)
28404 {
28405 	int i;
28406 	idl_t *idl;
28407 
28408 	IP_STAT(ipst, ip_conn_walk_drain);
28409 
28410 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28411 		idl = &ipst->ips_conn_drain_list[i];
28412 		mutex_enter(&idl->idl_lock);
28413 		if (idl->idl_conn == NULL) {
28414 			mutex_exit(&idl->idl_lock);
28415 			continue;
28416 		}
28417 		/*
28418 		 * If this list is not being drained currently by
28419 		 * an ip_wsrv thread, start the process.
28420 		 */
28421 		if (idl->idl_conn_draining == NULL) {
28422 			ASSERT(idl->idl_repeat == 0);
28423 			qenable(idl->idl_conn->conn_wq);
28424 			idl->idl_conn_draining = idl->idl_conn;
28425 		} else {
28426 			idl->idl_repeat = 1;
28427 		}
28428 		mutex_exit(&idl->idl_lock);
28429 	}
28430 }
28431 
28432 /*
28433  * Walk an conn hash table of `count' buckets, calling func for each entry.
28434  */
28435 static void
28436 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28437     zoneid_t zoneid)
28438 {
28439 	conn_t	*connp;
28440 
28441 	while (count-- > 0) {
28442 		mutex_enter(&connfp->connf_lock);
28443 		for (connp = connfp->connf_head; connp != NULL;
28444 		    connp = connp->conn_next) {
28445 			if (zoneid == GLOBAL_ZONEID ||
28446 			    zoneid == connp->conn_zoneid) {
28447 				CONN_INC_REF(connp);
28448 				mutex_exit(&connfp->connf_lock);
28449 				(*func)(connp, arg);
28450 				mutex_enter(&connfp->connf_lock);
28451 				CONN_DEC_REF(connp);
28452 			}
28453 		}
28454 		mutex_exit(&connfp->connf_lock);
28455 		connfp++;
28456 	}
28457 }
28458 
28459 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28460 static void
28461 conn_report1(conn_t *connp, void *mp)
28462 {
28463 	char	buf1[INET6_ADDRSTRLEN];
28464 	char	buf2[INET6_ADDRSTRLEN];
28465 	uint_t	print_len, buf_len;
28466 
28467 	ASSERT(connp != NULL);
28468 
28469 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28470 	if (buf_len <= 0)
28471 		return;
28472 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28473 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28474 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28475 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28476 	    "%5d %s/%05d %s/%05d\n",
28477 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28478 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28479 	    buf1, connp->conn_lport,
28480 	    buf2, connp->conn_fport);
28481 	if (print_len < buf_len) {
28482 		((mblk_t *)mp)->b_wptr += print_len;
28483 	} else {
28484 		((mblk_t *)mp)->b_wptr += buf_len;
28485 	}
28486 }
28487 
28488 /*
28489  * Named Dispatch routine to produce a formatted report on all conns
28490  * that are listed in one of the fanout tables.
28491  * This report is accessed by using the ndd utility to "get" ND variable
28492  * "ip_conn_status".
28493  */
28494 /* ARGSUSED */
28495 static int
28496 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28497 {
28498 	conn_t *connp = Q_TO_CONN(q);
28499 
28500 	(void) mi_mpprintf(mp,
28501 	    "CONN      " MI_COL_HDRPAD_STR
28502 	    "rfq      " MI_COL_HDRPAD_STR
28503 	    "stq      " MI_COL_HDRPAD_STR
28504 	    " zone local                 remote");
28505 
28506 	/*
28507 	 * Because of the ndd constraint, at most we can have 64K buffer
28508 	 * to put in all conn info.  So to be more efficient, just
28509 	 * allocate a 64K buffer here, assuming we need that large buffer.
28510 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28511 	 */
28512 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28513 		/* The following may work even if we cannot get a large buf. */
28514 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28515 		return (0);
28516 	}
28517 
28518 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28519 	    connp->conn_netstack->netstack_ip);
28520 	return (0);
28521 }
28522 
28523 /*
28524  * Determine if the ill and multicast aspects of that packets
28525  * "matches" the conn.
28526  */
28527 boolean_t
28528 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28529     zoneid_t zoneid)
28530 {
28531 	ill_t *in_ill;
28532 	boolean_t found;
28533 	ipif_t *ipif;
28534 	ire_t *ire;
28535 	ipaddr_t dst, src;
28536 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28537 
28538 	dst = ipha->ipha_dst;
28539 	src = ipha->ipha_src;
28540 
28541 	/*
28542 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28543 	 * unicast, broadcast and multicast reception to
28544 	 * conn_incoming_ill. conn_wantpacket itself is called
28545 	 * only for BROADCAST and multicast.
28546 	 *
28547 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28548 	 *    is part of a group. Hence, we should be receiving
28549 	 *    just one copy of broadcast for the whole group.
28550 	 *    Thus, if it is part of the group the packet could
28551 	 *    come on any ill of the group and hence we need a
28552 	 *    match on the group. Otherwise, match on ill should
28553 	 *    be sufficient.
28554 	 *
28555 	 * 2) ip_rput does not suppress duplicate multicast packets.
28556 	 *    If there are two interfaces in a ill group and we have
28557 	 *    2 applications (conns) joined a multicast group G on
28558 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28559 	 *    will give us two packets because we join G on both the
28560 	 *    interfaces rather than nominating just one interface
28561 	 *    for receiving multicast like broadcast above. So,
28562 	 *    we have to call ilg_lookup_ill to filter out duplicate
28563 	 *    copies, if ill is part of a group.
28564 	 */
28565 	in_ill = connp->conn_incoming_ill;
28566 	if (in_ill != NULL) {
28567 		if (in_ill->ill_group == NULL) {
28568 			if (in_ill != ill)
28569 				return (B_FALSE);
28570 		} else if (in_ill->ill_group != ill->ill_group) {
28571 			return (B_FALSE);
28572 		}
28573 	}
28574 
28575 	if (!CLASSD(dst)) {
28576 		if (IPCL_ZONE_MATCH(connp, zoneid))
28577 			return (B_TRUE);
28578 		/*
28579 		 * The conn is in a different zone; we need to check that this
28580 		 * broadcast address is configured in the application's zone and
28581 		 * on one ill in the group.
28582 		 */
28583 		ipif = ipif_get_next_ipif(NULL, ill);
28584 		if (ipif == NULL)
28585 			return (B_FALSE);
28586 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28587 		    connp->conn_zoneid, NULL,
28588 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28589 		ipif_refrele(ipif);
28590 		if (ire != NULL) {
28591 			ire_refrele(ire);
28592 			return (B_TRUE);
28593 		} else {
28594 			return (B_FALSE);
28595 		}
28596 	}
28597 
28598 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28599 	    connp->conn_zoneid == zoneid) {
28600 		/*
28601 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28602 		 * disabled, therefore we don't dispatch the multicast packet to
28603 		 * the sending zone.
28604 		 */
28605 		return (B_FALSE);
28606 	}
28607 
28608 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28609 		/*
28610 		 * Multicast packet on the loopback interface: we only match
28611 		 * conns who joined the group in the specified zone.
28612 		 */
28613 		return (B_FALSE);
28614 	}
28615 
28616 	if (connp->conn_multi_router) {
28617 		/* multicast packet and multicast router socket: send up */
28618 		return (B_TRUE);
28619 	}
28620 
28621 	mutex_enter(&connp->conn_lock);
28622 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28623 	mutex_exit(&connp->conn_lock);
28624 	return (found);
28625 }
28626 
28627 /*
28628  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28629  */
28630 /* ARGSUSED */
28631 static void
28632 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28633 {
28634 	ill_t *ill = (ill_t *)q->q_ptr;
28635 	mblk_t	*mp1, *mp2;
28636 	ipif_t  *ipif;
28637 	int err = 0;
28638 	conn_t *connp = NULL;
28639 	ipsq_t	*ipsq;
28640 	arc_t	*arc;
28641 
28642 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28643 
28644 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28645 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28646 
28647 	ASSERT(IAM_WRITER_ILL(ill));
28648 	mp2 = mp->b_cont;
28649 	mp->b_cont = NULL;
28650 
28651 	/*
28652 	 * We have now received the arp bringup completion message
28653 	 * from ARP. Mark the arp bringup as done. Also if the arp
28654 	 * stream has already started closing, send up the AR_ARP_CLOSING
28655 	 * ack now since ARP is waiting in close for this ack.
28656 	 */
28657 	mutex_enter(&ill->ill_lock);
28658 	ill->ill_arp_bringup_pending = 0;
28659 	if (ill->ill_arp_closing) {
28660 		mutex_exit(&ill->ill_lock);
28661 		/* Let's reuse the mp for sending the ack */
28662 		arc = (arc_t *)mp->b_rptr;
28663 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28664 		arc->arc_cmd = AR_ARP_CLOSING;
28665 		qreply(q, mp);
28666 	} else {
28667 		mutex_exit(&ill->ill_lock);
28668 		freeb(mp);
28669 	}
28670 
28671 	ipsq = ill->ill_phyint->phyint_ipsq;
28672 	ipif = ipsq->ipsq_pending_ipif;
28673 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28674 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28675 	if (mp1 == NULL) {
28676 		/* bringup was aborted by the user */
28677 		freemsg(mp2);
28678 		return;
28679 	}
28680 
28681 	/*
28682 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28683 	 * must have an associated conn_t.  Otherwise, we're bringing this
28684 	 * interface back up as part of handling an asynchronous event (e.g.,
28685 	 * physical address change).
28686 	 */
28687 	if (ipsq->ipsq_current_ioctl != 0) {
28688 		ASSERT(connp != NULL);
28689 		q = CONNP_TO_WQ(connp);
28690 	} else {
28691 		ASSERT(connp == NULL);
28692 		q = ill->ill_rq;
28693 	}
28694 
28695 	/*
28696 	 * If the DL_BIND_REQ fails, it is noted
28697 	 * in arc_name_offset.
28698 	 */
28699 	err = *((int *)mp2->b_rptr);
28700 	if (err == 0) {
28701 		if (ipif->ipif_isv6) {
28702 			if ((err = ipif_up_done_v6(ipif)) != 0)
28703 				ip0dbg(("ip_arp_done: init failed\n"));
28704 		} else {
28705 			if ((err = ipif_up_done(ipif)) != 0)
28706 				ip0dbg(("ip_arp_done: init failed\n"));
28707 		}
28708 	} else {
28709 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28710 	}
28711 
28712 	freemsg(mp2);
28713 
28714 	if ((err == 0) && (ill->ill_up_ipifs)) {
28715 		err = ill_up_ipifs(ill, q, mp1);
28716 		if (err == EINPROGRESS)
28717 			return;
28718 	}
28719 
28720 	if (ill->ill_up_ipifs)
28721 		ill_group_cleanup(ill);
28722 
28723 	/*
28724 	 * The operation must complete without EINPROGRESS since
28725 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28726 	 * Otherwise, the operation will be stuck forever in the ipsq.
28727 	 */
28728 	ASSERT(err != EINPROGRESS);
28729 	if (ipsq->ipsq_current_ioctl != 0)
28730 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28731 	else
28732 		ipsq_current_finish(ipsq);
28733 }
28734 
28735 /* Allocate the private structure */
28736 static int
28737 ip_priv_alloc(void **bufp)
28738 {
28739 	void	*buf;
28740 
28741 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28742 		return (ENOMEM);
28743 
28744 	*bufp = buf;
28745 	return (0);
28746 }
28747 
28748 /* Function to delete the private structure */
28749 void
28750 ip_priv_free(void *buf)
28751 {
28752 	ASSERT(buf != NULL);
28753 	kmem_free(buf, sizeof (ip_priv_t));
28754 }
28755 
28756 /*
28757  * The entry point for IPPF processing.
28758  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28759  * routine just returns.
28760  *
28761  * When called, ip_process generates an ipp_packet_t structure
28762  * which holds the state information for this packet and invokes the
28763  * the classifier (via ipp_packet_process). The classification, depending on
28764  * configured filters, results in a list of actions for this packet. Invoking
28765  * an action may cause the packet to be dropped, in which case the resulting
28766  * mblk (*mpp) is NULL. proc indicates the callout position for
28767  * this packet and ill_index is the interface this packet on or will leave
28768  * on (inbound and outbound resp.).
28769  */
28770 void
28771 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28772 {
28773 	mblk_t		*mp;
28774 	ip_priv_t	*priv;
28775 	ipp_action_id_t	aid;
28776 	int		rc = 0;
28777 	ipp_packet_t	*pp;
28778 #define	IP_CLASS	"ip"
28779 
28780 	/* If the classifier is not loaded, return  */
28781 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28782 		return;
28783 	}
28784 
28785 	mp = *mpp;
28786 	ASSERT(mp != NULL);
28787 
28788 	/* Allocate the packet structure */
28789 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28790 	if (rc != 0) {
28791 		*mpp = NULL;
28792 		freemsg(mp);
28793 		return;
28794 	}
28795 
28796 	/* Allocate the private structure */
28797 	rc = ip_priv_alloc((void **)&priv);
28798 	if (rc != 0) {
28799 		*mpp = NULL;
28800 		freemsg(mp);
28801 		ipp_packet_free(pp);
28802 		return;
28803 	}
28804 	priv->proc = proc;
28805 	priv->ill_index = ill_index;
28806 	ipp_packet_set_private(pp, priv, ip_priv_free);
28807 	ipp_packet_set_data(pp, mp);
28808 
28809 	/* Invoke the classifier */
28810 	rc = ipp_packet_process(&pp);
28811 	if (pp != NULL) {
28812 		mp = ipp_packet_get_data(pp);
28813 		ipp_packet_free(pp);
28814 		if (rc != 0) {
28815 			freemsg(mp);
28816 			*mpp = NULL;
28817 		}
28818 	} else {
28819 		*mpp = NULL;
28820 	}
28821 #undef	IP_CLASS
28822 }
28823 
28824 /*
28825  * Propagate a multicast group membership operation (add/drop) on
28826  * all the interfaces crossed by the related multirt routes.
28827  * The call is considered successful if the operation succeeds
28828  * on at least one interface.
28829  */
28830 static int
28831 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28832     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28833     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28834     mblk_t *first_mp)
28835 {
28836 	ire_t		*ire_gw;
28837 	irb_t		*irb;
28838 	int		error = 0;
28839 	opt_restart_t	*or;
28840 	ip_stack_t	*ipst = ire->ire_ipst;
28841 
28842 	irb = ire->ire_bucket;
28843 	ASSERT(irb != NULL);
28844 
28845 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28846 
28847 	or = (opt_restart_t *)first_mp->b_rptr;
28848 	IRB_REFHOLD(irb);
28849 	for (; ire != NULL; ire = ire->ire_next) {
28850 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28851 			continue;
28852 		if (ire->ire_addr != group)
28853 			continue;
28854 
28855 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28856 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28857 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28858 		/* No resolver exists for the gateway; skip this ire. */
28859 		if (ire_gw == NULL)
28860 			continue;
28861 
28862 		/*
28863 		 * This function can return EINPROGRESS. If so the operation
28864 		 * will be restarted from ip_restart_optmgmt which will
28865 		 * call ip_opt_set and option processing will restart for
28866 		 * this option. So we may end up calling 'fn' more than once.
28867 		 * This requires that 'fn' is idempotent except for the
28868 		 * return value. The operation is considered a success if
28869 		 * it succeeds at least once on any one interface.
28870 		 */
28871 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28872 		    NULL, fmode, src, first_mp);
28873 		if (error == 0)
28874 			or->or_private = CGTP_MCAST_SUCCESS;
28875 
28876 		if (ip_debug > 0) {
28877 			ulong_t	off;
28878 			char	*ksym;
28879 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28880 			ip2dbg(("ip_multirt_apply_membership: "
28881 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28882 			    "error %d [success %u]\n",
28883 			    ksym ? ksym : "?",
28884 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28885 			    error, or->or_private));
28886 		}
28887 
28888 		ire_refrele(ire_gw);
28889 		if (error == EINPROGRESS) {
28890 			IRB_REFRELE(irb);
28891 			return (error);
28892 		}
28893 	}
28894 	IRB_REFRELE(irb);
28895 	/*
28896 	 * Consider the call as successful if we succeeded on at least
28897 	 * one interface. Otherwise, return the last encountered error.
28898 	 */
28899 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28900 }
28901 
28902 
28903 /*
28904  * Issue a warning regarding a route crossing an interface with an
28905  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28906  * amount of time is logged.
28907  */
28908 static void
28909 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28910 {
28911 	hrtime_t	current = gethrtime();
28912 	char		buf[INET_ADDRSTRLEN];
28913 	ip_stack_t	*ipst = ire->ire_ipst;
28914 
28915 	/* Convert interval in ms to hrtime in ns */
28916 	if (ipst->ips_multirt_bad_mtu_last_time +
28917 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28918 	    current) {
28919 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28920 		    "to %s, incorrect MTU %u (expected %u)\n",
28921 		    ip_dot_addr(ire->ire_addr, buf),
28922 		    ire->ire_max_frag, max_frag);
28923 
28924 		ipst->ips_multirt_bad_mtu_last_time = current;
28925 	}
28926 }
28927 
28928 
28929 /*
28930  * Get the CGTP (multirouting) filtering status.
28931  * If 0, the CGTP hooks are transparent.
28932  */
28933 /* ARGSUSED */
28934 static int
28935 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28936 {
28937 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28938 
28939 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28940 	return (0);
28941 }
28942 
28943 
28944 /*
28945  * Set the CGTP (multirouting) filtering status.
28946  * If the status is changed from active to transparent
28947  * or from transparent to active, forward the new status
28948  * to the filtering module (if loaded).
28949  */
28950 /* ARGSUSED */
28951 static int
28952 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28953     cred_t *ioc_cr)
28954 {
28955 	long		new_value;
28956 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28957 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28958 
28959 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28960 		return (EPERM);
28961 
28962 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28963 	    new_value < 0 || new_value > 1) {
28964 		return (EINVAL);
28965 	}
28966 
28967 	if ((!*ip_cgtp_filter_value) && new_value) {
28968 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28969 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28970 		    " (module not loaded)" : "");
28971 	}
28972 	if (*ip_cgtp_filter_value && (!new_value)) {
28973 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28974 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28975 		    " (module not loaded)" : "");
28976 	}
28977 
28978 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28979 		int	res;
28980 		netstackid_t stackid;
28981 
28982 		stackid = ipst->ips_netstack->netstack_stackid;
28983 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28984 		    new_value);
28985 		if (res)
28986 			return (res);
28987 	}
28988 
28989 	*ip_cgtp_filter_value = (boolean_t)new_value;
28990 
28991 	return (0);
28992 }
28993 
28994 
28995 /*
28996  * Return the expected CGTP hooks version number.
28997  */
28998 int
28999 ip_cgtp_filter_supported(void)
29000 {
29001 	return (ip_cgtp_filter_rev);
29002 }
29003 
29004 
29005 /*
29006  * CGTP hooks can be registered by invoking this function.
29007  * Checks that the version number matches.
29008  */
29009 int
29010 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29011 {
29012 	netstack_t *ns;
29013 	ip_stack_t *ipst;
29014 
29015 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29016 		return (ENOTSUP);
29017 
29018 	ns = netstack_find_by_stackid(stackid);
29019 	if (ns == NULL)
29020 		return (EINVAL);
29021 	ipst = ns->netstack_ip;
29022 	ASSERT(ipst != NULL);
29023 
29024 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29025 		netstack_rele(ns);
29026 		return (EALREADY);
29027 	}
29028 
29029 	ipst->ips_ip_cgtp_filter_ops = ops;
29030 	netstack_rele(ns);
29031 	return (0);
29032 }
29033 
29034 /*
29035  * CGTP hooks can be unregistered by invoking this function.
29036  * Returns ENXIO if there was no registration.
29037  * Returns EBUSY if the ndd variable has not been turned off.
29038  */
29039 int
29040 ip_cgtp_filter_unregister(netstackid_t stackid)
29041 {
29042 	netstack_t *ns;
29043 	ip_stack_t *ipst;
29044 
29045 	ns = netstack_find_by_stackid(stackid);
29046 	if (ns == NULL)
29047 		return (EINVAL);
29048 	ipst = ns->netstack_ip;
29049 	ASSERT(ipst != NULL);
29050 
29051 	if (ipst->ips_ip_cgtp_filter) {
29052 		netstack_rele(ns);
29053 		return (EBUSY);
29054 	}
29055 
29056 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29057 		netstack_rele(ns);
29058 		return (ENXIO);
29059 	}
29060 	ipst->ips_ip_cgtp_filter_ops = NULL;
29061 	netstack_rele(ns);
29062 	return (0);
29063 }
29064 
29065 /*
29066  * Check whether there is a CGTP filter registration.
29067  * Returns non-zero if there is a registration, otherwise returns zero.
29068  * Note: returns zero if bad stackid.
29069  */
29070 int
29071 ip_cgtp_filter_is_registered(netstackid_t stackid)
29072 {
29073 	netstack_t *ns;
29074 	ip_stack_t *ipst;
29075 	int ret;
29076 
29077 	ns = netstack_find_by_stackid(stackid);
29078 	if (ns == NULL)
29079 		return (0);
29080 	ipst = ns->netstack_ip;
29081 	ASSERT(ipst != NULL);
29082 
29083 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29084 		ret = 1;
29085 	else
29086 		ret = 0;
29087 
29088 	netstack_rele(ns);
29089 	return (ret);
29090 }
29091 
29092 static squeue_func_t
29093 ip_squeue_switch(int val)
29094 {
29095 	squeue_func_t rval = squeue_fill;
29096 
29097 	switch (val) {
29098 	case IP_SQUEUE_ENTER_NODRAIN:
29099 		rval = squeue_enter_nodrain;
29100 		break;
29101 	case IP_SQUEUE_ENTER:
29102 		rval = squeue_enter;
29103 		break;
29104 	default:
29105 		break;
29106 	}
29107 	return (rval);
29108 }
29109 
29110 /* ARGSUSED */
29111 static int
29112 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29113     caddr_t addr, cred_t *cr)
29114 {
29115 	int *v = (int *)addr;
29116 	long new_value;
29117 
29118 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29119 		return (EPERM);
29120 
29121 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29122 		return (EINVAL);
29123 
29124 	ip_input_proc = ip_squeue_switch(new_value);
29125 	*v = new_value;
29126 	return (0);
29127 }
29128 
29129 /*
29130  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29131  * ip_debug.
29132  */
29133 /* ARGSUSED */
29134 static int
29135 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29136     caddr_t addr, cred_t *cr)
29137 {
29138 	int *v = (int *)addr;
29139 	long new_value;
29140 
29141 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29142 		return (EPERM);
29143 
29144 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29145 		return (EINVAL);
29146 
29147 	*v = new_value;
29148 	return (0);
29149 }
29150 
29151 /*
29152  * Handle changes to ipmp_hook_emulation ndd variable.
29153  * Need to update phyint_hook_ifindex.
29154  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29155  */
29156 static void
29157 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29158 {
29159 	phyint_t *phyi;
29160 	phyint_t *phyi_tmp;
29161 	char *groupname;
29162 	int namelen;
29163 	ill_t	*ill;
29164 	boolean_t new_group;
29165 
29166 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29167 	/*
29168 	 * Group indicies are stored in the phyint - a common structure
29169 	 * to both IPv4 and IPv6.
29170 	 */
29171 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29172 	for (; phyi != NULL;
29173 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29174 	    phyi, AVL_AFTER)) {
29175 		/* Ignore the ones that do not have a group */
29176 		if (phyi->phyint_groupname_len == 0)
29177 			continue;
29178 
29179 		/*
29180 		 * Look for other phyint in group.
29181 		 * Clear name/namelen so the lookup doesn't find ourselves.
29182 		 */
29183 		namelen = phyi->phyint_groupname_len;
29184 		groupname = phyi->phyint_groupname;
29185 		phyi->phyint_groupname_len = 0;
29186 		phyi->phyint_groupname = NULL;
29187 
29188 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29189 		/* Restore */
29190 		phyi->phyint_groupname_len = namelen;
29191 		phyi->phyint_groupname = groupname;
29192 
29193 		new_group = B_FALSE;
29194 		if (ipst->ips_ipmp_hook_emulation) {
29195 			/*
29196 			 * If the group already exists and has already
29197 			 * been assigned a group ifindex, we use the existing
29198 			 * group_ifindex, otherwise we pick a new group_ifindex
29199 			 * here.
29200 			 */
29201 			if (phyi_tmp != NULL &&
29202 			    phyi_tmp->phyint_group_ifindex != 0) {
29203 				phyi->phyint_group_ifindex =
29204 				    phyi_tmp->phyint_group_ifindex;
29205 			} else {
29206 				/* XXX We need a recovery strategy here. */
29207 				if (!ip_assign_ifindex(
29208 				    &phyi->phyint_group_ifindex, ipst))
29209 					cmn_err(CE_PANIC,
29210 					    "ip_assign_ifindex() failed");
29211 				new_group = B_TRUE;
29212 			}
29213 		} else {
29214 			phyi->phyint_group_ifindex = 0;
29215 		}
29216 		if (ipst->ips_ipmp_hook_emulation)
29217 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29218 		else
29219 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29220 
29221 		/*
29222 		 * For IP Filter to find out the relationship between
29223 		 * names and interface indicies, we need to generate
29224 		 * a NE_PLUMB event when a new group can appear.
29225 		 * We always generate events when a new interface appears
29226 		 * (even when ipmp_hook_emulation is set) so there
29227 		 * is no need to generate NE_PLUMB events when
29228 		 * ipmp_hook_emulation is turned off.
29229 		 * And since it isn't critical for IP Filter to get
29230 		 * the NE_UNPLUMB events we skip those here.
29231 		 */
29232 		if (new_group) {
29233 			/*
29234 			 * First phyint in group - generate group PLUMB event.
29235 			 * Since we are not running inside the ipsq we do
29236 			 * the dispatch immediately.
29237 			 */
29238 			if (phyi->phyint_illv4 != NULL)
29239 				ill = phyi->phyint_illv4;
29240 			else
29241 				ill = phyi->phyint_illv6;
29242 
29243 			if (ill != NULL) {
29244 				mutex_enter(&ill->ill_lock);
29245 				ill_nic_info_plumb(ill, B_TRUE);
29246 				ill_nic_info_dispatch(ill);
29247 				mutex_exit(&ill->ill_lock);
29248 			}
29249 		}
29250 	}
29251 	rw_exit(&ipst->ips_ill_g_lock);
29252 }
29253 
29254 /* ARGSUSED */
29255 static int
29256 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29257     caddr_t addr, cred_t *cr)
29258 {
29259 	int *v = (int *)addr;
29260 	long new_value;
29261 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29262 
29263 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29264 		return (EINVAL);
29265 
29266 	if (*v != new_value) {
29267 		*v = new_value;
29268 		ipmp_hook_emulation_changed(ipst);
29269 	}
29270 	return (0);
29271 }
29272 
29273 static void *
29274 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29275 {
29276 	kstat_t *ksp;
29277 
29278 	ip_stat_t template = {
29279 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29280 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29281 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29282 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29284 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29285 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29286 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29287 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29288 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29289 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29290 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29291 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29292 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29293 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29294 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29295 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29296 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29297 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29298 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29299 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29300 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29301 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29302 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29303 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29304 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29305 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29306 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29307 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29308 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29309 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29310 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29311 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29312 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29313 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29314 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29315 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29316 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29317 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29318 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29319 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29320 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29321 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29322 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29323 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29324 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29325 	};
29326 
29327 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29328 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29329 	    KSTAT_FLAG_VIRTUAL, stackid);
29330 
29331 	if (ksp == NULL)
29332 		return (NULL);
29333 
29334 	bcopy(&template, ip_statisticsp, sizeof (template));
29335 	ksp->ks_data = (void *)ip_statisticsp;
29336 	ksp->ks_private = (void *)(uintptr_t)stackid;
29337 
29338 	kstat_install(ksp);
29339 	return (ksp);
29340 }
29341 
29342 static void
29343 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29344 {
29345 	if (ksp != NULL) {
29346 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29347 		kstat_delete_netstack(ksp, stackid);
29348 	}
29349 }
29350 
29351 static void *
29352 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29353 {
29354 	kstat_t	*ksp;
29355 
29356 	ip_named_kstat_t template = {
29357 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29358 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29359 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29360 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29361 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29362 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29363 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29364 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29365 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29366 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29367 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29368 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29369 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29370 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29371 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29372 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29373 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29374 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29375 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29376 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29377 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29378 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29379 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29380 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29381 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29382 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29383 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29384 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29385 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29386 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29387 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29388 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29389 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29390 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29391 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29392 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29393 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29394 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29395 	};
29396 
29397 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29398 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29399 	if (ksp == NULL || ksp->ks_data == NULL)
29400 		return (NULL);
29401 
29402 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29403 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29404 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29405 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29406 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29407 
29408 	template.netToMediaEntrySize.value.i32 =
29409 	    sizeof (mib2_ipNetToMediaEntry_t);
29410 
29411 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29412 
29413 	bcopy(&template, ksp->ks_data, sizeof (template));
29414 	ksp->ks_update = ip_kstat_update;
29415 	ksp->ks_private = (void *)(uintptr_t)stackid;
29416 
29417 	kstat_install(ksp);
29418 	return (ksp);
29419 }
29420 
29421 static void
29422 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29423 {
29424 	if (ksp != NULL) {
29425 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29426 		kstat_delete_netstack(ksp, stackid);
29427 	}
29428 }
29429 
29430 static int
29431 ip_kstat_update(kstat_t *kp, int rw)
29432 {
29433 	ip_named_kstat_t *ipkp;
29434 	mib2_ipIfStatsEntry_t ipmib;
29435 	ill_walk_context_t ctx;
29436 	ill_t *ill;
29437 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29438 	netstack_t	*ns;
29439 	ip_stack_t	*ipst;
29440 
29441 	if (kp == NULL || kp->ks_data == NULL)
29442 		return (EIO);
29443 
29444 	if (rw == KSTAT_WRITE)
29445 		return (EACCES);
29446 
29447 	ns = netstack_find_by_stackid(stackid);
29448 	if (ns == NULL)
29449 		return (-1);
29450 	ipst = ns->netstack_ip;
29451 	if (ipst == NULL) {
29452 		netstack_rele(ns);
29453 		return (-1);
29454 	}
29455 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29456 
29457 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29458 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29459 	ill = ILL_START_WALK_V4(&ctx, ipst);
29460 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29461 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29462 	rw_exit(&ipst->ips_ill_g_lock);
29463 
29464 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29465 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29466 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29467 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29468 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29469 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29470 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29471 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29472 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29473 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29474 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29475 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29476 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29477 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29478 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29479 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29480 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29481 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29482 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29483 
29484 	ipkp->routingDiscards.value.ui32 =	0;
29485 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29486 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29487 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29488 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29489 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29490 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29491 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29492 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29493 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29494 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29495 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29496 
29497 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29498 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29499 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29500 
29501 	netstack_rele(ns);
29502 
29503 	return (0);
29504 }
29505 
29506 static void *
29507 icmp_kstat_init(netstackid_t stackid)
29508 {
29509 	kstat_t	*ksp;
29510 
29511 	icmp_named_kstat_t template = {
29512 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29513 		{ "inErrors",		KSTAT_DATA_UINT32 },
29514 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29515 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29516 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29517 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29518 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29519 		{ "inEchos",		KSTAT_DATA_UINT32 },
29520 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29521 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29522 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29523 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29524 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29525 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29526 		{ "outErrors",		KSTAT_DATA_UINT32 },
29527 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29528 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29529 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29530 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29531 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29532 		{ "outEchos",		KSTAT_DATA_UINT32 },
29533 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29534 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29535 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29536 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29537 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29538 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29539 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29540 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29541 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29542 		{ "outDrops",		KSTAT_DATA_UINT32 },
29543 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29544 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29545 	};
29546 
29547 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29548 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29549 	if (ksp == NULL || ksp->ks_data == NULL)
29550 		return (NULL);
29551 
29552 	bcopy(&template, ksp->ks_data, sizeof (template));
29553 
29554 	ksp->ks_update = icmp_kstat_update;
29555 	ksp->ks_private = (void *)(uintptr_t)stackid;
29556 
29557 	kstat_install(ksp);
29558 	return (ksp);
29559 }
29560 
29561 static void
29562 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29563 {
29564 	if (ksp != NULL) {
29565 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29566 		kstat_delete_netstack(ksp, stackid);
29567 	}
29568 }
29569 
29570 static int
29571 icmp_kstat_update(kstat_t *kp, int rw)
29572 {
29573 	icmp_named_kstat_t *icmpkp;
29574 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29575 	netstack_t	*ns;
29576 	ip_stack_t	*ipst;
29577 
29578 	if ((kp == NULL) || (kp->ks_data == NULL))
29579 		return (EIO);
29580 
29581 	if (rw == KSTAT_WRITE)
29582 		return (EACCES);
29583 
29584 	ns = netstack_find_by_stackid(stackid);
29585 	if (ns == NULL)
29586 		return (-1);
29587 	ipst = ns->netstack_ip;
29588 	if (ipst == NULL) {
29589 		netstack_rele(ns);
29590 		return (-1);
29591 	}
29592 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29593 
29594 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29595 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29596 	icmpkp->inDestUnreachs.value.ui32 =
29597 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29598 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29599 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29600 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29601 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29602 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29603 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29604 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29605 	icmpkp->inTimestampReps.value.ui32 =
29606 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29607 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29608 	icmpkp->inAddrMaskReps.value.ui32 =
29609 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29610 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29611 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29612 	icmpkp->outDestUnreachs.value.ui32 =
29613 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29614 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29615 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29616 	icmpkp->outSrcQuenchs.value.ui32 =
29617 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29618 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29619 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29620 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29621 	icmpkp->outTimestamps.value.ui32 =
29622 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29623 	icmpkp->outTimestampReps.value.ui32 =
29624 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29625 	icmpkp->outAddrMasks.value.ui32 =
29626 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29627 	icmpkp->outAddrMaskReps.value.ui32 =
29628 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29629 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29630 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29631 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29632 	icmpkp->outFragNeeded.value.ui32 =
29633 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29634 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29635 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29636 	icmpkp->inBadRedirects.value.ui32 =
29637 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29638 
29639 	netstack_rele(ns);
29640 	return (0);
29641 }
29642 
29643 /*
29644  * This is the fanout function for raw socket opened for SCTP.  Note
29645  * that it is called after SCTP checks that there is no socket which
29646  * wants a packet.  Then before SCTP handles this out of the blue packet,
29647  * this function is called to see if there is any raw socket for SCTP.
29648  * If there is and it is bound to the correct address, the packet will
29649  * be sent to that socket.  Note that only one raw socket can be bound to
29650  * a port.  This is assured in ipcl_sctp_hash_insert();
29651  */
29652 void
29653 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29654     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29655     zoneid_t zoneid)
29656 {
29657 	conn_t		*connp;
29658 	queue_t		*rq;
29659 	mblk_t		*first_mp;
29660 	boolean_t	secure;
29661 	ip6_t		*ip6h;
29662 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29663 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29664 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29665 	boolean_t	sctp_csum_err = B_FALSE;
29666 
29667 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29668 		sctp_csum_err = B_TRUE;
29669 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29670 	}
29671 
29672 	first_mp = mp;
29673 	if (mctl_present) {
29674 		mp = first_mp->b_cont;
29675 		secure = ipsec_in_is_secure(first_mp);
29676 		ASSERT(mp != NULL);
29677 	} else {
29678 		secure = B_FALSE;
29679 	}
29680 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29681 
29682 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29683 	if (connp == NULL) {
29684 		/*
29685 		 * Although raw sctp is not summed, OOB chunks must be.
29686 		 * Drop the packet here if the sctp checksum failed.
29687 		 */
29688 		if (sctp_csum_err) {
29689 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29690 			freemsg(first_mp);
29691 			return;
29692 		}
29693 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29694 		return;
29695 	}
29696 	rq = connp->conn_rq;
29697 	if (!canputnext(rq)) {
29698 		CONN_DEC_REF(connp);
29699 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29700 		freemsg(first_mp);
29701 		return;
29702 	}
29703 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29704 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29705 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29706 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29707 		if (first_mp == NULL) {
29708 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29709 			CONN_DEC_REF(connp);
29710 			return;
29711 		}
29712 	}
29713 	/*
29714 	 * We probably should not send M_CTL message up to
29715 	 * raw socket.
29716 	 */
29717 	if (mctl_present)
29718 		freeb(first_mp);
29719 
29720 	/* Initiate IPPF processing here if needed. */
29721 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29722 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29723 		ip_process(IPP_LOCAL_IN, &mp,
29724 		    recv_ill->ill_phyint->phyint_ifindex);
29725 		if (mp == NULL) {
29726 			CONN_DEC_REF(connp);
29727 			return;
29728 		}
29729 	}
29730 
29731 	if (connp->conn_recvif || connp->conn_recvslla ||
29732 	    ((connp->conn_ip_recvpktinfo ||
29733 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29734 	    (flags & IP_FF_IPINFO))) {
29735 		int in_flags = 0;
29736 
29737 		/*
29738 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29739 		 * IPF_RECVIF.
29740 		 */
29741 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29742 			in_flags = IPF_RECVIF;
29743 		}
29744 		if (connp->conn_recvslla) {
29745 			in_flags |= IPF_RECVSLLA;
29746 		}
29747 		if (isv4) {
29748 			mp = ip_add_info(mp, recv_ill, in_flags,
29749 			    IPCL_ZONEID(connp), ipst);
29750 		} else {
29751 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29752 			if (mp == NULL) {
29753 				BUMP_MIB(recv_ill->ill_ip_mib,
29754 				    ipIfStatsInDiscards);
29755 				CONN_DEC_REF(connp);
29756 				return;
29757 			}
29758 		}
29759 	}
29760 
29761 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29762 	/*
29763 	 * We are sending the IPSEC_IN message also up. Refer
29764 	 * to comments above this function.
29765 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29766 	 */
29767 	(connp->conn_recv)(connp, mp, NULL);
29768 	CONN_DEC_REF(connp);
29769 }
29770 
29771 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29772 {									\
29773 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29774 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29775 }
29776 /*
29777  * This function should be called only if all packet processing
29778  * including fragmentation is complete. Callers of this function
29779  * must set mp->b_prev to one of these values:
29780  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29781  * prior to handing over the mp as first argument to this function.
29782  *
29783  * If the ire passed by caller is incomplete, this function
29784  * queues the packet and if necessary, sends ARP request and bails.
29785  * If the ire passed is fully resolved, we simply prepend
29786  * the link-layer header to the packet, do ipsec hw acceleration
29787  * work if necessary, and send the packet out on the wire.
29788  *
29789  * NOTE: IPsec will only call this function with fully resolved
29790  * ires if hw acceleration is involved.
29791  * TODO list :
29792  * 	a Handle M_MULTIDATA so that
29793  *	  tcp_multisend->tcp_multisend_data can
29794  *	  call ip_xmit_v4 directly
29795  *	b Handle post-ARP work for fragments so that
29796  *	  ip_wput_frag can call this function.
29797  */
29798 ipxmit_state_t
29799 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29800 {
29801 	nce_t		*arpce;
29802 	queue_t		*q;
29803 	int		ill_index;
29804 	mblk_t		*nxt_mp, *first_mp;
29805 	boolean_t	xmit_drop = B_FALSE;
29806 	ip_proc_t	proc;
29807 	ill_t		*out_ill;
29808 	int		pkt_len;
29809 
29810 	arpce = ire->ire_nce;
29811 	ASSERT(arpce != NULL);
29812 
29813 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29814 
29815 	mutex_enter(&arpce->nce_lock);
29816 	switch (arpce->nce_state) {
29817 	case ND_REACHABLE:
29818 		/* If there are other queued packets, queue this packet */
29819 		if (arpce->nce_qd_mp != NULL) {
29820 			if (mp != NULL)
29821 				nce_queue_mp_common(arpce, mp, B_FALSE);
29822 			mp = arpce->nce_qd_mp;
29823 		}
29824 		arpce->nce_qd_mp = NULL;
29825 		mutex_exit(&arpce->nce_lock);
29826 
29827 		/*
29828 		 * Flush the queue.  In the common case, where the
29829 		 * ARP is already resolved,  it will go through the
29830 		 * while loop only once.
29831 		 */
29832 		while (mp != NULL) {
29833 
29834 			nxt_mp = mp->b_next;
29835 			mp->b_next = NULL;
29836 			ASSERT(mp->b_datap->db_type != M_CTL);
29837 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29838 			/*
29839 			 * This info is needed for IPQOS to do COS marking
29840 			 * in ip_wput_attach_llhdr->ip_process.
29841 			 */
29842 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29843 			mp->b_prev = NULL;
29844 
29845 			/* set up ill index for outbound qos processing */
29846 			out_ill = ire_to_ill(ire);
29847 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29848 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29849 			    ill_index);
29850 			if (first_mp == NULL) {
29851 				xmit_drop = B_TRUE;
29852 				BUMP_MIB(out_ill->ill_ip_mib,
29853 				    ipIfStatsOutDiscards);
29854 				goto next_mp;
29855 			}
29856 			/* non-ipsec hw accel case */
29857 			if (io == NULL || !io->ipsec_out_accelerated) {
29858 				/* send it */
29859 				q = ire->ire_stq;
29860 				if (proc == IPP_FWD_OUT) {
29861 					UPDATE_IB_PKT_COUNT(ire);
29862 				} else {
29863 					UPDATE_OB_PKT_COUNT(ire);
29864 				}
29865 				ire->ire_last_used_time = lbolt;
29866 
29867 				if (flow_ctl_enabled || canputnext(q)) {
29868 					if (proc == IPP_FWD_OUT) {
29869 
29870 					BUMP_MIB(out_ill->ill_ip_mib,
29871 					    ipIfStatsHCOutForwDatagrams);
29872 
29873 					}
29874 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29875 					    pkt_len);
29876 
29877 					putnext(q, first_mp);
29878 				} else {
29879 					BUMP_MIB(out_ill->ill_ip_mib,
29880 					    ipIfStatsOutDiscards);
29881 					xmit_drop = B_TRUE;
29882 					freemsg(first_mp);
29883 				}
29884 			} else {
29885 				/*
29886 				 * Safety Pup says: make sure this
29887 				 *  is going to the right interface!
29888 				 */
29889 				ill_t *ill1 =
29890 				    (ill_t *)ire->ire_stq->q_ptr;
29891 				int ifindex =
29892 				    ill1->ill_phyint->phyint_ifindex;
29893 				if (ifindex !=
29894 				    io->ipsec_out_capab_ill_index) {
29895 					xmit_drop = B_TRUE;
29896 					freemsg(mp);
29897 				} else {
29898 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29899 					    pkt_len);
29900 					ipsec_hw_putnext(ire->ire_stq, mp);
29901 				}
29902 			}
29903 next_mp:
29904 			mp = nxt_mp;
29905 		} /* while (mp != NULL) */
29906 		if (xmit_drop)
29907 			return (SEND_FAILED);
29908 		else
29909 			return (SEND_PASSED);
29910 
29911 	case ND_INITIAL:
29912 	case ND_INCOMPLETE:
29913 
29914 		/*
29915 		 * While we do send off packets to dests that
29916 		 * use fully-resolved CGTP routes, we do not
29917 		 * handle unresolved CGTP routes.
29918 		 */
29919 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29920 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29921 
29922 		if (mp != NULL) {
29923 			/* queue the packet */
29924 			nce_queue_mp_common(arpce, mp, B_FALSE);
29925 		}
29926 
29927 		if (arpce->nce_state == ND_INCOMPLETE) {
29928 			mutex_exit(&arpce->nce_lock);
29929 			DTRACE_PROBE3(ip__xmit__incomplete,
29930 			    (ire_t *), ire, (mblk_t *), mp,
29931 			    (ipsec_out_t *), io);
29932 			return (LOOKUP_IN_PROGRESS);
29933 		}
29934 
29935 		arpce->nce_state = ND_INCOMPLETE;
29936 		mutex_exit(&arpce->nce_lock);
29937 		/*
29938 		 * Note that ire_add() (called from ire_forward())
29939 		 * holds a ref on the ire until ARP is completed.
29940 		 */
29941 
29942 		ire_arpresolve(ire, ire_to_ill(ire));
29943 		return (LOOKUP_IN_PROGRESS);
29944 	default:
29945 		ASSERT(0);
29946 		mutex_exit(&arpce->nce_lock);
29947 		return (LLHDR_RESLV_FAILED);
29948 	}
29949 }
29950 
29951 #undef	UPDATE_IP_MIB_OB_COUNTERS
29952 
29953 /*
29954  * Return B_TRUE if the buffers differ in length or content.
29955  * This is used for comparing extension header buffers.
29956  * Note that an extension header would be declared different
29957  * even if all that changed was the next header value in that header i.e.
29958  * what really changed is the next extension header.
29959  */
29960 boolean_t
29961 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29962     uint_t blen)
29963 {
29964 	if (!b_valid)
29965 		blen = 0;
29966 
29967 	if (alen != blen)
29968 		return (B_TRUE);
29969 	if (alen == 0)
29970 		return (B_FALSE);	/* Both zero length */
29971 	return (bcmp(abuf, bbuf, alen));
29972 }
29973 
29974 /*
29975  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29976  * Return B_FALSE if memory allocation fails - don't change any state!
29977  */
29978 boolean_t
29979 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29980     const void *src, uint_t srclen)
29981 {
29982 	void *dst;
29983 
29984 	if (!src_valid)
29985 		srclen = 0;
29986 
29987 	ASSERT(*dstlenp == 0);
29988 	if (src != NULL && srclen != 0) {
29989 		dst = mi_alloc(srclen, BPRI_MED);
29990 		if (dst == NULL)
29991 			return (B_FALSE);
29992 	} else {
29993 		dst = NULL;
29994 	}
29995 	if (*dstp != NULL)
29996 		mi_free(*dstp);
29997 	*dstp = dst;
29998 	*dstlenp = dst == NULL ? 0 : srclen;
29999 	return (B_TRUE);
30000 }
30001 
30002 /*
30003  * Replace what is in *dst, *dstlen with the source.
30004  * Assumes ip_allocbuf has already been called.
30005  */
30006 void
30007 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30008     const void *src, uint_t srclen)
30009 {
30010 	if (!src_valid)
30011 		srclen = 0;
30012 
30013 	ASSERT(*dstlenp == srclen);
30014 	if (src != NULL && srclen != 0)
30015 		bcopy(src, *dstp, srclen);
30016 }
30017 
30018 /*
30019  * Free the storage pointed to by the members of an ip6_pkt_t.
30020  */
30021 void
30022 ip6_pkt_free(ip6_pkt_t *ipp)
30023 {
30024 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30025 
30026 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30027 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30028 		ipp->ipp_hopopts = NULL;
30029 		ipp->ipp_hopoptslen = 0;
30030 	}
30031 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30032 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30033 		ipp->ipp_rtdstopts = NULL;
30034 		ipp->ipp_rtdstoptslen = 0;
30035 	}
30036 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30037 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30038 		ipp->ipp_dstopts = NULL;
30039 		ipp->ipp_dstoptslen = 0;
30040 	}
30041 	if (ipp->ipp_fields & IPPF_RTHDR) {
30042 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30043 		ipp->ipp_rthdr = NULL;
30044 		ipp->ipp_rthdrlen = 0;
30045 	}
30046 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30047 	    IPPF_RTHDR);
30048 }
30049