xref: /illumos-gate/usr/src/uts/common/inet/ip/ip.c (revision ca9327a6de44d69ddab3668cc1e143ce781387a3)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
24  * Use is subject to license terms.
25  */
26 /* Copyright (c) 1990 Mentat Inc. */
27 
28 #pragma ident	"%Z%%M%	%I%	%E% SMI"
29 
30 #include <sys/types.h>
31 #include <sys/stream.h>
32 #include <sys/dlpi.h>
33 #include <sys/stropts.h>
34 #include <sys/sysmacros.h>
35 #include <sys/strsubr.h>
36 #include <sys/strlog.h>
37 #include <sys/strsun.h>
38 #include <sys/zone.h>
39 #define	_SUN_TPI_VERSION 2
40 #include <sys/tihdr.h>
41 #include <sys/xti_inet.h>
42 #include <sys/ddi.h>
43 #include <sys/sunddi.h>
44 #include <sys/cmn_err.h>
45 #include <sys/debug.h>
46 #include <sys/kobj.h>
47 #include <sys/modctl.h>
48 #include <sys/atomic.h>
49 #include <sys/policy.h>
50 #include <sys/priv.h>
51 
52 #include <sys/systm.h>
53 #include <sys/param.h>
54 #include <sys/kmem.h>
55 #include <sys/sdt.h>
56 #include <sys/socket.h>
57 #include <sys/vtrace.h>
58 #include <sys/isa_defs.h>
59 #include <sys/mac.h>
60 #include <net/if.h>
61 #include <net/if_arp.h>
62 #include <net/route.h>
63 #include <sys/sockio.h>
64 #include <netinet/in.h>
65 #include <net/if_dl.h>
66 
67 #include <inet/common.h>
68 #include <inet/mi.h>
69 #include <inet/mib2.h>
70 #include <inet/nd.h>
71 #include <inet/arp.h>
72 #include <inet/snmpcom.h>
73 #include <inet/optcom.h>
74 #include <inet/kstatcom.h>
75 
76 #include <netinet/igmp_var.h>
77 #include <netinet/ip6.h>
78 #include <netinet/icmp6.h>
79 #include <netinet/sctp.h>
80 
81 #include <inet/ip.h>
82 #include <inet/ip_impl.h>
83 #include <inet/ip6.h>
84 #include <inet/ip6_asp.h>
85 #include <inet/tcp.h>
86 #include <inet/tcp_impl.h>
87 #include <inet/ip_multi.h>
88 #include <inet/ip_if.h>
89 #include <inet/ip_ire.h>
90 #include <inet/ip_ftable.h>
91 #include <inet/ip_rts.h>
92 #include <inet/ip_ndp.h>
93 #include <inet/ip_listutils.h>
94 #include <netinet/igmp.h>
95 #include <netinet/ip_mroute.h>
96 #include <inet/ipp_common.h>
97 
98 #include <net/pfkeyv2.h>
99 #include <inet/ipsec_info.h>
100 #include <inet/sadb.h>
101 #include <inet/ipsec_impl.h>
102 #include <sys/iphada.h>
103 #include <inet/tun.h>
104 #include <inet/ipdrop.h>
105 #include <inet/ip_netinfo.h>
106 
107 #include <sys/ethernet.h>
108 #include <net/if_types.h>
109 #include <sys/cpuvar.h>
110 
111 #include <ipp/ipp.h>
112 #include <ipp/ipp_impl.h>
113 #include <ipp/ipgpc/ipgpc.h>
114 
115 #include <sys/multidata.h>
116 #include <sys/pattr.h>
117 
118 #include <inet/ipclassifier.h>
119 #include <inet/sctp_ip.h>
120 #include <inet/sctp/sctp_impl.h>
121 #include <inet/udp_impl.h>
122 #include <inet/rawip_impl.h>
123 #include <inet/rts_impl.h>
124 #include <sys/sunddi.h>
125 
126 #include <sys/tsol/label.h>
127 #include <sys/tsol/tnet.h>
128 
129 #include <rpc/pmap_prot.h>
130 
131 /*
132  * Values for squeue switch:
133  * IP_SQUEUE_ENTER_NODRAIN: squeue_enter_nodrain
134  * IP_SQUEUE_ENTER: squeue_enter
135  * IP_SQUEUE_FILL: squeue_fill
136  */
137 int ip_squeue_enter = 2;	/* Setable in /etc/system */
138 
139 squeue_func_t ip_input_proc;
140 #define	SET_BPREV_FLAG(x)	((mblk_t *)(uintptr_t)(x))
141 
142 /*
143  * Setable in /etc/system
144  */
145 int ip_poll_normal_ms = 100;
146 int ip_poll_normal_ticks = 0;
147 int ip_modclose_ackwait_ms = 3000;
148 
149 /*
150  * It would be nice to have these present only in DEBUG systems, but the
151  * current design of the global symbol checking logic requires them to be
152  * unconditionally present.
153  */
154 uint_t ip_thread_data;			/* TSD key for debug support */
155 krwlock_t ip_thread_rwlock;
156 list_t	ip_thread_list;
157 
158 /*
159  * Structure to represent a linked list of msgblks. Used by ip_snmp_ functions.
160  */
161 
162 struct listptr_s {
163 	mblk_t	*lp_head;	/* pointer to the head of the list */
164 	mblk_t	*lp_tail;	/* pointer to the tail of the list */
165 };
166 
167 typedef struct listptr_s listptr_t;
168 
169 /*
170  * This is used by ip_snmp_get_mib2_ip_route_media and
171  * ip_snmp_get_mib2_ip6_route_media to carry the lists of return data.
172  */
173 typedef struct iproutedata_s {
174 	uint_t		ird_idx;
175 	listptr_t	ird_route;	/* ipRouteEntryTable */
176 	listptr_t	ird_netmedia;	/* ipNetToMediaEntryTable */
177 	listptr_t	ird_attrs;	/* ipRouteAttributeTable */
178 } iproutedata_t;
179 
180 /*
181  * Cluster specific hooks. These should be NULL when booted as a non-cluster
182  */
183 
184 /*
185  * Hook functions to enable cluster networking
186  * On non-clustered systems these vectors must always be NULL.
187  *
188  * Hook function to Check ip specified ip address is a shared ip address
189  * in the cluster
190  *
191  */
192 int (*cl_inet_isclusterwide)(uint8_t protocol,
193     sa_family_t addr_family, uint8_t *laddrp) = NULL;
194 
195 /*
196  * Hook function to generate cluster wide ip fragment identifier
197  */
198 uint32_t (*cl_inet_ipident)(uint8_t protocol, sa_family_t addr_family,
199     uint8_t *laddrp, uint8_t *faddrp) = NULL;
200 
201 /*
202  * Synchronization notes:
203  *
204  * IP is a fully D_MP STREAMS module/driver. Thus it does not depend on any
205  * MT level protection given by STREAMS. IP uses a combination of its own
206  * internal serialization mechanism and standard Solaris locking techniques.
207  * The internal serialization is per phyint (no IPMP) or per IPMP group.
208  * This is used to serialize plumbing operations, IPMP operations, certain
209  * multicast operations, most set ioctls, igmp/mld timers etc.
210  *
211  * Plumbing is a long sequence of operations involving message
212  * exchanges between IP, ARP and device drivers. Many set ioctls are typically
213  * involved in plumbing operations. A natural model is to serialize these
214  * ioctls one per ill. For example plumbing of hme0 and qfe0 can go on in
215  * parallel without any interference. But various set ioctls on hme0 are best
216  * serialized. However if the system uses IPMP, the operations are easier if
217  * they are serialized on a per IPMP group basis since IPMP operations
218  * happen across ill's of a group. Thus the lowest common denominator is to
219  * serialize most set ioctls, multicast join/leave operations, IPMP operations
220  * igmp/mld timer operations, and processing of DLPI control messages received
221  * from drivers on a per IPMP group basis. If the system does not employ
222  * IPMP the serialization is on a per phyint basis. This serialization is
223  * provided by the ipsq_t and primitives operating on this. Details can
224  * be found in ip_if.c above the core primitives operating on ipsq_t.
225  *
226  * Lookups of an ipif or ill by a thread return a refheld ipif / ill.
227  * Simiarly lookup of an ire by a thread also returns a refheld ire.
228  * In addition ipif's and ill's referenced by the ire are also indirectly
229  * refheld. Thus no ipif or ill can vanish nor can critical parameters like
230  * the ipif's address or netmask change as long as an ipif is refheld
231  * directly or indirectly. For example an SIOCLIFADDR ioctl that changes the
232  * address of an ipif has to go through the ipsq_t. This ensures that only
233  * 1 such exclusive operation proceeds at any time on the ipif. It then
234  * deletes all ires associated with this ipif, and waits for all refcnts
235  * associated with this ipif to come down to zero. The address is changed
236  * only after the ipif has been quiesced. Then the ipif is brought up again.
237  * More details are described above the comment in ip_sioctl_flags.
238  *
239  * Packet processing is based mostly on IREs and are fully multi-threaded
240  * using standard Solaris MT techniques.
241  *
242  * There are explicit locks in IP to handle:
243  * - The ip_g_head list maintained by mi_open_link() and friends.
244  *
245  * - The reassembly data structures (one lock per hash bucket)
246  *
247  * - conn_lock is meant to protect conn_t fields. The fields actually
248  *   protected by conn_lock are documented in the conn_t definition.
249  *
250  * - ire_lock to protect some of the fields of the ire, IRE tables
251  *   (one lock per hash bucket). Refer to ip_ire.c for details.
252  *
253  * - ndp_g_lock and nce_lock for protecting NCEs.
254  *
255  * - ill_lock protects fields of the ill and ipif. Details in ip.h
256  *
257  * - ill_g_lock: This is a global reader/writer lock. Protects the following
258  *	* The AVL tree based global multi list of all ills.
259  *	* The linked list of all ipifs of an ill
260  *	* The <ill-ipsq> mapping
261  *	* The ipsq->ipsq_phyint_list threaded by phyint_ipsq_next
262  *	* The illgroup list threaded by ill_group_next.
263  *	* <ill-phyint> association
264  *   Insertion/deletion of an ill in the system, insertion/deletion of an ipif
265  *   into an ill, changing the <ill-ipsq> mapping of an ill, insertion/deletion
266  *   of an ill into the illgrp list, changing the <ill-phyint> assoc of an ill
267  *   will all have to hold the ill_g_lock as writer for the actual duration
268  *   of the insertion/deletion/change. More details about the <ill-ipsq> mapping
269  *   may be found in the IPMP section.
270  *
271  * - ill_lock:  This is a per ill mutex.
272  *   It protects some members of the ill and is documented below.
273  *   It also protects the <ill-ipsq> mapping
274  *   It also protects the illgroup list threaded by ill_group_next.
275  *   It also protects the <ill-phyint> assoc.
276  *   It also protects the list of ipifs hanging off the ill.
277  *
278  * - ipsq_lock: This is a per ipsq_t mutex lock.
279  *   This protects all the other members of the ipsq struct except
280  *   ipsq_refs and ipsq_phyint_list which are protected by ill_g_lock
281  *
282  * - illgrp_lock: This is a per ill_group mutex lock.
283  *   The only thing it protects is the illgrp_ill_schednext member of ill_group
284  *   which dictates which is the next ill in an ill_group that is to be chosen
285  *   for sending outgoing packets, through creation of an IRE_CACHE that
286  *   references this ill.
287  *
288  * - phyint_lock: This is a per phyint mutex lock. Protects just the
289  *   phyint_flags
290  *
291  * - ip_g_nd_lock: This is a global reader/writer lock.
292  *   Any call to nd_load to load a new parameter to the ND table must hold the
293  *   lock as writer. ND_GET/ND_SET routines that read the ND table hold the lock
294  *   as reader.
295  *
296  * - ip_addr_avail_lock: This is used to ensure the uniqueness of IP addresses.
297  *   This lock is held in ipif_up_done and the ipif is marked IPIF_UP and the
298  *   uniqueness check also done atomically.
299  *
300  * - ipsec_capab_ills_lock: This readers/writer lock protects the global
301  *   lists of IPsec capable ills (ipsec_capab_ills_{ah,esp}). It is taken
302  *   as a writer when adding or deleting elements from these lists, and
303  *   as a reader when walking these lists to send a SADB update to the
304  *   IPsec capable ills.
305  *
306  * - ill_g_usesrc_lock: This readers/writer lock protects the usesrc
307  *   group list linked by ill_usesrc_grp_next. It also protects the
308  *   ill_usesrc_ifindex field. It is taken as a writer when a member of the
309  *   group is being added or deleted.  This lock is taken as a reader when
310  *   walking the list/group(eg: to get the number of members in a usesrc group).
311  *   Note, it is only necessary to take this lock if the ill_usesrc_grp_next
312  *   field is changing state i.e from NULL to non-NULL or vice-versa. For
313  *   example, it is not necessary to take this lock in the initial portion
314  *   of ip_sioctl_slifusesrc or at all in ip_sioctl_groupname and
315  *   ip_sioctl_flags since the these operations are executed exclusively and
316  *   that ensures that the "usesrc group state" cannot change. The "usesrc
317  *   group state" change can happen only in the latter part of
318  *   ip_sioctl_slifusesrc and in ill_delete.
319  *
320  * Changing <ill-phyint>, <ill-ipsq>, <ill-illgroup> assocications.
321  *
322  * To change the <ill-phyint> association, the ill_g_lock must be held
323  * as writer, and the ill_locks of both the v4 and v6 instance of the ill
324  * must be held.
325  *
326  * To change the <ill-ipsq> association the ill_g_lock must be held as writer
327  * and the ill_lock of the ill in question must be held.
328  *
329  * To change the <ill-illgroup> association the ill_g_lock must be held as
330  * writer and the ill_lock of the ill in question must be held.
331  *
332  * To add or delete an ipif from the list of ipifs hanging off the ill,
333  * ill_g_lock (writer) and ill_lock must be held and the thread must be
334  * a writer on the associated ipsq,.
335  *
336  * To add or delete an ill to the system, the ill_g_lock must be held as
337  * writer and the thread must be a writer on the associated ipsq.
338  *
339  * To add or delete an ilm to an ill, the ill_lock must be held and the thread
340  * must be a writer on the associated ipsq.
341  *
342  * Lock hierarchy
343  *
344  * Some lock hierarchy scenarios are listed below.
345  *
346  * ill_g_lock -> conn_lock -> ill_lock -> ipsq_lock
347  * ill_g_lock -> illgrp_lock -> ill_lock
348  * ill_g_lock -> ill_lock(s) -> phyint_lock
349  * ill_g_lock -> ndp_g_lock -> ill_lock -> nce_lock
350  * ill_g_lock -> ip_addr_avail_lock
351  * conn_lock -> irb_lock -> ill_lock -> ire_lock
352  * ill_g_lock -> ip_g_nd_lock
353  *
354  * When more than 1 ill lock is needed to be held, all ill lock addresses
355  * are sorted on address and locked starting from highest addressed lock
356  * downward.
357  *
358  * IPsec scenarios
359  *
360  * ipsa_lock -> ill_g_lock -> ill_lock
361  * ipsec_capab_ills_lock -> ill_g_lock -> ill_lock
362  * ipsec_capab_ills_lock -> ipsa_lock
363  * ill_g_usesrc_lock -> ill_g_lock -> ill_lock
364  *
365  * Trusted Solaris scenarios
366  *
367  * igsa_lock -> gcgrp_rwlock -> gcgrp_lock
368  * igsa_lock -> gcdb_lock
369  * gcgrp_rwlock -> ire_lock
370  * gcgrp_rwlock -> gcdb_lock
371  *
372  *
373  * Routing/forwarding table locking notes:
374  *
375  * Lock acquisition order: Radix tree lock, irb_lock.
376  * Requirements:
377  * i.  Walker must not hold any locks during the walker callback.
378  * ii  Walker must not see a truncated tree during the walk because of any node
379  *     deletion.
380  * iii Existing code assumes ire_bucket is valid if it is non-null and is used
381  *     in many places in the code to walk the irb list. Thus even if all the
382  *     ires in a bucket have been deleted, we still can't free the radix node
383  *     until the ires have actually been inactive'd (freed).
384  *
385  * Tree traversal - Need to hold the global tree lock in read mode.
386  * Before dropping the global tree lock, need to either increment the ire_refcnt
387  * to ensure that the radix node can't be deleted.
388  *
389  * Tree add - Need to hold the global tree lock in write mode to add a
390  * radix node. To prevent the node from being deleted, increment the
391  * irb_refcnt, after the node is added to the tree. The ire itself is
392  * added later while holding the irb_lock, but not the tree lock.
393  *
394  * Tree delete - Need to hold the global tree lock and irb_lock in write mode.
395  * All associated ires must be inactive (i.e. freed), and irb_refcnt
396  * must be zero.
397  *
398  * Walker - Increment irb_refcnt before calling the walker callback. Hold the
399  * global tree lock (read mode) for traversal.
400  *
401  * IPsec notes :
402  *
403  * IP interacts with the IPsec code (AH/ESP) by tagging a M_CTL message
404  * in front of the actual packet. For outbound datagrams, the M_CTL
405  * contains a ipsec_out_t (defined in ipsec_info.h), which has the
406  * information used by the IPsec code for applying the right level of
407  * protection. The information initialized by IP in the ipsec_out_t
408  * is determined by the per-socket policy or global policy in the system.
409  * For inbound datagrams, the M_CTL contains a ipsec_in_t (defined in
410  * ipsec_info.h) which starts out with nothing in it. It gets filled
411  * with the right information if it goes through the AH/ESP code, which
412  * happens if the incoming packet is secure. The information initialized
413  * by AH/ESP, is later used by IP(during fanouts to ULP) to see whether
414  * the policy requirements needed by per-socket policy or global policy
415  * is met or not.
416  *
417  * If there is both per-socket policy (set using setsockopt) and there
418  * is also global policy match for the 5 tuples of the socket,
419  * ipsec_override_policy() makes the decision of which one to use.
420  *
421  * For fully connected sockets i.e dst, src [addr, port] is known,
422  * conn_policy_cached is set indicating that policy has been cached.
423  * conn_in_enforce_policy may or may not be set depending on whether
424  * there is a global policy match or per-socket policy match.
425  * Policy inheriting happpens in ip_bind during the ipa_conn_t bind.
426  * Once the right policy is set on the conn_t, policy cannot change for
427  * this socket. This makes life simpler for TCP (UDP ?) where
428  * re-transmissions go out with the same policy. For symmetry, policy
429  * is cached for fully connected UDP sockets also. Thus if policy is cached,
430  * it also implies that policy is latched i.e policy cannot change
431  * on these sockets. As we have the right policy on the conn, we don't
432  * have to lookup global policy for every outbound and inbound datagram
433  * and thus serving as an optimization. Note that a global policy change
434  * does not affect fully connected sockets if they have policy. If fully
435  * connected sockets did not have any policy associated with it, global
436  * policy change may affect them.
437  *
438  * IP Flow control notes:
439  *
440  * Non-TCP streams are flow controlled by IP. On the send side, if the packet
441  * cannot be sent down to the driver by IP, because of a canput failure, IP
442  * does a putq on the conn_wq. This will cause ip_wsrv to run on the conn_wq.
443  * ip_wsrv in turn, inserts the conn in a list of conn's that need to be drained
444  * when the flowcontrol condition subsides. Ultimately STREAMS backenables the
445  * ip_wsrv on the IP module, which in turn does a qenable of the conn_wq of the
446  * first conn in the list of conn's to be drained. ip_wsrv on this conn drains
447  * the queued messages, and removes the conn from the drain list, if all
448  * messages were drained. It also qenables the next conn in the drain list to
449  * continue the drain process.
450  *
451  * In reality the drain list is not a single list, but a configurable number
452  * of lists. The ip_wsrv on the IP module, qenables the first conn in each
453  * list. If the ip_wsrv of the next qenabled conn does not run, because the
454  * stream closes, ip_close takes responsibility to qenable the next conn in
455  * the drain list. The directly called ip_wput path always does a putq, if
456  * it cannot putnext. Thus synchronization problems are handled between
457  * ip_wsrv and ip_close. conn_drain_insert and conn_drain_tail are the only
458  * functions that manipulate this drain list. Furthermore conn_drain_insert
459  * is called only from ip_wsrv, and there can be only 1 instance of ip_wsrv
460  * running on a queue at any time. conn_drain_tail can be simultaneously called
461  * from both ip_wsrv and ip_close.
462  *
463  * IPQOS notes:
464  *
465  * IPQoS Policies are applied to packets using IPPF (IP Policy framework)
466  * and IPQoS modules. IPPF includes hooks in IP at different control points
467  * (callout positions) which direct packets to IPQoS modules for policy
468  * processing. Policies, if present, are global.
469  *
470  * The callout positions are located in the following paths:
471  *		o local_in (packets destined for this host)
472  *		o local_out (packets orginating from this host )
473  *		o fwd_in  (packets forwarded by this m/c - inbound)
474  *		o fwd_out (packets forwarded by this m/c - outbound)
475  * Hooks at these callout points can be enabled/disabled using the ndd variable
476  * ip_policy_mask (a bit mask with the 4 LSB indicating the callout positions).
477  * By default all the callout positions are enabled.
478  *
479  * Outbound (local_out)
480  * Hooks are placed in ip_wput_ire and ipsec_out_process.
481  *
482  * Inbound (local_in)
483  * Hooks are placed in ip_proto_input, icmp_inbound, ip_fanout_proto and
484  * TCP and UDP fanout routines.
485  *
486  * Forwarding (in and out)
487  * Hooks are placed in ip_rput_forward.
488  *
489  * IP Policy Framework processing (IPPF processing)
490  * Policy processing for a packet is initiated by ip_process, which ascertains
491  * that the classifier (ipgpc) is loaded and configured, failing which the
492  * packet resumes normal processing in IP. If the clasifier is present, the
493  * packet is acted upon by one or more IPQoS modules (action instances), per
494  * filters configured in ipgpc and resumes normal IP processing thereafter.
495  * An action instance can drop a packet in course of its processing.
496  *
497  * A boolean variable, ip_policy, is used in all the fanout routines that can
498  * invoke ip_process for a packet. This variable indicates if the packet should
499  * to be sent for policy processing. The variable is set to B_TRUE by default,
500  * i.e. when the routines are invoked in the normal ip procesing path for a
501  * packet. The two exceptions being ip_wput_local and icmp_inbound_error_fanout;
502  * ip_policy is set to B_FALSE for all the routines called in these two
503  * functions because, in the former case,  we don't process loopback traffic
504  * currently while in the latter, the packets have already been processed in
505  * icmp_inbound.
506  *
507  * Zones notes:
508  *
509  * The partitioning rules for networking are as follows:
510  * 1) Packets coming from a zone must have a source address belonging to that
511  * zone.
512  * 2) Packets coming from a zone can only be sent on a physical interface on
513  * which the zone has an IP address.
514  * 3) Between two zones on the same machine, packet delivery is only allowed if
515  * there's a matching route for the destination and zone in the forwarding
516  * table.
517  * 4) The TCP and UDP port spaces are per-zone; that is, two processes in
518  * different zones can bind to the same port with the wildcard address
519  * (INADDR_ANY).
520  *
521  * The granularity of interface partitioning is at the logical interface level.
522  * Therefore, every zone has its own IP addresses, and incoming packets can be
523  * attributed to a zone unambiguously. A logical interface is placed into a zone
524  * using the SIOCSLIFZONE ioctl; this sets the ipif_zoneid field in the ipif_t
525  * structure. Rule (1) is implemented by modifying the source address selection
526  * algorithm so that the list of eligible addresses is filtered based on the
527  * sending process zone.
528  *
529  * The Internet Routing Entries (IREs) are either exclusive to a zone or shared
530  * across all zones, depending on their type. Here is the break-up:
531  *
532  * IRE type				Shared/exclusive
533  * --------				----------------
534  * IRE_BROADCAST			Exclusive
535  * IRE_DEFAULT (default routes)		Shared (*)
536  * IRE_LOCAL				Exclusive (x)
537  * IRE_LOOPBACK				Exclusive
538  * IRE_PREFIX (net routes)		Shared (*)
539  * IRE_CACHE				Exclusive
540  * IRE_IF_NORESOLVER (interface routes)	Exclusive
541  * IRE_IF_RESOLVER (interface routes)	Exclusive
542  * IRE_HOST (host routes)		Shared (*)
543  *
544  * (*) A zone can only use a default or off-subnet route if the gateway is
545  * directly reachable from the zone, that is, if the gateway's address matches
546  * one of the zone's logical interfaces.
547  *
548  * (x) IRE_LOCAL are handled a bit differently, since for all other entries
549  * in ire_ctable and IRE_INTERFACE, ire_src_addr is what can be used as source
550  * when sending packets using the IRE. For IRE_LOCAL ire_src_addr is the IP
551  * address of the zone itself (the destination). Since IRE_LOCAL is used
552  * for communication between zones, ip_wput_ire has special logic to set
553  * the right source address when sending using an IRE_LOCAL.
554  *
555  * Furthermore, when ip_restrict_interzone_loopback is set (the default),
556  * ire_cache_lookup restricts loopback using an IRE_LOCAL
557  * between zone to the case when L2 would have conceptually looped the packet
558  * back, i.e. the loopback which is required since neither Ethernet drivers
559  * nor Ethernet hardware loops them back. This is the case when the normal
560  * routes (ignoring IREs with different zoneids) would send out the packet on
561  * the same ill (or ill group) as the ill with which is IRE_LOCAL is
562  * associated.
563  *
564  * Multiple zones can share a common broadcast address; typically all zones
565  * share the 255.255.255.255 address. Incoming as well as locally originated
566  * broadcast packets must be dispatched to all the zones on the broadcast
567  * network. For directed broadcasts (e.g. 10.16.72.255) this is not trivial
568  * since some zones may not be on the 10.16.72/24 network. To handle this, each
569  * zone has its own set of IRE_BROADCAST entries; then, broadcast packets are
570  * sent to every zone that has an IRE_BROADCAST entry for the destination
571  * address on the input ill, see conn_wantpacket().
572  *
573  * Applications in different zones can join the same multicast group address.
574  * For IPv4, group memberships are per-logical interface, so they're already
575  * inherently part of a zone. For IPv6, group memberships are per-physical
576  * interface, so we distinguish IPv6 group memberships based on group address,
577  * interface and zoneid. In both cases, received multicast packets are sent to
578  * every zone for which a group membership entry exists. On IPv6 we need to
579  * check that the target zone still has an address on the receiving physical
580  * interface; it could have been removed since the application issued the
581  * IPV6_JOIN_GROUP.
582  */
583 
584 /*
585  * Squeue Fanout flags:
586  *	0: No fanout.
587  *	1: Fanout across all squeues
588  */
589 boolean_t	ip_squeue_fanout = 0;
590 
591 /*
592  * Maximum dups allowed per packet.
593  */
594 uint_t ip_max_frag_dups = 10;
595 
596 #define	IS_SIMPLE_IPH(ipha)						\
597 	((ipha)->ipha_version_and_hdr_length == IP_SIMPLE_HDR_VERSION)
598 
599 /* RFC1122 Conformance */
600 #define	IP_FORWARD_DEFAULT	IP_FORWARD_NEVER
601 
602 #define	ILL_MAX_NAMELEN			LIFNAMSIZ
603 
604 static int	conn_set_held_ipif(conn_t *, ipif_t **, ipif_t *);
605 
606 static int	ip_open(queue_t *q, dev_t *devp, int flag, int sflag,
607 		    cred_t *credp, boolean_t isv6);
608 static mblk_t	*ip_wput_attach_llhdr(mblk_t *, ire_t *, ip_proc_t, uint32_t);
609 
610 static void	icmp_frag_needed(queue_t *, mblk_t *, int, zoneid_t,
611 		    ip_stack_t *);
612 static void	icmp_inbound(queue_t *, mblk_t *, boolean_t, ill_t *, int,
613 		    uint32_t, boolean_t, boolean_t, ill_t *, zoneid_t);
614 static ipaddr_t	icmp_get_nexthop_addr(ipha_t *, ill_t *, zoneid_t, mblk_t *mp);
615 static boolean_t icmp_inbound_too_big(icmph_t *, ipha_t *, ill_t *, zoneid_t,
616 		    mblk_t *, int, ip_stack_t *);
617 static void	icmp_inbound_error_fanout(queue_t *, ill_t *, mblk_t *,
618 		    icmph_t *, ipha_t *, int, int, boolean_t, boolean_t,
619 		    ill_t *, zoneid_t);
620 static void	icmp_options_update(ipha_t *);
621 static void	icmp_param_problem(queue_t *, mblk_t *, uint8_t, zoneid_t,
622 		    ip_stack_t *);
623 static void	icmp_pkt(queue_t *, mblk_t *, void *, size_t, boolean_t,
624 		    zoneid_t zoneid, ip_stack_t *);
625 static mblk_t	*icmp_pkt_err_ok(mblk_t *, ip_stack_t *);
626 static void	icmp_redirect(ill_t *, mblk_t *);
627 static void	icmp_send_redirect(queue_t *, mblk_t *, ipaddr_t,
628 		    ip_stack_t *);
629 
630 static void	ip_arp_news(queue_t *, mblk_t *);
631 static boolean_t ip_bind_insert_ire(mblk_t *, ire_t *, iulp_t *,
632 		    ip_stack_t *);
633 mblk_t		*ip_dlpi_alloc(size_t, t_uscalar_t);
634 char		*ip_dot_addr(ipaddr_t, char *);
635 mblk_t		*ip_carve_mp(mblk_t **, ssize_t);
636 int		ip_close(queue_t *, int);
637 static char	*ip_dot_saddr(uchar_t *, char *);
638 static void	ip_fanout_proto(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
639 		    boolean_t, boolean_t, ill_t *, zoneid_t);
640 static void	ip_fanout_tcp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint_t,
641 		    boolean_t, boolean_t, zoneid_t);
642 static void	ip_fanout_udp(queue_t *, mblk_t *, ill_t *, ipha_t *, uint32_t,
643 		    boolean_t, uint_t, boolean_t, boolean_t, ill_t *, zoneid_t);
644 static void	ip_lrput(queue_t *, mblk_t *);
645 ipaddr_t	ip_net_mask(ipaddr_t);
646 void		ip_newroute(queue_t *, mblk_t *, ipaddr_t, conn_t *, zoneid_t,
647 		    ip_stack_t *);
648 static void	ip_newroute_ipif(queue_t *, mblk_t *, ipif_t *, ipaddr_t,
649 		    conn_t *, uint32_t, zoneid_t, ip_opt_info_t *);
650 char		*ip_nv_lookup(nv_t *, int);
651 static boolean_t	ip_check_for_ipsec_opt(queue_t *, mblk_t *);
652 static int	ip_param_get(queue_t *, mblk_t *, caddr_t, cred_t *);
653 static int	ip_param_generic_get(queue_t *, mblk_t *, caddr_t, cred_t *);
654 static boolean_t	ip_param_register(IDP *ndp, ipparam_t *, size_t,
655     ipndp_t *, size_t);
656 static int	ip_param_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
657 void	ip_rput(queue_t *, mblk_t *);
658 static void	ip_rput_dlpi_writer(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
659 		    void *dummy_arg);
660 void	ip_rput_forward(ire_t *, ipha_t *, mblk_t *, ill_t *);
661 static int	ip_rput_forward_options(mblk_t *, ipha_t *, ire_t *,
662     ip_stack_t *);
663 static boolean_t	ip_rput_local_options(queue_t *, mblk_t *, ipha_t *,
664 			    ire_t *, ip_stack_t *);
665 static boolean_t	ip_rput_multimblk_ipoptions(queue_t *, ill_t *,
666 			    mblk_t *, ipha_t **, ipaddr_t *, ip_stack_t *);
667 static int	ip_rput_options(queue_t *, mblk_t *, ipha_t *, ipaddr_t *,
668     ip_stack_t *);
669 static boolean_t ip_rput_fragment(queue_t *, mblk_t **, ipha_t *, uint32_t *,
670 		    uint16_t *);
671 int		ip_snmp_get(queue_t *, mblk_t *, int);
672 static mblk_t	*ip_snmp_get_mib2_ip(queue_t *, mblk_t *,
673 		    mib2_ipIfStatsEntry_t *, ip_stack_t *);
674 static mblk_t	*ip_snmp_get_mib2_ip_traffic_stats(queue_t *, mblk_t *,
675 		    ip_stack_t *);
676 static mblk_t	*ip_snmp_get_mib2_ip6(queue_t *, mblk_t *, ip_stack_t *);
677 static mblk_t	*ip_snmp_get_mib2_icmp(queue_t *, mblk_t *, ip_stack_t *ipst);
678 static mblk_t	*ip_snmp_get_mib2_icmp6(queue_t *, mblk_t *, ip_stack_t *ipst);
679 static mblk_t	*ip_snmp_get_mib2_igmp(queue_t *, mblk_t *, ip_stack_t *ipst);
680 static mblk_t	*ip_snmp_get_mib2_multi(queue_t *, mblk_t *, ip_stack_t *ipst);
681 static mblk_t	*ip_snmp_get_mib2_ip_addr(queue_t *, mblk_t *,
682 		    ip_stack_t *ipst);
683 static mblk_t	*ip_snmp_get_mib2_ip6_addr(queue_t *, mblk_t *,
684 		    ip_stack_t *ipst);
685 static mblk_t	*ip_snmp_get_mib2_ip_group_src(queue_t *, mblk_t *,
686 		    ip_stack_t *ipst);
687 static mblk_t	*ip_snmp_get_mib2_ip6_group_src(queue_t *, mblk_t *,
688 		    ip_stack_t *ipst);
689 static mblk_t	*ip_snmp_get_mib2_ip_group_mem(queue_t *, mblk_t *,
690 		    ip_stack_t *ipst);
691 static mblk_t	*ip_snmp_get_mib2_ip6_group_mem(queue_t *, mblk_t *,
692 		    ip_stack_t *ipst);
693 static mblk_t	*ip_snmp_get_mib2_virt_multi(queue_t *, mblk_t *,
694 		    ip_stack_t *ipst);
695 static mblk_t	*ip_snmp_get_mib2_multi_rtable(queue_t *, mblk_t *,
696 		    ip_stack_t *ipst);
697 static mblk_t	*ip_snmp_get_mib2_ip_route_media(queue_t *, mblk_t *,
698 		    ip_stack_t *ipst);
699 static mblk_t	*ip_snmp_get_mib2_ip6_route_media(queue_t *, mblk_t *,
700 		    ip_stack_t *ipst);
701 static void	ip_snmp_get2_v4(ire_t *, iproutedata_t *);
702 static void	ip_snmp_get2_v6_route(ire_t *, iproutedata_t *);
703 static int	ip_snmp_get2_v6_media(nce_t *, iproutedata_t *);
704 int		ip_snmp_set(queue_t *, int, int, uchar_t *, int);
705 static boolean_t	ip_source_routed(ipha_t *, ip_stack_t *);
706 static boolean_t	ip_source_route_included(ipha_t *);
707 static void	ip_trash_ire_reclaim_stack(ip_stack_t *);
708 
709 static void	ip_wput_frag(ire_t *, mblk_t *, ip_pkt_t, uint32_t, uint32_t,
710 		    zoneid_t, ip_stack_t *);
711 static mblk_t	*ip_wput_frag_copyhdr(uchar_t *, int, int, ip_stack_t *);
712 static void	ip_wput_local_options(ipha_t *, ip_stack_t *);
713 static int	ip_wput_options(queue_t *, mblk_t *, ipha_t *, boolean_t,
714 		    zoneid_t, ip_stack_t *);
715 
716 static void	conn_drain_init(ip_stack_t *);
717 static void	conn_drain_fini(ip_stack_t *);
718 static void	conn_drain_tail(conn_t *connp, boolean_t closing);
719 
720 static void	conn_walk_drain(ip_stack_t *);
721 static void	conn_walk_fanout_table(connf_t *, uint_t, pfv_t, void *,
722     zoneid_t);
723 
724 static void	*ip_stack_init(netstackid_t stackid, netstack_t *ns);
725 static void	ip_stack_shutdown(netstackid_t stackid, void *arg);
726 static void	ip_stack_fini(netstackid_t stackid, void *arg);
727 
728 static boolean_t	conn_wantpacket(conn_t *, ill_t *, ipha_t *, int,
729     zoneid_t);
730 static void	ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp,
731     void *dummy_arg);
732 
733 static int	ip_forward_set(queue_t *, mblk_t *, char *, caddr_t, cred_t *);
734 
735 static int	ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t,
736     ipaddr_t, ipaddr_t, uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *,
737     conn_t *, boolean_t, ipaddr_t, mcast_record_t, ipaddr_t, mblk_t *);
738 static void	ip_multirt_bad_mtu(ire_t *, uint32_t);
739 
740 static int	ip_cgtp_filter_get(queue_t *, mblk_t *, caddr_t, cred_t *);
741 static int	ip_cgtp_filter_set(queue_t *, mblk_t *, char *,
742     caddr_t, cred_t *);
743 extern int	ip_squeue_bind_set(queue_t *q, mblk_t *mp, char *value,
744     caddr_t cp, cred_t *cr);
745 extern int	ip_squeue_profile_set(queue_t *, mblk_t *, char *, caddr_t,
746     cred_t *);
747 static int	ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
748     caddr_t cp, cred_t *cr);
749 static int	ip_int_set(queue_t *, mblk_t *, char *, caddr_t,
750     cred_t *);
751 static int	ipmp_hook_emulation_set(queue_t *, mblk_t *, char *, caddr_t,
752     cred_t *);
753 static squeue_func_t ip_squeue_switch(int);
754 
755 static void	*ip_kstat_init(netstackid_t, ip_stack_t *);
756 static void	ip_kstat_fini(netstackid_t, kstat_t *);
757 static int	ip_kstat_update(kstat_t *kp, int rw);
758 static void	*icmp_kstat_init(netstackid_t);
759 static void	icmp_kstat_fini(netstackid_t, kstat_t *);
760 static int	icmp_kstat_update(kstat_t *kp, int rw);
761 static void	*ip_kstat2_init(netstackid_t, ip_stat_t *);
762 static void	ip_kstat2_fini(netstackid_t, kstat_t *);
763 
764 static int	ip_conn_report(queue_t *, mblk_t *, caddr_t, cred_t *);
765 
766 static mblk_t	*ip_tcp_input(mblk_t *, ipha_t *, ill_t *, boolean_t,
767     ire_t *, mblk_t *, uint_t, queue_t *, ill_rx_ring_t *);
768 
769 static void	ip_rput_process_forward(queue_t *, mblk_t *, ire_t *,
770     ipha_t *, ill_t *, boolean_t);
771 ipaddr_t	ip_g_all_ones = IP_HOST_MASK;
772 
773 /* How long, in seconds, we allow frags to hang around. */
774 #define	IP_FRAG_TIMEOUT	60
775 
776 /*
777  * Threshold which determines whether MDT should be used when
778  * generating IP fragments; payload size must be greater than
779  * this threshold for MDT to take place.
780  */
781 #define	IP_WPUT_FRAG_MDT_MIN	32768
782 
783 /* Setable in /etc/system only */
784 int	ip_wput_frag_mdt_min = IP_WPUT_FRAG_MDT_MIN;
785 
786 static long ip_rput_pullups;
787 int	dohwcksum = 1;	/* use h/w cksum if supported by the hardware */
788 
789 vmem_t *ip_minor_arena_sa; /* for minor nos. from INET_MIN_DEV+2 thru 2^^18-1 */
790 vmem_t *ip_minor_arena_la; /* for minor nos. from 2^^18 thru 2^^32-1 */
791 
792 int	ip_debug;
793 
794 #ifdef DEBUG
795 uint32_t ipsechw_debug = 0;
796 #endif
797 
798 /*
799  * Multirouting/CGTP stuff
800  */
801 int	ip_cgtp_filter_rev = CGTP_FILTER_REV;	/* CGTP hooks version */
802 
803 /*
804  * XXX following really should only be in a header. Would need more
805  * header and .c clean up first.
806  */
807 extern optdb_obj_t	ip_opt_obj;
808 
809 ulong_t ip_squeue_enter_unbound = 0;
810 
811 /*
812  * Named Dispatch Parameter Table.
813  * All of these are alterable, within the min/max values given, at run time.
814  */
815 static ipparam_t	lcl_param_arr[] = {
816 	/* min	max	value	name */
817 	{  0,	1,	0,	"ip_respond_to_address_mask_broadcast"},
818 	{  0,	1,	1,	"ip_respond_to_echo_broadcast"},
819 	{  0,	1,	1,	"ip_respond_to_echo_multicast"},
820 	{  0,	1,	0,	"ip_respond_to_timestamp"},
821 	{  0,	1,	0,	"ip_respond_to_timestamp_broadcast"},
822 	{  0,	1,	1,	"ip_send_redirects"},
823 	{  0,	1,	0,	"ip_forward_directed_broadcasts"},
824 	{  0,	10,	0,	"ip_mrtdebug"},
825 	{  5000, 999999999,	60000, "ip_ire_timer_interval" },
826 	{  60000, 999999999,	1200000, "ip_ire_arp_interval" },
827 	{  60000, 999999999,	60000, "ip_ire_redirect_interval" },
828 	{  1,	255,	255,	"ip_def_ttl" },
829 	{  0,	1,	0,	"ip_forward_src_routed"},
830 	{  0,	256,	32,	"ip_wroff_extra" },
831 	{  5000, 999999999, 600000, "ip_ire_pathmtu_interval" },
832 	{  8,	65536,  64,	"ip_icmp_return_data_bytes" },
833 	{  0,	1,	1,	"ip_path_mtu_discovery" },
834 	{  0,	240,	30,	"ip_ignore_delete_time" },
835 	{  0,	1,	0,	"ip_ignore_redirect" },
836 	{  0,	1,	1,	"ip_output_queue" },
837 	{  1,	254,	1,	"ip_broadcast_ttl" },
838 	{  0,	99999,	100,	"ip_icmp_err_interval" },
839 	{  1,	99999,	10,	"ip_icmp_err_burst" },
840 	{  0,	999999999,	1000000, "ip_reass_queue_bytes" },
841 	{  0,	1,	0,	"ip_strict_dst_multihoming" },
842 	{  1,	MAX_ADDRS_PER_IF,	256,	"ip_addrs_per_if"},
843 	{  0,	1,	0,	"ipsec_override_persocket_policy" },
844 	{  0,	1,	1,	"icmp_accept_clear_messages" },
845 	{  0,	1,	1,	"igmp_accept_clear_messages" },
846 	{  2,	999999999, ND_DELAY_FIRST_PROBE_TIME,
847 				"ip_ndp_delay_first_probe_time"},
848 	{  1,	999999999, ND_MAX_UNICAST_SOLICIT,
849 				"ip_ndp_max_unicast_solicit"},
850 	{  1,	255,	IPV6_MAX_HOPS,	"ip6_def_hops" },
851 	{  8,	IPV6_MIN_MTU,	IPV6_MIN_MTU, "ip6_icmp_return_data_bytes" },
852 	{  0,	1,	0,	"ip6_forward_src_routed"},
853 	{  0,	1,	1,	"ip6_respond_to_echo_multicast"},
854 	{  0,	1,	1,	"ip6_send_redirects"},
855 	{  0,	1,	0,	"ip6_ignore_redirect" },
856 	{  0,	1,	0,	"ip6_strict_dst_multihoming" },
857 
858 	{  1,	8,	3,	"ip_ire_reclaim_fraction" },
859 
860 	{  0,	999999,	1000,	"ipsec_policy_log_interval" },
861 
862 	{  0,	1,	1,	"pim_accept_clear_messages" },
863 	{  1000, 20000,	2000,	"ip_ndp_unsolicit_interval" },
864 	{  1,	20,	3,	"ip_ndp_unsolicit_count" },
865 	{  0,	1,	1,	"ip6_ignore_home_address_opt" },
866 	{  0,	15,	0,	"ip_policy_mask" },
867 	{  1000, 60000, 1000,	"ip_multirt_resolution_interval" },
868 	{  0,	255,	1,	"ip_multirt_ttl" },
869 	{  0,	1,	1,	"ip_multidata_outbound" },
870 	{  0,	3600000, 300000, "ip_ndp_defense_interval" },
871 	{  0,	999999,	60*60*24, "ip_max_temp_idle" },
872 	{  0,	1000,	1,	"ip_max_temp_defend" },
873 	{  0,	1000,	3,	"ip_max_defend" },
874 	{  0,	999999,	30,	"ip_defend_interval" },
875 	{  0,	3600000, 300000, "ip_dup_recovery" },
876 	{  0,	1,	1,	"ip_restrict_interzone_loopback" },
877 	{  0,	1,	1,	"ip_lso_outbound" },
878 	{  IGMP_V1_ROUTER, IGMP_V3_ROUTER, IGMP_V3_ROUTER, "igmp_max_version" },
879 	{  MLD_V1_ROUTER, MLD_V2_ROUTER, MLD_V2_ROUTER, "mld_max_version" },
880 #ifdef DEBUG
881 	{  0,	1,	0,	"ip6_drop_inbound_icmpv6" },
882 #else
883 	{  0,	0,	0,	"" },
884 #endif
885 };
886 
887 /*
888  * Extended NDP table
889  * The addresses for the first two are filled in to be ips_ip_g_forward
890  * and ips_ipv6_forward at init time.
891  */
892 static ipndp_t	lcl_ndp_arr[] = {
893 	/* getf			setf		data			name */
894 #define	IPNDP_IP_FORWARDING_OFFSET	0
895 	{  ip_param_generic_get,	ip_forward_set,	NULL,
896 	    "ip_forwarding" },
897 #define	IPNDP_IP6_FORWARDING_OFFSET	1
898 	{  ip_param_generic_get,	ip_forward_set,	NULL,
899 	    "ip6_forwarding" },
900 	{  ip_ill_report,	NULL,		NULL,
901 	    "ip_ill_status" },
902 	{  ip_ipif_report,	NULL,		NULL,
903 	    "ip_ipif_status" },
904 	{  ip_conn_report,	NULL,		NULL,
905 	    "ip_conn_status" },
906 	{  nd_get_long,		nd_set_long,	(caddr_t)&ip_rput_pullups,
907 	    "ip_rput_pullups" },
908 	{  ip_srcid_report,	NULL,		NULL,
909 	    "ip_srcid_status" },
910 	{ ip_param_generic_get, ip_squeue_profile_set,
911 	    (caddr_t)&ip_squeue_profile, "ip_squeue_profile" },
912 	{ ip_param_generic_get, ip_squeue_bind_set,
913 	    (caddr_t)&ip_squeue_bind, "ip_squeue_bind" },
914 	{ ip_param_generic_get, ip_input_proc_set,
915 	    (caddr_t)&ip_squeue_enter, "ip_squeue_enter" },
916 	{ ip_param_generic_get, ip_int_set,
917 	    (caddr_t)&ip_squeue_fanout, "ip_squeue_fanout" },
918 #define	IPNDP_CGTP_FILTER_OFFSET	11
919 	{  ip_cgtp_filter_get,	ip_cgtp_filter_set, NULL,
920 	    "ip_cgtp_filter" },
921 	{ ip_param_generic_get, ip_int_set,
922 	    (caddr_t)&ip_soft_rings_cnt, "ip_soft_rings_cnt" },
923 #define	IPNDP_IPMP_HOOK_OFFSET	13
924 	{  ip_param_generic_get, ipmp_hook_emulation_set, NULL,
925 	    "ipmp_hook_emulation" },
926 	{  ip_param_generic_get, ip_int_set, (caddr_t)&ip_debug,
927 	    "ip_debug" },
928 };
929 
930 /*
931  * Table of IP ioctls encoding the various properties of the ioctl and
932  * indexed based on the last byte of the ioctl command. Occasionally there
933  * is a clash, and there is more than 1 ioctl with the same last byte.
934  * In such a case 1 ioctl is encoded in the ndx table and the remaining
935  * ioctls are encoded in the misc table. An entry in the ndx table is
936  * retrieved by indexing on the last byte of the ioctl command and comparing
937  * the ioctl command with the value in the ndx table. In the event of a
938  * mismatch the misc table is then searched sequentially for the desired
939  * ioctl command.
940  *
941  * Entry: <command> <copyin_size> <flags> <cmd_type> <function> <restart_func>
942  */
943 ip_ioctl_cmd_t ip_ndx_ioctl_table[] = {
944 	/* 000 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
945 	/* 001 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
946 	/* 002 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
947 	/* 003 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
948 	/* 004 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
949 	/* 005 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
950 	/* 006 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
951 	/* 007 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
952 	/* 008 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
953 	/* 009 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
954 
955 	/* 010 */ { SIOCADDRT,	sizeof (struct rtentry), IPI_PRIV,
956 			MISC_CMD, ip_siocaddrt, NULL },
957 	/* 011 */ { SIOCDELRT,	sizeof (struct rtentry), IPI_PRIV,
958 			MISC_CMD, ip_siocdelrt, NULL },
959 
960 	/* 012 */ { SIOCSIFADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
961 			IF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
962 	/* 013 */ { SIOCGIFADDR, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
963 			IF_CMD, ip_sioctl_get_addr, NULL },
964 
965 	/* 014 */ { SIOCSIFDSTADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
966 			IF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
967 	/* 015 */ { SIOCGIFDSTADDR, sizeof (struct ifreq),
968 			IPI_GET_CMD | IPI_REPL,
969 			IF_CMD, ip_sioctl_get_dstaddr, NULL },
970 
971 	/* 016 */ { SIOCSIFFLAGS, sizeof (struct ifreq),
972 			IPI_PRIV | IPI_WR | IPI_REPL,
973 			IF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
974 	/* 017 */ { SIOCGIFFLAGS, sizeof (struct ifreq),
975 			IPI_MODOK | IPI_GET_CMD | IPI_REPL,
976 			IF_CMD, ip_sioctl_get_flags, NULL },
977 
978 	/* 018 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
979 	/* 019 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
980 
981 	/* copyin size cannot be coded for SIOCGIFCONF */
982 	/* 020 */ { O_SIOCGIFCONF, 0, IPI_GET_CMD,
983 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
984 
985 	/* 021 */ { SIOCSIFMTU,	sizeof (struct ifreq), IPI_PRIV | IPI_WR,
986 			IF_CMD, ip_sioctl_mtu, NULL },
987 	/* 022 */ { SIOCGIFMTU,	sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
988 			IF_CMD, ip_sioctl_get_mtu, NULL },
989 	/* 023 */ { SIOCGIFBRDADDR, sizeof (struct ifreq),
990 			IPI_GET_CMD | IPI_REPL,
991 			IF_CMD, ip_sioctl_get_brdaddr, NULL },
992 	/* 024 */ { SIOCSIFBRDADDR, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
993 			IF_CMD, ip_sioctl_brdaddr, NULL },
994 	/* 025 */ { SIOCGIFNETMASK, sizeof (struct ifreq),
995 			IPI_GET_CMD | IPI_REPL,
996 			IF_CMD, ip_sioctl_get_netmask, NULL },
997 	/* 026 */ { SIOCSIFNETMASK, sizeof (struct ifreq), IPI_PRIV | IPI_WR,
998 			IF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
999 	/* 027 */ { SIOCGIFMETRIC, sizeof (struct ifreq),
1000 			IPI_GET_CMD | IPI_REPL,
1001 			IF_CMD, ip_sioctl_get_metric, NULL },
1002 	/* 028 */ { SIOCSIFMETRIC, sizeof (struct ifreq), IPI_PRIV,
1003 			IF_CMD, ip_sioctl_metric, NULL },
1004 	/* 029 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1005 
1006 	/* See 166-168 below for extended SIOC*XARP ioctls */
1007 	/* 030 */ { SIOCSARP, sizeof (struct arpreq), IPI_PRIV,
1008 			ARP_CMD, ip_sioctl_arp, NULL },
1009 	/* 031 */ { SIOCGARP, sizeof (struct arpreq), IPI_GET_CMD | IPI_REPL,
1010 			ARP_CMD, ip_sioctl_arp, NULL },
1011 	/* 032 */ { SIOCDARP, sizeof (struct arpreq), IPI_PRIV,
1012 			ARP_CMD, ip_sioctl_arp, NULL },
1013 
1014 	/* 033 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1015 	/* 034 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1016 	/* 035 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1017 	/* 036 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1018 	/* 037 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1019 	/* 038 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1020 	/* 039 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1021 	/* 040 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1022 	/* 041 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1023 	/* 042 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1024 	/* 043 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1025 	/* 044 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1026 	/* 045 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1027 	/* 046 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1028 	/* 047 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1029 	/* 048 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1030 	/* 049 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1031 	/* 050 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1032 	/* 051 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1033 	/* 052 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1034 	/* 053 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1035 
1036 	/* 054 */ { IF_UNITSEL,	sizeof (int), IPI_PRIV | IPI_WR | IPI_MODOK,
1037 			MISC_CMD, if_unitsel, if_unitsel_restart },
1038 
1039 	/* 055 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1040 	/* 056 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1041 	/* 057 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1042 	/* 058 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1043 	/* 059 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1044 	/* 060 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1045 	/* 061 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1046 	/* 062 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1047 	/* 063 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1048 	/* 064 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1049 	/* 065 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1050 	/* 066 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1051 	/* 067 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1052 	/* 068 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1053 	/* 069 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1054 	/* 070 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1055 	/* 071 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1056 	/* 072 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1057 
1058 	/* 073 */ { SIOCSIFNAME, sizeof (struct ifreq),
1059 			IPI_PRIV | IPI_WR | IPI_MODOK,
1060 			IF_CMD, ip_sioctl_sifname, NULL },
1061 
1062 	/* 074 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1063 	/* 075 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1064 	/* 076 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1065 	/* 077 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1066 	/* 078 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1067 	/* 079 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1068 	/* 080 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1069 	/* 081 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1070 	/* 082 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1071 	/* 083 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1072 	/* 084 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1073 	/* 085 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1074 	/* 086 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1075 
1076 	/* 087 */ { SIOCGIFNUM, sizeof (int), IPI_GET_CMD | IPI_REPL,
1077 			MISC_CMD, ip_sioctl_get_ifnum, NULL },
1078 	/* 088 */ { SIOCGIFMUXID, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1079 			IF_CMD, ip_sioctl_get_muxid, NULL },
1080 	/* 089 */ { SIOCSIFMUXID, sizeof (struct ifreq),
1081 			IPI_PRIV | IPI_WR | IPI_REPL,
1082 			IF_CMD, ip_sioctl_muxid, NULL },
1083 
1084 	/* Both if and lif variants share same func */
1085 	/* 090 */ { SIOCGIFINDEX, sizeof (struct ifreq), IPI_GET_CMD | IPI_REPL,
1086 			IF_CMD, ip_sioctl_get_lifindex, NULL },
1087 	/* Both if and lif variants share same func */
1088 	/* 091 */ { SIOCSIFINDEX, sizeof (struct ifreq),
1089 			IPI_PRIV | IPI_WR | IPI_REPL,
1090 			IF_CMD, ip_sioctl_slifindex, NULL },
1091 
1092 	/* copyin size cannot be coded for SIOCGIFCONF */
1093 	/* 092 */ { SIOCGIFCONF, 0, IPI_GET_CMD,
1094 			MISC_CMD, ip_sioctl_get_ifconf, NULL },
1095 	/* 093 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1096 	/* 094 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1097 	/* 095 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1098 	/* 096 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1099 	/* 097 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1100 	/* 098 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1101 	/* 099 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1102 	/* 100 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1103 	/* 101 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1104 	/* 102 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1105 	/* 103 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1106 	/* 104 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1107 	/* 105 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1108 	/* 106 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1109 	/* 107 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1110 	/* 108 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1111 	/* 109 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1112 
1113 	/* 110 */ { SIOCLIFREMOVEIF, sizeof (struct lifreq),
1114 			IPI_PRIV | IPI_WR | IPI_REPL,
1115 			LIF_CMD, ip_sioctl_removeif,
1116 			ip_sioctl_removeif_restart },
1117 	/* 111 */ { SIOCLIFADDIF, sizeof (struct lifreq),
1118 			IPI_GET_CMD | IPI_PRIV | IPI_WR | IPI_REPL,
1119 			LIF_CMD, ip_sioctl_addif, NULL },
1120 #define	SIOCLIFADDR_NDX 112
1121 	/* 112 */ { SIOCSLIFADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1122 			LIF_CMD, ip_sioctl_addr, ip_sioctl_addr_restart },
1123 	/* 113 */ { SIOCGLIFADDR, sizeof (struct lifreq),
1124 			IPI_GET_CMD | IPI_REPL,
1125 			LIF_CMD, ip_sioctl_get_addr, NULL },
1126 	/* 114 */ { SIOCSLIFDSTADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1127 			LIF_CMD, ip_sioctl_dstaddr, ip_sioctl_dstaddr_restart },
1128 	/* 115 */ { SIOCGLIFDSTADDR, sizeof (struct lifreq),
1129 			IPI_GET_CMD | IPI_REPL,
1130 			LIF_CMD, ip_sioctl_get_dstaddr, NULL },
1131 	/* 116 */ { SIOCSLIFFLAGS, sizeof (struct lifreq),
1132 			IPI_PRIV | IPI_WR | IPI_REPL,
1133 			LIF_CMD, ip_sioctl_flags, ip_sioctl_flags_restart },
1134 	/* 117 */ { SIOCGLIFFLAGS, sizeof (struct lifreq),
1135 			IPI_GET_CMD | IPI_MODOK | IPI_REPL,
1136 			LIF_CMD, ip_sioctl_get_flags, NULL },
1137 
1138 	/* 118 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1139 	/* 119 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1140 
1141 	/* 120 */ { O_SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1142 			ip_sioctl_get_lifconf, NULL },
1143 	/* 121 */ { SIOCSLIFMTU, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1144 			LIF_CMD, ip_sioctl_mtu, NULL },
1145 	/* 122 */ { SIOCGLIFMTU, sizeof (struct lifreq), IPI_GET_CMD | IPI_REPL,
1146 			LIF_CMD, ip_sioctl_get_mtu, NULL },
1147 	/* 123 */ { SIOCGLIFBRDADDR, sizeof (struct lifreq),
1148 			IPI_GET_CMD | IPI_REPL,
1149 			LIF_CMD, ip_sioctl_get_brdaddr, NULL },
1150 	/* 124 */ { SIOCSLIFBRDADDR, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1151 			LIF_CMD, ip_sioctl_brdaddr, NULL },
1152 	/* 125 */ { SIOCGLIFNETMASK, sizeof (struct lifreq),
1153 			IPI_GET_CMD | IPI_REPL,
1154 			LIF_CMD, ip_sioctl_get_netmask, NULL },
1155 	/* 126 */ { SIOCSLIFNETMASK, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1156 			LIF_CMD, ip_sioctl_netmask, ip_sioctl_netmask_restart },
1157 	/* 127 */ { SIOCGLIFMETRIC, sizeof (struct lifreq),
1158 			IPI_GET_CMD | IPI_REPL,
1159 			LIF_CMD, ip_sioctl_get_metric, NULL },
1160 	/* 128 */ { SIOCSLIFMETRIC, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1161 			LIF_CMD, ip_sioctl_metric, NULL },
1162 	/* 129 */ { SIOCSLIFNAME, sizeof (struct lifreq),
1163 			IPI_PRIV | IPI_WR | IPI_MODOK | IPI_REPL,
1164 			LIF_CMD, ip_sioctl_slifname,
1165 			ip_sioctl_slifname_restart },
1166 
1167 	/* 130 */ { SIOCGLIFNUM, sizeof (struct lifnum), IPI_GET_CMD | IPI_REPL,
1168 			MISC_CMD, ip_sioctl_get_lifnum, NULL },
1169 	/* 131 */ { SIOCGLIFMUXID, sizeof (struct lifreq),
1170 			IPI_GET_CMD | IPI_REPL,
1171 			LIF_CMD, ip_sioctl_get_muxid, NULL },
1172 	/* 132 */ { SIOCSLIFMUXID, sizeof (struct lifreq),
1173 			IPI_PRIV | IPI_WR | IPI_REPL,
1174 			LIF_CMD, ip_sioctl_muxid, NULL },
1175 	/* 133 */ { SIOCGLIFINDEX, sizeof (struct lifreq),
1176 			IPI_GET_CMD | IPI_REPL,
1177 			LIF_CMD, ip_sioctl_get_lifindex, 0 },
1178 	/* 134 */ { SIOCSLIFINDEX, sizeof (struct lifreq),
1179 			IPI_PRIV | IPI_WR | IPI_REPL,
1180 			LIF_CMD, ip_sioctl_slifindex, 0 },
1181 	/* 135 */ { SIOCSLIFTOKEN, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1182 			LIF_CMD, ip_sioctl_token, NULL },
1183 	/* 136 */ { SIOCGLIFTOKEN, sizeof (struct lifreq),
1184 			IPI_GET_CMD | IPI_REPL,
1185 			LIF_CMD, ip_sioctl_get_token, NULL },
1186 	/* 137 */ { SIOCSLIFSUBNET, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1187 			LIF_CMD, ip_sioctl_subnet, ip_sioctl_subnet_restart },
1188 	/* 138 */ { SIOCGLIFSUBNET, sizeof (struct lifreq),
1189 			IPI_GET_CMD | IPI_REPL,
1190 			LIF_CMD, ip_sioctl_get_subnet, NULL },
1191 	/* 139 */ { SIOCSLIFLNKINFO, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1192 			LIF_CMD, ip_sioctl_lnkinfo, NULL },
1193 
1194 	/* 140 */ { SIOCGLIFLNKINFO, sizeof (struct lifreq),
1195 			IPI_GET_CMD | IPI_REPL,
1196 			LIF_CMD, ip_sioctl_get_lnkinfo, NULL },
1197 	/* 141 */ { SIOCLIFDELND, sizeof (struct lifreq), IPI_PRIV,
1198 			LIF_CMD, ip_siocdelndp_v6, NULL },
1199 	/* 142 */ { SIOCLIFGETND, sizeof (struct lifreq), IPI_GET_CMD,
1200 			LIF_CMD, ip_siocqueryndp_v6, NULL },
1201 	/* 143 */ { SIOCLIFSETND, sizeof (struct lifreq), IPI_PRIV,
1202 			LIF_CMD, ip_siocsetndp_v6, NULL },
1203 	/* 144 */ { SIOCTMYADDR, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1204 			MISC_CMD, ip_sioctl_tmyaddr, NULL },
1205 	/* 145 */ { SIOCTONLINK, sizeof (struct sioc_addrreq), IPI_GET_CMD,
1206 			MISC_CMD, ip_sioctl_tonlink, NULL },
1207 	/* 146 */ { SIOCTMYSITE, sizeof (struct sioc_addrreq), 0,
1208 			MISC_CMD, ip_sioctl_tmysite, NULL },
1209 	/* 147 */ { SIOCGTUNPARAM, sizeof (struct iftun_req), IPI_REPL,
1210 			TUN_CMD, ip_sioctl_tunparam, NULL },
1211 	/* 148 */ { SIOCSTUNPARAM, sizeof (struct iftun_req),
1212 			IPI_PRIV | IPI_WR,
1213 			TUN_CMD, ip_sioctl_tunparam, NULL },
1214 
1215 	/* IPSECioctls handled in ip_sioctl_copyin_setup itself */
1216 	/* 149 */ { SIOCFIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1217 	/* 150 */ { SIOCSIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1218 	/* 151 */ { SIOCDIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1219 	/* 152 */ { SIOCLIPSECONFIG, 0, IPI_PRIV, MISC_CMD, NULL, NULL },
1220 
1221 	/* 153 */ { SIOCLIFFAILOVER, sizeof (struct lifreq),
1222 			IPI_PRIV | IPI_WR | IPI_REPL,
1223 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1224 	/* 154 */ { SIOCLIFFAILBACK, sizeof (struct lifreq),
1225 			IPI_PRIV | IPI_WR | IPI_REPL,
1226 			LIF_CMD, ip_sioctl_move, ip_sioctl_move },
1227 	/* 155 */ { SIOCSLIFGROUPNAME, sizeof (struct lifreq),
1228 			IPI_PRIV | IPI_WR,
1229 			LIF_CMD, ip_sioctl_groupname, ip_sioctl_groupname },
1230 	/* 156 */ { SIOCGLIFGROUPNAME, sizeof (struct lifreq),
1231 			IPI_GET_CMD | IPI_REPL,
1232 			LIF_CMD, ip_sioctl_get_groupname, NULL },
1233 	/* 157 */ { SIOCGLIFOINDEX, sizeof (struct lifreq),
1234 			IPI_GET_CMD | IPI_REPL,
1235 			LIF_CMD, ip_sioctl_get_oindex, NULL },
1236 
1237 	/* Leave 158-160 unused; used to be SIOC*IFARP ioctls */
1238 	/* 158 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1239 	/* 159 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1240 	/* 160 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1241 
1242 	/* 161 */ { SIOCSLIFOINDEX, sizeof (struct lifreq), IPI_PRIV | IPI_WR,
1243 		    LIF_CMD, ip_sioctl_slifoindex, NULL },
1244 
1245 	/* These are handled in ip_sioctl_copyin_setup itself */
1246 	/* 162 */ { SIOCGIP6ADDRPOLICY, 0, IPI_NULL_BCONT,
1247 			MISC_CMD, NULL, NULL },
1248 	/* 163 */ { SIOCSIP6ADDRPOLICY, 0, IPI_PRIV | IPI_NULL_BCONT,
1249 			MISC_CMD, NULL, NULL },
1250 	/* 164 */ { SIOCGDSTINFO, 0, IPI_GET_CMD, MISC_CMD, NULL, NULL },
1251 
1252 	/* 165 */ { SIOCGLIFCONF, 0, IPI_GET_CMD, MISC_CMD,
1253 			ip_sioctl_get_lifconf, NULL },
1254 
1255 	/* 166 */ { SIOCSXARP, sizeof (struct xarpreq), IPI_PRIV,
1256 			XARP_CMD, ip_sioctl_arp, NULL },
1257 	/* 167 */ { SIOCGXARP, sizeof (struct xarpreq), IPI_GET_CMD | IPI_REPL,
1258 			XARP_CMD, ip_sioctl_arp, NULL },
1259 	/* 168 */ { SIOCDXARP, sizeof (struct xarpreq), IPI_PRIV,
1260 			XARP_CMD, ip_sioctl_arp, NULL },
1261 
1262 	/* SIOCPOPSOCKFS is not handled by IP */
1263 	/* 169 */ { IPI_DONTCARE /* SIOCPOPSOCKFS */, 0, 0, 0, NULL, NULL },
1264 
1265 	/* 170 */ { SIOCGLIFZONE, sizeof (struct lifreq),
1266 			IPI_GET_CMD | IPI_REPL,
1267 			LIF_CMD, ip_sioctl_get_lifzone, NULL },
1268 	/* 171 */ { SIOCSLIFZONE, sizeof (struct lifreq),
1269 			IPI_PRIV | IPI_WR | IPI_REPL,
1270 			LIF_CMD, ip_sioctl_slifzone,
1271 			ip_sioctl_slifzone_restart },
1272 	/* 172-174 are SCTP ioctls and not handled by IP */
1273 	/* 172 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1274 	/* 173 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1275 	/* 174 */ { IPI_DONTCARE, 0, 0, 0, NULL, NULL },
1276 	/* 175 */ { SIOCGLIFUSESRC, sizeof (struct lifreq),
1277 			IPI_GET_CMD, LIF_CMD,
1278 			ip_sioctl_get_lifusesrc, 0 },
1279 	/* 176 */ { SIOCSLIFUSESRC, sizeof (struct lifreq),
1280 			IPI_PRIV | IPI_WR,
1281 			LIF_CMD, ip_sioctl_slifusesrc,
1282 			NULL },
1283 	/* 177 */ { SIOCGLIFSRCOF, 0, IPI_GET_CMD, MISC_CMD,
1284 			ip_sioctl_get_lifsrcof, NULL },
1285 	/* 178 */ { SIOCGMSFILTER, sizeof (struct group_filter), IPI_GET_CMD,
1286 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1287 	/* 179 */ { SIOCSMSFILTER, sizeof (struct group_filter), IPI_WR,
1288 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1289 	/* 180 */ { SIOCGIPMSFILTER, sizeof (struct ip_msfilter), IPI_GET_CMD,
1290 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1291 	/* 181 */ { SIOCSIPMSFILTER, sizeof (struct ip_msfilter), IPI_WR,
1292 			MSFILT_CMD, ip_sioctl_msfilter, NULL },
1293 	/* 182 */ { SIOCSIPMPFAILBACK, sizeof (int), IPI_PRIV, MISC_CMD,
1294 			ip_sioctl_set_ipmpfailback, NULL },
1295 	/* SIOCSENABLESDP is handled by SDP */
1296 	/* 183 */ { IPI_DONTCARE /* SIOCSENABLESDP */, 0, 0, 0, NULL, NULL },
1297 };
1298 
1299 int ip_ndx_ioctl_count = sizeof (ip_ndx_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1300 
1301 ip_ioctl_cmd_t ip_misc_ioctl_table[] = {
1302 	{ OSIOCGTUNPARAM, sizeof (struct old_iftun_req),
1303 		IPI_GET_CMD | IPI_REPL, TUN_CMD, ip_sioctl_tunparam, NULL },
1304 	{ OSIOCSTUNPARAM, sizeof (struct old_iftun_req), IPI_PRIV | IPI_WR,
1305 		TUN_CMD, ip_sioctl_tunparam, NULL },
1306 	{ I_LINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1307 	{ I_UNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1308 	{ I_PLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1309 	{ I_PUNLINK,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1310 	{ ND_GET,	0, IPI_PASS_DOWN, 0, NULL, NULL },
1311 	{ ND_SET,	0, IPI_PRIV | IPI_WR | IPI_PASS_DOWN, 0, NULL, NULL },
1312 	{ IP_IOCTL,	0, 0, 0, NULL, NULL },
1313 	{ SIOCGETVIFCNT, sizeof (struct sioc_vif_req), IPI_REPL | IPI_GET_CMD,
1314 		MISC_CMD, mrt_ioctl},
1315 	{ SIOCGETSGCNT,	sizeof (struct sioc_sg_req), IPI_REPL | IPI_GET_CMD,
1316 		MISC_CMD, mrt_ioctl},
1317 	{ SIOCGETLSGCNT, sizeof (struct sioc_lsg_req), IPI_REPL | IPI_GET_CMD,
1318 		MISC_CMD, mrt_ioctl}
1319 };
1320 
1321 int ip_misc_ioctl_count =
1322     sizeof (ip_misc_ioctl_table) / sizeof (ip_ioctl_cmd_t);
1323 
1324 int	conn_drain_nthreads;		/* Number of drainers reqd. */
1325 					/* Settable in /etc/system */
1326 /* Defined in ip_ire.c */
1327 extern uint32_t ip_ire_max_bucket_cnt, ip6_ire_max_bucket_cnt;
1328 extern uint32_t ip_ire_min_bucket_cnt, ip6_ire_min_bucket_cnt;
1329 extern uint32_t ip_ire_mem_ratio, ip_ire_cpu_ratio;
1330 
1331 static nv_t	ire_nv_arr[] = {
1332 	{ IRE_BROADCAST, "BROADCAST" },
1333 	{ IRE_LOCAL, "LOCAL" },
1334 	{ IRE_LOOPBACK, "LOOPBACK" },
1335 	{ IRE_CACHE, "CACHE" },
1336 	{ IRE_DEFAULT, "DEFAULT" },
1337 	{ IRE_PREFIX, "PREFIX" },
1338 	{ IRE_IF_NORESOLVER, "IF_NORESOL" },
1339 	{ IRE_IF_RESOLVER, "IF_RESOLV" },
1340 	{ IRE_HOST, "HOST" },
1341 	{ 0 }
1342 };
1343 
1344 nv_t	*ire_nv_tbl = ire_nv_arr;
1345 
1346 /* Simple ICMP IP Header Template */
1347 static ipha_t icmp_ipha = {
1348 	IP_SIMPLE_HDR_VERSION, 0, 0, 0, 0, 0, IPPROTO_ICMP
1349 };
1350 
1351 struct module_info ip_mod_info = {
1352 	IP_MOD_ID, IP_MOD_NAME, 1, INFPSZ, 65536, 1024
1353 };
1354 
1355 /*
1356  * Duplicate static symbols within a module confuses mdb; so we avoid the
1357  * problem by making the symbols here distinct from those in udp.c.
1358  */
1359 
1360 /*
1361  * Entry points for IP as a device and as a module.
1362  * FIXME: down the road we might want a separate module and driver qinit.
1363  * We have separate open functions for the /dev/ip and /dev/ip6 devices.
1364  */
1365 static struct qinit iprinitv4 = {
1366 	(pfi_t)ip_rput, NULL, ip_openv4, ip_close, NULL,
1367 	&ip_mod_info
1368 };
1369 
1370 struct qinit iprinitv6 = {
1371 	(pfi_t)ip_rput_v6, NULL, ip_openv6, ip_close, NULL,
1372 	&ip_mod_info
1373 };
1374 
1375 static struct qinit ipwinitv4 = {
1376 	(pfi_t)ip_wput, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1377 	&ip_mod_info
1378 };
1379 
1380 struct qinit ipwinitv6 = {
1381 	(pfi_t)ip_wput_v6, (pfi_t)ip_wsrv, NULL, NULL, NULL,
1382 	&ip_mod_info
1383 };
1384 
1385 static struct qinit iplrinit = {
1386 	(pfi_t)ip_lrput, NULL, ip_openv4, ip_close, NULL,
1387 	&ip_mod_info
1388 };
1389 
1390 static struct qinit iplwinit = {
1391 	(pfi_t)ip_lwput, NULL, NULL, NULL, NULL,
1392 	&ip_mod_info
1393 };
1394 
1395 /* For AF_INET aka /dev/ip */
1396 struct streamtab ipinfov4 = {
1397 	&iprinitv4, &ipwinitv4, &iplrinit, &iplwinit
1398 };
1399 
1400 /* For AF_INET6 aka /dev/ip6 */
1401 struct streamtab ipinfov6 = {
1402 	&iprinitv6, &ipwinitv6, &iplrinit, &iplwinit
1403 };
1404 
1405 #ifdef	DEBUG
1406 static boolean_t skip_sctp_cksum = B_FALSE;
1407 #endif
1408 
1409 /*
1410  * Prepend the zoneid using an ipsec_out_t for later use by functions like
1411  * ip_rput_v6(), ip_output(), etc.  If the message
1412  * block already has a M_CTL at the front of it, then simply set the zoneid
1413  * appropriately.
1414  */
1415 mblk_t *
1416 ip_prepend_zoneid(mblk_t *mp, zoneid_t zoneid, ip_stack_t *ipst)
1417 {
1418 	mblk_t		*first_mp;
1419 	ipsec_out_t	*io;
1420 
1421 	ASSERT(zoneid != ALL_ZONES);
1422 	if (mp->b_datap->db_type == M_CTL) {
1423 		io = (ipsec_out_t *)mp->b_rptr;
1424 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
1425 		io->ipsec_out_zoneid = zoneid;
1426 		return (mp);
1427 	}
1428 
1429 	first_mp = ipsec_alloc_ipsec_out(ipst->ips_netstack);
1430 	if (first_mp == NULL)
1431 		return (NULL);
1432 	io = (ipsec_out_t *)first_mp->b_rptr;
1433 	/* This is not a secure packet */
1434 	io->ipsec_out_secure = B_FALSE;
1435 	io->ipsec_out_zoneid = zoneid;
1436 	first_mp->b_cont = mp;
1437 	return (first_mp);
1438 }
1439 
1440 /*
1441  * Copy an M_CTL-tagged message, preserving reference counts appropriately.
1442  */
1443 mblk_t *
1444 ip_copymsg(mblk_t *mp)
1445 {
1446 	mblk_t *nmp;
1447 	ipsec_info_t *in;
1448 
1449 	if (mp->b_datap->db_type != M_CTL)
1450 		return (copymsg(mp));
1451 
1452 	in = (ipsec_info_t *)mp->b_rptr;
1453 
1454 	/*
1455 	 * Note that M_CTL is also used for delivering ICMP error messages
1456 	 * upstream to transport layers.
1457 	 */
1458 	if (in->ipsec_info_type != IPSEC_OUT &&
1459 	    in->ipsec_info_type != IPSEC_IN)
1460 		return (copymsg(mp));
1461 
1462 	nmp = copymsg(mp->b_cont);
1463 
1464 	if (in->ipsec_info_type == IPSEC_OUT) {
1465 		return (ipsec_out_tag(mp, nmp,
1466 		    ((ipsec_out_t *)in)->ipsec_out_ns));
1467 	} else {
1468 		return (ipsec_in_tag(mp, nmp,
1469 		    ((ipsec_in_t *)in)->ipsec_in_ns));
1470 	}
1471 }
1472 
1473 /* Generate an ICMP fragmentation needed message. */
1474 static void
1475 icmp_frag_needed(queue_t *q, mblk_t *mp, int mtu, zoneid_t zoneid,
1476     ip_stack_t *ipst)
1477 {
1478 	icmph_t	icmph;
1479 	mblk_t *first_mp;
1480 	boolean_t mctl_present;
1481 
1482 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
1483 
1484 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
1485 		if (mctl_present)
1486 			freeb(first_mp);
1487 		return;
1488 	}
1489 
1490 	bzero(&icmph, sizeof (icmph_t));
1491 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
1492 	icmph.icmph_code = ICMP_FRAGMENTATION_NEEDED;
1493 	icmph.icmph_du_mtu = htons((uint16_t)mtu);
1494 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutFragNeeded);
1495 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
1496 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
1497 	    ipst);
1498 }
1499 
1500 /*
1501  * icmp_inbound deals with ICMP messages in the following ways.
1502  *
1503  * 1) It needs to send a reply back and possibly delivering it
1504  *    to the "interested" upper clients.
1505  * 2) It needs to send it to the upper clients only.
1506  * 3) It needs to change some values in IP only.
1507  * 4) It needs to change some values in IP and upper layers e.g TCP.
1508  *
1509  * We need to accomodate icmp messages coming in clear until we get
1510  * everything secure from the wire. If icmp_accept_clear_messages
1511  * is zero we check with the global policy and act accordingly. If
1512  * it is non-zero, we accept the message without any checks. But
1513  * *this does not mean* that this will be delivered to the upper
1514  * clients. By accepting we might send replies back, change our MTU
1515  * value etc. but delivery to the ULP/clients depends on their policy
1516  * dispositions.
1517  *
1518  * We handle the above 4 cases in the context of IPsec in the
1519  * following way :
1520  *
1521  * 1) Send the reply back in the same way as the request came in.
1522  *    If it came in encrypted, it goes out encrypted. If it came in
1523  *    clear, it goes out in clear. Thus, this will prevent chosen
1524  *    plain text attack.
1525  * 2) The client may or may not expect things to come in secure.
1526  *    If it comes in secure, the policy constraints are checked
1527  *    before delivering it to the upper layers. If it comes in
1528  *    clear, ipsec_inbound_accept_clear will decide whether to
1529  *    accept this in clear or not. In both the cases, if the returned
1530  *    message (IP header + 8 bytes) that caused the icmp message has
1531  *    AH/ESP headers, it is sent up to AH/ESP for validation before
1532  *    sending up. If there are only 8 bytes of returned message, then
1533  *    upper client will not be notified.
1534  * 3) Check with global policy to see whether it matches the constaints.
1535  *    But this will be done only if icmp_accept_messages_in_clear is
1536  *    zero.
1537  * 4) If we need to change both in IP and ULP, then the decision taken
1538  *    while affecting the values in IP and while delivering up to TCP
1539  *    should be the same.
1540  *
1541  * 	There are two cases.
1542  *
1543  * 	a) If we reject data at the IP layer (ipsec_check_global_policy()
1544  *	   failed), we will not deliver it to the ULP, even though they
1545  *	   are *willing* to accept in *clear*. This is fine as our global
1546  *	   disposition to icmp messages asks us reject the datagram.
1547  *
1548  *	b) If we accept data at the IP layer (ipsec_check_global_policy()
1549  *	   succeeded or icmp_accept_messages_in_clear is 1), and not able
1550  *	   to deliver it to ULP (policy failed), it can lead to
1551  *	   consistency problems. The cases known at this time are
1552  *	   ICMP_DESTINATION_UNREACHABLE  messages with following code
1553  *	   values :
1554  *
1555  *	   - ICMP_FRAGMENTATION_NEEDED : IP adapts to the new value
1556  *	     and Upper layer rejects. Then the communication will
1557  *	     come to a stop. This is solved by making similar decisions
1558  *	     at both levels. Currently, when we are unable to deliver
1559  *	     to the Upper Layer (due to policy failures) while IP has
1560  *	     adjusted ire_max_frag, the next outbound datagram would
1561  *	     generate a local ICMP_FRAGMENTATION_NEEDED message - which
1562  *	     will be with the right level of protection. Thus the right
1563  *	     value will be communicated even if we are not able to
1564  *	     communicate when we get from the wire initially. But this
1565  *	     assumes there would be at least one outbound datagram after
1566  *	     IP has adjusted its ire_max_frag value. To make things
1567  *	     simpler, we accept in clear after the validation of
1568  *	     AH/ESP headers.
1569  *
1570  *	   - Other ICMP ERRORS : We may not be able to deliver it to the
1571  *	     upper layer depending on the level of protection the upper
1572  *	     layer expects and the disposition in ipsec_inbound_accept_clear().
1573  *	     ipsec_inbound_accept_clear() decides whether a given ICMP error
1574  *	     should be accepted in clear when the Upper layer expects secure.
1575  *	     Thus the communication may get aborted by some bad ICMP
1576  *	     packets.
1577  *
1578  * IPQoS Notes:
1579  * The only instance when a packet is sent for processing is when there
1580  * isn't an ICMP client and if we are interested in it.
1581  * If there is a client, IPPF processing will take place in the
1582  * ip_fanout_proto routine.
1583  *
1584  * Zones notes:
1585  * The packet is only processed in the context of the specified zone: typically
1586  * only this zone will reply to an echo request, and only interested clients in
1587  * this zone will receive a copy of the packet. This means that the caller must
1588  * call icmp_inbound() for each relevant zone.
1589  */
1590 static void
1591 icmp_inbound(queue_t *q, mblk_t *mp, boolean_t broadcast, ill_t *ill,
1592     int sum_valid, uint32_t sum, boolean_t mctl_present, boolean_t ip_policy,
1593     ill_t *recv_ill, zoneid_t zoneid)
1594 {
1595 	icmph_t	*icmph;
1596 	ipha_t	*ipha;
1597 	int	iph_hdr_length;
1598 	int	hdr_length;
1599 	boolean_t	interested;
1600 	uint32_t	ts;
1601 	uchar_t	*wptr;
1602 	ipif_t	*ipif;
1603 	mblk_t *first_mp;
1604 	ipsec_in_t *ii;
1605 	ire_t *src_ire;
1606 	boolean_t onlink;
1607 	timestruc_t now;
1608 	uint32_t ill_index;
1609 	ip_stack_t *ipst;
1610 
1611 	ASSERT(ill != NULL);
1612 	ipst = ill->ill_ipst;
1613 
1614 	first_mp = mp;
1615 	if (mctl_present) {
1616 		mp = first_mp->b_cont;
1617 		ASSERT(mp != NULL);
1618 	}
1619 
1620 	ipha = (ipha_t *)mp->b_rptr;
1621 	if (ipst->ips_icmp_accept_clear_messages == 0) {
1622 		first_mp = ipsec_check_global_policy(first_mp, NULL,
1623 		    ipha, NULL, mctl_present, ipst->ips_netstack);
1624 		if (first_mp == NULL)
1625 			return;
1626 	}
1627 
1628 	/*
1629 	 * On a labeled system, we have to check whether the zone itself is
1630 	 * permitted to receive raw traffic.
1631 	 */
1632 	if (is_system_labeled()) {
1633 		if (zoneid == ALL_ZONES)
1634 			zoneid = tsol_packet_to_zoneid(mp);
1635 		if (!tsol_can_accept_raw(mp, B_FALSE)) {
1636 			ip1dbg(("icmp_inbound: zone %d can't receive raw",
1637 			    zoneid));
1638 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1639 			freemsg(first_mp);
1640 			return;
1641 		}
1642 	}
1643 
1644 	/*
1645 	 * We have accepted the ICMP message. It means that we will
1646 	 * respond to the packet if needed. It may not be delivered
1647 	 * to the upper client depending on the policy constraints
1648 	 * and the disposition in ipsec_inbound_accept_clear.
1649 	 */
1650 
1651 	ASSERT(ill != NULL);
1652 
1653 	BUMP_MIB(&ipst->ips_icmp_mib, icmpInMsgs);
1654 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
1655 	if ((mp->b_wptr - mp->b_rptr) < (iph_hdr_length + ICMPH_SIZE)) {
1656 		/* Last chance to get real. */
1657 		if (!pullupmsg(mp, iph_hdr_length + ICMPH_SIZE)) {
1658 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1659 			freemsg(first_mp);
1660 			return;
1661 		}
1662 		/* Refresh iph following the pullup. */
1663 		ipha = (ipha_t *)mp->b_rptr;
1664 	}
1665 	/* ICMP header checksum, including checksum field, should be zero. */
1666 	if (sum_valid ? (sum != 0 && sum != 0xFFFF) :
1667 	    IP_CSUM(mp, iph_hdr_length, 0)) {
1668 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInCksumErrs);
1669 		freemsg(first_mp);
1670 		return;
1671 	}
1672 	/* The IP header will always be a multiple of four bytes */
1673 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1674 	ip2dbg(("icmp_inbound: type %d code %d\n", icmph->icmph_type,
1675 	    icmph->icmph_code));
1676 	wptr = (uchar_t *)icmph + ICMPH_SIZE;
1677 	/* We will set "interested" to "true" if we want a copy */
1678 	interested = B_FALSE;
1679 	switch (icmph->icmph_type) {
1680 	case ICMP_ECHO_REPLY:
1681 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchoReps);
1682 		break;
1683 	case ICMP_DEST_UNREACHABLE:
1684 		if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED)
1685 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInFragNeeded);
1686 		interested = B_TRUE;	/* Pass up to transport */
1687 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInDestUnreachs);
1688 		break;
1689 	case ICMP_SOURCE_QUENCH:
1690 		interested = B_TRUE;	/* Pass up to transport */
1691 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInSrcQuenchs);
1692 		break;
1693 	case ICMP_REDIRECT:
1694 		if (!ipst->ips_ip_ignore_redirect)
1695 			interested = B_TRUE;
1696 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInRedirects);
1697 		break;
1698 	case ICMP_ECHO_REQUEST:
1699 		/*
1700 		 * Whether to respond to echo requests that come in as IP
1701 		 * broadcasts or as IP multicast is subject to debate
1702 		 * (what isn't?).  We aim to please, you pick it.
1703 		 * Default is do it.
1704 		 */
1705 		if (!broadcast && !CLASSD(ipha->ipha_dst)) {
1706 			/* unicast: always respond */
1707 			interested = B_TRUE;
1708 		} else if (CLASSD(ipha->ipha_dst)) {
1709 			/* multicast: respond based on tunable */
1710 			interested = ipst->ips_ip_g_resp_to_echo_mcast;
1711 		} else if (broadcast) {
1712 			/* broadcast: respond based on tunable */
1713 			interested = ipst->ips_ip_g_resp_to_echo_bcast;
1714 		}
1715 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInEchos);
1716 		break;
1717 	case ICMP_ROUTER_ADVERTISEMENT:
1718 	case ICMP_ROUTER_SOLICITATION:
1719 		break;
1720 	case ICMP_TIME_EXCEEDED:
1721 		interested = B_TRUE;	/* Pass up to transport */
1722 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimeExcds);
1723 		break;
1724 	case ICMP_PARAM_PROBLEM:
1725 		interested = B_TRUE;	/* Pass up to transport */
1726 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInParmProbs);
1727 		break;
1728 	case ICMP_TIME_STAMP_REQUEST:
1729 		/* Response to Time Stamp Requests is local policy. */
1730 		if (ipst->ips_ip_g_resp_to_timestamp &&
1731 		    /* So is whether to respond if it was an IP broadcast. */
1732 		    (!broadcast || ipst->ips_ip_g_resp_to_timestamp_bcast)) {
1733 			int tstamp_len = 3 * sizeof (uint32_t);
1734 
1735 			if (wptr +  tstamp_len > mp->b_wptr) {
1736 				if (!pullupmsg(mp, wptr + tstamp_len -
1737 				    mp->b_rptr)) {
1738 					BUMP_MIB(ill->ill_ip_mib,
1739 					    ipIfStatsInDiscards);
1740 					freemsg(first_mp);
1741 					return;
1742 				}
1743 				/* Refresh ipha following the pullup. */
1744 				ipha = (ipha_t *)mp->b_rptr;
1745 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1746 				wptr = (uchar_t *)icmph + ICMPH_SIZE;
1747 			}
1748 			interested = B_TRUE;
1749 		}
1750 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestamps);
1751 		break;
1752 	case ICMP_TIME_STAMP_REPLY:
1753 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInTimestampReps);
1754 		break;
1755 	case ICMP_INFO_REQUEST:
1756 		/* Per RFC 1122 3.2.2.7, ignore this. */
1757 	case ICMP_INFO_REPLY:
1758 		break;
1759 	case ICMP_ADDRESS_MASK_REQUEST:
1760 		if ((ipst->ips_ip_respond_to_address_mask_broadcast ||
1761 		    !broadcast) &&
1762 		    /* TODO m_pullup of complete header? */
1763 		    (mp->b_datap->db_lim - wptr) >= IP_ADDR_LEN) {
1764 			interested = B_TRUE;
1765 		}
1766 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMasks);
1767 		break;
1768 	case ICMP_ADDRESS_MASK_REPLY:
1769 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInAddrMaskReps);
1770 		break;
1771 	default:
1772 		interested = B_TRUE;	/* Pass up to transport */
1773 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInUnknowns);
1774 		break;
1775 	}
1776 	/* See if there is an ICMP client. */
1777 	if (ipst->ips_ipcl_proto_fanout[IPPROTO_ICMP].connf_head != NULL) {
1778 		/* If there is an ICMP client and we want one too, copy it. */
1779 		mblk_t *first_mp1;
1780 
1781 		if (!interested) {
1782 			ip_fanout_proto(q, first_mp, ill, ipha, 0, mctl_present,
1783 			    ip_policy, recv_ill, zoneid);
1784 			return;
1785 		}
1786 		first_mp1 = ip_copymsg(first_mp);
1787 		if (first_mp1 != NULL) {
1788 			ip_fanout_proto(q, first_mp1, ill, ipha,
1789 			    0, mctl_present, ip_policy, recv_ill, zoneid);
1790 		}
1791 	} else if (!interested) {
1792 		freemsg(first_mp);
1793 		return;
1794 	} else {
1795 		/*
1796 		 * Initiate policy processing for this packet if ip_policy
1797 		 * is true.
1798 		 */
1799 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
1800 			ill_index = ill->ill_phyint->phyint_ifindex;
1801 			ip_process(IPP_LOCAL_IN, &mp, ill_index);
1802 			if (mp == NULL) {
1803 				if (mctl_present) {
1804 					freeb(first_mp);
1805 				}
1806 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
1807 				return;
1808 			}
1809 		}
1810 	}
1811 	/* We want to do something with it. */
1812 	/* Check db_ref to make sure we can modify the packet. */
1813 	if (mp->b_datap->db_ref > 1) {
1814 		mblk_t	*first_mp1;
1815 
1816 		first_mp1 = ip_copymsg(first_mp);
1817 		freemsg(first_mp);
1818 		if (!first_mp1) {
1819 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
1820 			return;
1821 		}
1822 		first_mp = first_mp1;
1823 		if (mctl_present) {
1824 			mp = first_mp->b_cont;
1825 			ASSERT(mp != NULL);
1826 		} else {
1827 			mp = first_mp;
1828 		}
1829 		ipha = (ipha_t *)mp->b_rptr;
1830 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1831 		wptr = (uchar_t *)icmph + ICMPH_SIZE;
1832 	}
1833 	switch (icmph->icmph_type) {
1834 	case ICMP_ADDRESS_MASK_REQUEST:
1835 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1836 		if (ipif == NULL) {
1837 			freemsg(first_mp);
1838 			return;
1839 		}
1840 		/*
1841 		 * outging interface must be IPv4
1842 		 */
1843 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1844 		icmph->icmph_type = ICMP_ADDRESS_MASK_REPLY;
1845 		bcopy(&ipif->ipif_net_mask, wptr, IP_ADDR_LEN);
1846 		ipif_refrele(ipif);
1847 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutAddrMaskReps);
1848 		break;
1849 	case ICMP_ECHO_REQUEST:
1850 		icmph->icmph_type = ICMP_ECHO_REPLY;
1851 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutEchoReps);
1852 		break;
1853 	case ICMP_TIME_STAMP_REQUEST: {
1854 		uint32_t *tsp;
1855 
1856 		icmph->icmph_type = ICMP_TIME_STAMP_REPLY;
1857 		tsp = (uint32_t *)wptr;
1858 		tsp++;		/* Skip past 'originate time' */
1859 		/* Compute # of milliseconds since midnight */
1860 		gethrestime(&now);
1861 		ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
1862 		    now.tv_nsec / (NANOSEC / MILLISEC);
1863 		*tsp++ = htonl(ts);	/* Lay in 'receive time' */
1864 		*tsp++ = htonl(ts);	/* Lay in 'send time' */
1865 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimestampReps);
1866 		break;
1867 	}
1868 	default:
1869 		ipha = (ipha_t *)&icmph[1];
1870 		if ((uchar_t *)&ipha[1] > mp->b_wptr) {
1871 			if (!pullupmsg(mp, (uchar_t *)&ipha[1] - mp->b_rptr)) {
1872 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1873 				freemsg(first_mp);
1874 				return;
1875 			}
1876 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1877 			ipha = (ipha_t *)&icmph[1];
1878 		}
1879 		if ((IPH_HDR_VERSION(ipha) != IPV4_VERSION)) {
1880 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1881 			freemsg(first_mp);
1882 			return;
1883 		}
1884 		hdr_length = IPH_HDR_LENGTH(ipha);
1885 		if (hdr_length < sizeof (ipha_t)) {
1886 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1887 			freemsg(first_mp);
1888 			return;
1889 		}
1890 		if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
1891 			if (!pullupmsg(mp,
1892 			    (uchar_t *)ipha + hdr_length - mp->b_rptr)) {
1893 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
1894 				freemsg(first_mp);
1895 				return;
1896 			}
1897 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1898 			ipha = (ipha_t *)&icmph[1];
1899 		}
1900 		switch (icmph->icmph_type) {
1901 		case ICMP_REDIRECT:
1902 			/*
1903 			 * As there is no upper client to deliver, we don't
1904 			 * need the first_mp any more.
1905 			 */
1906 			if (mctl_present) {
1907 				freeb(first_mp);
1908 			}
1909 			icmp_redirect(ill, mp);
1910 			return;
1911 		case ICMP_DEST_UNREACHABLE:
1912 			if (icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED) {
1913 				if (!icmp_inbound_too_big(icmph, ipha, ill,
1914 				    zoneid, mp, iph_hdr_length, ipst)) {
1915 					freemsg(first_mp);
1916 					return;
1917 				}
1918 				/*
1919 				 * icmp_inbound_too_big() may alter mp.
1920 				 * Resynch ipha and icmph accordingly.
1921 				 */
1922 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
1923 				ipha = (ipha_t *)&icmph[1];
1924 			}
1925 			/* FALLTHRU */
1926 		default :
1927 			/*
1928 			 * IPQoS notes: Since we have already done IPQoS
1929 			 * processing we don't want to do it again in
1930 			 * the fanout routines called by
1931 			 * icmp_inbound_error_fanout, hence the last
1932 			 * argument, ip_policy, is B_FALSE.
1933 			 */
1934 			icmp_inbound_error_fanout(q, ill, first_mp, icmph,
1935 			    ipha, iph_hdr_length, hdr_length, mctl_present,
1936 			    B_FALSE, recv_ill, zoneid);
1937 		}
1938 		return;
1939 	}
1940 	/* Send out an ICMP packet */
1941 	icmph->icmph_checksum = 0;
1942 	icmph->icmph_checksum = IP_CSUM(mp, iph_hdr_length, 0);
1943 	if (broadcast || CLASSD(ipha->ipha_dst)) {
1944 		ipif_t	*ipif_chosen;
1945 		/*
1946 		 * Make it look like it was directed to us, so we don't look
1947 		 * like a fool with a broadcast or multicast source address.
1948 		 */
1949 		ipif = ipif_lookup_remote(ill, ipha->ipha_src, zoneid);
1950 		/*
1951 		 * Make sure that we haven't grabbed an interface that's DOWN.
1952 		 */
1953 		if (ipif != NULL) {
1954 			ipif_chosen = ipif_select_source(ipif->ipif_ill,
1955 			    ipha->ipha_src, zoneid);
1956 			if (ipif_chosen != NULL) {
1957 				ipif_refrele(ipif);
1958 				ipif = ipif_chosen;
1959 			}
1960 		}
1961 		if (ipif == NULL) {
1962 			ip0dbg(("icmp_inbound: "
1963 			    "No source for broadcast/multicast:\n"
1964 			    "\tsrc 0x%x dst 0x%x ill %p "
1965 			    "ipif_lcl_addr 0x%x\n",
1966 			    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst),
1967 			    (void *)ill,
1968 			    ill->ill_ipif->ipif_lcl_addr));
1969 			freemsg(first_mp);
1970 			return;
1971 		}
1972 		ASSERT(ipif != NULL && !ipif->ipif_isv6);
1973 		ipha->ipha_dst = ipif->ipif_src_addr;
1974 		ipif_refrele(ipif);
1975 	}
1976 	/* Reset time to live. */
1977 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
1978 	{
1979 		/* Swap source and destination addresses */
1980 		ipaddr_t tmp;
1981 
1982 		tmp = ipha->ipha_src;
1983 		ipha->ipha_src = ipha->ipha_dst;
1984 		ipha->ipha_dst = tmp;
1985 	}
1986 	ipha->ipha_ident = 0;
1987 	if (!IS_SIMPLE_IPH(ipha))
1988 		icmp_options_update(ipha);
1989 
1990 	/*
1991 	 * ICMP echo replies should go out on the same interface
1992 	 * the request came on as probes used by in.mpathd for detecting
1993 	 * NIC failures are ECHO packets. We turn-off load spreading
1994 	 * by setting ipsec_in_attach_if to B_TRUE, which is copied
1995 	 * to ipsec_out_attach_if by ipsec_in_to_out called later in this
1996 	 * function. This is in turn handled by ip_wput and ip_newroute
1997 	 * to make sure that the packet goes out on the interface it came
1998 	 * in on. If we don't turnoff load spreading, the packets might get
1999 	 * dropped if there are no non-FAILED/INACTIVE interfaces for it
2000 	 * to go out and in.mpathd would wrongly detect a failure or
2001 	 * mis-detect a NIC failure for link failure. As load spreading
2002 	 * can happen only if ill_group is not NULL, we do only for
2003 	 * that case and this does not affect the normal case.
2004 	 *
2005 	 * We turn off load spreading only on echo packets that came from
2006 	 * on-link hosts. If the interface route has been deleted, this will
2007 	 * not be enforced as we can't do much. For off-link hosts, as the
2008 	 * default routes in IPv4 does not typically have an ire_ipif
2009 	 * pointer, we can't force MATCH_IRE_ILL in ip_wput/ip_newroute.
2010 	 * Moreover, expecting a default route through this interface may
2011 	 * not be correct. We use ipha_dst because of the swap above.
2012 	 */
2013 	onlink = B_FALSE;
2014 	if (icmph->icmph_type == ICMP_ECHO_REPLY && ill->ill_group != NULL) {
2015 		/*
2016 		 * First, we need to make sure that it is not one of our
2017 		 * local addresses. If we set onlink when it is one of
2018 		 * our local addresses, we will end up creating IRE_CACHES
2019 		 * for one of our local addresses. Then, we will never
2020 		 * accept packets for them afterwards.
2021 		 */
2022 		src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_LOCAL,
2023 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2024 		if (src_ire == NULL) {
2025 			ipif = ipif_get_next_ipif(NULL, ill);
2026 			if (ipif == NULL) {
2027 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2028 				freemsg(mp);
2029 				return;
2030 			}
2031 			src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0,
2032 			    IRE_INTERFACE, ipif, NULL, ALL_ZONES, 0,
2033 			    NULL, MATCH_IRE_ILL | MATCH_IRE_TYPE, ipst);
2034 			ipif_refrele(ipif);
2035 			if (src_ire != NULL) {
2036 				onlink = B_TRUE;
2037 				ire_refrele(src_ire);
2038 			}
2039 		} else {
2040 			ire_refrele(src_ire);
2041 		}
2042 	}
2043 	if (!mctl_present) {
2044 		/*
2045 		 * This packet should go out the same way as it
2046 		 * came in i.e in clear. To make sure that global
2047 		 * policy will not be applied to this in ip_wput_ire,
2048 		 * we attach a IPSEC_IN mp and clear ipsec_in_secure.
2049 		 */
2050 		ASSERT(first_mp == mp);
2051 		first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2052 		if (first_mp == NULL) {
2053 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2054 			freemsg(mp);
2055 			return;
2056 		}
2057 		ii = (ipsec_in_t *)first_mp->b_rptr;
2058 
2059 		/* This is not a secure packet */
2060 		ii->ipsec_in_secure = B_FALSE;
2061 		if (onlink) {
2062 			ii->ipsec_in_attach_if = B_TRUE;
2063 			ii->ipsec_in_ill_index =
2064 			    ill->ill_phyint->phyint_ifindex;
2065 			ii->ipsec_in_rill_index =
2066 			    recv_ill->ill_phyint->phyint_ifindex;
2067 		}
2068 		first_mp->b_cont = mp;
2069 	} else if (onlink) {
2070 		ii = (ipsec_in_t *)first_mp->b_rptr;
2071 		ii->ipsec_in_attach_if = B_TRUE;
2072 		ii->ipsec_in_ill_index = ill->ill_phyint->phyint_ifindex;
2073 		ii->ipsec_in_rill_index = recv_ill->ill_phyint->phyint_ifindex;
2074 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2075 	} else {
2076 		ii = (ipsec_in_t *)first_mp->b_rptr;
2077 		ii->ipsec_in_ns = ipst->ips_netstack;	/* No netstack_hold */
2078 	}
2079 	ii->ipsec_in_zoneid = zoneid;
2080 	ASSERT(zoneid != ALL_ZONES);
2081 	if (!ipsec_in_to_out(first_mp, ipha, NULL)) {
2082 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2083 		return;
2084 	}
2085 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
2086 	put(WR(q), first_mp);
2087 }
2088 
2089 static ipaddr_t
2090 icmp_get_nexthop_addr(ipha_t *ipha, ill_t *ill, zoneid_t zoneid, mblk_t *mp)
2091 {
2092 	conn_t *connp;
2093 	connf_t *connfp;
2094 	ipaddr_t nexthop_addr = INADDR_ANY;
2095 	int hdr_length = IPH_HDR_LENGTH(ipha);
2096 	uint16_t *up;
2097 	uint32_t ports;
2098 	ip_stack_t *ipst = ill->ill_ipst;
2099 
2100 	up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2101 	switch (ipha->ipha_protocol) {
2102 		case IPPROTO_TCP:
2103 		{
2104 			tcph_t *tcph;
2105 
2106 			/* do a reverse lookup */
2107 			tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2108 			connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph,
2109 			    TCPS_LISTEN, ipst);
2110 			break;
2111 		}
2112 		case IPPROTO_UDP:
2113 		{
2114 			uint32_t dstport, srcport;
2115 
2116 			((uint16_t *)&ports)[0] = up[1];
2117 			((uint16_t *)&ports)[1] = up[0];
2118 
2119 			/* Extract ports in net byte order */
2120 			dstport = htons(ntohl(ports) & 0xFFFF);
2121 			srcport = htons(ntohl(ports) >> 16);
2122 
2123 			connfp = &ipst->ips_ipcl_udp_fanout[
2124 			    IPCL_UDP_HASH(dstport, ipst)];
2125 			mutex_enter(&connfp->connf_lock);
2126 			connp = connfp->connf_head;
2127 
2128 			/* do a reverse lookup */
2129 			while ((connp != NULL) &&
2130 			    (!IPCL_UDP_MATCH(connp, dstport,
2131 			    ipha->ipha_src, srcport, ipha->ipha_dst) ||
2132 			    !IPCL_ZONE_MATCH(connp, zoneid))) {
2133 				connp = connp->conn_next;
2134 			}
2135 			if (connp != NULL)
2136 				CONN_INC_REF(connp);
2137 			mutex_exit(&connfp->connf_lock);
2138 			break;
2139 		}
2140 		case IPPROTO_SCTP:
2141 		{
2142 			in6_addr_t map_src, map_dst;
2143 
2144 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_src);
2145 			IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_dst);
2146 			((uint16_t *)&ports)[0] = up[1];
2147 			((uint16_t *)&ports)[1] = up[0];
2148 
2149 			connp = sctp_find_conn(&map_src, &map_dst, ports,
2150 			    zoneid, ipst->ips_netstack->netstack_sctp);
2151 			if (connp == NULL) {
2152 				connp = ipcl_classify_raw(mp, IPPROTO_SCTP,
2153 				    zoneid, ports, ipha, ipst);
2154 			} else {
2155 				CONN_INC_REF(connp);
2156 				SCTP_REFRELE(CONN2SCTP(connp));
2157 			}
2158 			break;
2159 		}
2160 		default:
2161 		{
2162 			ipha_t ripha;
2163 
2164 			ripha.ipha_src = ipha->ipha_dst;
2165 			ripha.ipha_dst = ipha->ipha_src;
2166 			ripha.ipha_protocol = ipha->ipha_protocol;
2167 
2168 			connfp = &ipst->ips_ipcl_proto_fanout[
2169 			    ipha->ipha_protocol];
2170 			mutex_enter(&connfp->connf_lock);
2171 			connp = connfp->connf_head;
2172 			for (connp = connfp->connf_head; connp != NULL;
2173 			    connp = connp->conn_next) {
2174 				if (IPCL_PROTO_MATCH(connp,
2175 				    ipha->ipha_protocol, &ripha, ill,
2176 				    0, zoneid)) {
2177 					CONN_INC_REF(connp);
2178 					break;
2179 				}
2180 			}
2181 			mutex_exit(&connfp->connf_lock);
2182 		}
2183 	}
2184 	if (connp != NULL) {
2185 		if (connp->conn_nexthop_set)
2186 			nexthop_addr = connp->conn_nexthop_v4;
2187 		CONN_DEC_REF(connp);
2188 	}
2189 	return (nexthop_addr);
2190 }
2191 
2192 /* Table from RFC 1191 */
2193 static int icmp_frag_size_table[] =
2194 { 32000, 17914, 8166, 4352, 2002, 1496, 1006, 508, 296, 68 };
2195 
2196 /*
2197  * Process received ICMP Packet too big.
2198  * After updating any IRE it does the fanout to any matching transport streams.
2199  * Assumes the message has been pulled up till the IP header that caused
2200  * the error.
2201  *
2202  * Returns B_FALSE on failure and B_TRUE on success.
2203  */
2204 static boolean_t
2205 icmp_inbound_too_big(icmph_t *icmph, ipha_t *ipha, ill_t *ill,
2206     zoneid_t zoneid, mblk_t *mp, int iph_hdr_length,
2207     ip_stack_t *ipst)
2208 {
2209 	ire_t	*ire, *first_ire;
2210 	int	mtu;
2211 	int	hdr_length;
2212 	ipaddr_t nexthop_addr;
2213 
2214 	ASSERT(icmph->icmph_type == ICMP_DEST_UNREACHABLE &&
2215 	    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED);
2216 	ASSERT(ill != NULL);
2217 
2218 	hdr_length = IPH_HDR_LENGTH(ipha);
2219 
2220 	/* Drop if the original packet contained a source route */
2221 	if (ip_source_route_included(ipha)) {
2222 		return (B_FALSE);
2223 	}
2224 	/*
2225 	 * Verify we have atleast ICMP_MIN_TP_HDR_LENGTH bytes of transport
2226 	 * header.
2227 	 */
2228 	if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2229 	    mp->b_wptr) {
2230 		if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2231 		    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2232 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2233 			ip1dbg(("icmp_inbound_too_big: insufficient hdr\n"));
2234 			return (B_FALSE);
2235 		}
2236 		icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2237 		ipha = (ipha_t *)&icmph[1];
2238 	}
2239 	nexthop_addr = icmp_get_nexthop_addr(ipha, ill, zoneid, mp);
2240 	if (nexthop_addr != INADDR_ANY) {
2241 		/* nexthop set */
2242 		first_ire = ire_ctable_lookup(ipha->ipha_dst,
2243 		    nexthop_addr, 0, NULL, ALL_ZONES, MBLK_GETLABEL(mp),
2244 		    MATCH_IRE_MARK_PRIVATE_ADDR | MATCH_IRE_GW, ipst);
2245 	} else {
2246 		/* nexthop not set */
2247 		first_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_CACHE,
2248 		    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
2249 	}
2250 
2251 	if (!first_ire) {
2252 		ip1dbg(("icmp_inbound_too_big: no route for 0x%x\n",
2253 		    ntohl(ipha->ipha_dst)));
2254 		return (B_FALSE);
2255 	}
2256 	/* Check for MTU discovery advice as described in RFC 1191 */
2257 	mtu = ntohs(icmph->icmph_du_mtu);
2258 	rw_enter(&first_ire->ire_bucket->irb_lock, RW_READER);
2259 	for (ire = first_ire; ire != NULL && ire->ire_addr == ipha->ipha_dst;
2260 	    ire = ire->ire_next) {
2261 		/*
2262 		 * Look for the connection to which this ICMP message is
2263 		 * directed. If it has the IP_NEXTHOP option set, then the
2264 		 * search is limited to IREs with the MATCH_IRE_PRIVATE
2265 		 * option. Else the search is limited to regular IREs.
2266 		 */
2267 		if (((ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2268 		    (nexthop_addr != ire->ire_gateway_addr)) ||
2269 		    (!(ire->ire_marks & IRE_MARK_PRIVATE_ADDR) &&
2270 		    (nexthop_addr != INADDR_ANY)))
2271 			continue;
2272 
2273 		mutex_enter(&ire->ire_lock);
2274 		if (icmph->icmph_du_zero == 0 && mtu > 68) {
2275 			/* Reduce the IRE max frag value as advised. */
2276 			ip1dbg(("Received mtu from router: %d (was %d)\n",
2277 			    mtu, ire->ire_max_frag));
2278 			ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2279 		} else {
2280 			uint32_t length;
2281 			int	i;
2282 
2283 			/*
2284 			 * Use the table from RFC 1191 to figure out
2285 			 * the next "plateau" based on the length in
2286 			 * the original IP packet.
2287 			 */
2288 			length = ntohs(ipha->ipha_length);
2289 			if (ire->ire_max_frag <= length &&
2290 			    ire->ire_max_frag >= length - hdr_length) {
2291 				/*
2292 				 * Handle broken BSD 4.2 systems that
2293 				 * return the wrong iph_length in ICMP
2294 				 * errors.
2295 				 */
2296 				ip1dbg(("Wrong mtu: sent %d, ire %d\n",
2297 				    length, ire->ire_max_frag));
2298 				length -= hdr_length;
2299 			}
2300 			for (i = 0; i < A_CNT(icmp_frag_size_table); i++) {
2301 				if (length > icmp_frag_size_table[i])
2302 					break;
2303 			}
2304 			if (i == A_CNT(icmp_frag_size_table)) {
2305 				/* Smaller than 68! */
2306 				ip1dbg(("Too big for packet size %d\n",
2307 				    length));
2308 				ire->ire_max_frag = MIN(ire->ire_max_frag, 576);
2309 				ire->ire_frag_flag = 0;
2310 			} else {
2311 				mtu = icmp_frag_size_table[i];
2312 				ip1dbg(("Calculated mtu %d, packet size %d, "
2313 				    "before %d", mtu, length,
2314 				    ire->ire_max_frag));
2315 				ire->ire_max_frag = MIN(ire->ire_max_frag, mtu);
2316 				ip1dbg((", after %d\n", ire->ire_max_frag));
2317 			}
2318 			/* Record the new max frag size for the ULP. */
2319 			icmph->icmph_du_zero = 0;
2320 			icmph->icmph_du_mtu =
2321 			    htons((uint16_t)ire->ire_max_frag);
2322 		}
2323 		mutex_exit(&ire->ire_lock);
2324 	}
2325 	rw_exit(&first_ire->ire_bucket->irb_lock);
2326 	ire_refrele(first_ire);
2327 	return (B_TRUE);
2328 }
2329 
2330 /*
2331  * If the packet in error is Self-Encapsulated, icmp_inbound_error_fanout
2332  * calls this function.
2333  */
2334 static mblk_t *
2335 icmp_inbound_self_encap_error(mblk_t *mp, int iph_hdr_length, int hdr_length)
2336 {
2337 	ipha_t *ipha;
2338 	icmph_t *icmph;
2339 	ipha_t *in_ipha;
2340 	int length;
2341 
2342 	ASSERT(mp->b_datap->db_type == M_DATA);
2343 
2344 	/*
2345 	 * For Self-encapsulated packets, we added an extra IP header
2346 	 * without the options. Inner IP header is the one from which
2347 	 * the outer IP header was formed. Thus, we need to remove the
2348 	 * outer IP header. To do this, we pullup the whole message
2349 	 * and overlay whatever follows the outer IP header over the
2350 	 * outer IP header.
2351 	 */
2352 
2353 	if (!pullupmsg(mp, -1))
2354 		return (NULL);
2355 
2356 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2357 	ipha = (ipha_t *)&icmph[1];
2358 	in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2359 
2360 	/*
2361 	 * The length that we want to overlay is following the inner
2362 	 * IP header. Subtracting the IP header + icmp header + outer
2363 	 * IP header's length should give us the length that we want to
2364 	 * overlay.
2365 	 */
2366 	length = msgdsize(mp) - iph_hdr_length - sizeof (icmph_t) -
2367 	    hdr_length;
2368 	/*
2369 	 * Overlay whatever follows the inner header over the
2370 	 * outer header.
2371 	 */
2372 	bcopy((uchar_t *)in_ipha, (uchar_t *)ipha, length);
2373 
2374 	/* Set the wptr to account for the outer header */
2375 	mp->b_wptr -= hdr_length;
2376 	return (mp);
2377 }
2378 
2379 /*
2380  * Try to pass the ICMP message upstream in case the ULP cares.
2381  *
2382  * If the packet that caused the ICMP error is secure, we send
2383  * it to AH/ESP to make sure that the attached packet has a
2384  * valid association. ipha in the code below points to the
2385  * IP header of the packet that caused the error.
2386  *
2387  * We handle ICMP_FRAGMENTATION_NEEDED(IFN) message differently
2388  * in the context of IPsec. Normally we tell the upper layer
2389  * whenever we send the ire (including ip_bind), the IPsec header
2390  * length in ire_ipsec_overhead. TCP can deduce the MSS as it
2391  * has both the MTU (ire_max_frag) and the ire_ipsec_overhead.
2392  * Similarly, we pass the new MTU icmph_du_mtu and TCP does the
2393  * same thing. As TCP has the IPsec options size that needs to be
2394  * adjusted, we just pass the MTU unchanged.
2395  *
2396  * IFN could have been generated locally or by some router.
2397  *
2398  * LOCAL : *ip_wput_ire -> icmp_frag_needed could have generated this.
2399  *	    This happens because IP adjusted its value of MTU on an
2400  *	    earlier IFN message and could not tell the upper layer,
2401  *	    the new adjusted value of MTU e.g. Packet was encrypted
2402  *	    or there was not enough information to fanout to upper
2403  *	    layers. Thus on the next outbound datagram, ip_wput_ire
2404  *	    generates the IFN, where IPsec processing has *not* been
2405  *	    done.
2406  *
2407  *	   *ip_wput_ire_fragmentit -> ip_wput_frag -> icmp_frag_needed
2408  *	    could have generated this. This happens because ire_max_frag
2409  *	    value in IP was set to a new value, while the IPsec processing
2410  *	    was being done and after we made the fragmentation check in
2411  *	    ip_wput_ire. Thus on return from IPsec processing,
2412  *	    ip_wput_ipsec_out finds that the new length is > ire_max_frag
2413  *	    and generates the IFN. As IPsec processing is over, we fanout
2414  *	    to AH/ESP to remove the header.
2415  *
2416  *	    In both these cases, ipsec_in_loopback will be set indicating
2417  *	    that IFN was generated locally.
2418  *
2419  * ROUTER : IFN could be secure or non-secure.
2420  *
2421  *	    * SECURE : We use the IPSEC_IN to fanout to AH/ESP if the
2422  *	      packet in error has AH/ESP headers to validate the AH/ESP
2423  *	      headers. AH/ESP will verify whether there is a valid SA or
2424  *	      not and send it back. We will fanout again if we have more
2425  *	      data in the packet.
2426  *
2427  *	      If the packet in error does not have AH/ESP, we handle it
2428  *	      like any other case.
2429  *
2430  *	    * NON_SECURE : If the packet in error has AH/ESP headers,
2431  *	      we attach a dummy ipsec_in and send it up to AH/ESP
2432  *	      for validation. AH/ESP will verify whether there is a
2433  *	      valid SA or not and send it back. We will fanout again if
2434  *	      we have more data in the packet.
2435  *
2436  *	      If the packet in error does not have AH/ESP, we handle it
2437  *	      like any other case.
2438  */
2439 static void
2440 icmp_inbound_error_fanout(queue_t *q, ill_t *ill, mblk_t *mp,
2441     icmph_t *icmph, ipha_t *ipha, int iph_hdr_length, int hdr_length,
2442     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
2443     zoneid_t zoneid)
2444 {
2445 	uint16_t *up;	/* Pointer to ports in ULP header */
2446 	uint32_t ports;	/* reversed ports for fanout */
2447 	ipha_t ripha;	/* With reversed addresses */
2448 	mblk_t *first_mp;
2449 	ipsec_in_t *ii;
2450 	tcph_t	*tcph;
2451 	conn_t	*connp;
2452 	ip_stack_t *ipst;
2453 
2454 	ASSERT(ill != NULL);
2455 
2456 	ASSERT(recv_ill != NULL);
2457 	ipst = recv_ill->ill_ipst;
2458 
2459 	first_mp = mp;
2460 	if (mctl_present) {
2461 		mp = first_mp->b_cont;
2462 		ASSERT(mp != NULL);
2463 
2464 		ii = (ipsec_in_t *)first_mp->b_rptr;
2465 		ASSERT(ii->ipsec_in_type == IPSEC_IN);
2466 	} else {
2467 		ii = NULL;
2468 	}
2469 
2470 	switch (ipha->ipha_protocol) {
2471 	case IPPROTO_UDP:
2472 		/*
2473 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2474 		 * transport header.
2475 		 */
2476 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2477 		    mp->b_wptr) {
2478 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2479 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2480 				goto discard_pkt;
2481 			}
2482 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2483 			ipha = (ipha_t *)&icmph[1];
2484 		}
2485 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2486 
2487 		/*
2488 		 * Attempt to find a client stream based on port.
2489 		 * Note that we do a reverse lookup since the header is
2490 		 * in the form we sent it out.
2491 		 * The ripha header is only used for the IP_UDP_MATCH and we
2492 		 * only set the src and dst addresses and protocol.
2493 		 */
2494 		ripha.ipha_src = ipha->ipha_dst;
2495 		ripha.ipha_dst = ipha->ipha_src;
2496 		ripha.ipha_protocol = ipha->ipha_protocol;
2497 		((uint16_t *)&ports)[0] = up[1];
2498 		((uint16_t *)&ports)[1] = up[0];
2499 		ip2dbg(("icmp_inbound_error: UDP %x:%d to %x:%d: %d/%d\n",
2500 		    ntohl(ipha->ipha_src), ntohs(up[0]),
2501 		    ntohl(ipha->ipha_dst), ntohs(up[1]),
2502 		    icmph->icmph_type, icmph->icmph_code));
2503 
2504 		/* Have to change db_type after any pullupmsg */
2505 		DB_TYPE(mp) = M_CTL;
2506 
2507 		ip_fanout_udp(q, first_mp, ill, &ripha, ports, B_FALSE, 0,
2508 		    mctl_present, ip_policy, recv_ill, zoneid);
2509 		return;
2510 
2511 	case IPPROTO_TCP:
2512 		/*
2513 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2514 		 * transport header.
2515 		 */
2516 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2517 		    mp->b_wptr) {
2518 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2519 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2520 				goto discard_pkt;
2521 			}
2522 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2523 			ipha = (ipha_t *)&icmph[1];
2524 		}
2525 		/*
2526 		 * Find a TCP client stream for this packet.
2527 		 * Note that we do a reverse lookup since the header is
2528 		 * in the form we sent it out.
2529 		 */
2530 		tcph = (tcph_t *)((uchar_t *)ipha + hdr_length);
2531 		connp = ipcl_tcp_lookup_reversed_ipv4(ipha, tcph, TCPS_LISTEN,
2532 		    ipst);
2533 		if (connp == NULL)
2534 			goto discard_pkt;
2535 
2536 		/* Have to change db_type after any pullupmsg */
2537 		DB_TYPE(mp) = M_CTL;
2538 		squeue_fill(connp->conn_sqp, first_mp, tcp_input,
2539 		    connp, SQTAG_TCP_INPUT_ICMP_ERR);
2540 		return;
2541 
2542 	case IPPROTO_SCTP:
2543 		/*
2544 		 * Verify we have at least ICMP_MIN_TP_HDR_LEN bytes of
2545 		 * transport header.
2546 		 */
2547 		if ((uchar_t *)ipha + hdr_length + ICMP_MIN_TP_HDR_LEN >
2548 		    mp->b_wptr) {
2549 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
2550 			    ICMP_MIN_TP_HDR_LEN - mp->b_rptr)) {
2551 				goto discard_pkt;
2552 			}
2553 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2554 			ipha = (ipha_t *)&icmph[1];
2555 		}
2556 		up = (uint16_t *)((uchar_t *)ipha + hdr_length);
2557 		/*
2558 		 * Find a SCTP client stream for this packet.
2559 		 * Note that we do a reverse lookup since the header is
2560 		 * in the form we sent it out.
2561 		 * The ripha header is only used for the matching and we
2562 		 * only set the src and dst addresses, protocol, and version.
2563 		 */
2564 		ripha.ipha_src = ipha->ipha_dst;
2565 		ripha.ipha_dst = ipha->ipha_src;
2566 		ripha.ipha_protocol = ipha->ipha_protocol;
2567 		ripha.ipha_version_and_hdr_length =
2568 		    ipha->ipha_version_and_hdr_length;
2569 		((uint16_t *)&ports)[0] = up[1];
2570 		((uint16_t *)&ports)[1] = up[0];
2571 
2572 		/* Have to change db_type after any pullupmsg */
2573 		DB_TYPE(mp) = M_CTL;
2574 		ip_fanout_sctp(first_mp, recv_ill, &ripha, ports, 0,
2575 		    mctl_present, ip_policy, zoneid);
2576 		return;
2577 
2578 	case IPPROTO_ESP:
2579 	case IPPROTO_AH: {
2580 		int ipsec_rc;
2581 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
2582 
2583 		/*
2584 		 * We need a IPSEC_IN in the front to fanout to AH/ESP.
2585 		 * We will re-use the IPSEC_IN if it is already present as
2586 		 * AH/ESP will not affect any fields in the IPSEC_IN for
2587 		 * ICMP errors. If there is no IPSEC_IN, allocate a new
2588 		 * one and attach it in the front.
2589 		 */
2590 		if (ii != NULL) {
2591 			/*
2592 			 * ip_fanout_proto_again converts the ICMP errors
2593 			 * that come back from AH/ESP to M_DATA so that
2594 			 * if it is non-AH/ESP and we do a pullupmsg in
2595 			 * this function, it would work. Convert it back
2596 			 * to M_CTL before we send up as this is a ICMP
2597 			 * error. This could have been generated locally or
2598 			 * by some router. Validate the inner IPsec
2599 			 * headers.
2600 			 *
2601 			 * NOTE : ill_index is used by ip_fanout_proto_again
2602 			 * to locate the ill.
2603 			 */
2604 			ASSERT(ill != NULL);
2605 			ii->ipsec_in_ill_index =
2606 			    ill->ill_phyint->phyint_ifindex;
2607 			ii->ipsec_in_rill_index =
2608 			    recv_ill->ill_phyint->phyint_ifindex;
2609 			DB_TYPE(first_mp->b_cont) = M_CTL;
2610 		} else {
2611 			/*
2612 			 * IPSEC_IN is not present. We attach a ipsec_in
2613 			 * message and send up to IPsec for validating
2614 			 * and removing the IPsec headers. Clear
2615 			 * ipsec_in_secure so that when we return
2616 			 * from IPsec, we don't mistakenly think that this
2617 			 * is a secure packet came from the network.
2618 			 *
2619 			 * NOTE : ill_index is used by ip_fanout_proto_again
2620 			 * to locate the ill.
2621 			 */
2622 			ASSERT(first_mp == mp);
2623 			first_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
2624 			if (first_mp == NULL) {
2625 				freemsg(mp);
2626 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2627 				return;
2628 			}
2629 			ii = (ipsec_in_t *)first_mp->b_rptr;
2630 
2631 			/* This is not a secure packet */
2632 			ii->ipsec_in_secure = B_FALSE;
2633 			first_mp->b_cont = mp;
2634 			DB_TYPE(mp) = M_CTL;
2635 			ASSERT(ill != NULL);
2636 			ii->ipsec_in_ill_index =
2637 			    ill->ill_phyint->phyint_ifindex;
2638 			ii->ipsec_in_rill_index =
2639 			    recv_ill->ill_phyint->phyint_ifindex;
2640 		}
2641 		ip2dbg(("icmp_inbound_error: ipsec\n"));
2642 
2643 		if (!ipsec_loaded(ipss)) {
2644 			ip_proto_not_sup(q, first_mp, 0, zoneid, ipst);
2645 			return;
2646 		}
2647 
2648 		if (ipha->ipha_protocol == IPPROTO_ESP)
2649 			ipsec_rc = ipsecesp_icmp_error(first_mp);
2650 		else
2651 			ipsec_rc = ipsecah_icmp_error(first_mp);
2652 		if (ipsec_rc == IPSEC_STATUS_FAILED)
2653 			return;
2654 
2655 		ip_fanout_proto_again(first_mp, ill, recv_ill, NULL);
2656 		return;
2657 	}
2658 	default:
2659 		/*
2660 		 * The ripha header is only used for the lookup and we
2661 		 * only set the src and dst addresses and protocol.
2662 		 */
2663 		ripha.ipha_src = ipha->ipha_dst;
2664 		ripha.ipha_dst = ipha->ipha_src;
2665 		ripha.ipha_protocol = ipha->ipha_protocol;
2666 		ip2dbg(("icmp_inbound_error: proto %d %x to %x: %d/%d\n",
2667 		    ripha.ipha_protocol, ntohl(ipha->ipha_src),
2668 		    ntohl(ipha->ipha_dst),
2669 		    icmph->icmph_type, icmph->icmph_code));
2670 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2671 			ipha_t *in_ipha;
2672 
2673 			if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
2674 			    mp->b_wptr) {
2675 				if (!pullupmsg(mp, (uchar_t *)ipha +
2676 				    hdr_length + sizeof (ipha_t) -
2677 				    mp->b_rptr)) {
2678 					goto discard_pkt;
2679 				}
2680 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2681 				ipha = (ipha_t *)&icmph[1];
2682 			}
2683 			/*
2684 			 * Caller has verified that length has to be
2685 			 * at least the size of IP header.
2686 			 */
2687 			ASSERT(hdr_length >= sizeof (ipha_t));
2688 			/*
2689 			 * Check the sanity of the inner IP header like
2690 			 * we did for the outer header.
2691 			 */
2692 			in_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
2693 			if ((IPH_HDR_VERSION(in_ipha) != IPV4_VERSION)) {
2694 				goto discard_pkt;
2695 			}
2696 			if (IPH_HDR_LENGTH(in_ipha) < sizeof (ipha_t)) {
2697 				goto discard_pkt;
2698 			}
2699 			/* Check for Self-encapsulated tunnels */
2700 			if (in_ipha->ipha_src == ipha->ipha_src &&
2701 			    in_ipha->ipha_dst == ipha->ipha_dst) {
2702 
2703 				mp = icmp_inbound_self_encap_error(mp,
2704 				    iph_hdr_length, hdr_length);
2705 				if (mp == NULL)
2706 					goto discard_pkt;
2707 				icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
2708 				ipha = (ipha_t *)&icmph[1];
2709 				hdr_length = IPH_HDR_LENGTH(ipha);
2710 				/*
2711 				 * The packet in error is self-encapsualted.
2712 				 * And we are finding it further encapsulated
2713 				 * which we could not have possibly generated.
2714 				 */
2715 				if (ipha->ipha_protocol == IPPROTO_ENCAP) {
2716 					goto discard_pkt;
2717 				}
2718 				icmp_inbound_error_fanout(q, ill, first_mp,
2719 				    icmph, ipha, iph_hdr_length, hdr_length,
2720 				    mctl_present, ip_policy, recv_ill, zoneid);
2721 				return;
2722 			}
2723 		}
2724 		if ((ipha->ipha_protocol == IPPROTO_ENCAP ||
2725 		    ipha->ipha_protocol == IPPROTO_IPV6) &&
2726 		    icmph->icmph_code == ICMP_FRAGMENTATION_NEEDED &&
2727 		    ii != NULL &&
2728 		    ii->ipsec_in_loopback &&
2729 		    ii->ipsec_in_secure) {
2730 			/*
2731 			 * For IP tunnels that get a looped-back
2732 			 * ICMP_FRAGMENTATION_NEEDED message, adjust the
2733 			 * reported new MTU to take into account the IPsec
2734 			 * headers protecting this configured tunnel.
2735 			 *
2736 			 * This allows the tunnel module (tun.c) to blindly
2737 			 * accept the MTU reported in an ICMP "too big"
2738 			 * message.
2739 			 *
2740 			 * Non-looped back ICMP messages will just be
2741 			 * handled by the security protocols (if needed),
2742 			 * and the first subsequent packet will hit this
2743 			 * path.
2744 			 */
2745 			icmph->icmph_du_mtu = htons(ntohs(icmph->icmph_du_mtu) -
2746 			    ipsec_in_extra_length(first_mp));
2747 		}
2748 		/* Have to change db_type after any pullupmsg */
2749 		DB_TYPE(mp) = M_CTL;
2750 
2751 		ip_fanout_proto(q, first_mp, ill, &ripha, 0, mctl_present,
2752 		    ip_policy, recv_ill, zoneid);
2753 		return;
2754 	}
2755 	/* NOTREACHED */
2756 discard_pkt:
2757 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
2758 drop_pkt:;
2759 	ip1dbg(("icmp_inbound_error_fanout: drop pkt\n"));
2760 	freemsg(first_mp);
2761 }
2762 
2763 /*
2764  * Common IP options parser.
2765  *
2766  * Setup routine: fill in *optp with options-parsing state, then
2767  * tail-call ipoptp_next to return the first option.
2768  */
2769 uint8_t
2770 ipoptp_first(ipoptp_t *optp, ipha_t *ipha)
2771 {
2772 	uint32_t totallen; /* total length of all options */
2773 
2774 	totallen = ipha->ipha_version_and_hdr_length -
2775 	    (uint8_t)((IP_VERSION << 4) + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
2776 	totallen <<= 2;
2777 	optp->ipoptp_next = (uint8_t *)(&ipha[1]);
2778 	optp->ipoptp_end = optp->ipoptp_next + totallen;
2779 	optp->ipoptp_flags = 0;
2780 	return (ipoptp_next(optp));
2781 }
2782 
2783 /*
2784  * Common IP options parser: extract next option.
2785  */
2786 uint8_t
2787 ipoptp_next(ipoptp_t *optp)
2788 {
2789 	uint8_t *end = optp->ipoptp_end;
2790 	uint8_t *cur = optp->ipoptp_next;
2791 	uint8_t opt, len, pointer;
2792 
2793 	/*
2794 	 * If cur > end already, then the ipoptp_end or ipoptp_next pointer
2795 	 * has been corrupted.
2796 	 */
2797 	ASSERT(cur <= end);
2798 
2799 	if (cur == end)
2800 		return (IPOPT_EOL);
2801 
2802 	opt = cur[IPOPT_OPTVAL];
2803 
2804 	/*
2805 	 * Skip any NOP options.
2806 	 */
2807 	while (opt == IPOPT_NOP) {
2808 		cur++;
2809 		if (cur == end)
2810 			return (IPOPT_EOL);
2811 		opt = cur[IPOPT_OPTVAL];
2812 	}
2813 
2814 	if (opt == IPOPT_EOL)
2815 		return (IPOPT_EOL);
2816 
2817 	/*
2818 	 * Option requiring a length.
2819 	 */
2820 	if ((cur + 1) >= end) {
2821 		optp->ipoptp_flags |= IPOPTP_ERROR;
2822 		return (IPOPT_EOL);
2823 	}
2824 	len = cur[IPOPT_OLEN];
2825 	if (len < 2) {
2826 		optp->ipoptp_flags |= IPOPTP_ERROR;
2827 		return (IPOPT_EOL);
2828 	}
2829 	optp->ipoptp_cur = cur;
2830 	optp->ipoptp_len = len;
2831 	optp->ipoptp_next = cur + len;
2832 	if (cur + len > end) {
2833 		optp->ipoptp_flags |= IPOPTP_ERROR;
2834 		return (IPOPT_EOL);
2835 	}
2836 
2837 	/*
2838 	 * For the options which require a pointer field, make sure
2839 	 * its there, and make sure it points to either something
2840 	 * inside this option, or the end of the option.
2841 	 */
2842 	switch (opt) {
2843 	case IPOPT_RR:
2844 	case IPOPT_TS:
2845 	case IPOPT_LSRR:
2846 	case IPOPT_SSRR:
2847 		if (len <= IPOPT_OFFSET) {
2848 			optp->ipoptp_flags |= IPOPTP_ERROR;
2849 			return (opt);
2850 		}
2851 		pointer = cur[IPOPT_OFFSET];
2852 		if (pointer - 1 > len) {
2853 			optp->ipoptp_flags |= IPOPTP_ERROR;
2854 			return (opt);
2855 		}
2856 		break;
2857 	}
2858 
2859 	/*
2860 	 * Sanity check the pointer field based on the type of the
2861 	 * option.
2862 	 */
2863 	switch (opt) {
2864 	case IPOPT_RR:
2865 	case IPOPT_SSRR:
2866 	case IPOPT_LSRR:
2867 		if (pointer < IPOPT_MINOFF_SR)
2868 			optp->ipoptp_flags |= IPOPTP_ERROR;
2869 		break;
2870 	case IPOPT_TS:
2871 		if (pointer < IPOPT_MINOFF_IT)
2872 			optp->ipoptp_flags |= IPOPTP_ERROR;
2873 		/*
2874 		 * Note that the Internet Timestamp option also
2875 		 * contains two four bit fields (the Overflow field,
2876 		 * and the Flag field), which follow the pointer
2877 		 * field.  We don't need to check that these fields
2878 		 * fall within the length of the option because this
2879 		 * was implicitely done above.  We've checked that the
2880 		 * pointer value is at least IPOPT_MINOFF_IT, and that
2881 		 * it falls within the option.  Since IPOPT_MINOFF_IT >
2882 		 * IPOPT_POS_OV_FLG, we don't need the explicit check.
2883 		 */
2884 		ASSERT(len > IPOPT_POS_OV_FLG);
2885 		break;
2886 	}
2887 
2888 	return (opt);
2889 }
2890 
2891 /*
2892  * Use the outgoing IP header to create an IP_OPTIONS option the way
2893  * it was passed down from the application.
2894  */
2895 int
2896 ip_opt_get_user(const ipha_t *ipha, uchar_t *buf)
2897 {
2898 	ipoptp_t	opts;
2899 	const uchar_t	*opt;
2900 	uint8_t		optval;
2901 	uint8_t		optlen;
2902 	uint32_t	len = 0;
2903 	uchar_t	*buf1 = buf;
2904 
2905 	buf += IP_ADDR_LEN;	/* Leave room for final destination */
2906 	len += IP_ADDR_LEN;
2907 	bzero(buf1, IP_ADDR_LEN);
2908 
2909 	/*
2910 	 * OK to cast away const here, as we don't store through the returned
2911 	 * opts.ipoptp_cur pointer.
2912 	 */
2913 	for (optval = ipoptp_first(&opts, (ipha_t *)ipha);
2914 	    optval != IPOPT_EOL;
2915 	    optval = ipoptp_next(&opts)) {
2916 		int	off;
2917 
2918 		opt = opts.ipoptp_cur;
2919 		optlen = opts.ipoptp_len;
2920 		switch (optval) {
2921 		case IPOPT_SSRR:
2922 		case IPOPT_LSRR:
2923 
2924 			/*
2925 			 * Insert ipha_dst as the first entry in the source
2926 			 * route and move down the entries on step.
2927 			 * The last entry gets placed at buf1.
2928 			 */
2929 			buf[IPOPT_OPTVAL] = optval;
2930 			buf[IPOPT_OLEN] = optlen;
2931 			buf[IPOPT_OFFSET] = optlen;
2932 
2933 			off = optlen - IP_ADDR_LEN;
2934 			if (off < 0) {
2935 				/* No entries in source route */
2936 				break;
2937 			}
2938 			/* Last entry in source route */
2939 			bcopy(opt + off, buf1, IP_ADDR_LEN);
2940 			off -= IP_ADDR_LEN;
2941 
2942 			while (off > 0) {
2943 				bcopy(opt + off,
2944 				    buf + off + IP_ADDR_LEN,
2945 				    IP_ADDR_LEN);
2946 				off -= IP_ADDR_LEN;
2947 			}
2948 			/* ipha_dst into first slot */
2949 			bcopy(&ipha->ipha_dst,
2950 			    buf + off + IP_ADDR_LEN,
2951 			    IP_ADDR_LEN);
2952 			buf += optlen;
2953 			len += optlen;
2954 			break;
2955 
2956 		case IPOPT_COMSEC:
2957 		case IPOPT_SECURITY:
2958 			/* if passing up a label is not ok, then remove */
2959 			if (is_system_labeled())
2960 				break;
2961 			/* FALLTHROUGH */
2962 		default:
2963 			bcopy(opt, buf, optlen);
2964 			buf += optlen;
2965 			len += optlen;
2966 			break;
2967 		}
2968 	}
2969 done:
2970 	/* Pad the resulting options */
2971 	while (len & 0x3) {
2972 		*buf++ = IPOPT_EOL;
2973 		len++;
2974 	}
2975 	return (len);
2976 }
2977 
2978 /*
2979  * Update any record route or timestamp options to include this host.
2980  * Reverse any source route option.
2981  * This routine assumes that the options are well formed i.e. that they
2982  * have already been checked.
2983  */
2984 static void
2985 icmp_options_update(ipha_t *ipha)
2986 {
2987 	ipoptp_t	opts;
2988 	uchar_t		*opt;
2989 	uint8_t		optval;
2990 	ipaddr_t	src;		/* Our local address */
2991 	ipaddr_t	dst;
2992 
2993 	ip2dbg(("icmp_options_update\n"));
2994 	src = ipha->ipha_src;
2995 	dst = ipha->ipha_dst;
2996 
2997 	for (optval = ipoptp_first(&opts, ipha);
2998 	    optval != IPOPT_EOL;
2999 	    optval = ipoptp_next(&opts)) {
3000 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
3001 		opt = opts.ipoptp_cur;
3002 		ip2dbg(("icmp_options_update: opt %d, len %d\n",
3003 		    optval, opts.ipoptp_len));
3004 		switch (optval) {
3005 			int off1, off2;
3006 		case IPOPT_SSRR:
3007 		case IPOPT_LSRR:
3008 			/*
3009 			 * Reverse the source route.  The first entry
3010 			 * should be the next to last one in the current
3011 			 * source route (the last entry is our address).
3012 			 * The last entry should be the final destination.
3013 			 */
3014 			off1 = IPOPT_MINOFF_SR - 1;
3015 			off2 = opt[IPOPT_OFFSET] - IP_ADDR_LEN - 1;
3016 			if (off2 < 0) {
3017 				/* No entries in source route */
3018 				ip1dbg((
3019 				    "icmp_options_update: bad src route\n"));
3020 				break;
3021 			}
3022 			bcopy((char *)opt + off2, &dst, IP_ADDR_LEN);
3023 			bcopy(&ipha->ipha_dst, (char *)opt + off2, IP_ADDR_LEN);
3024 			bcopy(&dst, &ipha->ipha_dst, IP_ADDR_LEN);
3025 			off2 -= IP_ADDR_LEN;
3026 
3027 			while (off1 < off2) {
3028 				bcopy((char *)opt + off1, &src, IP_ADDR_LEN);
3029 				bcopy((char *)opt + off2, (char *)opt + off1,
3030 				    IP_ADDR_LEN);
3031 				bcopy(&src, (char *)opt + off2, IP_ADDR_LEN);
3032 				off1 += IP_ADDR_LEN;
3033 				off2 -= IP_ADDR_LEN;
3034 			}
3035 			opt[IPOPT_OFFSET] = IPOPT_MINOFF_SR;
3036 			break;
3037 		}
3038 	}
3039 }
3040 
3041 /*
3042  * Process received ICMP Redirect messages.
3043  */
3044 static void
3045 icmp_redirect(ill_t *ill, mblk_t *mp)
3046 {
3047 	ipha_t	*ipha;
3048 	int	iph_hdr_length;
3049 	icmph_t	*icmph;
3050 	ipha_t	*ipha_err;
3051 	ire_t	*ire;
3052 	ire_t	*prev_ire;
3053 	ire_t	*save_ire;
3054 	ipaddr_t  src, dst, gateway;
3055 	iulp_t	ulp_info = { 0 };
3056 	int	error;
3057 	ip_stack_t *ipst;
3058 
3059 	ASSERT(ill != NULL);
3060 	ipst = ill->ill_ipst;
3061 
3062 	ipha = (ipha_t *)mp->b_rptr;
3063 	iph_hdr_length = IPH_HDR_LENGTH(ipha);
3064 	if (((mp->b_wptr - mp->b_rptr) - iph_hdr_length) <
3065 	    sizeof (icmph_t) + IP_SIMPLE_HDR_LENGTH) {
3066 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3067 		freemsg(mp);
3068 		return;
3069 	}
3070 	icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
3071 	ipha_err = (ipha_t *)&icmph[1];
3072 	src = ipha->ipha_src;
3073 	dst = ipha_err->ipha_dst;
3074 	gateway = icmph->icmph_rd_gateway;
3075 	/* Make sure the new gateway is reachable somehow. */
3076 	ire = ire_route_lookup(gateway, 0, 0, IRE_INTERFACE, NULL, NULL,
3077 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3078 	/*
3079 	 * Make sure we had a route for the dest in question and that
3080 	 * that route was pointing to the old gateway (the source of the
3081 	 * redirect packet.)
3082 	 */
3083 	prev_ire = ire_route_lookup(dst, 0, src, 0, NULL, NULL, ALL_ZONES,
3084 	    NULL, MATCH_IRE_GW, ipst);
3085 	/*
3086 	 * Check that
3087 	 *	the redirect was not from ourselves
3088 	 *	the new gateway and the old gateway are directly reachable
3089 	 */
3090 	if (!prev_ire ||
3091 	    !ire ||
3092 	    ire->ire_type == IRE_LOCAL) {
3093 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3094 		freemsg(mp);
3095 		if (ire != NULL)
3096 			ire_refrele(ire);
3097 		if (prev_ire != NULL)
3098 			ire_refrele(prev_ire);
3099 		return;
3100 	}
3101 
3102 	/*
3103 	 * Should we use the old ULP info to create the new gateway?  From
3104 	 * a user's perspective, we should inherit the info so that it
3105 	 * is a "smooth" transition.  If we do not do that, then new
3106 	 * connections going thru the new gateway will have no route metrics,
3107 	 * which is counter-intuitive to user.  From a network point of
3108 	 * view, this may or may not make sense even though the new gateway
3109 	 * is still directly connected to us so the route metrics should not
3110 	 * change much.
3111 	 *
3112 	 * But if the old ire_uinfo is not initialized, we do another
3113 	 * recursive lookup on the dest using the new gateway.  There may
3114 	 * be a route to that.  If so, use it to initialize the redirect
3115 	 * route.
3116 	 */
3117 	if (prev_ire->ire_uinfo.iulp_set) {
3118 		bcopy(&prev_ire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3119 	} else {
3120 		ire_t *tmp_ire;
3121 		ire_t *sire;
3122 
3123 		tmp_ire = ire_ftable_lookup(dst, 0, gateway, 0, NULL, &sire,
3124 		    ALL_ZONES, 0, NULL,
3125 		    (MATCH_IRE_RECURSIVE | MATCH_IRE_GW | MATCH_IRE_DEFAULT),
3126 		    ipst);
3127 		if (sire != NULL) {
3128 			bcopy(&sire->ire_uinfo, &ulp_info, sizeof (iulp_t));
3129 			/*
3130 			 * If sire != NULL, ire_ftable_lookup() should not
3131 			 * return a NULL value.
3132 			 */
3133 			ASSERT(tmp_ire != NULL);
3134 			ire_refrele(tmp_ire);
3135 			ire_refrele(sire);
3136 		} else if (tmp_ire != NULL) {
3137 			bcopy(&tmp_ire->ire_uinfo, &ulp_info,
3138 			    sizeof (iulp_t));
3139 			ire_refrele(tmp_ire);
3140 		}
3141 	}
3142 	if (prev_ire->ire_type == IRE_CACHE)
3143 		ire_delete(prev_ire);
3144 	ire_refrele(prev_ire);
3145 	/*
3146 	 * TODO: more precise handling for cases 0, 2, 3, the latter two
3147 	 * require TOS routing
3148 	 */
3149 	switch (icmph->icmph_code) {
3150 	case 0:
3151 	case 1:
3152 		/* TODO: TOS specificity for cases 2 and 3 */
3153 	case 2:
3154 	case 3:
3155 		break;
3156 	default:
3157 		freemsg(mp);
3158 		BUMP_MIB(&ipst->ips_icmp_mib, icmpInBadRedirects);
3159 		ire_refrele(ire);
3160 		return;
3161 	}
3162 	/*
3163 	 * Create a Route Association.  This will allow us to remember that
3164 	 * someone we believe told us to use the particular gateway.
3165 	 */
3166 	save_ire = ire;
3167 	ire = ire_create(
3168 	    (uchar_t *)&dst,			/* dest addr */
3169 	    (uchar_t *)&ip_g_all_ones,		/* mask */
3170 	    (uchar_t *)&save_ire->ire_src_addr,	/* source addr */
3171 	    (uchar_t *)&gateway,		/* gateway addr */
3172 	    &save_ire->ire_max_frag,		/* max frag */
3173 	    NULL,				/* no src nce */
3174 	    NULL,				/* no rfq */
3175 	    NULL,				/* no stq */
3176 	    IRE_HOST,
3177 	    NULL,				/* ipif */
3178 	    0,					/* cmask */
3179 	    0,					/* phandle */
3180 	    0,					/* ihandle */
3181 	    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST),
3182 	    &ulp_info,
3183 	    NULL,				/* tsol_gc_t */
3184 	    NULL,				/* gcgrp */
3185 	    ipst);
3186 
3187 	if (ire == NULL) {
3188 		freemsg(mp);
3189 		ire_refrele(save_ire);
3190 		return;
3191 	}
3192 	error = ire_add(&ire, NULL, NULL, NULL, B_FALSE);
3193 	ire_refrele(save_ire);
3194 	atomic_inc_32(&ipst->ips_ip_redirect_cnt);
3195 
3196 	if (error == 0) {
3197 		ire_refrele(ire);		/* Held in ire_add_v4 */
3198 		/* tell routing sockets that we received a redirect */
3199 		ip_rts_change(RTM_REDIRECT, dst, gateway, IP_HOST_MASK, 0, src,
3200 		    (RTF_DYNAMIC | RTF_GATEWAY | RTF_HOST), 0,
3201 		    (RTA_DST | RTA_GATEWAY | RTA_NETMASK | RTA_AUTHOR), ipst);
3202 	}
3203 
3204 	/*
3205 	 * Delete any existing IRE_HOST type redirect ires for this destination.
3206 	 * This together with the added IRE has the effect of
3207 	 * modifying an existing redirect.
3208 	 */
3209 	prev_ire = ire_ftable_lookup(dst, 0, src, IRE_HOST, NULL, NULL,
3210 	    ALL_ZONES, 0, NULL, (MATCH_IRE_GW | MATCH_IRE_TYPE), ipst);
3211 	if (prev_ire != NULL) {
3212 		if (prev_ire ->ire_flags & RTF_DYNAMIC)
3213 			ire_delete(prev_ire);
3214 		ire_refrele(prev_ire);
3215 	}
3216 
3217 	freemsg(mp);
3218 }
3219 
3220 /*
3221  * Generate an ICMP parameter problem message.
3222  */
3223 static void
3224 icmp_param_problem(queue_t *q, mblk_t *mp, uint8_t ptr, zoneid_t zoneid,
3225 	ip_stack_t *ipst)
3226 {
3227 	icmph_t	icmph;
3228 	boolean_t mctl_present;
3229 	mblk_t *first_mp;
3230 
3231 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3232 
3233 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3234 		if (mctl_present)
3235 			freeb(first_mp);
3236 		return;
3237 	}
3238 
3239 	bzero(&icmph, sizeof (icmph_t));
3240 	icmph.icmph_type = ICMP_PARAM_PROBLEM;
3241 	icmph.icmph_pp_ptr = ptr;
3242 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutParmProbs);
3243 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3244 	    ipst);
3245 }
3246 
3247 /*
3248  * Build and ship an IPv4 ICMP message using the packet data in mp, and
3249  * the ICMP header pointed to by "stuff".  (May be called as writer.)
3250  * Note: assumes that icmp_pkt_err_ok has been called to verify that
3251  * an icmp error packet can be sent.
3252  * Assigns an appropriate source address to the packet. If ipha_dst is
3253  * one of our addresses use it for source. Otherwise pick a source based
3254  * on a route lookup back to ipha_src.
3255  * Note that ipha_src must be set here since the
3256  * packet is likely to arrive on an ill queue in ip_wput() which will
3257  * not set a source address.
3258  */
3259 static void
3260 icmp_pkt(queue_t *q, mblk_t *mp, void *stuff, size_t len,
3261     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
3262 {
3263 	ipaddr_t dst;
3264 	icmph_t	*icmph;
3265 	ipha_t	*ipha;
3266 	uint_t	len_needed;
3267 	size_t	msg_len;
3268 	mblk_t	*mp1;
3269 	ipaddr_t src;
3270 	ire_t	*ire;
3271 	mblk_t *ipsec_mp;
3272 	ipsec_out_t	*io = NULL;
3273 
3274 	if (mctl_present) {
3275 		/*
3276 		 * If it is :
3277 		 *
3278 		 * 1) a IPSEC_OUT, then this is caused by outbound
3279 		 *    datagram originating on this host. IPsec processing
3280 		 *    may or may not have been done. Refer to comments above
3281 		 *    icmp_inbound_error_fanout for details.
3282 		 *
3283 		 * 2) a IPSEC_IN if we are generating a icmp_message
3284 		 *    for an incoming datagram destined for us i.e called
3285 		 *    from ip_fanout_send_icmp.
3286 		 */
3287 		ipsec_info_t *in;
3288 		ipsec_mp = mp;
3289 		mp = ipsec_mp->b_cont;
3290 
3291 		in = (ipsec_info_t *)ipsec_mp->b_rptr;
3292 		ipha = (ipha_t *)mp->b_rptr;
3293 
3294 		ASSERT(in->ipsec_info_type == IPSEC_OUT ||
3295 		    in->ipsec_info_type == IPSEC_IN);
3296 
3297 		if (in->ipsec_info_type == IPSEC_IN) {
3298 			/*
3299 			 * Convert the IPSEC_IN to IPSEC_OUT.
3300 			 */
3301 			if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3302 				BUMP_MIB(&ipst->ips_ip_mib,
3303 				    ipIfStatsOutDiscards);
3304 				return;
3305 			}
3306 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
3307 		} else {
3308 			ASSERT(in->ipsec_info_type == IPSEC_OUT);
3309 			io = (ipsec_out_t *)in;
3310 			/*
3311 			 * Clear out ipsec_out_proc_begin, so we do a fresh
3312 			 * ire lookup.
3313 			 */
3314 			io->ipsec_out_proc_begin = B_FALSE;
3315 		}
3316 		ASSERT(zoneid == io->ipsec_out_zoneid);
3317 		ASSERT(zoneid != ALL_ZONES);
3318 	} else {
3319 		/*
3320 		 * This is in clear. The icmp message we are building
3321 		 * here should go out in clear.
3322 		 *
3323 		 * Pardon the convolution of it all, but it's easier to
3324 		 * allocate a "use cleartext" IPSEC_IN message and convert
3325 		 * it than it is to allocate a new one.
3326 		 */
3327 		ipsec_in_t *ii;
3328 		ASSERT(DB_TYPE(mp) == M_DATA);
3329 		ipsec_mp = ipsec_in_alloc(B_TRUE, ipst->ips_netstack);
3330 		if (ipsec_mp == NULL) {
3331 			freemsg(mp);
3332 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3333 			return;
3334 		}
3335 		ii = (ipsec_in_t *)ipsec_mp->b_rptr;
3336 
3337 		/* This is not a secure packet */
3338 		ii->ipsec_in_secure = B_FALSE;
3339 		/*
3340 		 * For trusted extensions using a shared IP address we can
3341 		 * send using any zoneid.
3342 		 */
3343 		if (zoneid == ALL_ZONES)
3344 			ii->ipsec_in_zoneid = GLOBAL_ZONEID;
3345 		else
3346 			ii->ipsec_in_zoneid = zoneid;
3347 		ipsec_mp->b_cont = mp;
3348 		ipha = (ipha_t *)mp->b_rptr;
3349 		/*
3350 		 * Convert the IPSEC_IN to IPSEC_OUT.
3351 		 */
3352 		if (!ipsec_in_to_out(ipsec_mp, ipha, NULL)) {
3353 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3354 			return;
3355 		}
3356 		io = (ipsec_out_t *)ipsec_mp->b_rptr;
3357 	}
3358 
3359 	/* Remember our eventual destination */
3360 	dst = ipha->ipha_src;
3361 
3362 	ire = ire_route_lookup(ipha->ipha_dst, 0, 0, (IRE_LOCAL|IRE_LOOPBACK),
3363 	    NULL, NULL, zoneid, NULL, MATCH_IRE_TYPE, ipst);
3364 	if (ire != NULL &&
3365 	    (ire->ire_zoneid == zoneid || ire->ire_zoneid == ALL_ZONES)) {
3366 		src = ipha->ipha_dst;
3367 	} else {
3368 		if (ire != NULL)
3369 			ire_refrele(ire);
3370 		ire = ire_route_lookup(dst, 0, 0, 0, NULL, NULL, zoneid, NULL,
3371 		    (MATCH_IRE_DEFAULT|MATCH_IRE_RECURSIVE|MATCH_IRE_ZONEONLY),
3372 		    ipst);
3373 		if (ire == NULL) {
3374 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
3375 			freemsg(ipsec_mp);
3376 			return;
3377 		}
3378 		src = ire->ire_src_addr;
3379 	}
3380 
3381 	if (ire != NULL)
3382 		ire_refrele(ire);
3383 
3384 	/*
3385 	 * Check if we can send back more then 8 bytes in addition to
3386 	 * the IP header.  We try to send 64 bytes of data and the internal
3387 	 * header in the special cases of ipv4 encapsulated ipv4 or ipv6.
3388 	 */
3389 	len_needed = IPH_HDR_LENGTH(ipha);
3390 	if (ipha->ipha_protocol == IPPROTO_ENCAP ||
3391 	    ipha->ipha_protocol == IPPROTO_IPV6) {
3392 
3393 		if (!pullupmsg(mp, -1)) {
3394 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
3395 			freemsg(ipsec_mp);
3396 			return;
3397 		}
3398 		ipha = (ipha_t *)mp->b_rptr;
3399 
3400 		if (ipha->ipha_protocol == IPPROTO_ENCAP) {
3401 			len_needed += IPH_HDR_LENGTH(((uchar_t *)ipha +
3402 			    len_needed));
3403 		} else {
3404 			ip6_t *ip6h = (ip6_t *)((uchar_t *)ipha + len_needed);
3405 
3406 			ASSERT(ipha->ipha_protocol == IPPROTO_IPV6);
3407 			len_needed += ip_hdr_length_v6(mp, ip6h);
3408 		}
3409 	}
3410 	len_needed += ipst->ips_ip_icmp_return;
3411 	msg_len = msgdsize(mp);
3412 	if (msg_len > len_needed) {
3413 		(void) adjmsg(mp, len_needed - msg_len);
3414 		msg_len = len_needed;
3415 	}
3416 	mp1 = allocb_tmpl(sizeof (icmp_ipha) + len, mp);
3417 	if (mp1 == NULL) {
3418 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutErrors);
3419 		freemsg(ipsec_mp);
3420 		return;
3421 	}
3422 	mp1->b_cont = mp;
3423 	mp = mp1;
3424 	ASSERT(ipsec_mp->b_datap->db_type == M_CTL &&
3425 	    ipsec_mp->b_rptr == (uint8_t *)io &&
3426 	    io->ipsec_out_type == IPSEC_OUT);
3427 	ipsec_mp->b_cont = mp;
3428 
3429 	/*
3430 	 * Set ipsec_out_icmp_loopback so we can let the ICMP messages this
3431 	 * node generates be accepted in peace by all on-host destinations.
3432 	 * If we do NOT assume that all on-host destinations trust
3433 	 * self-generated ICMP messages, then rework here, ip6.c, and spd.c.
3434 	 * (Look for ipsec_out_icmp_loopback).
3435 	 */
3436 	io->ipsec_out_icmp_loopback = B_TRUE;
3437 
3438 	ipha = (ipha_t *)mp->b_rptr;
3439 	mp1->b_wptr = (uchar_t *)ipha + (sizeof (icmp_ipha) + len);
3440 	*ipha = icmp_ipha;
3441 	ipha->ipha_src = src;
3442 	ipha->ipha_dst = dst;
3443 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
3444 	msg_len += sizeof (icmp_ipha) + len;
3445 	if (msg_len > IP_MAXPACKET) {
3446 		(void) adjmsg(mp, IP_MAXPACKET - msg_len);
3447 		msg_len = IP_MAXPACKET;
3448 	}
3449 	ipha->ipha_length = htons((uint16_t)msg_len);
3450 	icmph = (icmph_t *)&ipha[1];
3451 	bcopy(stuff, icmph, len);
3452 	icmph->icmph_checksum = 0;
3453 	icmph->icmph_checksum = IP_CSUM(mp, (int32_t)sizeof (ipha_t), 0);
3454 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutMsgs);
3455 	put(q, ipsec_mp);
3456 }
3457 
3458 /*
3459  * Determine if an ICMP error packet can be sent given the rate limit.
3460  * The limit consists of an average frequency (icmp_pkt_err_interval measured
3461  * in milliseconds) and a burst size. Burst size number of packets can
3462  * be sent arbitrarely closely spaced.
3463  * The state is tracked using two variables to implement an approximate
3464  * token bucket filter:
3465  *	icmp_pkt_err_last - lbolt value when the last burst started
3466  *	icmp_pkt_err_sent - number of packets sent in current burst
3467  */
3468 boolean_t
3469 icmp_err_rate_limit(ip_stack_t *ipst)
3470 {
3471 	clock_t now = TICK_TO_MSEC(lbolt);
3472 	uint_t refilled; /* Number of packets refilled in tbf since last */
3473 	/* Guard against changes by loading into local variable */
3474 	uint_t err_interval = ipst->ips_ip_icmp_err_interval;
3475 
3476 	if (err_interval == 0)
3477 		return (B_FALSE);
3478 
3479 	if (ipst->ips_icmp_pkt_err_last > now) {
3480 		/* 100HZ lbolt in ms for 32bit arch wraps every 49.7 days */
3481 		ipst->ips_icmp_pkt_err_last = 0;
3482 		ipst->ips_icmp_pkt_err_sent = 0;
3483 	}
3484 	/*
3485 	 * If we are in a burst update the token bucket filter.
3486 	 * Update the "last" time to be close to "now" but make sure
3487 	 * we don't loose precision.
3488 	 */
3489 	if (ipst->ips_icmp_pkt_err_sent != 0) {
3490 		refilled = (now - ipst->ips_icmp_pkt_err_last)/err_interval;
3491 		if (refilled > ipst->ips_icmp_pkt_err_sent) {
3492 			ipst->ips_icmp_pkt_err_sent = 0;
3493 		} else {
3494 			ipst->ips_icmp_pkt_err_sent -= refilled;
3495 			ipst->ips_icmp_pkt_err_last += refilled * err_interval;
3496 		}
3497 	}
3498 	if (ipst->ips_icmp_pkt_err_sent == 0) {
3499 		/* Start of new burst */
3500 		ipst->ips_icmp_pkt_err_last = now;
3501 	}
3502 	if (ipst->ips_icmp_pkt_err_sent < ipst->ips_ip_icmp_err_burst) {
3503 		ipst->ips_icmp_pkt_err_sent++;
3504 		ip1dbg(("icmp_err_rate_limit: %d sent in burst\n",
3505 		    ipst->ips_icmp_pkt_err_sent));
3506 		return (B_FALSE);
3507 	}
3508 	ip1dbg(("icmp_err_rate_limit: dropped\n"));
3509 	return (B_TRUE);
3510 }
3511 
3512 /*
3513  * Check if it is ok to send an IPv4 ICMP error packet in
3514  * response to the IPv4 packet in mp.
3515  * Free the message and return null if no
3516  * ICMP error packet should be sent.
3517  */
3518 static mblk_t *
3519 icmp_pkt_err_ok(mblk_t *mp, ip_stack_t *ipst)
3520 {
3521 	icmph_t	*icmph;
3522 	ipha_t	*ipha;
3523 	uint_t	len_needed;
3524 	ire_t	*src_ire;
3525 	ire_t	*dst_ire;
3526 
3527 	if (!mp)
3528 		return (NULL);
3529 	ipha = (ipha_t *)mp->b_rptr;
3530 	if (ip_csum_hdr(ipha)) {
3531 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInCksumErrs);
3532 		freemsg(mp);
3533 		return (NULL);
3534 	}
3535 	src_ire = ire_ctable_lookup(ipha->ipha_dst, 0, IRE_BROADCAST,
3536 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3537 	dst_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST,
3538 	    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
3539 	if (src_ire != NULL || dst_ire != NULL ||
3540 	    CLASSD(ipha->ipha_dst) ||
3541 	    CLASSD(ipha->ipha_src) ||
3542 	    (ntohs(ipha->ipha_fragment_offset_and_flags) & IPH_OFFSET)) {
3543 		/* Note: only errors to the fragment with offset 0 */
3544 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3545 		freemsg(mp);
3546 		if (src_ire != NULL)
3547 			ire_refrele(src_ire);
3548 		if (dst_ire != NULL)
3549 			ire_refrele(dst_ire);
3550 		return (NULL);
3551 	}
3552 	if (ipha->ipha_protocol == IPPROTO_ICMP) {
3553 		/*
3554 		 * Check the ICMP type.  RFC 1122 sez:  don't send ICMP
3555 		 * errors in response to any ICMP errors.
3556 		 */
3557 		len_needed = IPH_HDR_LENGTH(ipha) + ICMPH_SIZE;
3558 		if (mp->b_wptr - mp->b_rptr < len_needed) {
3559 			if (!pullupmsg(mp, len_needed)) {
3560 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInErrors);
3561 				freemsg(mp);
3562 				return (NULL);
3563 			}
3564 			ipha = (ipha_t *)mp->b_rptr;
3565 		}
3566 		icmph = (icmph_t *)
3567 		    (&((char *)ipha)[IPH_HDR_LENGTH(ipha)]);
3568 		switch (icmph->icmph_type) {
3569 		case ICMP_DEST_UNREACHABLE:
3570 		case ICMP_SOURCE_QUENCH:
3571 		case ICMP_TIME_EXCEEDED:
3572 		case ICMP_PARAM_PROBLEM:
3573 		case ICMP_REDIRECT:
3574 			BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3575 			freemsg(mp);
3576 			return (NULL);
3577 		default:
3578 			break;
3579 		}
3580 	}
3581 	/*
3582 	 * If this is a labeled system, then check to see if we're allowed to
3583 	 * send a response to this particular sender.  If not, then just drop.
3584 	 */
3585 	if (is_system_labeled() && !tsol_can_reply_error(mp)) {
3586 		ip2dbg(("icmp_pkt_err_ok: can't respond to packet\n"));
3587 		BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDrops);
3588 		freemsg(mp);
3589 		return (NULL);
3590 	}
3591 	if (icmp_err_rate_limit(ipst)) {
3592 		/*
3593 		 * Only send ICMP error packets every so often.
3594 		 * This should be done on a per port/source basis,
3595 		 * but for now this will suffice.
3596 		 */
3597 		freemsg(mp);
3598 		return (NULL);
3599 	}
3600 	return (mp);
3601 }
3602 
3603 /*
3604  * Generate an ICMP redirect message.
3605  */
3606 static void
3607 icmp_send_redirect(queue_t *q, mblk_t *mp, ipaddr_t gateway, ip_stack_t *ipst)
3608 {
3609 	icmph_t	icmph;
3610 
3611 	/*
3612 	 * We are called from ip_rput where we could
3613 	 * not have attached an IPSEC_IN.
3614 	 */
3615 	ASSERT(mp->b_datap->db_type == M_DATA);
3616 
3617 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3618 		return;
3619 	}
3620 
3621 	bzero(&icmph, sizeof (icmph_t));
3622 	icmph.icmph_type = ICMP_REDIRECT;
3623 	icmph.icmph_code = 1;
3624 	icmph.icmph_rd_gateway = gateway;
3625 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutRedirects);
3626 	/* Redirects sent by router, and router is global zone */
3627 	icmp_pkt(q, mp, &icmph, sizeof (icmph_t), B_FALSE, GLOBAL_ZONEID, ipst);
3628 }
3629 
3630 /*
3631  * Generate an ICMP time exceeded message.
3632  */
3633 void
3634 icmp_time_exceeded(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3635     ip_stack_t *ipst)
3636 {
3637 	icmph_t	icmph;
3638 	boolean_t mctl_present;
3639 	mblk_t *first_mp;
3640 
3641 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3642 
3643 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3644 		if (mctl_present)
3645 			freeb(first_mp);
3646 		return;
3647 	}
3648 
3649 	bzero(&icmph, sizeof (icmph_t));
3650 	icmph.icmph_type = ICMP_TIME_EXCEEDED;
3651 	icmph.icmph_code = code;
3652 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutTimeExcds);
3653 	icmp_pkt(q, first_mp, &icmph, sizeof (icmph_t), mctl_present, zoneid,
3654 	    ipst);
3655 }
3656 
3657 /*
3658  * Generate an ICMP unreachable message.
3659  */
3660 void
3661 icmp_unreachable(queue_t *q, mblk_t *mp, uint8_t code, zoneid_t zoneid,
3662     ip_stack_t *ipst)
3663 {
3664 	icmph_t	icmph;
3665 	mblk_t *first_mp;
3666 	boolean_t mctl_present;
3667 
3668 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
3669 
3670 	if (!(mp = icmp_pkt_err_ok(mp, ipst))) {
3671 		if (mctl_present)
3672 			freeb(first_mp);
3673 		return;
3674 	}
3675 
3676 	bzero(&icmph, sizeof (icmph_t));
3677 	icmph.icmph_type = ICMP_DEST_UNREACHABLE;
3678 	icmph.icmph_code = code;
3679 	BUMP_MIB(&ipst->ips_icmp_mib, icmpOutDestUnreachs);
3680 	ip2dbg(("send icmp destination unreachable code %d\n", code));
3681 	icmp_pkt(q, first_mp, (char *)&icmph, sizeof (icmph_t), mctl_present,
3682 	    zoneid, ipst);
3683 }
3684 
3685 /*
3686  * Attempt to start recovery of an IPv4 interface that's been shut down as a
3687  * duplicate.  As long as someone else holds the address, the interface will
3688  * stay down.  When that conflict goes away, the interface is brought back up.
3689  * This is done so that accidental shutdowns of addresses aren't made
3690  * permanent.  Your server will recover from a failure.
3691  *
3692  * For DHCP, recovery is not done in the kernel.  Instead, it's handled by a
3693  * user space process (dhcpagent).
3694  *
3695  * Recovery completes if ARP reports that the address is now ours (via
3696  * AR_CN_READY).  In that case, we go to ip_arp_excl to finish the operation.
3697  *
3698  * This function is entered on a timer expiry; the ID is in ipif_recovery_id.
3699  */
3700 static void
3701 ipif_dup_recovery(void *arg)
3702 {
3703 	ipif_t *ipif = arg;
3704 	ill_t *ill = ipif->ipif_ill;
3705 	mblk_t *arp_add_mp;
3706 	mblk_t *arp_del_mp;
3707 	area_t *area;
3708 	ip_stack_t *ipst = ill->ill_ipst;
3709 
3710 	ipif->ipif_recovery_id = 0;
3711 
3712 	/*
3713 	 * No lock needed for moving or condemned check, as this is just an
3714 	 * optimization.
3715 	 */
3716 	if (ill->ill_arp_closing || !(ipif->ipif_flags & IPIF_DUPLICATE) ||
3717 	    (ipif->ipif_flags & IPIF_POINTOPOINT) ||
3718 	    (ipif->ipif_state_flags & (IPIF_MOVING | IPIF_CONDEMNED))) {
3719 		/* No reason to try to bring this address back. */
3720 		return;
3721 	}
3722 
3723 	if ((arp_add_mp = ipif_area_alloc(ipif)) == NULL)
3724 		goto alloc_fail;
3725 
3726 	if (ipif->ipif_arp_del_mp == NULL) {
3727 		if ((arp_del_mp = ipif_ared_alloc(ipif)) == NULL)
3728 			goto alloc_fail;
3729 		ipif->ipif_arp_del_mp = arp_del_mp;
3730 	}
3731 
3732 	/* Setting the 'unverified' flag restarts DAD */
3733 	area = (area_t *)arp_add_mp->b_rptr;
3734 	area->area_flags = ACE_F_PERMANENT | ACE_F_PUBLISH | ACE_F_MYADDR |
3735 	    ACE_F_UNVERIFIED;
3736 	putnext(ill->ill_rq, arp_add_mp);
3737 	return;
3738 
3739 alloc_fail:
3740 	/*
3741 	 * On allocation failure, just restart the timer.  Note that the ipif
3742 	 * is down here, so no other thread could be trying to start a recovery
3743 	 * timer.  The ill_lock protects the condemned flag and the recovery
3744 	 * timer ID.
3745 	 */
3746 	freemsg(arp_add_mp);
3747 	mutex_enter(&ill->ill_lock);
3748 	if (ipst->ips_ip_dup_recovery > 0 && ipif->ipif_recovery_id == 0 &&
3749 	    !(ipif->ipif_state_flags & IPIF_CONDEMNED)) {
3750 		ipif->ipif_recovery_id = timeout(ipif_dup_recovery, ipif,
3751 		    MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3752 	}
3753 	mutex_exit(&ill->ill_lock);
3754 }
3755 
3756 /*
3757  * This is for exclusive changes due to ARP.  Either tear down an interface due
3758  * to AR_CN_FAILED and AR_CN_BOGON, or bring one up for successful recovery.
3759  */
3760 /* ARGSUSED */
3761 static void
3762 ip_arp_excl(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3763 {
3764 	ill_t	*ill = rq->q_ptr;
3765 	arh_t *arh;
3766 	ipaddr_t src;
3767 	ipif_t	*ipif;
3768 	char ibuf[LIFNAMSIZ + 10];	/* 10 digits for logical i/f number */
3769 	char hbuf[MAC_STR_LEN];
3770 	char sbuf[INET_ADDRSTRLEN];
3771 	const char *failtype;
3772 	boolean_t bring_up;
3773 	ip_stack_t *ipst = ill->ill_ipst;
3774 
3775 	switch (((arcn_t *)mp->b_rptr)->arcn_code) {
3776 	case AR_CN_READY:
3777 		failtype = NULL;
3778 		bring_up = B_TRUE;
3779 		break;
3780 	case AR_CN_FAILED:
3781 		failtype = "in use";
3782 		bring_up = B_FALSE;
3783 		break;
3784 	default:
3785 		failtype = "claimed";
3786 		bring_up = B_FALSE;
3787 		break;
3788 	}
3789 
3790 	arh = (arh_t *)mp->b_cont->b_rptr;
3791 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3792 
3793 	/* Handle failures due to probes */
3794 	if (src == 0) {
3795 		bcopy((char *)&arh[1] + 2 * arh->arh_hlen + IP_ADDR_LEN, &src,
3796 		    IP_ADDR_LEN);
3797 	}
3798 
3799 	(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen, hbuf,
3800 	    sizeof (hbuf));
3801 	(void) ip_dot_addr(src, sbuf);
3802 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3803 
3804 		if ((ipif->ipif_flags & IPIF_POINTOPOINT) ||
3805 		    ipif->ipif_lcl_addr != src) {
3806 			continue;
3807 		}
3808 
3809 		/*
3810 		 * If we failed on a recovery probe, then restart the timer to
3811 		 * try again later.
3812 		 */
3813 		if (!bring_up && (ipif->ipif_flags & IPIF_DUPLICATE) &&
3814 		    !(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3815 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3816 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3817 		    ipst->ips_ip_dup_recovery > 0 &&
3818 		    ipif->ipif_recovery_id == 0) {
3819 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3820 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3821 			continue;
3822 		}
3823 
3824 		/*
3825 		 * If what we're trying to do has already been done, then do
3826 		 * nothing.
3827 		 */
3828 		if (bring_up == ((ipif->ipif_flags & IPIF_UP) != 0))
3829 			continue;
3830 
3831 		ipif_get_name(ipif, ibuf, sizeof (ibuf));
3832 
3833 		if (failtype == NULL) {
3834 			cmn_err(CE_NOTE, "recovered address %s on %s", sbuf,
3835 			    ibuf);
3836 		} else {
3837 			cmn_err(CE_WARN, "%s has duplicate address %s (%s "
3838 			    "by %s); disabled", ibuf, sbuf, failtype, hbuf);
3839 		}
3840 
3841 		if (bring_up) {
3842 			ASSERT(ill->ill_dl_up);
3843 			/*
3844 			 * Free up the ARP delete message so we can allocate
3845 			 * a fresh one through the normal path.
3846 			 */
3847 			freemsg(ipif->ipif_arp_del_mp);
3848 			ipif->ipif_arp_del_mp = NULL;
3849 			if (ipif_resolver_up(ipif, Res_act_initial) !=
3850 			    EINPROGRESS) {
3851 				ipif->ipif_addr_ready = 1;
3852 				(void) ipif_up_done(ipif);
3853 			}
3854 			continue;
3855 		}
3856 
3857 		mutex_enter(&ill->ill_lock);
3858 		ASSERT(!(ipif->ipif_flags & IPIF_DUPLICATE));
3859 		ipif->ipif_flags |= IPIF_DUPLICATE;
3860 		ill->ill_ipif_dup_count++;
3861 		mutex_exit(&ill->ill_lock);
3862 		/*
3863 		 * Already exclusive on the ill; no need to handle deferred
3864 		 * processing here.
3865 		 */
3866 		(void) ipif_down(ipif, NULL, NULL);
3867 		ipif_down_tail(ipif);
3868 		mutex_enter(&ill->ill_lock);
3869 		if (!(ipif->ipif_flags & (IPIF_DHCPRUNNING|IPIF_TEMPORARY)) &&
3870 		    ill->ill_net_type == IRE_IF_RESOLVER &&
3871 		    !(ipif->ipif_state_flags & IPIF_CONDEMNED) &&
3872 		    ipst->ips_ip_dup_recovery > 0) {
3873 			ipif->ipif_recovery_id = timeout(ipif_dup_recovery,
3874 			    ipif, MSEC_TO_TICK(ipst->ips_ip_dup_recovery));
3875 		}
3876 		mutex_exit(&ill->ill_lock);
3877 	}
3878 	freemsg(mp);
3879 }
3880 
3881 /* ARGSUSED */
3882 static void
3883 ip_arp_defend(ipsq_t *ipsq, queue_t *rq, mblk_t *mp, void *dummy_arg)
3884 {
3885 	ill_t	*ill = rq->q_ptr;
3886 	arh_t *arh;
3887 	ipaddr_t src;
3888 	ipif_t	*ipif;
3889 
3890 	arh = (arh_t *)mp->b_cont->b_rptr;
3891 	bcopy((char *)&arh[1] + arh->arh_hlen, &src, IP_ADDR_LEN);
3892 	for (ipif = ill->ill_ipif; ipif != NULL; ipif = ipif->ipif_next) {
3893 		if ((ipif->ipif_flags & IPIF_UP) && ipif->ipif_lcl_addr == src)
3894 			(void) ipif_resolver_up(ipif, Res_act_defend);
3895 	}
3896 	freemsg(mp);
3897 }
3898 
3899 /*
3900  * News from ARP.  ARP sends notification of interesting events down
3901  * to its clients using M_CTL messages with the interesting ARP packet
3902  * attached via b_cont.
3903  * The interesting event from a device comes up the corresponding ARP-IP-DEV
3904  * queue as opposed to ARP sending the message to all the clients, i.e. all
3905  * its ARP-IP-DEV instances. Thus, for AR_CN_ANNOUNCE, we must walk the cache
3906  * table if a cache IRE is found to delete all the entries for the address in
3907  * the packet.
3908  */
3909 static void
3910 ip_arp_news(queue_t *q, mblk_t *mp)
3911 {
3912 	arcn_t		*arcn;
3913 	arh_t		*arh;
3914 	ire_t		*ire = NULL;
3915 	char		hbuf[MAC_STR_LEN];
3916 	char		sbuf[INET_ADDRSTRLEN];
3917 	ipaddr_t	src;
3918 	in6_addr_t	v6src;
3919 	boolean_t	isv6 = B_FALSE;
3920 	ipif_t		*ipif;
3921 	ill_t		*ill;
3922 	ip_stack_t	*ipst;
3923 
3924 	if (CONN_Q(q)) {
3925 		conn_t *connp = Q_TO_CONN(q);
3926 
3927 		ipst = connp->conn_netstack->netstack_ip;
3928 	} else {
3929 		ill_t *ill = (ill_t *)q->q_ptr;
3930 
3931 		ipst = ill->ill_ipst;
3932 	}
3933 
3934 	if ((mp->b_wptr - mp->b_rptr) < sizeof (arcn_t)	|| !mp->b_cont) {
3935 		if (q->q_next) {
3936 			putnext(q, mp);
3937 		} else
3938 			freemsg(mp);
3939 		return;
3940 	}
3941 	arh = (arh_t *)mp->b_cont->b_rptr;
3942 	/* Is it one we are interested in? */
3943 	if (BE16_TO_U16(arh->arh_proto) == IP6_DL_SAP) {
3944 		isv6 = B_TRUE;
3945 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &v6src,
3946 		    IPV6_ADDR_LEN);
3947 	} else if (BE16_TO_U16(arh->arh_proto) == IP_ARP_PROTO_TYPE) {
3948 		bcopy((char *)&arh[1] + (arh->arh_hlen & 0xFF), &src,
3949 		    IP_ADDR_LEN);
3950 	} else {
3951 		freemsg(mp);
3952 		return;
3953 	}
3954 
3955 	ill = q->q_ptr;
3956 
3957 	arcn = (arcn_t *)mp->b_rptr;
3958 	switch (arcn->arcn_code) {
3959 	case AR_CN_BOGON:
3960 		/*
3961 		 * Someone is sending ARP packets with a source protocol
3962 		 * address that we have published and for which we believe our
3963 		 * entry is authoritative and (when ill_arp_extend is set)
3964 		 * verified to be unique on the network.
3965 		 *
3966 		 * The ARP module internally handles the cases where the sender
3967 		 * is just probing (for DAD) and where the hardware address of
3968 		 * a non-authoritative entry has changed.  Thus, these are the
3969 		 * real conflicts, and we have to do resolution.
3970 		 *
3971 		 * We back away quickly from the address if it's from DHCP or
3972 		 * otherwise temporary and hasn't been used recently (or at
3973 		 * all).  We'd like to include "deprecated" addresses here as
3974 		 * well (as there's no real reason to defend something we're
3975 		 * discarding), but IPMP "reuses" this flag to mean something
3976 		 * other than the standard meaning.
3977 		 *
3978 		 * If the ARP module above is not extended (meaning that it
3979 		 * doesn't know how to defend the address), then we just log
3980 		 * the problem as we always did and continue on.  It's not
3981 		 * right, but there's little else we can do, and those old ATM
3982 		 * users are going away anyway.
3983 		 */
3984 		(void) mac_colon_addr((uint8_t *)(arh + 1), arh->arh_hlen,
3985 		    hbuf, sizeof (hbuf));
3986 		(void) ip_dot_addr(src, sbuf);
3987 		if (isv6) {
3988 			ire = ire_cache_lookup_v6(&v6src, ALL_ZONES, NULL,
3989 			    ipst);
3990 		} else {
3991 			ire = ire_cache_lookup(src, ALL_ZONES, NULL, ipst);
3992 		}
3993 		if (ire != NULL	&& IRE_IS_LOCAL(ire)) {
3994 			uint32_t now;
3995 			uint32_t maxage;
3996 			clock_t lused;
3997 			uint_t maxdefense;
3998 			uint_t defs;
3999 
4000 			/*
4001 			 * First, figure out if this address hasn't been used
4002 			 * in a while.  If it hasn't, then it's a better
4003 			 * candidate for abandoning.
4004 			 */
4005 			ipif = ire->ire_ipif;
4006 			ASSERT(ipif != NULL);
4007 			now = gethrestime_sec();
4008 			maxage = now - ire->ire_create_time;
4009 			if (maxage > ipst->ips_ip_max_temp_idle)
4010 				maxage = ipst->ips_ip_max_temp_idle;
4011 			lused = drv_hztousec(ddi_get_lbolt() -
4012 			    ire->ire_last_used_time) / MICROSEC + 1;
4013 			if (lused >= maxage && (ipif->ipif_flags &
4014 			    (IPIF_DHCPRUNNING | IPIF_TEMPORARY)))
4015 				maxdefense = ipst->ips_ip_max_temp_defend;
4016 			else
4017 				maxdefense = ipst->ips_ip_max_defend;
4018 
4019 			/*
4020 			 * Now figure out how many times we've defended
4021 			 * ourselves.  Ignore defenses that happened long in
4022 			 * the past.
4023 			 */
4024 			mutex_enter(&ire->ire_lock);
4025 			if ((defs = ire->ire_defense_count) > 0 &&
4026 			    now - ire->ire_defense_time >
4027 			    ipst->ips_ip_defend_interval) {
4028 				ire->ire_defense_count = defs = 0;
4029 			}
4030 			ire->ire_defense_count++;
4031 			ire->ire_defense_time = now;
4032 			mutex_exit(&ire->ire_lock);
4033 			ill_refhold(ill);
4034 			ire_refrele(ire);
4035 
4036 			/*
4037 			 * If we've defended ourselves too many times already,
4038 			 * then give up and tear down the interface(s) using
4039 			 * this address.  Otherwise, defend by sending out a
4040 			 * gratuitous ARP.
4041 			 */
4042 			if (defs >= maxdefense && ill->ill_arp_extend) {
4043 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4044 				    B_FALSE);
4045 			} else {
4046 				cmn_err(CE_WARN,
4047 				    "node %s is using our IP address %s on %s",
4048 				    hbuf, sbuf, ill->ill_name);
4049 				/*
4050 				 * If this is an old (ATM) ARP module, then
4051 				 * don't try to defend the address.  Remain
4052 				 * compatible with the old behavior.  Defend
4053 				 * only with new ARP.
4054 				 */
4055 				if (ill->ill_arp_extend) {
4056 					qwriter_ip(ill, q, mp, ip_arp_defend,
4057 					    NEW_OP, B_FALSE);
4058 				} else {
4059 					ill_refrele(ill);
4060 				}
4061 			}
4062 			return;
4063 		}
4064 		cmn_err(CE_WARN,
4065 		    "proxy ARP problem?  Node '%s' is using %s on %s",
4066 		    hbuf, sbuf, ill->ill_name);
4067 		if (ire != NULL)
4068 			ire_refrele(ire);
4069 		break;
4070 	case AR_CN_ANNOUNCE:
4071 		if (isv6) {
4072 			/*
4073 			 * For XRESOLV interfaces.
4074 			 * Delete the IRE cache entry and NCE for this
4075 			 * v6 address
4076 			 */
4077 			ip_ire_clookup_and_delete_v6(&v6src, ipst);
4078 			/*
4079 			 * If v6src is a non-zero, it's a router address
4080 			 * as below. Do the same sort of thing to clean
4081 			 * out off-net IRE_CACHE entries that go through
4082 			 * the router.
4083 			 */
4084 			if (!IN6_IS_ADDR_UNSPECIFIED(&v6src)) {
4085 				ire_walk_v6(ire_delete_cache_gw_v6,
4086 				    (char *)&v6src, ALL_ZONES, ipst);
4087 			}
4088 		} else {
4089 			nce_hw_map_t hwm;
4090 
4091 			/*
4092 			 * ARP gives us a copy of any packet where it thinks
4093 			 * the address has changed, so that we can update our
4094 			 * caches.  We're responsible for caching known answers
4095 			 * in the current design.  We check whether the
4096 			 * hardware address really has changed in all of our
4097 			 * entries that have cached this mapping, and if so, we
4098 			 * blow them away.  This way we will immediately pick
4099 			 * up the rare case of a host changing hardware
4100 			 * address.
4101 			 */
4102 			if (src == 0)
4103 				break;
4104 			hwm.hwm_addr = src;
4105 			hwm.hwm_hwlen = arh->arh_hlen;
4106 			hwm.hwm_hwaddr = (uchar_t *)(arh + 1);
4107 			NDP_HW_CHANGE_INCR(ipst->ips_ndp4);
4108 			ndp_walk_common(ipst->ips_ndp4, NULL,
4109 			    (pfi_t)nce_delete_hw_changed, &hwm, ALL_ZONES);
4110 			NDP_HW_CHANGE_DECR(ipst->ips_ndp4);
4111 		}
4112 		break;
4113 	case AR_CN_READY:
4114 		/* No external v6 resolver has a contract to use this */
4115 		if (isv6)
4116 			break;
4117 		/* If the link is down, we'll retry this later */
4118 		if (!(ill->ill_phyint->phyint_flags & PHYI_RUNNING))
4119 			break;
4120 		ipif = ipif_lookup_addr(src, ill, ALL_ZONES, NULL, NULL,
4121 		    NULL, NULL, ipst);
4122 		if (ipif != NULL) {
4123 			/*
4124 			 * If this is a duplicate recovery, then we now need to
4125 			 * go exclusive to bring this thing back up.
4126 			 */
4127 			if ((ipif->ipif_flags & (IPIF_UP|IPIF_DUPLICATE)) ==
4128 			    IPIF_DUPLICATE) {
4129 				ipif_refrele(ipif);
4130 				ill_refhold(ill);
4131 				qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP,
4132 				    B_FALSE);
4133 				return;
4134 			}
4135 			/*
4136 			 * If this is the first notice that this address is
4137 			 * ready, then let the user know now.
4138 			 */
4139 			if ((ipif->ipif_flags & IPIF_UP) &&
4140 			    !ipif->ipif_addr_ready) {
4141 				ipif_mask_reply(ipif);
4142 				ip_rts_ifmsg(ipif);
4143 				ip_rts_newaddrmsg(RTM_ADD, 0, ipif);
4144 				sctp_update_ipif(ipif, SCTP_IPIF_UP);
4145 			}
4146 			ipif->ipif_addr_ready = 1;
4147 			ipif_refrele(ipif);
4148 		}
4149 		ire = ire_cache_lookup(src, ALL_ZONES, MBLK_GETLABEL(mp), ipst);
4150 		if (ire != NULL) {
4151 			ire->ire_defense_count = 0;
4152 			ire_refrele(ire);
4153 		}
4154 		break;
4155 	case AR_CN_FAILED:
4156 		/* No external v6 resolver has a contract to use this */
4157 		if (isv6)
4158 			break;
4159 		ill_refhold(ill);
4160 		qwriter_ip(ill, q, mp, ip_arp_excl, NEW_OP, B_FALSE);
4161 		return;
4162 	}
4163 	freemsg(mp);
4164 }
4165 
4166 /*
4167  * Create a mblk suitable for carrying the interface index and/or source link
4168  * address. This mblk is tagged as an M_CTL and is sent to ULP. This is used
4169  * when the IP_RECVIF and/or IP_RECVSLLA socket option is set by the user
4170  * application.
4171  */
4172 mblk_t *
4173 ip_add_info(mblk_t *data_mp, ill_t *ill, uint_t flags, zoneid_t zoneid,
4174     ip_stack_t *ipst)
4175 {
4176 	mblk_t		*mp;
4177 	ip_pktinfo_t	*pinfo;
4178 	ipha_t *ipha;
4179 	struct ether_header *pether;
4180 
4181 	mp = allocb(sizeof (ip_pktinfo_t), BPRI_MED);
4182 	if (mp == NULL) {
4183 		ip1dbg(("ip_add_info: allocation failure.\n"));
4184 		return (data_mp);
4185 	}
4186 
4187 	ipha	= (ipha_t *)data_mp->b_rptr;
4188 	pinfo = (ip_pktinfo_t *)mp->b_rptr;
4189 	bzero(pinfo, sizeof (ip_pktinfo_t));
4190 	pinfo->ip_pkt_flags = (uchar_t)flags;
4191 	pinfo->ip_pkt_ulp_type = IN_PKTINFO;	/* Tell ULP what type of info */
4192 
4193 	if (flags & (IPF_RECVIF | IPF_RECVADDR))
4194 		pinfo->ip_pkt_ifindex = ill->ill_phyint->phyint_ifindex;
4195 	if (flags & IPF_RECVADDR) {
4196 		ipif_t	*ipif;
4197 		ire_t	*ire;
4198 
4199 		/*
4200 		 * Only valid for V4
4201 		 */
4202 		ASSERT((ipha->ipha_version_and_hdr_length & 0xf0) ==
4203 		    (IPV4_VERSION << 4));
4204 
4205 		ipif = ipif_get_next_ipif(NULL, ill);
4206 		if (ipif != NULL) {
4207 			/*
4208 			 * Since a decision has already been made to deliver the
4209 			 * packet, there is no need to test for SECATTR and
4210 			 * ZONEONLY.
4211 			 * When a multicast packet is transmitted
4212 			 * a cache entry is created for the multicast address.
4213 			 * When delivering a copy of the packet or when new
4214 			 * packets are received we do not want to match on the
4215 			 * cached entry so explicitly match on
4216 			 * IRE_LOCAL and IRE_LOOPBACK
4217 			 */
4218 			ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4219 			    IRE_LOCAL | IRE_LOOPBACK,
4220 			    ipif, zoneid, NULL,
4221 			    MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP, ipst);
4222 			if (ire == NULL) {
4223 				/*
4224 				 * packet must have come on a different
4225 				 * interface.
4226 				 * Since a decision has already been made to
4227 				 * deliver the packet, there is no need to test
4228 				 * for SECATTR and ZONEONLY.
4229 				 * Only match on local and broadcast ire's.
4230 				 * See detailed comment above.
4231 				 */
4232 				ire = ire_ctable_lookup(ipha->ipha_dst, 0,
4233 				    IRE_LOCAL | IRE_LOOPBACK, ipif, zoneid,
4234 				    NULL, MATCH_IRE_TYPE, ipst);
4235 			}
4236 
4237 			if (ire == NULL) {
4238 				/*
4239 				 * This is either a multicast packet or
4240 				 * the address has been removed since
4241 				 * the packet was received.
4242 				 * Return INADDR_ANY so that normal source
4243 				 * selection occurs for the response.
4244 				 */
4245 
4246 				pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4247 			} else {
4248 				pinfo->ip_pkt_match_addr.s_addr =
4249 				    ire->ire_src_addr;
4250 				ire_refrele(ire);
4251 			}
4252 			ipif_refrele(ipif);
4253 		} else {
4254 			pinfo->ip_pkt_match_addr.s_addr = INADDR_ANY;
4255 		}
4256 	}
4257 
4258 	pether = (struct ether_header *)((char *)ipha
4259 	    - sizeof (struct ether_header));
4260 	/*
4261 	 * Make sure the interface is an ethernet type, since this option
4262 	 * is currently supported only on this type of interface. Also make
4263 	 * sure we are pointing correctly above db_base.
4264 	 */
4265 
4266 	if ((flags & IPF_RECVSLLA) &&
4267 	    ((uchar_t *)pether >= data_mp->b_datap->db_base) &&
4268 	    (ill->ill_type == IFT_ETHER) &&
4269 	    (ill->ill_net_type == IRE_IF_RESOLVER)) {
4270 
4271 		pinfo->ip_pkt_slla.sdl_type = IFT_ETHER;
4272 		bcopy((uchar_t *)pether->ether_shost.ether_addr_octet,
4273 		    (uchar_t *)pinfo->ip_pkt_slla.sdl_data, ETHERADDRL);
4274 	} else {
4275 		/*
4276 		 * Clear the bit. Indicate to upper layer that IP is not
4277 		 * sending this ancillary info.
4278 		 */
4279 		pinfo->ip_pkt_flags = pinfo->ip_pkt_flags & ~IPF_RECVSLLA;
4280 	}
4281 
4282 	mp->b_datap->db_type = M_CTL;
4283 	mp->b_wptr += sizeof (ip_pktinfo_t);
4284 	mp->b_cont = data_mp;
4285 
4286 	return (mp);
4287 }
4288 
4289 /*
4290  * Latch in the IPsec state for a stream based on the ipsec_in_t passed in as
4291  * part of the bind request.
4292  */
4293 
4294 boolean_t
4295 ip_bind_ipsec_policy_set(conn_t *connp, mblk_t *policy_mp)
4296 {
4297 	ipsec_in_t *ii;
4298 
4299 	ASSERT(policy_mp != NULL);
4300 	ASSERT(policy_mp->b_datap->db_type == IPSEC_POLICY_SET);
4301 
4302 	ii = (ipsec_in_t *)policy_mp->b_rptr;
4303 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
4304 
4305 	connp->conn_policy = ii->ipsec_in_policy;
4306 	ii->ipsec_in_policy = NULL;
4307 
4308 	if (ii->ipsec_in_action != NULL) {
4309 		if (connp->conn_latch == NULL) {
4310 			connp->conn_latch = iplatch_create();
4311 			if (connp->conn_latch == NULL)
4312 				return (B_FALSE);
4313 		}
4314 		ipsec_latch_inbound(connp->conn_latch, ii);
4315 	}
4316 	return (B_TRUE);
4317 }
4318 
4319 /*
4320  * Upper level protocols (ULP) pass through bind requests to IP for inspection
4321  * and to arrange for power-fanout assist.  The ULP is identified by
4322  * adding a single byte at the end of the original bind message.
4323  * A ULP other than UDP or TCP that wishes to be recognized passes
4324  * down a bind with a zero length address.
4325  *
4326  * The binding works as follows:
4327  * - A zero byte address means just bind to the protocol.
4328  * - A four byte address is treated as a request to validate
4329  *   that the address is a valid local address, appropriate for
4330  *   an application to bind to. This does not affect any fanout
4331  *   information in IP.
4332  * - A sizeof sin_t byte address is used to bind to only the local address
4333  *   and port.
4334  * - A sizeof ipa_conn_t byte address contains complete fanout information
4335  *   consisting of local and remote addresses and ports.  In
4336  *   this case, the addresses are both validated as appropriate
4337  *   for this operation, and, if so, the information is retained
4338  *   for use in the inbound fanout.
4339  *
4340  * The ULP (except in the zero-length bind) can append an
4341  * additional mblk of db_type IRE_DB_REQ_TYPE or IPSEC_POLICY_SET to the
4342  * T_BIND_REQ/O_T_BIND_REQ. IRE_DB_REQ_TYPE indicates that the ULP wants
4343  * a copy of the source or destination IRE (source for local bind;
4344  * destination for complete bind). IPSEC_POLICY_SET indicates that the
4345  * policy information contained should be copied on to the conn.
4346  *
4347  * NOTE : Only one of IRE_DB_REQ_TYPE or IPSEC_POLICY_SET can be present.
4348  */
4349 mblk_t *
4350 ip_bind_v4(queue_t *q, mblk_t *mp, conn_t *connp)
4351 {
4352 	ssize_t		len;
4353 	struct T_bind_req	*tbr;
4354 	sin_t		*sin;
4355 	ipa_conn_t	*ac;
4356 	uchar_t		*ucp;
4357 	mblk_t		*mp1;
4358 	boolean_t	ire_requested;
4359 	boolean_t	ipsec_policy_set = B_FALSE;
4360 	int		error = 0;
4361 	int		protocol;
4362 	ipa_conn_x_t	*acx;
4363 
4364 	ASSERT(!connp->conn_af_isv6);
4365 	connp->conn_pkt_isv6 = B_FALSE;
4366 
4367 	len = MBLKL(mp);
4368 	if (len < (sizeof (*tbr) + 1)) {
4369 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
4370 		    "ip_bind: bogus msg, len %ld", len);
4371 		/* XXX: Need to return something better */
4372 		goto bad_addr;
4373 	}
4374 	/* Back up and extract the protocol identifier. */
4375 	mp->b_wptr--;
4376 	protocol = *mp->b_wptr & 0xFF;
4377 	tbr = (struct T_bind_req *)mp->b_rptr;
4378 	/* Reset the message type in preparation for shipping it back. */
4379 	DB_TYPE(mp) = M_PCPROTO;
4380 
4381 	connp->conn_ulp = (uint8_t)protocol;
4382 
4383 	/*
4384 	 * Check for a zero length address.  This is from a protocol that
4385 	 * wants to register to receive all packets of its type.
4386 	 */
4387 	if (tbr->ADDR_length == 0) {
4388 		/*
4389 		 * These protocols are now intercepted in ip_bind_v6().
4390 		 * Reject protocol-level binds here for now.
4391 		 *
4392 		 * For SCTP raw socket, ICMP sends down a bind with sin_t
4393 		 * so that the protocol type cannot be SCTP.
4394 		 */
4395 		if (protocol == IPPROTO_TCP || protocol == IPPROTO_AH ||
4396 		    protocol == IPPROTO_ESP || protocol == IPPROTO_SCTP) {
4397 			goto bad_addr;
4398 		}
4399 
4400 		/*
4401 		 *
4402 		 * The udp module never sends down a zero-length address,
4403 		 * and allowing this on a labeled system will break MLP
4404 		 * functionality.
4405 		 */
4406 		if (is_system_labeled() && protocol == IPPROTO_UDP)
4407 			goto bad_addr;
4408 
4409 		if (connp->conn_mac_exempt)
4410 			goto bad_addr;
4411 
4412 		/* No hash here really.  The table is big enough. */
4413 		connp->conn_srcv6 = ipv6_all_zeros;
4414 
4415 		ipcl_proto_insert(connp, protocol);
4416 
4417 		tbr->PRIM_type = T_BIND_ACK;
4418 		return (mp);
4419 	}
4420 
4421 	/* Extract the address pointer from the message. */
4422 	ucp = (uchar_t *)mi_offset_param(mp, tbr->ADDR_offset,
4423 	    tbr->ADDR_length);
4424 	if (ucp == NULL) {
4425 		ip1dbg(("ip_bind: no address\n"));
4426 		goto bad_addr;
4427 	}
4428 	if (!OK_32PTR(ucp)) {
4429 		ip1dbg(("ip_bind: unaligned address\n"));
4430 		goto bad_addr;
4431 	}
4432 	/*
4433 	 * Check for trailing mps.
4434 	 */
4435 
4436 	mp1 = mp->b_cont;
4437 	ire_requested = (mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE);
4438 	ipsec_policy_set = (mp1 != NULL && DB_TYPE(mp1) == IPSEC_POLICY_SET);
4439 
4440 	switch (tbr->ADDR_length) {
4441 	default:
4442 		ip1dbg(("ip_bind: bad address length %d\n",
4443 		    (int)tbr->ADDR_length));
4444 		goto bad_addr;
4445 
4446 	case IP_ADDR_LEN:
4447 		/* Verification of local address only */
4448 		error = ip_bind_laddr(connp, mp, *(ipaddr_t *)ucp, 0,
4449 		    ire_requested, ipsec_policy_set, B_FALSE);
4450 		break;
4451 
4452 	case sizeof (sin_t):
4453 		sin = (sin_t *)ucp;
4454 		error = ip_bind_laddr(connp, mp, sin->sin_addr.s_addr,
4455 		    sin->sin_port, ire_requested, ipsec_policy_set, B_TRUE);
4456 		break;
4457 
4458 	case sizeof (ipa_conn_t):
4459 		ac = (ipa_conn_t *)ucp;
4460 		/* For raw socket, the local port is not set. */
4461 		if (ac->ac_lport == 0)
4462 			ac->ac_lport = connp->conn_lport;
4463 		/* Always verify destination reachability. */
4464 		error = ip_bind_connected(connp, mp, &ac->ac_laddr,
4465 		    ac->ac_lport, ac->ac_faddr, ac->ac_fport, ire_requested,
4466 		    ipsec_policy_set, B_TRUE, B_TRUE);
4467 		break;
4468 
4469 	case sizeof (ipa_conn_x_t):
4470 		acx = (ipa_conn_x_t *)ucp;
4471 		/*
4472 		 * Whether or not to verify destination reachability depends
4473 		 * on the setting of the ACX_VERIFY_DST flag in acx->acx_flags.
4474 		 */
4475 		error = ip_bind_connected(connp, mp, &acx->acx_conn.ac_laddr,
4476 		    acx->acx_conn.ac_lport, acx->acx_conn.ac_faddr,
4477 		    acx->acx_conn.ac_fport, ire_requested, ipsec_policy_set,
4478 		    B_TRUE, (acx->acx_flags & ACX_VERIFY_DST) != 0);
4479 		break;
4480 	}
4481 	if (error == EINPROGRESS)
4482 		return (NULL);
4483 	else if (error != 0)
4484 		goto bad_addr;
4485 	/*
4486 	 * Pass the IPsec headers size in ire_ipsec_overhead.
4487 	 * We can't do this in ip_bind_insert_ire because the policy
4488 	 * may not have been inherited at that point in time and hence
4489 	 * conn_out_enforce_policy may not be set.
4490 	 */
4491 	mp1 = mp->b_cont;
4492 	if (ire_requested && connp->conn_out_enforce_policy &&
4493 	    mp1 != NULL && DB_TYPE(mp1) == IRE_DB_REQ_TYPE) {
4494 		ire_t *ire = (ire_t *)mp1->b_rptr;
4495 		ASSERT(MBLKL(mp1) >= sizeof (ire_t));
4496 		ire->ire_ipsec_overhead = conn_ipsec_length(connp);
4497 	}
4498 
4499 	/* Send it home. */
4500 	mp->b_datap->db_type = M_PCPROTO;
4501 	tbr->PRIM_type = T_BIND_ACK;
4502 	return (mp);
4503 
4504 bad_addr:
4505 	/*
4506 	 * If error = -1 then we generate a TBADADDR - otherwise error is
4507 	 * a unix errno.
4508 	 */
4509 	if (error > 0)
4510 		mp = mi_tpi_err_ack_alloc(mp, TSYSERR, error);
4511 	else
4512 		mp = mi_tpi_err_ack_alloc(mp, TBADADDR, 0);
4513 	return (mp);
4514 }
4515 
4516 /*
4517  * Here address is verified to be a valid local address.
4518  * If the IRE_DB_REQ_TYPE mp is present, a broadcast/multicast
4519  * address is also considered a valid local address.
4520  * In the case of a broadcast/multicast address, however, the
4521  * upper protocol is expected to reset the src address
4522  * to 0 if it sees a IRE_BROADCAST type returned so that
4523  * no packets are emitted with broadcast/multicast address as
4524  * source address (that violates hosts requirements RFC1122)
4525  * The addresses valid for bind are:
4526  *	(1) - INADDR_ANY (0)
4527  *	(2) - IP address of an UP interface
4528  *	(3) - IP address of a DOWN interface
4529  *	(4) - valid local IP broadcast addresses. In this case
4530  *	the conn will only receive packets destined to
4531  *	the specified broadcast address.
4532  *	(5) - a multicast address. In this case
4533  *	the conn will only receive packets destined to
4534  *	the specified multicast address. Note: the
4535  *	application still has to issue an
4536  *	IP_ADD_MEMBERSHIP socket option.
4537  *
4538  * On error, return -1 for TBADADDR otherwise pass the
4539  * errno with TSYSERR reply.
4540  *
4541  * In all the above cases, the bound address must be valid in the current zone.
4542  * When the address is loopback, multicast or broadcast, there might be many
4543  * matching IREs so bind has to look up based on the zone.
4544  *
4545  * Note: lport is in network byte order.
4546  */
4547 int
4548 ip_bind_laddr(conn_t *connp, mblk_t *mp, ipaddr_t src_addr, uint16_t lport,
4549     boolean_t ire_requested, boolean_t ipsec_policy_set,
4550     boolean_t fanout_insert)
4551 {
4552 	int		error = 0;
4553 	ire_t		*src_ire;
4554 	mblk_t		*policy_mp;
4555 	ipif_t		*ipif;
4556 	zoneid_t	zoneid;
4557 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4558 
4559 	if (ipsec_policy_set) {
4560 		policy_mp = mp->b_cont;
4561 	}
4562 
4563 	/*
4564 	 * If it was previously connected, conn_fully_bound would have
4565 	 * been set.
4566 	 */
4567 	connp->conn_fully_bound = B_FALSE;
4568 
4569 	src_ire = NULL;
4570 	ipif = NULL;
4571 
4572 	zoneid = IPCL_ZONEID(connp);
4573 
4574 	if (src_addr) {
4575 		src_ire = ire_route_lookup(src_addr, 0, 0, 0,
4576 		    NULL, NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
4577 		/*
4578 		 * If an address other than 0.0.0.0 is requested,
4579 		 * we verify that it is a valid address for bind
4580 		 * Note: Following code is in if-else-if form for
4581 		 * readability compared to a condition check.
4582 		 */
4583 		/* LINTED - statement has no consequent */
4584 		if (IRE_IS_LOCAL(src_ire)) {
4585 			/*
4586 			 * (2) Bind to address of local UP interface
4587 			 */
4588 		} else if (src_ire && src_ire->ire_type == IRE_BROADCAST) {
4589 			/*
4590 			 * (4) Bind to broadcast address
4591 			 * Note: permitted only from transports that
4592 			 * request IRE
4593 			 */
4594 			if (!ire_requested)
4595 				error = EADDRNOTAVAIL;
4596 		} else {
4597 			/*
4598 			 * (3) Bind to address of local DOWN interface
4599 			 * (ipif_lookup_addr() looks up all interfaces
4600 			 * but we do not get here for UP interfaces
4601 			 * - case (2) above)
4602 			 * We put the protocol byte back into the mblk
4603 			 * since we may come back via ip_wput_nondata()
4604 			 * later with this mblk if ipif_lookup_addr chooses
4605 			 * to defer processing.
4606 			 */
4607 			*mp->b_wptr++ = (char)connp->conn_ulp;
4608 			if ((ipif = ipif_lookup_addr(src_addr, NULL, zoneid,
4609 			    CONNP_TO_WQ(connp), mp, ip_wput_nondata,
4610 			    &error, ipst)) != NULL) {
4611 				ipif_refrele(ipif);
4612 			} else if (error == EINPROGRESS) {
4613 				if (src_ire != NULL)
4614 					ire_refrele(src_ire);
4615 				return (EINPROGRESS);
4616 			} else if (CLASSD(src_addr)) {
4617 				error = 0;
4618 				if (src_ire != NULL)
4619 					ire_refrele(src_ire);
4620 				/*
4621 				 * (5) bind to multicast address.
4622 				 * Fake out the IRE returned to upper
4623 				 * layer to be a broadcast IRE.
4624 				 */
4625 				src_ire = ire_ctable_lookup(
4626 				    INADDR_BROADCAST, INADDR_ANY,
4627 				    IRE_BROADCAST, NULL, zoneid, NULL,
4628 				    (MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY),
4629 				    ipst);
4630 				if (src_ire == NULL || !ire_requested)
4631 					error = EADDRNOTAVAIL;
4632 			} else {
4633 				/*
4634 				 * Not a valid address for bind
4635 				 */
4636 				error = EADDRNOTAVAIL;
4637 			}
4638 			/*
4639 			 * Just to keep it consistent with the processing in
4640 			 * ip_bind_v4()
4641 			 */
4642 			mp->b_wptr--;
4643 		}
4644 		if (error) {
4645 			/* Red Alert!  Attempting to be a bogon! */
4646 			ip1dbg(("ip_bind: bad src address 0x%x\n",
4647 			    ntohl(src_addr)));
4648 			goto bad_addr;
4649 		}
4650 	}
4651 
4652 	/*
4653 	 * Allow setting new policies. For example, disconnects come
4654 	 * down as ipa_t bind. As we would have set conn_policy_cached
4655 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
4656 	 * can change after the disconnect.
4657 	 */
4658 	connp->conn_policy_cached = B_FALSE;
4659 
4660 	/*
4661 	 * If not fanout_insert this was just an address verification
4662 	 */
4663 	if (fanout_insert) {
4664 		/*
4665 		 * The addresses have been verified. Time to insert in
4666 		 * the correct fanout list.
4667 		 */
4668 		IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
4669 		IN6_IPADDR_TO_V4MAPPED(INADDR_ANY, &connp->conn_remv6);
4670 		connp->conn_lport = lport;
4671 		connp->conn_fport = 0;
4672 		/*
4673 		 * Do we need to add a check to reject Multicast packets
4674 		 */
4675 		error = ipcl_bind_insert(connp, *mp->b_wptr, src_addr, lport);
4676 	}
4677 
4678 	if (error == 0) {
4679 		if (ire_requested) {
4680 			if (!ip_bind_insert_ire(mp, src_ire, NULL, ipst)) {
4681 				error = -1;
4682 				/* Falls through to bad_addr */
4683 			}
4684 		} else if (ipsec_policy_set) {
4685 			if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
4686 				error = -1;
4687 				/* Falls through to bad_addr */
4688 			}
4689 		}
4690 	}
4691 bad_addr:
4692 	if (error != 0) {
4693 		if (connp->conn_anon_port) {
4694 			(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
4695 			    connp->conn_mlp_type, connp->conn_ulp, ntohs(lport),
4696 			    B_FALSE);
4697 		}
4698 		connp->conn_mlp_type = mlptSingle;
4699 	}
4700 	if (src_ire != NULL)
4701 		IRE_REFRELE(src_ire);
4702 	if (ipsec_policy_set) {
4703 		ASSERT(policy_mp == mp->b_cont);
4704 		ASSERT(policy_mp != NULL);
4705 		freeb(policy_mp);
4706 		/*
4707 		 * As of now assume that nothing else accompanies
4708 		 * IPSEC_POLICY_SET.
4709 		 */
4710 		mp->b_cont = NULL;
4711 	}
4712 	return (error);
4713 }
4714 
4715 /*
4716  * Verify that both the source and destination addresses
4717  * are valid.  If verify_dst is false, then the destination address may be
4718  * unreachable, i.e. have no route to it.  Protocols like TCP want to verify
4719  * destination reachability, while tunnels do not.
4720  * Note that we allow connect to broadcast and multicast
4721  * addresses when ire_requested is set. Thus the ULP
4722  * has to check for IRE_BROADCAST and multicast.
4723  *
4724  * Returns zero if ok.
4725  * On error: returns -1 to mean TBADADDR otherwise returns an errno
4726  * (for use with TSYSERR reply).
4727  *
4728  * Note: lport and fport are in network byte order.
4729  */
4730 int
4731 ip_bind_connected(conn_t *connp, mblk_t *mp, ipaddr_t *src_addrp,
4732     uint16_t lport, ipaddr_t dst_addr, uint16_t fport,
4733     boolean_t ire_requested, boolean_t ipsec_policy_set,
4734     boolean_t fanout_insert, boolean_t verify_dst)
4735 {
4736 	ire_t		*src_ire;
4737 	ire_t		*dst_ire;
4738 	int		error = 0;
4739 	int 		protocol;
4740 	mblk_t		*policy_mp;
4741 	ire_t		*sire = NULL;
4742 	ire_t		*md_dst_ire = NULL;
4743 	ire_t		*lso_dst_ire = NULL;
4744 	ill_t		*ill = NULL;
4745 	zoneid_t	zoneid;
4746 	ipaddr_t	src_addr = *src_addrp;
4747 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
4748 
4749 	src_ire = dst_ire = NULL;
4750 	protocol = *mp->b_wptr & 0xFF;
4751 
4752 	/*
4753 	 * If we never got a disconnect before, clear it now.
4754 	 */
4755 	connp->conn_fully_bound = B_FALSE;
4756 
4757 	if (ipsec_policy_set) {
4758 		policy_mp = mp->b_cont;
4759 	}
4760 
4761 	zoneid = IPCL_ZONEID(connp);
4762 
4763 	if (CLASSD(dst_addr)) {
4764 		/* Pick up an IRE_BROADCAST */
4765 		dst_ire = ire_route_lookup(ip_g_all_ones, 0, 0, 0, NULL,
4766 		    NULL, zoneid, MBLK_GETLABEL(mp),
4767 		    (MATCH_IRE_RECURSIVE |
4768 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE |
4769 		    MATCH_IRE_SECATTR), ipst);
4770 	} else {
4771 		/*
4772 		 * If conn_dontroute is set or if conn_nexthop_set is set,
4773 		 * and onlink ipif is not found set ENETUNREACH error.
4774 		 */
4775 		if (connp->conn_dontroute || connp->conn_nexthop_set) {
4776 			ipif_t *ipif;
4777 
4778 			ipif = ipif_lookup_onlink_addr(connp->conn_dontroute ?
4779 			    dst_addr : connp->conn_nexthop_v4, zoneid, ipst);
4780 			if (ipif == NULL) {
4781 				error = ENETUNREACH;
4782 				goto bad_addr;
4783 			}
4784 			ipif_refrele(ipif);
4785 		}
4786 
4787 		if (connp->conn_nexthop_set) {
4788 			dst_ire = ire_route_lookup(connp->conn_nexthop_v4, 0,
4789 			    0, 0, NULL, NULL, zoneid, MBLK_GETLABEL(mp),
4790 			    MATCH_IRE_SECATTR, ipst);
4791 		} else {
4792 			dst_ire = ire_route_lookup(dst_addr, 0, 0, 0, NULL,
4793 			    &sire, zoneid, MBLK_GETLABEL(mp),
4794 			    (MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4795 			    MATCH_IRE_PARENT | MATCH_IRE_RJ_BHOLE |
4796 			    MATCH_IRE_SECATTR), ipst);
4797 		}
4798 	}
4799 	/*
4800 	 * dst_ire can't be a broadcast when not ire_requested.
4801 	 * We also prevent ire's with src address INADDR_ANY to
4802 	 * be used, which are created temporarily for
4803 	 * sending out packets from endpoints that have
4804 	 * conn_unspec_src set.  If verify_dst is true, the destination must be
4805 	 * reachable.  If verify_dst is false, the destination needn't be
4806 	 * reachable.
4807 	 *
4808 	 * If we match on a reject or black hole, then we've got a
4809 	 * local failure.  May as well fail out the connect() attempt,
4810 	 * since it's never going to succeed.
4811 	 */
4812 	if (dst_ire == NULL || dst_ire->ire_src_addr == INADDR_ANY ||
4813 	    (dst_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) ||
4814 	    ((dst_ire->ire_type & IRE_BROADCAST) && !ire_requested)) {
4815 		/*
4816 		 * If we're verifying destination reachability, we always want
4817 		 * to complain here.
4818 		 *
4819 		 * If we're not verifying destination reachability but the
4820 		 * destination has a route, we still want to fail on the
4821 		 * temporary address and broadcast address tests.
4822 		 */
4823 		if (verify_dst || (dst_ire != NULL)) {
4824 			if (ip_debug > 2) {
4825 				pr_addr_dbg("ip_bind_connected: bad connected "
4826 				    "dst %s\n", AF_INET, &dst_addr);
4827 			}
4828 			if (dst_ire == NULL || !(dst_ire->ire_type & IRE_HOST))
4829 				error = ENETUNREACH;
4830 			else
4831 				error = EHOSTUNREACH;
4832 			goto bad_addr;
4833 		}
4834 	}
4835 
4836 	/*
4837 	 * We now know that routing will allow us to reach the destination.
4838 	 * Check whether Trusted Solaris policy allows communication with this
4839 	 * host, and pretend that the destination is unreachable if not.
4840 	 *
4841 	 * This is never a problem for TCP, since that transport is known to
4842 	 * compute the label properly as part of the tcp_rput_other T_BIND_ACK
4843 	 * handling.  If the remote is unreachable, it will be detected at that
4844 	 * point, so there's no reason to check it here.
4845 	 *
4846 	 * Note that for sendto (and other datagram-oriented friends), this
4847 	 * check is done as part of the data path label computation instead.
4848 	 * The check here is just to make non-TCP connect() report the right
4849 	 * error.
4850 	 */
4851 	if (dst_ire != NULL && is_system_labeled() &&
4852 	    !IPCL_IS_TCP(connp) &&
4853 	    tsol_compute_label(DB_CREDDEF(mp, connp->conn_cred), dst_addr, NULL,
4854 	    connp->conn_mac_exempt, ipst) != 0) {
4855 		error = EHOSTUNREACH;
4856 		if (ip_debug > 2) {
4857 			pr_addr_dbg("ip_bind_connected: no label for dst %s\n",
4858 			    AF_INET, &dst_addr);
4859 		}
4860 		goto bad_addr;
4861 	}
4862 
4863 	/*
4864 	 * If the app does a connect(), it means that it will most likely
4865 	 * send more than 1 packet to the destination.  It makes sense
4866 	 * to clear the temporary flag.
4867 	 */
4868 	if (dst_ire != NULL && dst_ire->ire_type == IRE_CACHE &&
4869 	    (dst_ire->ire_marks & IRE_MARK_TEMPORARY)) {
4870 		irb_t *irb = dst_ire->ire_bucket;
4871 
4872 		rw_enter(&irb->irb_lock, RW_WRITER);
4873 		/*
4874 		 * We need to recheck for IRE_MARK_TEMPORARY after acquiring
4875 		 * the lock to guarantee irb_tmp_ire_cnt.
4876 		 */
4877 		if (dst_ire->ire_marks & IRE_MARK_TEMPORARY) {
4878 			dst_ire->ire_marks &= ~IRE_MARK_TEMPORARY;
4879 			irb->irb_tmp_ire_cnt--;
4880 		}
4881 		rw_exit(&irb->irb_lock);
4882 	}
4883 
4884 	/*
4885 	 * See if we should notify ULP about LSO/MDT; we do this whether or not
4886 	 * ire_requested is TRUE, in order to handle active connects; LSO/MDT
4887 	 * eligibility tests for passive connects are handled separately
4888 	 * through tcp_adapt_ire().  We do this before the source address
4889 	 * selection, because dst_ire may change after a call to
4890 	 * ipif_select_source().  This is a best-effort check, as the
4891 	 * packet for this connection may not actually go through
4892 	 * dst_ire->ire_stq, and the exact IRE can only be known after
4893 	 * calling ip_newroute().  This is why we further check on the
4894 	 * IRE during LSO/Multidata packet transmission in
4895 	 * tcp_lsosend()/tcp_multisend().
4896 	 */
4897 	if (!ipsec_policy_set && dst_ire != NULL &&
4898 	    !(dst_ire->ire_type & (IRE_LOCAL | IRE_LOOPBACK | IRE_BROADCAST)) &&
4899 	    (ill = ire_to_ill(dst_ire), ill != NULL)) {
4900 		if (ipst->ips_ip_lso_outbound && ILL_LSO_CAPABLE(ill)) {
4901 			lso_dst_ire = dst_ire;
4902 			IRE_REFHOLD(lso_dst_ire);
4903 		} else if (ipst->ips_ip_multidata_outbound &&
4904 		    ILL_MDT_CAPABLE(ill)) {
4905 			md_dst_ire = dst_ire;
4906 			IRE_REFHOLD(md_dst_ire);
4907 		}
4908 	}
4909 
4910 	if (dst_ire != NULL &&
4911 	    dst_ire->ire_type == IRE_LOCAL &&
4912 	    dst_ire->ire_zoneid != zoneid && dst_ire->ire_zoneid != ALL_ZONES) {
4913 		/*
4914 		 * If the IRE belongs to a different zone, look for a matching
4915 		 * route in the forwarding table and use the source address from
4916 		 * that route.
4917 		 */
4918 		src_ire = ire_ftable_lookup(dst_addr, 0, 0, 0, NULL, NULL,
4919 		    zoneid, 0, NULL,
4920 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
4921 		    MATCH_IRE_RJ_BHOLE, ipst);
4922 		if (src_ire == NULL) {
4923 			error = EHOSTUNREACH;
4924 			goto bad_addr;
4925 		} else if (src_ire->ire_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
4926 			if (!(src_ire->ire_type & IRE_HOST))
4927 				error = ENETUNREACH;
4928 			else
4929 				error = EHOSTUNREACH;
4930 			goto bad_addr;
4931 		}
4932 		if (src_addr == INADDR_ANY)
4933 			src_addr = src_ire->ire_src_addr;
4934 		ire_refrele(src_ire);
4935 		src_ire = NULL;
4936 	} else if ((src_addr == INADDR_ANY) && (dst_ire != NULL)) {
4937 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
4938 			src_addr = sire->ire_src_addr;
4939 			ire_refrele(dst_ire);
4940 			dst_ire = sire;
4941 			sire = NULL;
4942 		} else {
4943 			/*
4944 			 * Pick a source address so that a proper inbound
4945 			 * load spreading would happen.
4946 			 */
4947 			ill_t *dst_ill = dst_ire->ire_ipif->ipif_ill;
4948 			ipif_t *src_ipif = NULL;
4949 			ire_t *ipif_ire;
4950 
4951 			/*
4952 			 * Supply a local source address such that inbound
4953 			 * load spreading happens.
4954 			 *
4955 			 * Determine the best source address on this ill for
4956 			 * the destination.
4957 			 *
4958 			 * 1) For broadcast, we should return a broadcast ire
4959 			 *    found above so that upper layers know that the
4960 			 *    destination address is a broadcast address.
4961 			 *
4962 			 * 2) If this is part of a group, select a better
4963 			 *    source address so that better inbound load
4964 			 *    balancing happens. Do the same if the ipif
4965 			 *    is DEPRECATED.
4966 			 *
4967 			 * 3) If the outgoing interface is part of a usesrc
4968 			 *    group, then try selecting a source address from
4969 			 *    the usesrc ILL.
4970 			 */
4971 			if ((dst_ire->ire_zoneid != zoneid &&
4972 			    dst_ire->ire_zoneid != ALL_ZONES) ||
4973 			    (!(dst_ire->ire_flags & RTF_SETSRC)) &&
4974 			    (!(dst_ire->ire_type & IRE_BROADCAST) &&
4975 			    ((dst_ill->ill_group != NULL) ||
4976 			    (dst_ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
4977 			    (dst_ill->ill_usesrc_ifindex != 0)))) {
4978 				/*
4979 				 * If the destination is reachable via a
4980 				 * given gateway, the selected source address
4981 				 * should be in the same subnet as the gateway.
4982 				 * Otherwise, the destination is not reachable.
4983 				 *
4984 				 * If there are no interfaces on the same subnet
4985 				 * as the destination, ipif_select_source gives
4986 				 * first non-deprecated interface which might be
4987 				 * on a different subnet than the gateway.
4988 				 * This is not desirable. Hence pass the dst_ire
4989 				 * source address to ipif_select_source.
4990 				 * It is sure that the destination is reachable
4991 				 * with the dst_ire source address subnet.
4992 				 * So passing dst_ire source address to
4993 				 * ipif_select_source will make sure that the
4994 				 * selected source will be on the same subnet
4995 				 * as dst_ire source address.
4996 				 */
4997 				ipaddr_t saddr =
4998 				    dst_ire->ire_ipif->ipif_src_addr;
4999 				src_ipif = ipif_select_source(dst_ill,
5000 				    saddr, zoneid);
5001 				if (src_ipif != NULL) {
5002 					if (IS_VNI(src_ipif->ipif_ill)) {
5003 						/*
5004 						 * For VNI there is no
5005 						 * interface route
5006 						 */
5007 						src_addr =
5008 						    src_ipif->ipif_src_addr;
5009 					} else {
5010 						ipif_ire =
5011 						    ipif_to_ire(src_ipif);
5012 						if (ipif_ire != NULL) {
5013 							IRE_REFRELE(dst_ire);
5014 							dst_ire = ipif_ire;
5015 						}
5016 						src_addr =
5017 						    dst_ire->ire_src_addr;
5018 					}
5019 					ipif_refrele(src_ipif);
5020 				} else {
5021 					src_addr = dst_ire->ire_src_addr;
5022 				}
5023 			} else {
5024 				src_addr = dst_ire->ire_src_addr;
5025 			}
5026 		}
5027 	}
5028 
5029 	/*
5030 	 * We do ire_route_lookup() here (and not
5031 	 * interface lookup as we assert that
5032 	 * src_addr should only come from an
5033 	 * UP interface for hard binding.
5034 	 */
5035 	ASSERT(src_ire == NULL);
5036 	src_ire = ire_route_lookup(src_addr, 0, 0, 0, NULL,
5037 	    NULL, zoneid, NULL, MATCH_IRE_ZONEONLY, ipst);
5038 	/* src_ire must be a local|loopback */
5039 	if (!IRE_IS_LOCAL(src_ire)) {
5040 		if (ip_debug > 2) {
5041 			pr_addr_dbg("ip_bind_connected: bad connected "
5042 			    "src %s\n", AF_INET, &src_addr);
5043 		}
5044 		error = EADDRNOTAVAIL;
5045 		goto bad_addr;
5046 	}
5047 
5048 	/*
5049 	 * If the source address is a loopback address, the
5050 	 * destination had best be local or multicast.
5051 	 * The transports that can't handle multicast will reject
5052 	 * those addresses.
5053 	 */
5054 	if (src_ire->ire_type == IRE_LOOPBACK &&
5055 	    !(IRE_IS_LOCAL(dst_ire) || CLASSD(dst_addr))) {
5056 		ip1dbg(("ip_bind_connected: bad connected loopback\n"));
5057 		error = -1;
5058 		goto bad_addr;
5059 	}
5060 
5061 	/*
5062 	 * Allow setting new policies. For example, disconnects come
5063 	 * down as ipa_t bind. As we would have set conn_policy_cached
5064 	 * to B_TRUE before, we should set it to B_FALSE, so that policy
5065 	 * can change after the disconnect.
5066 	 */
5067 	connp->conn_policy_cached = B_FALSE;
5068 
5069 	/*
5070 	 * Set the conn addresses/ports immediately, so the IPsec policy calls
5071 	 * can handle their passed-in conn's.
5072 	 */
5073 
5074 	IN6_IPADDR_TO_V4MAPPED(src_addr, &connp->conn_srcv6);
5075 	IN6_IPADDR_TO_V4MAPPED(dst_addr, &connp->conn_remv6);
5076 	connp->conn_lport = lport;
5077 	connp->conn_fport = fport;
5078 	*src_addrp = src_addr;
5079 
5080 	ASSERT(!(ipsec_policy_set && ire_requested));
5081 	if (ire_requested) {
5082 		iulp_t *ulp_info = NULL;
5083 
5084 		/*
5085 		 * Note that sire will not be NULL if this is an off-link
5086 		 * connection and there is not cache for that dest yet.
5087 		 *
5088 		 * XXX Because of an existing bug, if there are multiple
5089 		 * default routes, the IRE returned now may not be the actual
5090 		 * default route used (default routes are chosen in a
5091 		 * round robin fashion).  So if the metrics for different
5092 		 * default routes are different, we may return the wrong
5093 		 * metrics.  This will not be a problem if the existing
5094 		 * bug is fixed.
5095 		 */
5096 		if (sire != NULL) {
5097 			ulp_info = &(sire->ire_uinfo);
5098 		}
5099 		if (!ip_bind_insert_ire(mp, dst_ire, ulp_info, ipst)) {
5100 			error = -1;
5101 			goto bad_addr;
5102 		}
5103 	} else if (ipsec_policy_set) {
5104 		if (!ip_bind_ipsec_policy_set(connp, policy_mp)) {
5105 			error = -1;
5106 			goto bad_addr;
5107 		}
5108 	}
5109 
5110 	/*
5111 	 * Cache IPsec policy in this conn.  If we have per-socket policy,
5112 	 * we'll cache that.  If we don't, we'll inherit global policy.
5113 	 *
5114 	 * We can't insert until the conn reflects the policy. Note that
5115 	 * conn_policy_cached is set by ipsec_conn_cache_policy() even for
5116 	 * connections where we don't have a policy. This is to prevent
5117 	 * global policy lookups in the inbound path.
5118 	 *
5119 	 * If we insert before we set conn_policy_cached,
5120 	 * CONN_INBOUND_POLICY_PRESENT() check can still evaluate true
5121 	 * because global policy cound be non-empty. We normally call
5122 	 * ipsec_check_policy() for conn_policy_cached connections only if
5123 	 * ipc_in_enforce_policy is set. But in this case,
5124 	 * conn_policy_cached can get set anytime since we made the
5125 	 * CONN_INBOUND_POLICY_PRESENT() check and ipsec_check_policy() is
5126 	 * called, which will make the above assumption false.  Thus, we
5127 	 * need to insert after we set conn_policy_cached.
5128 	 */
5129 	if ((error = ipsec_conn_cache_policy(connp, B_TRUE)) != 0)
5130 		goto bad_addr;
5131 
5132 	if (fanout_insert) {
5133 		/*
5134 		 * The addresses have been verified. Time to insert in
5135 		 * the correct fanout list.
5136 		 */
5137 		error = ipcl_conn_insert(connp, protocol, src_addr,
5138 		    dst_addr, connp->conn_ports);
5139 	}
5140 
5141 	if (error == 0) {
5142 		connp->conn_fully_bound = B_TRUE;
5143 		/*
5144 		 * Our initial checks for LSO/MDT have passed; the IRE is not
5145 		 * LOCAL/LOOPBACK/BROADCAST, and the link layer seems to
5146 		 * be supporting LSO/MDT.  Pass the IRE, IPC and ILL into
5147 		 * ip_xxinfo_return(), which performs further checks
5148 		 * against them and upon success, returns the LSO/MDT info
5149 		 * mblk which we will attach to the bind acknowledgment.
5150 		 */
5151 		if (lso_dst_ire != NULL) {
5152 			mblk_t *lsoinfo_mp;
5153 
5154 			ASSERT(ill->ill_lso_capab != NULL);
5155 			if ((lsoinfo_mp = ip_lsoinfo_return(lso_dst_ire, connp,
5156 			    ill->ill_name, ill->ill_lso_capab)) != NULL)
5157 				linkb(mp, lsoinfo_mp);
5158 		} else if (md_dst_ire != NULL) {
5159 			mblk_t *mdinfo_mp;
5160 
5161 			ASSERT(ill->ill_mdt_capab != NULL);
5162 			if ((mdinfo_mp = ip_mdinfo_return(md_dst_ire, connp,
5163 			    ill->ill_name, ill->ill_mdt_capab)) != NULL)
5164 				linkb(mp, mdinfo_mp);
5165 		}
5166 	}
5167 bad_addr:
5168 	if (ipsec_policy_set) {
5169 		ASSERT(policy_mp == mp->b_cont);
5170 		ASSERT(policy_mp != NULL);
5171 		freeb(policy_mp);
5172 		/*
5173 		 * As of now assume that nothing else accompanies
5174 		 * IPSEC_POLICY_SET.
5175 		 */
5176 		mp->b_cont = NULL;
5177 	}
5178 	if (src_ire != NULL)
5179 		IRE_REFRELE(src_ire);
5180 	if (dst_ire != NULL)
5181 		IRE_REFRELE(dst_ire);
5182 	if (sire != NULL)
5183 		IRE_REFRELE(sire);
5184 	if (md_dst_ire != NULL)
5185 		IRE_REFRELE(md_dst_ire);
5186 	if (lso_dst_ire != NULL)
5187 		IRE_REFRELE(lso_dst_ire);
5188 	return (error);
5189 }
5190 
5191 /*
5192  * Insert the ire in b_cont. Returns false if it fails (due to lack of space).
5193  * Prefers dst_ire over src_ire.
5194  */
5195 static boolean_t
5196 ip_bind_insert_ire(mblk_t *mp, ire_t *ire, iulp_t *ulp_info, ip_stack_t *ipst)
5197 {
5198 	mblk_t	*mp1;
5199 	ire_t *ret_ire = NULL;
5200 
5201 	mp1 = mp->b_cont;
5202 	ASSERT(mp1 != NULL);
5203 
5204 	if (ire != NULL) {
5205 		/*
5206 		 * mp1 initialized above to IRE_DB_REQ_TYPE
5207 		 * appended mblk. Its <upper protocol>'s
5208 		 * job to make sure there is room.
5209 		 */
5210 		if ((mp1->b_datap->db_lim - mp1->b_rptr) < sizeof (ire_t))
5211 			return (0);
5212 
5213 		mp1->b_datap->db_type = IRE_DB_TYPE;
5214 		mp1->b_wptr = mp1->b_rptr + sizeof (ire_t);
5215 		bcopy(ire, mp1->b_rptr, sizeof (ire_t));
5216 		ret_ire = (ire_t *)mp1->b_rptr;
5217 		/*
5218 		 * Pass the latest setting of the ip_path_mtu_discovery and
5219 		 * copy the ulp info if any.
5220 		 */
5221 		ret_ire->ire_frag_flag |= (ipst->ips_ip_path_mtu_discovery) ?
5222 		    IPH_DF : 0;
5223 		if (ulp_info != NULL) {
5224 			bcopy(ulp_info, &(ret_ire->ire_uinfo),
5225 			    sizeof (iulp_t));
5226 		}
5227 		ret_ire->ire_mp = mp1;
5228 	} else {
5229 		/*
5230 		 * No IRE was found. Remove IRE mblk.
5231 		 */
5232 		mp->b_cont = mp1->b_cont;
5233 		freeb(mp1);
5234 	}
5235 
5236 	return (1);
5237 }
5238 
5239 /*
5240  * Carve "len" bytes out of an mblk chain, consuming any we empty, and duping
5241  * the final piece where we don't.  Return a pointer to the first mblk in the
5242  * result, and update the pointer to the next mblk to chew on.  If anything
5243  * goes wrong (i.e., dupb fails), we waste everything in sight and return a
5244  * NULL pointer.
5245  */
5246 mblk_t *
5247 ip_carve_mp(mblk_t **mpp, ssize_t len)
5248 {
5249 	mblk_t	*mp0;
5250 	mblk_t	*mp1;
5251 	mblk_t	*mp2;
5252 
5253 	if (!len || !mpp || !(mp0 = *mpp))
5254 		return (NULL);
5255 	/* If we aren't going to consume the first mblk, we need a dup. */
5256 	if (mp0->b_wptr - mp0->b_rptr > len) {
5257 		mp1 = dupb(mp0);
5258 		if (mp1) {
5259 			/* Partition the data between the two mblks. */
5260 			mp1->b_wptr = mp1->b_rptr + len;
5261 			mp0->b_rptr = mp1->b_wptr;
5262 			/*
5263 			 * after adjustments if mblk not consumed is now
5264 			 * unaligned, try to align it. If this fails free
5265 			 * all messages and let upper layer recover.
5266 			 */
5267 			if (!OK_32PTR(mp0->b_rptr)) {
5268 				if (!pullupmsg(mp0, -1)) {
5269 					freemsg(mp0);
5270 					freemsg(mp1);
5271 					*mpp = NULL;
5272 					return (NULL);
5273 				}
5274 			}
5275 		}
5276 		return (mp1);
5277 	}
5278 	/* Eat through as many mblks as we need to get len bytes. */
5279 	len -= mp0->b_wptr - mp0->b_rptr;
5280 	for (mp2 = mp1 = mp0; (mp2 = mp2->b_cont) != 0 && len; mp1 = mp2) {
5281 		if (mp2->b_wptr - mp2->b_rptr > len) {
5282 			/*
5283 			 * We won't consume the entire last mblk.  Like
5284 			 * above, dup and partition it.
5285 			 */
5286 			mp1->b_cont = dupb(mp2);
5287 			mp1 = mp1->b_cont;
5288 			if (!mp1) {
5289 				/*
5290 				 * Trouble.  Rather than go to a lot of
5291 				 * trouble to clean up, we free the messages.
5292 				 * This won't be any worse than losing it on
5293 				 * the wire.
5294 				 */
5295 				freemsg(mp0);
5296 				freemsg(mp2);
5297 				*mpp = NULL;
5298 				return (NULL);
5299 			}
5300 			mp1->b_wptr = mp1->b_rptr + len;
5301 			mp2->b_rptr = mp1->b_wptr;
5302 			/*
5303 			 * after adjustments if mblk not consumed is now
5304 			 * unaligned, try to align it. If this fails free
5305 			 * all messages and let upper layer recover.
5306 			 */
5307 			if (!OK_32PTR(mp2->b_rptr)) {
5308 				if (!pullupmsg(mp2, -1)) {
5309 					freemsg(mp0);
5310 					freemsg(mp2);
5311 					*mpp = NULL;
5312 					return (NULL);
5313 				}
5314 			}
5315 			*mpp = mp2;
5316 			return (mp0);
5317 		}
5318 		/* Decrement len by the amount we just got. */
5319 		len -= mp2->b_wptr - mp2->b_rptr;
5320 	}
5321 	/*
5322 	 * len should be reduced to zero now.  If not our caller has
5323 	 * screwed up.
5324 	 */
5325 	if (len) {
5326 		/* Shouldn't happen! */
5327 		freemsg(mp0);
5328 		*mpp = NULL;
5329 		return (NULL);
5330 	}
5331 	/*
5332 	 * We consumed up to exactly the end of an mblk.  Detach the part
5333 	 * we are returning from the rest of the chain.
5334 	 */
5335 	mp1->b_cont = NULL;
5336 	*mpp = mp2;
5337 	return (mp0);
5338 }
5339 
5340 /* The ill stream is being unplumbed. Called from ip_close */
5341 int
5342 ip_modclose(ill_t *ill)
5343 {
5344 	boolean_t success;
5345 	ipsq_t	*ipsq;
5346 	ipif_t	*ipif;
5347 	queue_t	*q = ill->ill_rq;
5348 	ip_stack_t	*ipst = ill->ill_ipst;
5349 	clock_t timeout;
5350 
5351 	/*
5352 	 * Wait for the ACKs of all deferred control messages to be processed.
5353 	 * In particular, we wait for a potential capability reset initiated
5354 	 * in ip_sioctl_plink() to complete before proceeding.
5355 	 *
5356 	 * Note: we wait for at most ip_modclose_ackwait_ms (by default 3000 ms)
5357 	 * in case the driver never replies.
5358 	 */
5359 	timeout = lbolt + MSEC_TO_TICK(ip_modclose_ackwait_ms);
5360 	mutex_enter(&ill->ill_lock);
5361 	while (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
5362 		if (cv_timedwait(&ill->ill_cv, &ill->ill_lock, timeout) < 0) {
5363 			/* Timeout */
5364 			break;
5365 		}
5366 	}
5367 	mutex_exit(&ill->ill_lock);
5368 
5369 	/*
5370 	 * Forcibly enter the ipsq after some delay. This is to take
5371 	 * care of the case when some ioctl does not complete because
5372 	 * we sent a control message to the driver and it did not
5373 	 * send us a reply. We want to be able to at least unplumb
5374 	 * and replumb rather than force the user to reboot the system.
5375 	 */
5376 	success = ipsq_enter(ill, B_FALSE);
5377 
5378 	/*
5379 	 * Open/close/push/pop is guaranteed to be single threaded
5380 	 * per stream by STREAMS. FS guarantees that all references
5381 	 * from top are gone before close is called. So there can't
5382 	 * be another close thread that has set CONDEMNED on this ill.
5383 	 * and cause ipsq_enter to return failure.
5384 	 */
5385 	ASSERT(success);
5386 	ipsq = ill->ill_phyint->phyint_ipsq;
5387 
5388 	/*
5389 	 * Mark it condemned. No new reference will be made to this ill.
5390 	 * Lookup functions will return an error. Threads that try to
5391 	 * increment the refcnt must check for ILL_CAN_LOOKUP. This ensures
5392 	 * that the refcnt will drop down to zero.
5393 	 */
5394 	mutex_enter(&ill->ill_lock);
5395 	ill->ill_state_flags |= ILL_CONDEMNED;
5396 	for (ipif = ill->ill_ipif; ipif != NULL;
5397 	    ipif = ipif->ipif_next) {
5398 		ipif->ipif_state_flags |= IPIF_CONDEMNED;
5399 	}
5400 	/*
5401 	 * Wake up anybody waiting to enter the ipsq. ipsq_enter
5402 	 * returns  error if ILL_CONDEMNED is set
5403 	 */
5404 	cv_broadcast(&ill->ill_cv);
5405 	mutex_exit(&ill->ill_lock);
5406 
5407 	/*
5408 	 * Send all the deferred DLPI messages downstream which came in
5409 	 * during the small window right before ipsq_enter(). We do this
5410 	 * without waiting for the ACKs because all the ACKs for M_PROTO
5411 	 * messages are ignored in ip_rput() when ILL_CONDEMNED is set.
5412 	 */
5413 	ill_dlpi_send_deferred(ill);
5414 
5415 	/*
5416 	 * Shut down fragmentation reassembly.
5417 	 * ill_frag_timer won't start a timer again.
5418 	 * Now cancel any existing timer
5419 	 */
5420 	(void) untimeout(ill->ill_frag_timer_id);
5421 	(void) ill_frag_timeout(ill, 0);
5422 
5423 	/*
5424 	 * If MOVE was in progress, clear the
5425 	 * move_in_progress fields also.
5426 	 */
5427 	if (ill->ill_move_in_progress) {
5428 		ILL_CLEAR_MOVE(ill);
5429 	}
5430 
5431 	/*
5432 	 * Call ill_delete to bring down the ipifs, ilms and ill on
5433 	 * this ill. Then wait for the refcnts to drop to zero.
5434 	 * ill_is_freeable checks whether the ill is really quiescent.
5435 	 * Then make sure that threads that are waiting to enter the
5436 	 * ipsq have seen the error returned by ipsq_enter and have
5437 	 * gone away. Then we call ill_delete_tail which does the
5438 	 * DL_UNBIND_REQ with the driver and then qprocsoff.
5439 	 */
5440 	ill_delete(ill);
5441 	mutex_enter(&ill->ill_lock);
5442 	while (!ill_is_freeable(ill))
5443 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5444 	while (ill->ill_waiters)
5445 		cv_wait(&ill->ill_cv, &ill->ill_lock);
5446 
5447 	mutex_exit(&ill->ill_lock);
5448 
5449 	/*
5450 	 * ill_delete_tail drops reference on ill_ipst, but we need to keep
5451 	 * it held until the end of the function since the cleanup
5452 	 * below needs to be able to use the ip_stack_t.
5453 	 */
5454 	netstack_hold(ipst->ips_netstack);
5455 
5456 	/* qprocsoff is called in ill_delete_tail */
5457 	ill_delete_tail(ill);
5458 	ASSERT(ill->ill_ipst == NULL);
5459 
5460 	/*
5461 	 * Walk through all upper (conn) streams and qenable
5462 	 * those that have queued data.
5463 	 * close synchronization needs this to
5464 	 * be done to ensure that all upper layers blocked
5465 	 * due to flow control to the closing device
5466 	 * get unblocked.
5467 	 */
5468 	ip1dbg(("ip_wsrv: walking\n"));
5469 	conn_walk_drain(ipst);
5470 
5471 	mutex_enter(&ipst->ips_ip_mi_lock);
5472 	mi_close_unlink(&ipst->ips_ip_g_head, (IDP)ill);
5473 	mutex_exit(&ipst->ips_ip_mi_lock);
5474 
5475 	/*
5476 	 * credp could be null if the open didn't succeed and ip_modopen
5477 	 * itself calls ip_close.
5478 	 */
5479 	if (ill->ill_credp != NULL)
5480 		crfree(ill->ill_credp);
5481 
5482 	mutex_enter(&ill->ill_lock);
5483 	ill_nic_info_dispatch(ill);
5484 	mutex_exit(&ill->ill_lock);
5485 
5486 	/*
5487 	 * Now we are done with the module close pieces that
5488 	 * need the netstack_t.
5489 	 */
5490 	netstack_rele(ipst->ips_netstack);
5491 
5492 	mi_close_free((IDP)ill);
5493 	q->q_ptr = WR(q)->q_ptr = NULL;
5494 
5495 	ipsq_exit(ipsq, B_TRUE, B_TRUE);
5496 
5497 	return (0);
5498 }
5499 
5500 /*
5501  * This is called as part of close() for IP, UDP, ICMP, and RTS
5502  * in order to quiesce the conn.
5503  */
5504 void
5505 ip_quiesce_conn(conn_t *connp)
5506 {
5507 	boolean_t	drain_cleanup_reqd = B_FALSE;
5508 	boolean_t	conn_ioctl_cleanup_reqd = B_FALSE;
5509 	boolean_t	ilg_cleanup_reqd = B_FALSE;
5510 	ip_stack_t	*ipst;
5511 
5512 	ASSERT(!IPCL_IS_TCP(connp));
5513 	ipst = connp->conn_netstack->netstack_ip;
5514 
5515 	/*
5516 	 * Mark the conn as closing, and this conn must not be
5517 	 * inserted in future into any list. Eg. conn_drain_insert(),
5518 	 * won't insert this conn into the conn_drain_list.
5519 	 * Similarly ill_pending_mp_add() will not add any mp to
5520 	 * the pending mp list, after this conn has started closing.
5521 	 *
5522 	 * conn_idl, conn_pending_ill, conn_down_pending_ill, conn_ilg
5523 	 * cannot get set henceforth.
5524 	 */
5525 	mutex_enter(&connp->conn_lock);
5526 	ASSERT(!(connp->conn_state_flags & CONN_QUIESCED));
5527 	connp->conn_state_flags |= CONN_CLOSING;
5528 	if (connp->conn_idl != NULL)
5529 		drain_cleanup_reqd = B_TRUE;
5530 	if (connp->conn_oper_pending_ill != NULL)
5531 		conn_ioctl_cleanup_reqd = B_TRUE;
5532 	if (connp->conn_dhcpinit_ill != NULL) {
5533 		ASSERT(connp->conn_dhcpinit_ill->ill_dhcpinit != 0);
5534 		atomic_dec_32(&connp->conn_dhcpinit_ill->ill_dhcpinit);
5535 		connp->conn_dhcpinit_ill = NULL;
5536 	}
5537 	if (connp->conn_ilg_inuse != 0)
5538 		ilg_cleanup_reqd = B_TRUE;
5539 	mutex_exit(&connp->conn_lock);
5540 
5541 	if (conn_ioctl_cleanup_reqd)
5542 		conn_ioctl_cleanup(connp);
5543 
5544 	if (is_system_labeled() && connp->conn_anon_port) {
5545 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
5546 		    connp->conn_mlp_type, connp->conn_ulp,
5547 		    ntohs(connp->conn_lport), B_FALSE);
5548 		connp->conn_anon_port = 0;
5549 	}
5550 	connp->conn_mlp_type = mlptSingle;
5551 
5552 	/*
5553 	 * Remove this conn from any fanout list it is on.
5554 	 * and then wait for any threads currently operating
5555 	 * on this endpoint to finish
5556 	 */
5557 	ipcl_hash_remove(connp);
5558 
5559 	/*
5560 	 * Remove this conn from the drain list, and do
5561 	 * any other cleanup that may be required.
5562 	 * (Only non-tcp streams may have a non-null conn_idl.
5563 	 * TCP streams are never flow controlled, and
5564 	 * conn_idl will be null)
5565 	 */
5566 	if (drain_cleanup_reqd)
5567 		conn_drain_tail(connp, B_TRUE);
5568 
5569 	if (connp == ipst->ips_ip_g_mrouter)
5570 		(void) ip_mrouter_done(NULL, ipst);
5571 
5572 	if (ilg_cleanup_reqd)
5573 		ilg_delete_all(connp);
5574 
5575 	conn_delete_ire(connp, NULL);
5576 
5577 	/*
5578 	 * Now conn refcnt can increase only thru CONN_INC_REF_LOCKED.
5579 	 * callers from write side can't be there now because close
5580 	 * is in progress. The only other caller is ipcl_walk
5581 	 * which checks for the condemned flag.
5582 	 */
5583 	mutex_enter(&connp->conn_lock);
5584 	connp->conn_state_flags |= CONN_CONDEMNED;
5585 	while (connp->conn_ref != 1)
5586 		cv_wait(&connp->conn_cv, &connp->conn_lock);
5587 	connp->conn_state_flags |= CONN_QUIESCED;
5588 	mutex_exit(&connp->conn_lock);
5589 }
5590 
5591 /* ARGSUSED */
5592 int
5593 ip_close(queue_t *q, int flags)
5594 {
5595 	conn_t		*connp;
5596 
5597 	TRACE_1(TR_FAC_IP, TR_IP_CLOSE, "ip_close: q %p", q);
5598 
5599 	/*
5600 	 * Call the appropriate delete routine depending on whether this is
5601 	 * a module or device.
5602 	 */
5603 	if (WR(q)->q_next != NULL) {
5604 		/* This is a module close */
5605 		return (ip_modclose((ill_t *)q->q_ptr));
5606 	}
5607 
5608 	connp = q->q_ptr;
5609 	ip_quiesce_conn(connp);
5610 
5611 	qprocsoff(q);
5612 
5613 	/*
5614 	 * Now we are truly single threaded on this stream, and can
5615 	 * delete the things hanging off the connp, and finally the connp.
5616 	 * We removed this connp from the fanout list, it cannot be
5617 	 * accessed thru the fanouts, and we already waited for the
5618 	 * conn_ref to drop to 0. We are already in close, so
5619 	 * there cannot be any other thread from the top. qprocsoff
5620 	 * has completed, and service has completed or won't run in
5621 	 * future.
5622 	 */
5623 	ASSERT(connp->conn_ref == 1);
5624 
5625 	inet_minor_free(connp->conn_minor_arena, connp->conn_dev);
5626 
5627 	connp->conn_ref--;
5628 	ipcl_conn_destroy(connp);
5629 
5630 	q->q_ptr = WR(q)->q_ptr = NULL;
5631 	return (0);
5632 }
5633 
5634 /*
5635  * Wapper around putnext() so that ip_rts_request can merely use
5636  * conn_recv.
5637  */
5638 /*ARGSUSED2*/
5639 static void
5640 ip_conn_input(void *arg1, mblk_t *mp, void *arg2)
5641 {
5642 	conn_t *connp = (conn_t *)arg1;
5643 
5644 	putnext(connp->conn_rq, mp);
5645 }
5646 
5647 /* Return the IP checksum for the IP header at "iph". */
5648 uint16_t
5649 ip_csum_hdr(ipha_t *ipha)
5650 {
5651 	uint16_t	*uph;
5652 	uint32_t	sum;
5653 	int		opt_len;
5654 
5655 	opt_len = (ipha->ipha_version_and_hdr_length & 0xF) -
5656 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
5657 	uph = (uint16_t *)ipha;
5658 	sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
5659 	    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
5660 	if (opt_len > 0) {
5661 		do {
5662 			sum += uph[10];
5663 			sum += uph[11];
5664 			uph += 2;
5665 		} while (--opt_len);
5666 	}
5667 	sum = (sum & 0xFFFF) + (sum >> 16);
5668 	sum = ~(sum + (sum >> 16)) & 0xFFFF;
5669 	if (sum == 0xffff)
5670 		sum = 0;
5671 	return ((uint16_t)sum);
5672 }
5673 
5674 /*
5675  * Called when the module is about to be unloaded
5676  */
5677 void
5678 ip_ddi_destroy(void)
5679 {
5680 	tnet_fini();
5681 
5682 	icmp_ddi_destroy();
5683 	rts_ddi_destroy();
5684 	udp_ddi_destroy();
5685 	sctp_ddi_g_destroy();
5686 	tcp_ddi_g_destroy();
5687 	ipsec_policy_g_destroy();
5688 	ipcl_g_destroy();
5689 	ip_net_g_destroy();
5690 	ip_ire_g_fini();
5691 	inet_minor_destroy(ip_minor_arena_sa);
5692 #if defined(_LP64)
5693 	inet_minor_destroy(ip_minor_arena_la);
5694 #endif
5695 
5696 #ifdef DEBUG
5697 	list_destroy(&ip_thread_list);
5698 	rw_destroy(&ip_thread_rwlock);
5699 	tsd_destroy(&ip_thread_data);
5700 #endif
5701 
5702 	netstack_unregister(NS_IP);
5703 }
5704 
5705 /*
5706  * First step in cleanup.
5707  */
5708 /* ARGSUSED */
5709 static void
5710 ip_stack_shutdown(netstackid_t stackid, void *arg)
5711 {
5712 	ip_stack_t *ipst = (ip_stack_t *)arg;
5713 
5714 #ifdef NS_DEBUG
5715 	printf("ip_stack_shutdown(%p, stack %d)\n", (void *)ipst, stackid);
5716 #endif
5717 
5718 	/* Get rid of loopback interfaces and their IREs */
5719 	ip_loopback_cleanup(ipst);
5720 }
5721 
5722 /*
5723  * Free the IP stack instance.
5724  */
5725 static void
5726 ip_stack_fini(netstackid_t stackid, void *arg)
5727 {
5728 	ip_stack_t *ipst = (ip_stack_t *)arg;
5729 	int ret;
5730 
5731 #ifdef NS_DEBUG
5732 	printf("ip_stack_fini(%p, stack %d)\n", (void *)ipst, stackid);
5733 #endif
5734 	ipv4_hook_destroy(ipst);
5735 	ipv6_hook_destroy(ipst);
5736 	ip_net_destroy(ipst);
5737 
5738 	rw_destroy(&ipst->ips_srcid_lock);
5739 
5740 	ip_kstat_fini(stackid, ipst->ips_ip_mibkp);
5741 	ipst->ips_ip_mibkp = NULL;
5742 	icmp_kstat_fini(stackid, ipst->ips_icmp_mibkp);
5743 	ipst->ips_icmp_mibkp = NULL;
5744 	ip_kstat2_fini(stackid, ipst->ips_ip_kstat);
5745 	ipst->ips_ip_kstat = NULL;
5746 	bzero(&ipst->ips_ip_statistics, sizeof (ipst->ips_ip_statistics));
5747 	ip6_kstat_fini(stackid, ipst->ips_ip6_kstat);
5748 	ipst->ips_ip6_kstat = NULL;
5749 	bzero(&ipst->ips_ip6_statistics, sizeof (ipst->ips_ip6_statistics));
5750 
5751 	nd_free(&ipst->ips_ip_g_nd);
5752 	kmem_free(ipst->ips_param_arr, sizeof (lcl_param_arr));
5753 	ipst->ips_param_arr = NULL;
5754 	kmem_free(ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5755 	ipst->ips_ndp_arr = NULL;
5756 
5757 	ip_mrouter_stack_destroy(ipst);
5758 
5759 	mutex_destroy(&ipst->ips_ip_mi_lock);
5760 	rw_destroy(&ipst->ips_ipsec_capab_ills_lock);
5761 	rw_destroy(&ipst->ips_ill_g_usesrc_lock);
5762 	rw_destroy(&ipst->ips_ip_g_nd_lock);
5763 
5764 	ret = untimeout(ipst->ips_igmp_timeout_id);
5765 	if (ret == -1) {
5766 		ASSERT(ipst->ips_igmp_timeout_id == 0);
5767 	} else {
5768 		ASSERT(ipst->ips_igmp_timeout_id != 0);
5769 		ipst->ips_igmp_timeout_id = 0;
5770 	}
5771 	ret = untimeout(ipst->ips_igmp_slowtimeout_id);
5772 	if (ret == -1) {
5773 		ASSERT(ipst->ips_igmp_slowtimeout_id == 0);
5774 	} else {
5775 		ASSERT(ipst->ips_igmp_slowtimeout_id != 0);
5776 		ipst->ips_igmp_slowtimeout_id = 0;
5777 	}
5778 	ret = untimeout(ipst->ips_mld_timeout_id);
5779 	if (ret == -1) {
5780 		ASSERT(ipst->ips_mld_timeout_id == 0);
5781 	} else {
5782 		ASSERT(ipst->ips_mld_timeout_id != 0);
5783 		ipst->ips_mld_timeout_id = 0;
5784 	}
5785 	ret = untimeout(ipst->ips_mld_slowtimeout_id);
5786 	if (ret == -1) {
5787 		ASSERT(ipst->ips_mld_slowtimeout_id == 0);
5788 	} else {
5789 		ASSERT(ipst->ips_mld_slowtimeout_id != 0);
5790 		ipst->ips_mld_slowtimeout_id = 0;
5791 	}
5792 	ret = untimeout(ipst->ips_ip_ire_expire_id);
5793 	if (ret == -1) {
5794 		ASSERT(ipst->ips_ip_ire_expire_id == 0);
5795 	} else {
5796 		ASSERT(ipst->ips_ip_ire_expire_id != 0);
5797 		ipst->ips_ip_ire_expire_id = 0;
5798 	}
5799 
5800 	mutex_destroy(&ipst->ips_igmp_timer_lock);
5801 	mutex_destroy(&ipst->ips_mld_timer_lock);
5802 	mutex_destroy(&ipst->ips_igmp_slowtimeout_lock);
5803 	mutex_destroy(&ipst->ips_mld_slowtimeout_lock);
5804 	mutex_destroy(&ipst->ips_ip_addr_avail_lock);
5805 	rw_destroy(&ipst->ips_ill_g_lock);
5806 
5807 	ip_ire_fini(ipst);
5808 	ip6_asp_free(ipst);
5809 	conn_drain_fini(ipst);
5810 	ipcl_destroy(ipst);
5811 
5812 	mutex_destroy(&ipst->ips_ndp4->ndp_g_lock);
5813 	mutex_destroy(&ipst->ips_ndp6->ndp_g_lock);
5814 	kmem_free(ipst->ips_ndp4, sizeof (ndp_g_t));
5815 	ipst->ips_ndp4 = NULL;
5816 	kmem_free(ipst->ips_ndp6, sizeof (ndp_g_t));
5817 	ipst->ips_ndp6 = NULL;
5818 
5819 	if (ipst->ips_loopback_ksp != NULL) {
5820 		kstat_delete_netstack(ipst->ips_loopback_ksp, stackid);
5821 		ipst->ips_loopback_ksp = NULL;
5822 	}
5823 
5824 	kmem_free(ipst->ips_phyint_g_list, sizeof (phyint_list_t));
5825 	ipst->ips_phyint_g_list = NULL;
5826 	kmem_free(ipst->ips_ill_g_heads, sizeof (ill_g_head_t) * MAX_G_HEADS);
5827 	ipst->ips_ill_g_heads = NULL;
5828 
5829 	kmem_free(ipst, sizeof (*ipst));
5830 }
5831 
5832 /*
5833  * This function is called from the TSD destructor, and is used to debug
5834  * reference count issues in IP. See block comment in <inet/ip_if.h> for
5835  * details.
5836  */
5837 static void
5838 ip_thread_exit(void *phash)
5839 {
5840 	th_hash_t *thh = phash;
5841 
5842 	rw_enter(&ip_thread_rwlock, RW_WRITER);
5843 	list_remove(&ip_thread_list, thh);
5844 	rw_exit(&ip_thread_rwlock);
5845 	mod_hash_destroy_hash(thh->thh_hash);
5846 	kmem_free(thh, sizeof (*thh));
5847 }
5848 
5849 /*
5850  * Called when the IP kernel module is loaded into the kernel
5851  */
5852 void
5853 ip_ddi_init(void)
5854 {
5855 	ip_input_proc = ip_squeue_switch(ip_squeue_enter);
5856 
5857 	/*
5858 	 * For IP and TCP the minor numbers should start from 2 since we have 4
5859 	 * initial devices: ip, ip6, tcp, tcp6.
5860 	 */
5861 	/*
5862 	 * If this is a 64-bit kernel, then create two separate arenas -
5863 	 * one for TLIs in the range of INET_MIN_DEV+2 through 2^^18-1, and the
5864 	 * other for socket apps in the range 2^^18 through 2^^32-1.
5865 	 */
5866 	ip_minor_arena_la = NULL;
5867 	ip_minor_arena_sa = NULL;
5868 #if defined(_LP64)
5869 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5870 	    INET_MIN_DEV + 2, MAXMIN32, KM_SLEEP)) == NULL) {
5871 		cmn_err(CE_PANIC,
5872 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5873 	}
5874 	if ((ip_minor_arena_la = inet_minor_create("ip_minor_arena_la",
5875 	    MAXMIN32 + 1, MAXMIN64, KM_SLEEP)) == NULL) {
5876 		cmn_err(CE_PANIC,
5877 		    "ip_ddi_init: ip_minor_arena_la creation failed\n");
5878 	}
5879 #else
5880 	if ((ip_minor_arena_sa = inet_minor_create("ip_minor_arena_sa",
5881 	    INET_MIN_DEV + 2, MAXMIN, KM_SLEEP)) == NULL) {
5882 		cmn_err(CE_PANIC,
5883 		    "ip_ddi_init: ip_minor_arena_sa creation failed\n");
5884 	}
5885 #endif
5886 	ip_poll_normal_ticks = MSEC_TO_TICK_ROUNDUP(ip_poll_normal_ms);
5887 
5888 	ipcl_g_init();
5889 	ip_ire_g_init();
5890 	ip_net_g_init();
5891 
5892 #ifdef DEBUG
5893 	tsd_create(&ip_thread_data, ip_thread_exit);
5894 	rw_init(&ip_thread_rwlock, NULL, RW_DEFAULT, NULL);
5895 	list_create(&ip_thread_list, sizeof (th_hash_t),
5896 	    offsetof(th_hash_t, thh_link));
5897 #endif
5898 
5899 	/*
5900 	 * We want to be informed each time a stack is created or
5901 	 * destroyed in the kernel, so we can maintain the
5902 	 * set of udp_stack_t's.
5903 	 */
5904 	netstack_register(NS_IP, ip_stack_init, ip_stack_shutdown,
5905 	    ip_stack_fini);
5906 
5907 	ipsec_policy_g_init();
5908 	tcp_ddi_g_init();
5909 	sctp_ddi_g_init();
5910 
5911 	tnet_init();
5912 
5913 	udp_ddi_init();
5914 	rts_ddi_init();
5915 	icmp_ddi_init();
5916 }
5917 
5918 /*
5919  * Initialize the IP stack instance.
5920  */
5921 static void *
5922 ip_stack_init(netstackid_t stackid, netstack_t *ns)
5923 {
5924 	ip_stack_t	*ipst;
5925 	ipparam_t	*pa;
5926 	ipndp_t		*na;
5927 
5928 #ifdef NS_DEBUG
5929 	printf("ip_stack_init(stack %d)\n", stackid);
5930 #endif
5931 
5932 	ipst = (ip_stack_t *)kmem_zalloc(sizeof (*ipst), KM_SLEEP);
5933 	ipst->ips_netstack = ns;
5934 
5935 	ipst->ips_ill_g_heads = kmem_zalloc(sizeof (ill_g_head_t) * MAX_G_HEADS,
5936 	    KM_SLEEP);
5937 	ipst->ips_phyint_g_list = kmem_zalloc(sizeof (phyint_list_t),
5938 	    KM_SLEEP);
5939 	ipst->ips_ndp4 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5940 	ipst->ips_ndp6 = kmem_zalloc(sizeof (ndp_g_t), KM_SLEEP);
5941 	mutex_init(&ipst->ips_ndp4->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5942 	mutex_init(&ipst->ips_ndp6->ndp_g_lock, NULL, MUTEX_DEFAULT, NULL);
5943 
5944 	rw_init(&ipst->ips_ip_g_nd_lock, NULL, RW_DEFAULT, NULL);
5945 	mutex_init(&ipst->ips_igmp_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5946 	ipst->ips_igmp_deferred_next = INFINITY;
5947 	mutex_init(&ipst->ips_mld_timer_lock, NULL, MUTEX_DEFAULT, NULL);
5948 	ipst->ips_mld_deferred_next = INFINITY;
5949 	mutex_init(&ipst->ips_igmp_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5950 	mutex_init(&ipst->ips_mld_slowtimeout_lock, NULL, MUTEX_DEFAULT, NULL);
5951 	mutex_init(&ipst->ips_ip_mi_lock, NULL, MUTEX_DEFAULT, NULL);
5952 	mutex_init(&ipst->ips_ip_addr_avail_lock, NULL, MUTEX_DEFAULT, NULL);
5953 	rw_init(&ipst->ips_ill_g_lock, NULL, RW_DEFAULT, NULL);
5954 	rw_init(&ipst->ips_ipsec_capab_ills_lock, NULL, RW_DEFAULT, NULL);
5955 	rw_init(&ipst->ips_ill_g_usesrc_lock, NULL, RW_DEFAULT, NULL);
5956 
5957 	ipcl_init(ipst);
5958 	ip_ire_init(ipst);
5959 	ip6_asp_init(ipst);
5960 	ipif_init(ipst);
5961 	conn_drain_init(ipst);
5962 	ip_mrouter_stack_init(ipst);
5963 
5964 	ipst->ips_ip_g_frag_timeout = IP_FRAG_TIMEOUT;
5965 	ipst->ips_ip_g_frag_timo_ms = IP_FRAG_TIMEOUT * 1000;
5966 
5967 	ipst->ips_ip_multirt_log_interval = 1000;
5968 
5969 	ipst->ips_ip_g_forward = IP_FORWARD_DEFAULT;
5970 	ipst->ips_ipv6_forward = IP_FORWARD_DEFAULT;
5971 	ipst->ips_ill_index = 1;
5972 
5973 	ipst->ips_saved_ip_g_forward = -1;
5974 	ipst->ips_reg_vif_num = ALL_VIFS; 	/* Index to Register vif */
5975 
5976 	pa = (ipparam_t *)kmem_alloc(sizeof (lcl_param_arr), KM_SLEEP);
5977 	ipst->ips_param_arr = pa;
5978 	bcopy(lcl_param_arr, ipst->ips_param_arr, sizeof (lcl_param_arr));
5979 
5980 	na = (ipndp_t *)kmem_alloc(sizeof (lcl_ndp_arr), KM_SLEEP);
5981 	ipst->ips_ndp_arr = na;
5982 	bcopy(lcl_ndp_arr, ipst->ips_ndp_arr, sizeof (lcl_ndp_arr));
5983 	ipst->ips_ndp_arr[IPNDP_IP_FORWARDING_OFFSET].ip_ndp_data =
5984 	    (caddr_t)&ipst->ips_ip_g_forward;
5985 	ipst->ips_ndp_arr[IPNDP_IP6_FORWARDING_OFFSET].ip_ndp_data =
5986 	    (caddr_t)&ipst->ips_ipv6_forward;
5987 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_name,
5988 	    "ip_cgtp_filter") == 0);
5989 	ipst->ips_ndp_arr[IPNDP_CGTP_FILTER_OFFSET].ip_ndp_data =
5990 	    (caddr_t)&ipst->ips_ip_cgtp_filter;
5991 	ASSERT(strcmp(ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_name,
5992 	    "ipmp_hook_emulation") == 0);
5993 	ipst->ips_ndp_arr[IPNDP_IPMP_HOOK_OFFSET].ip_ndp_data =
5994 	    (caddr_t)&ipst->ips_ipmp_hook_emulation;
5995 
5996 	(void) ip_param_register(&ipst->ips_ip_g_nd,
5997 	    ipst->ips_param_arr, A_CNT(lcl_param_arr),
5998 	    ipst->ips_ndp_arr, A_CNT(lcl_ndp_arr));
5999 
6000 	ipst->ips_ip_mibkp = ip_kstat_init(stackid, ipst);
6001 	ipst->ips_icmp_mibkp = icmp_kstat_init(stackid);
6002 	ipst->ips_ip_kstat = ip_kstat2_init(stackid, &ipst->ips_ip_statistics);
6003 	ipst->ips_ip6_kstat =
6004 	    ip6_kstat_init(stackid, &ipst->ips_ip6_statistics);
6005 
6006 	ipst->ips_ipmp_enable_failback = B_TRUE;
6007 
6008 	ipst->ips_ip_src_id = 1;
6009 	rw_init(&ipst->ips_srcid_lock, NULL, RW_DEFAULT, NULL);
6010 
6011 	ip_net_init(ipst, ns);
6012 	ipv4_hook_init(ipst);
6013 	ipv6_hook_init(ipst);
6014 
6015 	return (ipst);
6016 }
6017 
6018 /*
6019  * Allocate and initialize a DLPI template of the specified length.  (May be
6020  * called as writer.)
6021  */
6022 mblk_t *
6023 ip_dlpi_alloc(size_t len, t_uscalar_t prim)
6024 {
6025 	mblk_t	*mp;
6026 
6027 	mp = allocb(len, BPRI_MED);
6028 	if (!mp)
6029 		return (NULL);
6030 
6031 	/*
6032 	 * DLPIv2 says that DL_INFO_REQ and DL_TOKEN_REQ (the latter
6033 	 * of which we don't seem to use) are sent with M_PCPROTO, and
6034 	 * that other DLPI are M_PROTO.
6035 	 */
6036 	if (prim == DL_INFO_REQ) {
6037 		mp->b_datap->db_type = M_PCPROTO;
6038 	} else {
6039 		mp->b_datap->db_type = M_PROTO;
6040 	}
6041 
6042 	mp->b_wptr = mp->b_rptr + len;
6043 	bzero(mp->b_rptr, len);
6044 	((dl_unitdata_req_t *)mp->b_rptr)->dl_primitive = prim;
6045 	return (mp);
6046 }
6047 
6048 /*
6049  * Debug formatting routine.  Returns a character string representation of the
6050  * addr in buf, of the form xxx.xxx.xxx.xxx.  This routine takes the address
6051  * in the form of a ipaddr_t and calls ip_dot_saddr with a pointer.
6052  *
6053  * Once the ndd table-printing interfaces are removed, this can be changed to
6054  * standard dotted-decimal form.
6055  */
6056 char *
6057 ip_dot_addr(ipaddr_t addr, char *buf)
6058 {
6059 	uint8_t *ap = (uint8_t *)&addr;
6060 
6061 	(void) mi_sprintf(buf, "%03d.%03d.%03d.%03d",
6062 	    ap[0] & 0xFF, ap[1] & 0xFF, ap[2] & 0xFF, ap[3] & 0xFF);
6063 	return (buf);
6064 }
6065 
6066 /*
6067  * Write the given MAC address as a printable string in the usual colon-
6068  * separated format.
6069  */
6070 const char *
6071 mac_colon_addr(const uint8_t *addr, size_t alen, char *buf, size_t buflen)
6072 {
6073 	char *bp;
6074 
6075 	if (alen == 0 || buflen < 4)
6076 		return ("?");
6077 	bp = buf;
6078 	for (;;) {
6079 		/*
6080 		 * If there are more MAC address bytes available, but we won't
6081 		 * have any room to print them, then add "..." to the string
6082 		 * instead.  See below for the 'magic number' explanation.
6083 		 */
6084 		if ((alen == 2 && buflen < 6) || (alen > 2 && buflen < 7)) {
6085 			(void) strcpy(bp, "...");
6086 			break;
6087 		}
6088 		(void) sprintf(bp, "%02x", *addr++);
6089 		bp += 2;
6090 		if (--alen == 0)
6091 			break;
6092 		*bp++ = ':';
6093 		buflen -= 3;
6094 		/*
6095 		 * At this point, based on the first 'if' statement above,
6096 		 * either alen == 1 and buflen >= 3, or alen > 1 and
6097 		 * buflen >= 4.  The first case leaves room for the final "xx"
6098 		 * number and trailing NUL byte.  The second leaves room for at
6099 		 * least "...".  Thus the apparently 'magic' numbers chosen for
6100 		 * that statement.
6101 		 */
6102 	}
6103 	return (buf);
6104 }
6105 
6106 /*
6107  * Send an ICMP error after patching up the packet appropriately.  Returns
6108  * non-zero if the appropriate MIB should be bumped; zero otherwise.
6109  */
6110 static boolean_t
6111 ip_fanout_send_icmp(queue_t *q, mblk_t *mp, uint_t flags,
6112     uint_t icmp_type, uint_t icmp_code, boolean_t mctl_present,
6113     zoneid_t zoneid, ip_stack_t *ipst)
6114 {
6115 	ipha_t *ipha;
6116 	mblk_t *first_mp;
6117 	boolean_t secure;
6118 	unsigned char db_type;
6119 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6120 
6121 	first_mp = mp;
6122 	if (mctl_present) {
6123 		mp = mp->b_cont;
6124 		secure = ipsec_in_is_secure(first_mp);
6125 		ASSERT(mp != NULL);
6126 	} else {
6127 		/*
6128 		 * If this is an ICMP error being reported - which goes
6129 		 * up as M_CTLs, we need to convert them to M_DATA till
6130 		 * we finish checking with global policy because
6131 		 * ipsec_check_global_policy() assumes M_DATA as clear
6132 		 * and M_CTL as secure.
6133 		 */
6134 		db_type = DB_TYPE(mp);
6135 		DB_TYPE(mp) = M_DATA;
6136 		secure = B_FALSE;
6137 	}
6138 	/*
6139 	 * We are generating an icmp error for some inbound packet.
6140 	 * Called from all ip_fanout_(udp, tcp, proto) functions.
6141 	 * Before we generate an error, check with global policy
6142 	 * to see whether this is allowed to enter the system. As
6143 	 * there is no "conn", we are checking with global policy.
6144 	 */
6145 	ipha = (ipha_t *)mp->b_rptr;
6146 	if (secure || ipss->ipsec_inbound_v4_policy_present) {
6147 		first_mp = ipsec_check_global_policy(first_mp, NULL,
6148 		    ipha, NULL, mctl_present, ipst->ips_netstack);
6149 		if (first_mp == NULL)
6150 			return (B_FALSE);
6151 	}
6152 
6153 	if (!mctl_present)
6154 		DB_TYPE(mp) = db_type;
6155 
6156 	if (flags & IP_FF_SEND_ICMP) {
6157 		if (flags & IP_FF_HDR_COMPLETE) {
6158 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
6159 				freemsg(first_mp);
6160 				return (B_TRUE);
6161 			}
6162 		}
6163 		if (flags & IP_FF_CKSUM) {
6164 			/*
6165 			 * Have to correct checksum since
6166 			 * the packet might have been
6167 			 * fragmented and the reassembly code in ip_rput
6168 			 * does not restore the IP checksum.
6169 			 */
6170 			ipha->ipha_hdr_checksum = 0;
6171 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
6172 		}
6173 		switch (icmp_type) {
6174 		case ICMP_DEST_UNREACHABLE:
6175 			icmp_unreachable(WR(q), first_mp, icmp_code, zoneid,
6176 			    ipst);
6177 			break;
6178 		default:
6179 			freemsg(first_mp);
6180 			break;
6181 		}
6182 	} else {
6183 		freemsg(first_mp);
6184 		return (B_FALSE);
6185 	}
6186 
6187 	return (B_TRUE);
6188 }
6189 
6190 /*
6191  * Used to send an ICMP error message when a packet is received for
6192  * a protocol that is not supported. The mblk passed as argument
6193  * is consumed by this function.
6194  */
6195 void
6196 ip_proto_not_sup(queue_t *q, mblk_t *ipsec_mp, uint_t flags, zoneid_t zoneid,
6197     ip_stack_t *ipst)
6198 {
6199 	mblk_t *mp;
6200 	ipha_t *ipha;
6201 	ill_t *ill;
6202 	ipsec_in_t *ii;
6203 
6204 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6205 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6206 
6207 	mp = ipsec_mp->b_cont;
6208 	ipsec_mp->b_cont = NULL;
6209 	ipha = (ipha_t *)mp->b_rptr;
6210 	/* Get ill from index in ipsec_in_t. */
6211 	ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
6212 	    (IPH_HDR_VERSION(ipha) == IPV6_VERSION), NULL, NULL, NULL, NULL,
6213 	    ipst);
6214 	if (ill != NULL) {
6215 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
6216 			if (ip_fanout_send_icmp(q, mp, flags,
6217 			    ICMP_DEST_UNREACHABLE,
6218 			    ICMP_PROTOCOL_UNREACHABLE, B_FALSE, zoneid, ipst)) {
6219 				BUMP_MIB(ill->ill_ip_mib,
6220 				    ipIfStatsInUnknownProtos);
6221 			}
6222 		} else {
6223 			if (ip_fanout_send_icmp_v6(q, mp, flags,
6224 			    ICMP6_PARAM_PROB, ICMP6_PARAMPROB_NEXTHEADER,
6225 			    0, B_FALSE, zoneid, ipst)) {
6226 				BUMP_MIB(ill->ill_ip_mib,
6227 				    ipIfStatsInUnknownProtos);
6228 			}
6229 		}
6230 		ill_refrele(ill);
6231 	} else { /* re-link for the freemsg() below. */
6232 		ipsec_mp->b_cont = mp;
6233 	}
6234 
6235 	/* If ICMP delivered, ipsec_mp will be a singleton (b_cont == NULL). */
6236 	freemsg(ipsec_mp);
6237 }
6238 
6239 /*
6240  * See if the inbound datagram has had IPsec processing applied to it.
6241  */
6242 boolean_t
6243 ipsec_in_is_secure(mblk_t *ipsec_mp)
6244 {
6245 	ipsec_in_t *ii;
6246 
6247 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
6248 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
6249 
6250 	if (ii->ipsec_in_loopback) {
6251 		return (ii->ipsec_in_secure);
6252 	} else {
6253 		return (ii->ipsec_in_ah_sa != NULL ||
6254 		    ii->ipsec_in_esp_sa != NULL ||
6255 		    ii->ipsec_in_decaps);
6256 	}
6257 }
6258 
6259 /*
6260  * Handle protocols with which IP is less intimate.  There
6261  * can be more than one stream bound to a particular
6262  * protocol.  When this is the case, normally each one gets a copy
6263  * of any incoming packets.
6264  *
6265  * IPsec NOTE :
6266  *
6267  * Don't allow a secure packet going up a non-secure connection.
6268  * We don't allow this because
6269  *
6270  * 1) Reply might go out in clear which will be dropped at
6271  *    the sending side.
6272  * 2) If the reply goes out in clear it will give the
6273  *    adversary enough information for getting the key in
6274  *    most of the cases.
6275  *
6276  * Moreover getting a secure packet when we expect clear
6277  * implies that SA's were added without checking for
6278  * policy on both ends. This should not happen once ISAKMP
6279  * is used to negotiate SAs as SAs will be added only after
6280  * verifying the policy.
6281  *
6282  * NOTE : If the packet was tunneled and not multicast we only send
6283  * to it the first match. Unlike TCP and UDP fanouts this doesn't fall
6284  * back to delivering packets to AF_INET6 raw sockets.
6285  *
6286  * IPQoS Notes:
6287  * Once we have determined the client, invoke IPPF processing.
6288  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6289  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6290  * ip_policy will be false.
6291  *
6292  * Zones notes:
6293  * Currently only applications in the global zone can create raw sockets for
6294  * protocols other than ICMP. So unlike the broadcast / multicast case of
6295  * ip_fanout_udp(), we only send a copy of the packet to streams in the
6296  * specified zone. For ICMP, this is handled by the callers of icmp_inbound().
6297  */
6298 static void
6299 ip_fanout_proto(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha, uint_t flags,
6300     boolean_t mctl_present, boolean_t ip_policy, ill_t *recv_ill,
6301     zoneid_t zoneid)
6302 {
6303 	queue_t	*rq;
6304 	mblk_t	*mp1, *first_mp1;
6305 	uint_t	protocol = ipha->ipha_protocol;
6306 	ipaddr_t dst;
6307 	boolean_t one_only;
6308 	mblk_t *first_mp = mp;
6309 	boolean_t secure;
6310 	uint32_t ill_index;
6311 	conn_t	*connp, *first_connp, *next_connp;
6312 	connf_t	*connfp;
6313 	boolean_t shared_addr;
6314 	mib2_ipIfStatsEntry_t *mibptr;
6315 	ip_stack_t *ipst = recv_ill->ill_ipst;
6316 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6317 
6318 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
6319 	if (mctl_present) {
6320 		mp = first_mp->b_cont;
6321 		secure = ipsec_in_is_secure(first_mp);
6322 		ASSERT(mp != NULL);
6323 	} else {
6324 		secure = B_FALSE;
6325 	}
6326 	dst = ipha->ipha_dst;
6327 	/*
6328 	 * If the packet was tunneled and not multicast we only send to it
6329 	 * the first match.
6330 	 */
6331 	one_only = ((protocol == IPPROTO_ENCAP || protocol == IPPROTO_IPV6) &&
6332 	    !CLASSD(dst));
6333 
6334 	shared_addr = (zoneid == ALL_ZONES);
6335 	if (shared_addr) {
6336 		/*
6337 		 * We don't allow multilevel ports for raw IP, so no need to
6338 		 * check for that here.
6339 		 */
6340 		zoneid = tsol_packet_to_zoneid(mp);
6341 	}
6342 
6343 	connfp = &ipst->ips_ipcl_proto_fanout[protocol];
6344 	mutex_enter(&connfp->connf_lock);
6345 	connp = connfp->connf_head;
6346 	for (connp = connfp->connf_head; connp != NULL;
6347 	    connp = connp->conn_next) {
6348 		if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill, flags,
6349 		    zoneid) &&
6350 		    (!is_system_labeled() ||
6351 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
6352 		    connp))) {
6353 			break;
6354 		}
6355 	}
6356 
6357 	if (connp == NULL || connp->conn_upq == NULL) {
6358 		/*
6359 		 * No one bound to these addresses.  Is
6360 		 * there a client that wants all
6361 		 * unclaimed datagrams?
6362 		 */
6363 		mutex_exit(&connfp->connf_lock);
6364 		/*
6365 		 * Check for IPPROTO_ENCAP...
6366 		 */
6367 		if (protocol == IPPROTO_ENCAP && ipst->ips_ip_g_mrouter) {
6368 			/*
6369 			 * If an IPsec mblk is here on a multicast
6370 			 * tunnel (using ip_mroute stuff), check policy here,
6371 			 * THEN ship off to ip_mroute_decap().
6372 			 *
6373 			 * BTW,  If I match a configured IP-in-IP
6374 			 * tunnel, this path will not be reached, and
6375 			 * ip_mroute_decap will never be called.
6376 			 */
6377 			first_mp = ipsec_check_global_policy(first_mp, connp,
6378 			    ipha, NULL, mctl_present, ipst->ips_netstack);
6379 			if (first_mp != NULL) {
6380 				if (mctl_present)
6381 					freeb(first_mp);
6382 				ip_mroute_decap(q, mp, ill);
6383 			} /* Else we already freed everything! */
6384 		} else {
6385 			/*
6386 			 * Otherwise send an ICMP protocol unreachable.
6387 			 */
6388 			if (ip_fanout_send_icmp(q, first_mp, flags,
6389 			    ICMP_DEST_UNREACHABLE, ICMP_PROTOCOL_UNREACHABLE,
6390 			    mctl_present, zoneid, ipst)) {
6391 				BUMP_MIB(mibptr, ipIfStatsInUnknownProtos);
6392 			}
6393 		}
6394 		return;
6395 	}
6396 	CONN_INC_REF(connp);
6397 	first_connp = connp;
6398 
6399 	/*
6400 	 * Only send message to one tunnel driver by immediately
6401 	 * terminating the loop.
6402 	 */
6403 	connp = one_only ? NULL : connp->conn_next;
6404 
6405 	for (;;) {
6406 		while (connp != NULL) {
6407 			if (IPCL_PROTO_MATCH(connp, protocol, ipha, ill,
6408 			    flags, zoneid) &&
6409 			    (!is_system_labeled() ||
6410 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
6411 			    shared_addr, connp)))
6412 				break;
6413 			connp = connp->conn_next;
6414 		}
6415 
6416 		/*
6417 		 * Copy the packet.
6418 		 */
6419 		if (connp == NULL || connp->conn_upq == NULL ||
6420 		    (((first_mp1 = dupmsg(first_mp)) == NULL) &&
6421 		    ((first_mp1 = ip_copymsg(first_mp)) == NULL))) {
6422 			/*
6423 			 * No more interested clients or memory
6424 			 * allocation failed
6425 			 */
6426 			connp = first_connp;
6427 			break;
6428 		}
6429 		mp1 = mctl_present ? first_mp1->b_cont : first_mp1;
6430 		CONN_INC_REF(connp);
6431 		mutex_exit(&connfp->connf_lock);
6432 		rq = connp->conn_rq;
6433 		if (!canputnext(rq)) {
6434 			if (flags & IP_FF_RAWIP) {
6435 				BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6436 			} else {
6437 				BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6438 			}
6439 
6440 			freemsg(first_mp1);
6441 		} else {
6442 			/*
6443 			 * Don't enforce here if we're an actual tunnel -
6444 			 * let "tun" do it instead.
6445 			 */
6446 			if (!IPCL_IS_IPTUN(connp) &&
6447 			    (CONN_INBOUND_POLICY_PRESENT(connp, ipss) ||
6448 			    secure)) {
6449 				first_mp1 = ipsec_check_inbound_policy
6450 				    (first_mp1, connp, ipha, NULL,
6451 				    mctl_present);
6452 			}
6453 			if (first_mp1 != NULL) {
6454 				int in_flags = 0;
6455 				/*
6456 				 * ip_fanout_proto also gets called from
6457 				 * icmp_inbound_error_fanout, in which case
6458 				 * the msg type is M_CTL.  Don't add info
6459 				 * in this case for the time being. In future
6460 				 * when there is a need for knowing the
6461 				 * inbound iface index for ICMP error msgs,
6462 				 * then this can be changed.
6463 				 */
6464 				if (connp->conn_recvif)
6465 					in_flags = IPF_RECVIF;
6466 				/*
6467 				 * The ULP may support IP_RECVPKTINFO for both
6468 				 * IP v4 and v6 so pass the appropriate argument
6469 				 * based on conn IP version.
6470 				 */
6471 				if (connp->conn_ip_recvpktinfo) {
6472 					if (connp->conn_af_isv6) {
6473 						/*
6474 						 * V6 only needs index
6475 						 */
6476 						in_flags |= IPF_RECVIF;
6477 					} else {
6478 						/*
6479 						 * V4 needs index +
6480 						 * matching address.
6481 						 */
6482 						in_flags |= IPF_RECVADDR;
6483 					}
6484 				}
6485 				if ((in_flags != 0) &&
6486 				    (mp->b_datap->db_type != M_CTL)) {
6487 					/*
6488 					 * the actual data will be
6489 					 * contained in b_cont upon
6490 					 * successful return of the
6491 					 * following call else
6492 					 * original mblk is returned
6493 					 */
6494 					ASSERT(recv_ill != NULL);
6495 					mp1 = ip_add_info(mp1, recv_ill,
6496 					    in_flags, IPCL_ZONEID(connp), ipst);
6497 				}
6498 				BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6499 				if (mctl_present)
6500 					freeb(first_mp1);
6501 				(connp->conn_recv)(connp, mp1, NULL);
6502 			}
6503 		}
6504 		mutex_enter(&connfp->connf_lock);
6505 		/* Follow the next pointer before releasing the conn. */
6506 		next_connp = connp->conn_next;
6507 		CONN_DEC_REF(connp);
6508 		connp = next_connp;
6509 	}
6510 
6511 	/* Last one.  Send it upstream. */
6512 	mutex_exit(&connfp->connf_lock);
6513 
6514 	/*
6515 	 * If this packet is coming from icmp_inbound_error_fanout ip_policy
6516 	 * will be set to false.
6517 	 */
6518 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6519 		ill_index = ill->ill_phyint->phyint_ifindex;
6520 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6521 		if (mp == NULL) {
6522 			CONN_DEC_REF(connp);
6523 			if (mctl_present) {
6524 				freeb(first_mp);
6525 			}
6526 			return;
6527 		}
6528 	}
6529 
6530 	rq = connp->conn_rq;
6531 	if (!canputnext(rq)) {
6532 		if (flags & IP_FF_RAWIP) {
6533 			BUMP_MIB(mibptr, rawipIfStatsInOverflows);
6534 		} else {
6535 			BUMP_MIB(&ipst->ips_icmp_mib, icmpInOverflows);
6536 		}
6537 
6538 		freemsg(first_mp);
6539 	} else {
6540 		if (IPCL_IS_IPTUN(connp)) {
6541 			/*
6542 			 * Tunneled packet.  We enforce policy in the tunnel
6543 			 * module itself.
6544 			 *
6545 			 * Send the WHOLE packet up (incl. IPSEC_IN) without
6546 			 * a policy check.
6547 			 * FIXME to use conn_recv for tun later.
6548 			 */
6549 			putnext(rq, first_mp);
6550 			CONN_DEC_REF(connp);
6551 			return;
6552 		}
6553 
6554 		if ((CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure)) {
6555 			first_mp = ipsec_check_inbound_policy(first_mp, connp,
6556 			    ipha, NULL, mctl_present);
6557 		}
6558 
6559 		if (first_mp != NULL) {
6560 			int in_flags = 0;
6561 
6562 			/*
6563 			 * ip_fanout_proto also gets called
6564 			 * from icmp_inbound_error_fanout, in
6565 			 * which case the msg type is M_CTL.
6566 			 * Don't add info in this case for time
6567 			 * being. In future when there is a
6568 			 * need for knowing the inbound iface
6569 			 * index for ICMP error msgs, then this
6570 			 * can be changed
6571 			 */
6572 			if (connp->conn_recvif)
6573 				in_flags = IPF_RECVIF;
6574 			if (connp->conn_ip_recvpktinfo) {
6575 				if (connp->conn_af_isv6) {
6576 					/*
6577 					 * V6 only needs index
6578 					 */
6579 					in_flags |= IPF_RECVIF;
6580 				} else {
6581 					/*
6582 					 * V4 needs index +
6583 					 * matching address.
6584 					 */
6585 					in_flags |= IPF_RECVADDR;
6586 				}
6587 			}
6588 			if ((in_flags != 0) &&
6589 			    (mp->b_datap->db_type != M_CTL)) {
6590 
6591 				/*
6592 				 * the actual data will be contained in
6593 				 * b_cont upon successful return
6594 				 * of the following call else original
6595 				 * mblk is returned
6596 				 */
6597 				ASSERT(recv_ill != NULL);
6598 				mp = ip_add_info(mp, recv_ill,
6599 				    in_flags, IPCL_ZONEID(connp), ipst);
6600 			}
6601 			BUMP_MIB(mibptr, ipIfStatsHCInDelivers);
6602 			(connp->conn_recv)(connp, mp, NULL);
6603 			if (mctl_present)
6604 				freeb(first_mp);
6605 		}
6606 	}
6607 	CONN_DEC_REF(connp);
6608 }
6609 
6610 /*
6611  * Fanout for TCP packets
6612  * The caller puts <fport, lport> in the ports parameter.
6613  *
6614  * IPQoS Notes
6615  * Before sending it to the client, invoke IPPF processing.
6616  * Policy processing takes place only if the callout_position, IPP_LOCAL_IN,
6617  * is enabled. If we get here from icmp_inbound_error_fanout or ip_wput_local
6618  * ip_policy is false.
6619  */
6620 static void
6621 ip_fanout_tcp(queue_t *q, mblk_t *mp, ill_t *recv_ill, ipha_t *ipha,
6622     uint_t flags, boolean_t mctl_present, boolean_t ip_policy, zoneid_t zoneid)
6623 {
6624 	mblk_t  *first_mp;
6625 	boolean_t secure;
6626 	uint32_t ill_index;
6627 	int	ip_hdr_len;
6628 	tcph_t	*tcph;
6629 	boolean_t syn_present = B_FALSE;
6630 	conn_t	*connp;
6631 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6632 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6633 
6634 	ASSERT(recv_ill != NULL);
6635 
6636 	first_mp = mp;
6637 	if (mctl_present) {
6638 		ASSERT(first_mp->b_datap->db_type == M_CTL);
6639 		mp = first_mp->b_cont;
6640 		secure = ipsec_in_is_secure(first_mp);
6641 		ASSERT(mp != NULL);
6642 	} else {
6643 		secure = B_FALSE;
6644 	}
6645 
6646 	ip_hdr_len = IPH_HDR_LENGTH(mp->b_rptr);
6647 
6648 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
6649 	    zoneid, ipst)) == NULL) {
6650 		/*
6651 		 * No connected connection or listener. Send a
6652 		 * TH_RST via tcp_xmit_listeners_reset.
6653 		 */
6654 
6655 		/* Initiate IPPf processing, if needed. */
6656 		if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
6657 			uint32_t ill_index;
6658 			ill_index = recv_ill->ill_phyint->phyint_ifindex;
6659 			ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
6660 			if (first_mp == NULL)
6661 				return;
6662 		}
6663 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6664 		ip2dbg(("ip_fanout_tcp: no listener; send reset to zone %d\n",
6665 		    zoneid));
6666 		tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6667 		    ipst->ips_netstack->netstack_tcp, NULL);
6668 		return;
6669 	}
6670 
6671 	/*
6672 	 * Allocate the SYN for the TCP connection here itself
6673 	 */
6674 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
6675 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
6676 		if (IPCL_IS_TCP(connp)) {
6677 			squeue_t *sqp;
6678 
6679 			/*
6680 			 * For fused tcp loopback, assign the eager's
6681 			 * squeue to be that of the active connect's.
6682 			 * Note that we don't check for IP_FF_LOOPBACK
6683 			 * here since this routine gets called only
6684 			 * for loopback (unlike the IPv6 counterpart).
6685 			 */
6686 			ASSERT(Q_TO_CONN(q) != NULL);
6687 			if (do_tcp_fusion &&
6688 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss) &&
6689 			    !secure &&
6690 			    !IPP_ENABLED(IPP_LOCAL_IN, ipst) && !ip_policy &&
6691 			    IPCL_IS_TCP(Q_TO_CONN(q))) {
6692 				ASSERT(Q_TO_CONN(q)->conn_sqp != NULL);
6693 				sqp = Q_TO_CONN(q)->conn_sqp;
6694 			} else {
6695 				sqp = IP_SQUEUE_GET(lbolt);
6696 			}
6697 
6698 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
6699 			DB_CKSUMSTART(mp) = (intptr_t)sqp;
6700 			syn_present = B_TRUE;
6701 		}
6702 	}
6703 
6704 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
6705 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
6706 		BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6707 		if ((flags & TH_RST) || (flags & TH_URG)) {
6708 			CONN_DEC_REF(connp);
6709 			freemsg(first_mp);
6710 			return;
6711 		}
6712 		if (flags & TH_ACK) {
6713 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
6714 			    ipst->ips_netstack->netstack_tcp, connp);
6715 			CONN_DEC_REF(connp);
6716 			return;
6717 		}
6718 
6719 		CONN_DEC_REF(connp);
6720 		freemsg(first_mp);
6721 		return;
6722 	}
6723 
6724 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6725 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6726 		    NULL, mctl_present);
6727 		if (first_mp == NULL) {
6728 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6729 			CONN_DEC_REF(connp);
6730 			return;
6731 		}
6732 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
6733 			ASSERT(syn_present);
6734 			if (mctl_present) {
6735 				ASSERT(first_mp != mp);
6736 				first_mp->b_datap->db_struioflag |=
6737 				    STRUIO_POLICY;
6738 			} else {
6739 				ASSERT(first_mp == mp);
6740 				mp->b_datap->db_struioflag &=
6741 				    ~STRUIO_EAGER;
6742 				mp->b_datap->db_struioflag |=
6743 				    STRUIO_POLICY;
6744 			}
6745 		} else {
6746 			/*
6747 			 * Discard first_mp early since we're dealing with a
6748 			 * fully-connected conn_t and tcp doesn't do policy in
6749 			 * this case.
6750 			 */
6751 			if (mctl_present) {
6752 				freeb(first_mp);
6753 				mctl_present = B_FALSE;
6754 			}
6755 			first_mp = mp;
6756 		}
6757 	}
6758 
6759 	/*
6760 	 * Initiate policy processing here if needed. If we get here from
6761 	 * icmp_inbound_error_fanout, ip_policy is false.
6762 	 */
6763 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
6764 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
6765 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
6766 		if (mp == NULL) {
6767 			CONN_DEC_REF(connp);
6768 			if (mctl_present)
6769 				freeb(first_mp);
6770 			return;
6771 		} else if (mctl_present) {
6772 			ASSERT(first_mp != mp);
6773 			first_mp->b_cont = mp;
6774 		} else {
6775 			first_mp = mp;
6776 		}
6777 	}
6778 
6779 
6780 
6781 	/* Handle socket options. */
6782 	if (!syn_present &&
6783 	    connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
6784 		/* Add header */
6785 		ASSERT(recv_ill != NULL);
6786 		/*
6787 		 * Since tcp does not support IP_RECVPKTINFO for V4, only pass
6788 		 * IPF_RECVIF.
6789 		 */
6790 		mp = ip_add_info(mp, recv_ill, IPF_RECVIF, IPCL_ZONEID(connp),
6791 		    ipst);
6792 		if (mp == NULL) {
6793 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
6794 			CONN_DEC_REF(connp);
6795 			if (mctl_present)
6796 				freeb(first_mp);
6797 			return;
6798 		} else if (mctl_present) {
6799 			/*
6800 			 * ip_add_info might return a new mp.
6801 			 */
6802 			ASSERT(first_mp != mp);
6803 			first_mp->b_cont = mp;
6804 		} else {
6805 			first_mp = mp;
6806 		}
6807 	}
6808 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
6809 	if (IPCL_IS_TCP(connp)) {
6810 		/* do not drain, certain use cases can blow the stack */
6811 		squeue_enter_nodrain(connp->conn_sqp, first_mp,
6812 		    connp->conn_recv, connp, SQTAG_IP_FANOUT_TCP);
6813 	} else {
6814 		/* Not TCP; must be SOCK_RAW, IPPROTO_TCP */
6815 		(connp->conn_recv)(connp, first_mp, NULL);
6816 		CONN_DEC_REF(connp);
6817 	}
6818 }
6819 
6820 /*
6821  * If we have a IPsec NAT-Traversal packet, strip the zero-SPI or
6822  * pass it along to ESP if the SPI is non-zero.  Returns TRUE if the mblk
6823  * is not consumed.
6824  *
6825  * One of four things can happen, all of which affect the passed-in mblk:
6826  *
6827  * 1.) ICMP messages that go through here just get returned TRUE.
6828  *
6829  * 2.) The packet is stock UDP and gets its zero-SPI stripped.  Return TRUE.
6830  *
6831  * 3.) The packet is ESP-in-UDP, gets transformed into an equivalent
6832  *     ESP packet, and is passed along to ESP for consumption.  Return FALSE.
6833  *
6834  * 4.) The packet is an ESP-in-UDP Keepalive.  Drop it and return FALSE.
6835  */
6836 static boolean_t
6837 zero_spi_check(queue_t *q, mblk_t *mp, ire_t *ire, ill_t *recv_ill,
6838     ipsec_stack_t *ipss)
6839 {
6840 	int shift, plen, iph_len;
6841 	ipha_t *ipha;
6842 	udpha_t *udpha;
6843 	uint32_t *spi;
6844 	uint8_t *orptr;
6845 	boolean_t udp_pkt, free_ire;
6846 
6847 	if (DB_TYPE(mp) == M_CTL) {
6848 		/*
6849 		 * ICMP message with UDP inside.  Don't bother stripping, just
6850 		 * send it up.
6851 		 *
6852 		 * NOTE: Any app with UDP_NAT_T_ENDPOINT set is probably going
6853 		 * to ignore errors set by ICMP anyway ('cause they might be
6854 		 * forged), but that's the app's decision, not ours.
6855 		 */
6856 
6857 		/* Bunch of reality checks for DEBUG kernels... */
6858 		ASSERT(IPH_HDR_VERSION(mp->b_rptr) == IPV4_VERSION);
6859 		ASSERT(((ipha_t *)mp->b_rptr)->ipha_protocol == IPPROTO_ICMP);
6860 
6861 		return (B_TRUE);
6862 	}
6863 
6864 	ipha = (ipha_t *)mp->b_rptr;
6865 	iph_len = IPH_HDR_LENGTH(ipha);
6866 	plen = ntohs(ipha->ipha_length);
6867 
6868 	if (plen - iph_len - sizeof (udpha_t) < sizeof (uint32_t)) {
6869 		/*
6870 		 * Most likely a keepalive for the benefit of an intervening
6871 		 * NAT.  These aren't for us, per se, so drop it.
6872 		 *
6873 		 * RFC 3947/8 doesn't say for sure what to do for 2-3
6874 		 * byte packets (keepalives are 1-byte), but we'll drop them
6875 		 * also.
6876 		 */
6877 		ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6878 		    DROPPER(ipss, ipds_esp_nat_t_ka), &ipss->ipsec_dropper);
6879 		return (B_FALSE);
6880 	}
6881 
6882 	if (MBLKL(mp) < iph_len + sizeof (udpha_t) + sizeof (*spi)) {
6883 		/* might as well pull it all up - it might be ESP. */
6884 		if (!pullupmsg(mp, -1)) {
6885 			ip_drop_packet(mp, B_TRUE, recv_ill, NULL,
6886 			    DROPPER(ipss, ipds_esp_nomem),
6887 			    &ipss->ipsec_dropper);
6888 			return (B_FALSE);
6889 		}
6890 
6891 		ipha = (ipha_t *)mp->b_rptr;
6892 	}
6893 	spi = (uint32_t *)(mp->b_rptr + iph_len + sizeof (udpha_t));
6894 	if (*spi == 0) {
6895 		/* UDP packet - remove 0-spi. */
6896 		shift = sizeof (uint32_t);
6897 	} else {
6898 		/* ESP-in-UDP packet - reduce to ESP. */
6899 		ipha->ipha_protocol = IPPROTO_ESP;
6900 		shift = sizeof (udpha_t);
6901 	}
6902 
6903 	/* Fix IP header */
6904 	ipha->ipha_length = htons(plen - shift);
6905 	ipha->ipha_hdr_checksum = 0;
6906 
6907 	orptr = mp->b_rptr;
6908 	mp->b_rptr += shift;
6909 
6910 	if (*spi == 0) {
6911 		ASSERT((uint8_t *)ipha == orptr);
6912 		udpha = (udpha_t *)(orptr + iph_len);
6913 		udpha->uha_length = htons(plen - shift - iph_len);
6914 		iph_len += sizeof (udpha_t);	/* For the call to ovbcopy(). */
6915 		udp_pkt = B_TRUE;
6916 	} else {
6917 		udp_pkt = B_FALSE;
6918 	}
6919 	ovbcopy(orptr, orptr + shift, iph_len);
6920 	if (!udp_pkt) /* Punt up for ESP processing. */ {
6921 		ipha = (ipha_t *)(orptr + shift);
6922 
6923 		free_ire = (ire == NULL);
6924 		if (free_ire) {
6925 			/* Re-acquire ire. */
6926 			ire = ire_cache_lookup(ipha->ipha_dst, ALL_ZONES, NULL,
6927 			    ipss->ipsec_netstack->netstack_ip);
6928 			if (ire == NULL || !(ire->ire_type & IRE_LOCAL)) {
6929 				if (ire != NULL)
6930 					ire_refrele(ire);
6931 				/*
6932 				 * Do a regular freemsg(), as this is an IP
6933 				 * error (no local route) not an IPsec one.
6934 				 */
6935 				freemsg(mp);
6936 			}
6937 		}
6938 
6939 		ip_proto_input(q, mp, ipha, ire, recv_ill, B_TRUE);
6940 		if (free_ire)
6941 			ire_refrele(ire);
6942 	}
6943 
6944 	return (udp_pkt);
6945 }
6946 
6947 /*
6948  * Deliver a udp packet to the given conn, possibly applying ipsec policy.
6949  * We are responsible for disposing of mp, such as by freemsg() or putnext()
6950  * Caller is responsible for dropping references to the conn, and freeing
6951  * first_mp.
6952  *
6953  * IPQoS Notes
6954  * Before sending it to the client, invoke IPPF processing. Policy processing
6955  * takes place only if the callout_position, IPP_LOCAL_IN, is enabled and
6956  * ip_policy is true. If we get here from icmp_inbound_error_fanout or
6957  * ip_wput_local, ip_policy is false.
6958  */
6959 static void
6960 ip_fanout_udp_conn(conn_t *connp, mblk_t *first_mp, mblk_t *mp,
6961     boolean_t secure, ill_t *ill, ipha_t *ipha, uint_t flags, ill_t *recv_ill,
6962     boolean_t ip_policy)
6963 {
6964 	boolean_t	mctl_present = (first_mp != NULL);
6965 	uint32_t	in_flags = 0; /* set to IP_RECVSLLA and/or IP_RECVIF */
6966 	uint32_t	ill_index;
6967 	ip_stack_t	*ipst = recv_ill->ill_ipst;
6968 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
6969 
6970 	ASSERT(ill != NULL);
6971 
6972 	if (mctl_present)
6973 		first_mp->b_cont = mp;
6974 	else
6975 		first_mp = mp;
6976 
6977 	if (CONN_UDP_FLOWCTLD(connp)) {
6978 		BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
6979 		freemsg(first_mp);
6980 		return;
6981 	}
6982 
6983 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || secure) {
6984 		first_mp = ipsec_check_inbound_policy(first_mp, connp, ipha,
6985 		    NULL, mctl_present);
6986 		if (first_mp == NULL) {
6987 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
6988 			return;	/* Freed by ipsec_check_inbound_policy(). */
6989 		}
6990 	}
6991 	if (mctl_present)
6992 		freeb(first_mp);
6993 
6994 	/* Let's hope the compilers utter "branch, predict-not-taken..." ;) */
6995 	if (connp->conn_udp->udp_nat_t_endpoint) {
6996 		if (mctl_present) {
6997 			/* mctl_present *shouldn't* happen. */
6998 			ip_drop_packet(mp, B_TRUE, NULL, NULL,
6999 			    DROPPER(ipss, ipds_esp_nat_t_ipsec),
7000 			    &ipss->ipsec_dropper);
7001 			return;
7002 		}
7003 
7004 		if (!zero_spi_check(ill->ill_rq, mp, NULL, recv_ill, ipss))
7005 			return;
7006 	}
7007 
7008 	/* Handle options. */
7009 	if (connp->conn_recvif)
7010 		in_flags = IPF_RECVIF;
7011 	/*
7012 	 * UDP supports IP_RECVPKTINFO option for both v4 and v6 so the flag
7013 	 * passed to ip_add_info is based on IP version of connp.
7014 	 */
7015 	if (connp->conn_ip_recvpktinfo && (flags & IP_FF_IPINFO)) {
7016 		if (connp->conn_af_isv6) {
7017 			/*
7018 			 * V6 only needs index
7019 			 */
7020 			in_flags |= IPF_RECVIF;
7021 		} else {
7022 			/*
7023 			 * V4 needs index + matching address.
7024 			 */
7025 			in_flags |= IPF_RECVADDR;
7026 		}
7027 	}
7028 
7029 	if (connp->conn_recvslla && !(flags & IP_FF_SEND_SLLA))
7030 		in_flags |= IPF_RECVSLLA;
7031 
7032 	/*
7033 	 * Initiate IPPF processing here, if needed. Note first_mp won't be
7034 	 * freed if the packet is dropped. The caller will do so.
7035 	 */
7036 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) {
7037 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
7038 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
7039 		if (mp == NULL) {
7040 			return;
7041 		}
7042 	}
7043 	if ((in_flags != 0) &&
7044 	    (mp->b_datap->db_type != M_CTL)) {
7045 		/*
7046 		 * The actual data will be contained in b_cont
7047 		 * upon successful return of the following call
7048 		 * else original mblk is returned
7049 		 */
7050 		ASSERT(recv_ill != NULL);
7051 		mp = ip_add_info(mp, recv_ill, in_flags, IPCL_ZONEID(connp),
7052 		    ipst);
7053 	}
7054 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
7055 	/* Send it upstream */
7056 	(connp->conn_recv)(connp, mp, NULL);
7057 }
7058 
7059 /*
7060  * Fanout for UDP packets.
7061  * The caller puts <fport, lport> in the ports parameter.
7062  *
7063  * If SO_REUSEADDR is set all multicast and broadcast packets
7064  * will be delivered to all streams bound to the same port.
7065  *
7066  * Zones notes:
7067  * Multicast and broadcast packets will be distributed to streams in all zones.
7068  * In the special case where an AF_INET socket binds to 0.0.0.0/<port> and an
7069  * AF_INET6 socket binds to ::/<port>, only the AF_INET socket receives the IPv4
7070  * packets. To maintain this behavior with multiple zones, the conns are grouped
7071  * by zone and the SO_REUSEADDR flag is checked for the first matching conn in
7072  * each zone. If unset, all the following conns in the same zone are skipped.
7073  */
7074 static void
7075 ip_fanout_udp(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
7076     uint32_t ports, boolean_t broadcast, uint_t flags, boolean_t mctl_present,
7077     boolean_t ip_policy, ill_t *recv_ill, zoneid_t zoneid)
7078 {
7079 	uint32_t	dstport, srcport;
7080 	ipaddr_t	dst;
7081 	mblk_t		*first_mp;
7082 	boolean_t	secure;
7083 	in6_addr_t	v6src;
7084 	conn_t		*connp;
7085 	connf_t		*connfp;
7086 	conn_t		*first_connp;
7087 	conn_t		*next_connp;
7088 	mblk_t		*mp1, *first_mp1;
7089 	ipaddr_t	src;
7090 	zoneid_t	last_zoneid;
7091 	boolean_t	reuseaddr;
7092 	boolean_t	shared_addr;
7093 	ip_stack_t	*ipst;
7094 
7095 	ASSERT(recv_ill != NULL);
7096 	ipst = recv_ill->ill_ipst;
7097 
7098 	first_mp = mp;
7099 	if (mctl_present) {
7100 		mp = first_mp->b_cont;
7101 		first_mp->b_cont = NULL;
7102 		secure = ipsec_in_is_secure(first_mp);
7103 		ASSERT(mp != NULL);
7104 	} else {
7105 		first_mp = NULL;
7106 		secure = B_FALSE;
7107 	}
7108 
7109 	/* Extract ports in net byte order */
7110 	dstport = htons(ntohl(ports) & 0xFFFF);
7111 	srcport = htons(ntohl(ports) >> 16);
7112 	dst = ipha->ipha_dst;
7113 	src = ipha->ipha_src;
7114 
7115 	shared_addr = (zoneid == ALL_ZONES);
7116 	if (shared_addr) {
7117 		/*
7118 		 * No need to handle exclusive-stack zones since ALL_ZONES
7119 		 * only applies to the shared stack.
7120 		 */
7121 		zoneid = tsol_mlp_findzone(IPPROTO_UDP, dstport);
7122 		if (zoneid == ALL_ZONES)
7123 			zoneid = tsol_packet_to_zoneid(mp);
7124 	}
7125 
7126 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7127 	mutex_enter(&connfp->connf_lock);
7128 	connp = connfp->connf_head;
7129 	if (!broadcast && !CLASSD(dst)) {
7130 		/*
7131 		 * Not broadcast or multicast. Send to the one (first)
7132 		 * client we find. No need to check conn_wantpacket()
7133 		 * since IP_BOUND_IF/conn_incoming_ill does not apply to
7134 		 * IPv4 unicast packets.
7135 		 */
7136 		while ((connp != NULL) &&
7137 		    (!IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) ||
7138 		    !IPCL_ZONE_MATCH(connp, zoneid))) {
7139 			connp = connp->conn_next;
7140 		}
7141 
7142 		if (connp == NULL || connp->conn_upq == NULL)
7143 			goto notfound;
7144 
7145 		if (is_system_labeled() &&
7146 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7147 		    connp))
7148 			goto notfound;
7149 
7150 		CONN_INC_REF(connp);
7151 		mutex_exit(&connfp->connf_lock);
7152 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7153 		    flags, recv_ill, ip_policy);
7154 		IP_STAT(ipst, ip_udp_fannorm);
7155 		CONN_DEC_REF(connp);
7156 		return;
7157 	}
7158 
7159 	/*
7160 	 * Broadcast and multicast case
7161 	 *
7162 	 * Need to check conn_wantpacket().
7163 	 * If SO_REUSEADDR has been set on the first we send the
7164 	 * packet to all clients that have joined the group and
7165 	 * match the port.
7166 	 */
7167 
7168 	while (connp != NULL) {
7169 		if ((IPCL_UDP_MATCH(connp, dstport, dst, srcport, src)) &&
7170 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7171 		    (!is_system_labeled() ||
7172 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7173 		    connp)))
7174 			break;
7175 		connp = connp->conn_next;
7176 	}
7177 
7178 	if (connp == NULL || connp->conn_upq == NULL)
7179 		goto notfound;
7180 
7181 	first_connp = connp;
7182 	/*
7183 	 * When SO_REUSEADDR is not set, send the packet only to the first
7184 	 * matching connection in its zone by keeping track of the zoneid.
7185 	 */
7186 	reuseaddr = first_connp->conn_reuseaddr;
7187 	last_zoneid = first_connp->conn_zoneid;
7188 
7189 	CONN_INC_REF(connp);
7190 	connp = connp->conn_next;
7191 	for (;;) {
7192 		while (connp != NULL) {
7193 			if (IPCL_UDP_MATCH(connp, dstport, dst, srcport, src) &&
7194 			    (reuseaddr || connp->conn_zoneid != last_zoneid) &&
7195 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7196 			    (!is_system_labeled() ||
7197 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7198 			    shared_addr, connp)))
7199 				break;
7200 			connp = connp->conn_next;
7201 		}
7202 		/*
7203 		 * Just copy the data part alone. The mctl part is
7204 		 * needed just for verifying policy and it is never
7205 		 * sent up.
7206 		 */
7207 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7208 		    ((mp1 = copymsg(mp)) == NULL))) {
7209 			/*
7210 			 * No more interested clients or memory
7211 			 * allocation failed
7212 			 */
7213 			connp = first_connp;
7214 			break;
7215 		}
7216 		if (connp->conn_zoneid != last_zoneid) {
7217 			/*
7218 			 * Update the zoneid so that the packet isn't sent to
7219 			 * any more conns in the same zone unless SO_REUSEADDR
7220 			 * is set.
7221 			 */
7222 			reuseaddr = connp->conn_reuseaddr;
7223 			last_zoneid = connp->conn_zoneid;
7224 		}
7225 		if (first_mp != NULL) {
7226 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7227 			    ipsec_info_type == IPSEC_IN);
7228 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7229 			    ipst->ips_netstack);
7230 			if (first_mp1 == NULL) {
7231 				freemsg(mp1);
7232 				connp = first_connp;
7233 				break;
7234 			}
7235 		} else {
7236 			first_mp1 = NULL;
7237 		}
7238 		CONN_INC_REF(connp);
7239 		mutex_exit(&connfp->connf_lock);
7240 		/*
7241 		 * IPQoS notes: We don't send the packet for policy
7242 		 * processing here, will do it for the last one (below).
7243 		 * i.e. we do it per-packet now, but if we do policy
7244 		 * processing per-conn, then we would need to do it
7245 		 * here too.
7246 		 */
7247 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7248 		    ipha, flags, recv_ill, B_FALSE);
7249 		mutex_enter(&connfp->connf_lock);
7250 		/* Follow the next pointer before releasing the conn. */
7251 		next_connp = connp->conn_next;
7252 		IP_STAT(ipst, ip_udp_fanmb);
7253 		CONN_DEC_REF(connp);
7254 		connp = next_connp;
7255 	}
7256 
7257 	/* Last one.  Send it upstream. */
7258 	mutex_exit(&connfp->connf_lock);
7259 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7260 	    recv_ill, ip_policy);
7261 	IP_STAT(ipst, ip_udp_fanmb);
7262 	CONN_DEC_REF(connp);
7263 	return;
7264 
7265 notfound:
7266 
7267 	mutex_exit(&connfp->connf_lock);
7268 	IP_STAT(ipst, ip_udp_fanothers);
7269 	/*
7270 	 * IPv6 endpoints bound to unicast or multicast IPv4-mapped addresses
7271 	 * have already been matched above, since they live in the IPv4
7272 	 * fanout tables. This implies we only need to
7273 	 * check for IPv6 in6addr_any endpoints here.
7274 	 * Thus we compare using ipv6_all_zeros instead of the destination
7275 	 * address, except for the multicast group membership lookup which
7276 	 * uses the IPv4 destination.
7277 	 */
7278 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &v6src);
7279 	connfp = &ipst->ips_ipcl_udp_fanout[IPCL_UDP_HASH(dstport, ipst)];
7280 	mutex_enter(&connfp->connf_lock);
7281 	connp = connfp->connf_head;
7282 	if (!broadcast && !CLASSD(dst)) {
7283 		while (connp != NULL) {
7284 			if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7285 			    srcport, v6src) && IPCL_ZONE_MATCH(connp, zoneid) &&
7286 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7287 			    !connp->conn_ipv6_v6only)
7288 				break;
7289 			connp = connp->conn_next;
7290 		}
7291 
7292 		if (connp != NULL && is_system_labeled() &&
7293 		    !tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7294 		    connp))
7295 			connp = NULL;
7296 
7297 		if (connp == NULL || connp->conn_upq == NULL) {
7298 			/*
7299 			 * No one bound to this port.  Is
7300 			 * there a client that wants all
7301 			 * unclaimed datagrams?
7302 			 */
7303 			mutex_exit(&connfp->connf_lock);
7304 
7305 			if (mctl_present)
7306 				first_mp->b_cont = mp;
7307 			else
7308 				first_mp = mp;
7309 			if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].
7310 			    connf_head != NULL) {
7311 				ip_fanout_proto(q, first_mp, ill, ipha,
7312 				    flags | IP_FF_RAWIP, mctl_present,
7313 				    ip_policy, recv_ill, zoneid);
7314 			} else {
7315 				if (ip_fanout_send_icmp(q, first_mp, flags,
7316 				    ICMP_DEST_UNREACHABLE,
7317 				    ICMP_PORT_UNREACHABLE,
7318 				    mctl_present, zoneid, ipst)) {
7319 					BUMP_MIB(ill->ill_ip_mib,
7320 					    udpIfStatsNoPorts);
7321 				}
7322 			}
7323 			return;
7324 		}
7325 
7326 		CONN_INC_REF(connp);
7327 		mutex_exit(&connfp->connf_lock);
7328 		ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha,
7329 		    flags, recv_ill, ip_policy);
7330 		CONN_DEC_REF(connp);
7331 		return;
7332 	}
7333 	/*
7334 	 * IPv4 multicast packet being delivered to an AF_INET6
7335 	 * in6addr_any endpoint.
7336 	 * Need to check conn_wantpacket(). Note that we use conn_wantpacket()
7337 	 * and not conn_wantpacket_v6() since any multicast membership is
7338 	 * for an IPv4-mapped multicast address.
7339 	 * The packet is sent to all clients in all zones that have joined the
7340 	 * group and match the port.
7341 	 */
7342 	while (connp != NULL) {
7343 		if (IPCL_UDP_MATCH_V6(connp, dstport, ipv6_all_zeros,
7344 		    srcport, v6src) &&
7345 		    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7346 		    (!is_system_labeled() ||
7347 		    tsol_receive_local(mp, &dst, IPV4_VERSION, shared_addr,
7348 		    connp)))
7349 			break;
7350 		connp = connp->conn_next;
7351 	}
7352 
7353 	if (connp == NULL || connp->conn_upq == NULL) {
7354 		/*
7355 		 * No one bound to this port.  Is
7356 		 * there a client that wants all
7357 		 * unclaimed datagrams?
7358 		 */
7359 		mutex_exit(&connfp->connf_lock);
7360 
7361 		if (mctl_present)
7362 			first_mp->b_cont = mp;
7363 		else
7364 			first_mp = mp;
7365 		if (ipst->ips_ipcl_proto_fanout[IPPROTO_UDP].connf_head !=
7366 		    NULL) {
7367 			ip_fanout_proto(q, first_mp, ill, ipha,
7368 			    flags | IP_FF_RAWIP, mctl_present, ip_policy,
7369 			    recv_ill, zoneid);
7370 		} else {
7371 			/*
7372 			 * We used to attempt to send an icmp error here, but
7373 			 * since this is known to be a multicast packet
7374 			 * and we don't send icmp errors in response to
7375 			 * multicast, just drop the packet and give up sooner.
7376 			 */
7377 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsNoPorts);
7378 			freemsg(first_mp);
7379 		}
7380 		return;
7381 	}
7382 
7383 	first_connp = connp;
7384 
7385 	CONN_INC_REF(connp);
7386 	connp = connp->conn_next;
7387 	for (;;) {
7388 		while (connp != NULL) {
7389 			if (IPCL_UDP_MATCH_V6(connp, dstport,
7390 			    ipv6_all_zeros, srcport, v6src) &&
7391 			    conn_wantpacket(connp, ill, ipha, flags, zoneid) &&
7392 			    (!is_system_labeled() ||
7393 			    tsol_receive_local(mp, &dst, IPV4_VERSION,
7394 			    shared_addr, connp)))
7395 				break;
7396 			connp = connp->conn_next;
7397 		}
7398 		/*
7399 		 * Just copy the data part alone. The mctl part is
7400 		 * needed just for verifying policy and it is never
7401 		 * sent up.
7402 		 */
7403 		if (connp == NULL || (((mp1 = dupmsg(mp)) == NULL) &&
7404 		    ((mp1 = copymsg(mp)) == NULL))) {
7405 			/*
7406 			 * No more intested clients or memory
7407 			 * allocation failed
7408 			 */
7409 			connp = first_connp;
7410 			break;
7411 		}
7412 		if (first_mp != NULL) {
7413 			ASSERT(((ipsec_info_t *)first_mp->b_rptr)->
7414 			    ipsec_info_type == IPSEC_IN);
7415 			first_mp1 = ipsec_in_tag(first_mp, NULL,
7416 			    ipst->ips_netstack);
7417 			if (first_mp1 == NULL) {
7418 				freemsg(mp1);
7419 				connp = first_connp;
7420 				break;
7421 			}
7422 		} else {
7423 			first_mp1 = NULL;
7424 		}
7425 		CONN_INC_REF(connp);
7426 		mutex_exit(&connfp->connf_lock);
7427 		/*
7428 		 * IPQoS notes: We don't send the packet for policy
7429 		 * processing here, will do it for the last one (below).
7430 		 * i.e. we do it per-packet now, but if we do policy
7431 		 * processing per-conn, then we would need to do it
7432 		 * here too.
7433 		 */
7434 		ip_fanout_udp_conn(connp, first_mp1, mp1, secure, ill,
7435 		    ipha, flags, recv_ill, B_FALSE);
7436 		mutex_enter(&connfp->connf_lock);
7437 		/* Follow the next pointer before releasing the conn. */
7438 		next_connp = connp->conn_next;
7439 		CONN_DEC_REF(connp);
7440 		connp = next_connp;
7441 	}
7442 
7443 	/* Last one.  Send it upstream. */
7444 	mutex_exit(&connfp->connf_lock);
7445 	ip_fanout_udp_conn(connp, first_mp, mp, secure, ill, ipha, flags,
7446 	    recv_ill, ip_policy);
7447 	CONN_DEC_REF(connp);
7448 }
7449 
7450 /*
7451  * Complete the ip_wput header so that it
7452  * is possible to generate ICMP
7453  * errors.
7454  */
7455 int
7456 ip_hdr_complete(ipha_t *ipha, zoneid_t zoneid, ip_stack_t *ipst)
7457 {
7458 	ire_t *ire;
7459 
7460 	if (ipha->ipha_src == INADDR_ANY) {
7461 		ire = ire_lookup_local(zoneid, ipst);
7462 		if (ire == NULL) {
7463 			ip1dbg(("ip_hdr_complete: no source IRE\n"));
7464 			return (1);
7465 		}
7466 		ipha->ipha_src = ire->ire_addr;
7467 		ire_refrele(ire);
7468 	}
7469 	ipha->ipha_ttl = ipst->ips_ip_def_ttl;
7470 	ipha->ipha_hdr_checksum = 0;
7471 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
7472 	return (0);
7473 }
7474 
7475 /*
7476  * Nobody should be sending
7477  * packets up this stream
7478  */
7479 static void
7480 ip_lrput(queue_t *q, mblk_t *mp)
7481 {
7482 	mblk_t *mp1;
7483 
7484 	switch (mp->b_datap->db_type) {
7485 	case M_FLUSH:
7486 		/* Turn around */
7487 		if (*mp->b_rptr & FLUSHW) {
7488 			*mp->b_rptr &= ~FLUSHR;
7489 			qreply(q, mp);
7490 			return;
7491 		}
7492 		break;
7493 	}
7494 	/* Could receive messages that passed through ar_rput */
7495 	for (mp1 = mp; mp1; mp1 = mp1->b_cont)
7496 		mp1->b_prev = mp1->b_next = NULL;
7497 	freemsg(mp);
7498 }
7499 
7500 /* Nobody should be sending packets down this stream */
7501 /* ARGSUSED */
7502 void
7503 ip_lwput(queue_t *q, mblk_t *mp)
7504 {
7505 	freemsg(mp);
7506 }
7507 
7508 /*
7509  * Move the first hop in any source route to ipha_dst and remove that part of
7510  * the source route.  Called by other protocols.  Errors in option formatting
7511  * are ignored - will be handled by ip_wput_options Return the final
7512  * destination (either ipha_dst or the last entry in a source route.)
7513  */
7514 ipaddr_t
7515 ip_massage_options(ipha_t *ipha, netstack_t *ns)
7516 {
7517 	ipoptp_t	opts;
7518 	uchar_t		*opt;
7519 	uint8_t		optval;
7520 	uint8_t		optlen;
7521 	ipaddr_t	dst;
7522 	int		i;
7523 	ire_t		*ire;
7524 	ip_stack_t	*ipst = ns->netstack_ip;
7525 
7526 	ip2dbg(("ip_massage_options\n"));
7527 	dst = ipha->ipha_dst;
7528 	for (optval = ipoptp_first(&opts, ipha);
7529 	    optval != IPOPT_EOL;
7530 	    optval = ipoptp_next(&opts)) {
7531 		opt = opts.ipoptp_cur;
7532 		switch (optval) {
7533 			uint8_t off;
7534 		case IPOPT_SSRR:
7535 		case IPOPT_LSRR:
7536 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
7537 				ip1dbg(("ip_massage_options: bad src route\n"));
7538 				break;
7539 			}
7540 			optlen = opts.ipoptp_len;
7541 			off = opt[IPOPT_OFFSET];
7542 			off--;
7543 		redo_srr:
7544 			if (optlen < IP_ADDR_LEN ||
7545 			    off > optlen - IP_ADDR_LEN) {
7546 				/* End of source route */
7547 				ip1dbg(("ip_massage_options: end of SR\n"));
7548 				break;
7549 			}
7550 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
7551 			ip1dbg(("ip_massage_options: next hop 0x%x\n",
7552 			    ntohl(dst)));
7553 			/*
7554 			 * Check if our address is present more than
7555 			 * once as consecutive hops in source route.
7556 			 * XXX verify per-interface ip_forwarding
7557 			 * for source route?
7558 			 */
7559 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
7560 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
7561 			if (ire != NULL) {
7562 				ire_refrele(ire);
7563 				off += IP_ADDR_LEN;
7564 				goto redo_srr;
7565 			}
7566 			if (dst == htonl(INADDR_LOOPBACK)) {
7567 				ip1dbg(("ip_massage_options: loopback addr in "
7568 				    "source route!\n"));
7569 				break;
7570 			}
7571 			/*
7572 			 * Update ipha_dst to be the first hop and remove the
7573 			 * first hop from the source route (by overwriting
7574 			 * part of the option with NOP options).
7575 			 */
7576 			ipha->ipha_dst = dst;
7577 			/* Put the last entry in dst */
7578 			off = ((optlen - IP_ADDR_LEN - 3) & ~(IP_ADDR_LEN-1)) +
7579 			    3;
7580 			bcopy(&opt[off], &dst, IP_ADDR_LEN);
7581 
7582 			ip1dbg(("ip_massage_options: last hop 0x%x\n",
7583 			    ntohl(dst)));
7584 			/* Move down and overwrite */
7585 			opt[IP_ADDR_LEN] = opt[0];
7586 			opt[IP_ADDR_LEN+1] = opt[IPOPT_OLEN] - IP_ADDR_LEN;
7587 			opt[IP_ADDR_LEN+2] = opt[IPOPT_OFFSET];
7588 			for (i = 0; i < IP_ADDR_LEN; i++)
7589 				opt[i] = IPOPT_NOP;
7590 			break;
7591 		}
7592 	}
7593 	return (dst);
7594 }
7595 
7596 /*
7597  * Return the network mask
7598  * associated with the specified address.
7599  */
7600 ipaddr_t
7601 ip_net_mask(ipaddr_t addr)
7602 {
7603 	uchar_t	*up = (uchar_t *)&addr;
7604 	ipaddr_t mask = 0;
7605 	uchar_t	*maskp = (uchar_t *)&mask;
7606 
7607 #if defined(__i386) || defined(__amd64)
7608 #define	TOTALLY_BRAIN_DAMAGED_C_COMPILER
7609 #endif
7610 #ifdef  TOTALLY_BRAIN_DAMAGED_C_COMPILER
7611 	maskp[0] = maskp[1] = maskp[2] = maskp[3] = 0;
7612 #endif
7613 	if (CLASSD(addr)) {
7614 		maskp[0] = 0xF0;
7615 		return (mask);
7616 	}
7617 
7618 	/* We assume Class E default netmask to be 32 */
7619 	if (CLASSE(addr))
7620 		return (0xffffffffU);
7621 
7622 	if (addr == 0)
7623 		return (0);
7624 	maskp[0] = 0xFF;
7625 	if ((up[0] & 0x80) == 0)
7626 		return (mask);
7627 
7628 	maskp[1] = 0xFF;
7629 	if ((up[0] & 0xC0) == 0x80)
7630 		return (mask);
7631 
7632 	maskp[2] = 0xFF;
7633 	if ((up[0] & 0xE0) == 0xC0)
7634 		return (mask);
7635 
7636 	/* Otherwise return no mask */
7637 	return ((ipaddr_t)0);
7638 }
7639 
7640 /*
7641  * Select an ill for the packet by considering load spreading across
7642  * a different ill in the group if dst_ill is part of some group.
7643  */
7644 ill_t *
7645 ip_newroute_get_dst_ill(ill_t *dst_ill)
7646 {
7647 	ill_t *ill;
7648 
7649 	/*
7650 	 * We schedule irrespective of whether the source address is
7651 	 * INADDR_ANY or not. illgrp_scheduler returns a held ill.
7652 	 */
7653 	ill = illgrp_scheduler(dst_ill);
7654 	if (ill == NULL)
7655 		return (NULL);
7656 
7657 	/*
7658 	 * For groups with names ip_sioctl_groupname ensures that all
7659 	 * ills are of same type. For groups without names, ifgrp_insert
7660 	 * ensures this.
7661 	 */
7662 	ASSERT(dst_ill->ill_type == ill->ill_type);
7663 
7664 	return (ill);
7665 }
7666 
7667 /*
7668  * Helper function for the IPIF_NOFAILOVER/ATTACH_IF interface attachment case.
7669  */
7670 ill_t *
7671 ip_grab_attach_ill(ill_t *ill, mblk_t *first_mp, int ifindex, boolean_t isv6,
7672     ip_stack_t *ipst)
7673 {
7674 	ill_t *ret_ill;
7675 
7676 	ASSERT(ifindex != 0);
7677 	ret_ill = ill_lookup_on_ifindex(ifindex, isv6, NULL, NULL, NULL, NULL,
7678 	    ipst);
7679 	if (ret_ill == NULL ||
7680 	    (ret_ill->ill_phyint->phyint_flags & PHYI_OFFLINE)) {
7681 		if (isv6) {
7682 			if (ill != NULL) {
7683 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7684 			} else {
7685 				BUMP_MIB(&ipst->ips_ip6_mib,
7686 				    ipIfStatsOutDiscards);
7687 			}
7688 			ip1dbg(("ip_grab_attach_ill (IPv6): "
7689 			    "bad ifindex %d.\n", ifindex));
7690 		} else {
7691 			if (ill != NULL) {
7692 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
7693 			} else {
7694 				BUMP_MIB(&ipst->ips_ip_mib,
7695 				    ipIfStatsOutDiscards);
7696 			}
7697 			ip1dbg(("ip_grab_attach_ill (IPv4): "
7698 			    "bad ifindex %d.\n", ifindex));
7699 		}
7700 		if (ret_ill != NULL)
7701 			ill_refrele(ret_ill);
7702 		freemsg(first_mp);
7703 		return (NULL);
7704 	}
7705 
7706 	return (ret_ill);
7707 }
7708 
7709 /*
7710  * IPv4 -
7711  * ip_newroute is called by ip_rput or ip_wput whenever we need to send
7712  * out a packet to a destination address for which we do not have specific
7713  * (or sufficient) routing information.
7714  *
7715  * NOTE : These are the scopes of some of the variables that point at IRE,
7716  *	  which needs to be followed while making any future modifications
7717  *	  to avoid memory leaks.
7718  *
7719  *	- ire and sire are the entries looked up initially by
7720  *	  ire_ftable_lookup.
7721  *	- ipif_ire is used to hold the interface ire associated with
7722  *	  the new cache ire. But it's scope is limited, so we always REFRELE
7723  *	  it before branching out to error paths.
7724  *	- save_ire is initialized before ire_create, so that ire returned
7725  *	  by ire_create will not over-write the ire. We REFRELE save_ire
7726  *	  before breaking out of the switch.
7727  *
7728  *	Thus on failures, we have to REFRELE only ire and sire, if they
7729  *	are not NULL.
7730  */
7731 void
7732 ip_newroute(queue_t *q, mblk_t *mp, ipaddr_t dst, conn_t *connp,
7733     zoneid_t zoneid, ip_stack_t *ipst)
7734 {
7735 	areq_t	*areq;
7736 	ipaddr_t gw = 0;
7737 	ire_t	*ire = NULL;
7738 	mblk_t	*res_mp;
7739 	ipaddr_t *addrp;
7740 	ipaddr_t nexthop_addr;
7741 	ipif_t  *src_ipif = NULL;
7742 	ill_t	*dst_ill = NULL;
7743 	ipha_t  *ipha;
7744 	ire_t	*sire = NULL;
7745 	mblk_t	*first_mp;
7746 	ire_t	*save_ire;
7747 	ill_t	*attach_ill = NULL;	/* Bind to IPIF_NOFAILOVER address */
7748 	ushort_t ire_marks = 0;
7749 	boolean_t mctl_present;
7750 	ipsec_out_t *io;
7751 	mblk_t	*saved_mp;
7752 	ire_t	*first_sire = NULL;
7753 	mblk_t	*copy_mp = NULL;
7754 	mblk_t	*xmit_mp = NULL;
7755 	ipaddr_t save_dst;
7756 	uint32_t multirt_flags =
7757 	    MULTIRT_CACHEGW | MULTIRT_USESTAMP | MULTIRT_SETSTAMP;
7758 	boolean_t multirt_is_resolvable;
7759 	boolean_t multirt_resolve_next;
7760 	boolean_t unspec_src;
7761 	boolean_t do_attach_ill = B_FALSE;
7762 	boolean_t ip_nexthop = B_FALSE;
7763 	tsol_ire_gw_secattr_t *attrp = NULL;
7764 	tsol_gcgrp_t *gcgrp = NULL;
7765 	tsol_gcgrp_addr_t ga;
7766 
7767 	if (ip_debug > 2) {
7768 		/* ip1dbg */
7769 		pr_addr_dbg("ip_newroute: dst %s\n", AF_INET, &dst);
7770 	}
7771 
7772 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
7773 	if (mctl_present) {
7774 		io = (ipsec_out_t *)first_mp->b_rptr;
7775 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
7776 		ASSERT(zoneid == io->ipsec_out_zoneid);
7777 		ASSERT(zoneid != ALL_ZONES);
7778 	}
7779 
7780 	ipha = (ipha_t *)mp->b_rptr;
7781 
7782 	/* All multicast lookups come through ip_newroute_ipif() */
7783 	if (CLASSD(dst)) {
7784 		ip0dbg(("ip_newroute: CLASSD 0x%x (b_prev %p, b_next %p)\n",
7785 		    ntohl(dst), (void *)mp->b_prev, (void *)mp->b_next));
7786 		freemsg(first_mp);
7787 		return;
7788 	}
7789 
7790 	if (mctl_present && io->ipsec_out_attach_if) {
7791 		/* ip_grab_attach_ill returns a held ill */
7792 		attach_ill = ip_grab_attach_ill(NULL, first_mp,
7793 		    io->ipsec_out_ill_index, B_FALSE, ipst);
7794 
7795 		/* Failure case frees things for us. */
7796 		if (attach_ill == NULL)
7797 			return;
7798 
7799 		/*
7800 		 * Check if we need an ire that will not be
7801 		 * looked up by anybody else i.e. HIDDEN.
7802 		 */
7803 		if (ill_is_probeonly(attach_ill))
7804 			ire_marks = IRE_MARK_HIDDEN;
7805 	}
7806 	if (mctl_present && io->ipsec_out_ip_nexthop) {
7807 		ip_nexthop = B_TRUE;
7808 		nexthop_addr = io->ipsec_out_nexthop_addr;
7809 	}
7810 	/*
7811 	 * If this IRE is created for forwarding or it is not for
7812 	 * traffic for congestion controlled protocols, mark it as temporary.
7813 	 */
7814 	if (mp->b_prev != NULL || !IP_FLOW_CONTROLLED_ULP(ipha->ipha_protocol))
7815 		ire_marks |= IRE_MARK_TEMPORARY;
7816 
7817 	/*
7818 	 * Get what we can from ire_ftable_lookup which will follow an IRE
7819 	 * chain until it gets the most specific information available.
7820 	 * For example, we know that there is no IRE_CACHE for this dest,
7821 	 * but there may be an IRE_OFFSUBNET which specifies a gateway.
7822 	 * ire_ftable_lookup will look up the gateway, etc.
7823 	 * Otherwise, given ire_ftable_lookup algorithm, only one among routes
7824 	 * to the destination, of equal netmask length in the forward table,
7825 	 * will be recursively explored. If no information is available
7826 	 * for the final gateway of that route, we force the returned ire
7827 	 * to be equal to sire using MATCH_IRE_PARENT.
7828 	 * At least, in this case we have a starting point (in the buckets)
7829 	 * to look for other routes to the destination in the forward table.
7830 	 * This is actually used only for multirouting, where a list
7831 	 * of routes has to be processed in sequence.
7832 	 *
7833 	 * In the process of coming up with the most specific information,
7834 	 * ire_ftable_lookup may end up with an incomplete IRE_CACHE entry
7835 	 * for the gateway (i.e., one for which the ire_nce->nce_state is
7836 	 * not yet ND_REACHABLE, and is in the middle of arp resolution).
7837 	 * Two caveats when handling incomplete ire's in ip_newroute:
7838 	 * - we should be careful when accessing its ire_nce (specifically
7839 	 *   the nce_res_mp) ast it might change underneath our feet, and,
7840 	 * - not all legacy code path callers are prepared to handle
7841 	 *   incomplete ire's, so we should not create/add incomplete
7842 	 *   ire_cache entries here. (See discussion about temporary solution
7843 	 *   further below).
7844 	 *
7845 	 * In order to minimize packet dropping, and to preserve existing
7846 	 * behavior, we treat this case as if there were no IRE_CACHE for the
7847 	 * gateway, and instead use the IF_RESOLVER ire to send out
7848 	 * another request to ARP (this is achieved by passing the
7849 	 * MATCH_IRE_COMPLETE flag to ire_ftable_lookup). When the
7850 	 * arp response comes back in ip_wput_nondata, we will create
7851 	 * a per-dst ire_cache that has an ND_COMPLETE ire.
7852 	 *
7853 	 * Note that this is a temporary solution; the correct solution is
7854 	 * to create an incomplete  per-dst ire_cache entry, and send the
7855 	 * packet out when the gw's nce is resolved. In order to achieve this,
7856 	 * all packet processing must have been completed prior to calling
7857 	 * ire_add_then_send. Some legacy code paths (e.g. cgtp) would need
7858 	 * to be modified to accomodate this solution.
7859 	 */
7860 	if (ip_nexthop) {
7861 		/*
7862 		 * The first time we come here, we look for an IRE_INTERFACE
7863 		 * entry for the specified nexthop, set the dst to be the
7864 		 * nexthop address and create an IRE_CACHE entry for the
7865 		 * nexthop. The next time around, we are able to find an
7866 		 * IRE_CACHE entry for the nexthop, set the gateway to be the
7867 		 * nexthop address and create an IRE_CACHE entry for the
7868 		 * destination address via the specified nexthop.
7869 		 */
7870 		ire = ire_cache_lookup(nexthop_addr, zoneid,
7871 		    MBLK_GETLABEL(mp), ipst);
7872 		if (ire != NULL) {
7873 			gw = nexthop_addr;
7874 			ire_marks |= IRE_MARK_PRIVATE_ADDR;
7875 		} else {
7876 			ire = ire_ftable_lookup(nexthop_addr, 0, 0,
7877 			    IRE_INTERFACE, NULL, NULL, zoneid, 0,
7878 			    MBLK_GETLABEL(mp),
7879 			    MATCH_IRE_TYPE | MATCH_IRE_SECATTR,
7880 			    ipst);
7881 			if (ire != NULL) {
7882 				dst = nexthop_addr;
7883 			}
7884 		}
7885 	} else if (attach_ill == NULL) {
7886 		ire = ire_ftable_lookup(dst, 0, 0, 0,
7887 		    NULL, &sire, zoneid, 0, MBLK_GETLABEL(mp),
7888 		    MATCH_IRE_RECURSIVE | MATCH_IRE_DEFAULT |
7889 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_PARENT |
7890 		    MATCH_IRE_SECATTR | MATCH_IRE_COMPLETE,
7891 		    ipst);
7892 	} else {
7893 		/*
7894 		 * attach_ill is set only for communicating with
7895 		 * on-link hosts. So, don't look for DEFAULT.
7896 		 */
7897 		ipif_t	*attach_ipif;
7898 
7899 		attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
7900 		if (attach_ipif == NULL) {
7901 			ill_refrele(attach_ill);
7902 			goto icmp_err_ret;
7903 		}
7904 		ire = ire_ftable_lookup(dst, 0, 0, 0, attach_ipif,
7905 		    &sire, zoneid, 0, MBLK_GETLABEL(mp),
7906 		    MATCH_IRE_RJ_BHOLE | MATCH_IRE_ILL |
7907 		    MATCH_IRE_SECATTR, ipst);
7908 		ipif_refrele(attach_ipif);
7909 	}
7910 	ip3dbg(("ip_newroute: ire_ftable_lookup() "
7911 	    "returned ire %p, sire %p\n", (void *)ire, (void *)sire));
7912 
7913 	/*
7914 	 * This loop is run only once in most cases.
7915 	 * We loop to resolve further routes only when the destination
7916 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
7917 	 */
7918 	do {
7919 		/* Clear the previous iteration's values */
7920 		if (src_ipif != NULL) {
7921 			ipif_refrele(src_ipif);
7922 			src_ipif = NULL;
7923 		}
7924 		if (dst_ill != NULL) {
7925 			ill_refrele(dst_ill);
7926 			dst_ill = NULL;
7927 		}
7928 
7929 		multirt_resolve_next = B_FALSE;
7930 		/*
7931 		 * We check if packets have to be multirouted.
7932 		 * In this case, given the current <ire, sire> couple,
7933 		 * we look for the next suitable <ire, sire>.
7934 		 * This check is done in ire_multirt_lookup(),
7935 		 * which applies various criteria to find the next route
7936 		 * to resolve. ire_multirt_lookup() leaves <ire, sire>
7937 		 * unchanged if it detects it has not been tried yet.
7938 		 */
7939 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
7940 			ip3dbg(("ip_newroute: starting next_resolution "
7941 			    "with first_mp %p, tag %d\n",
7942 			    (void *)first_mp,
7943 			    MULTIRT_DEBUG_TAGGED(first_mp)));
7944 
7945 			ASSERT(sire != NULL);
7946 			multirt_is_resolvable =
7947 			    ire_multirt_lookup(&ire, &sire, multirt_flags,
7948 			    MBLK_GETLABEL(mp), ipst);
7949 
7950 			ip3dbg(("ip_newroute: multirt_is_resolvable %d, "
7951 			    "ire %p, sire %p\n",
7952 			    multirt_is_resolvable,
7953 			    (void *)ire, (void *)sire));
7954 
7955 			if (!multirt_is_resolvable) {
7956 				/*
7957 				 * No more multirt route to resolve; give up
7958 				 * (all routes resolved or no more
7959 				 * resolvable routes).
7960 				 */
7961 				if (ire != NULL) {
7962 					ire_refrele(ire);
7963 					ire = NULL;
7964 				}
7965 			} else {
7966 				ASSERT(sire != NULL);
7967 				ASSERT(ire != NULL);
7968 				/*
7969 				 * We simply use first_sire as a flag that
7970 				 * indicates if a resolvable multirt route
7971 				 * has already been found.
7972 				 * If it is not the case, we may have to send
7973 				 * an ICMP error to report that the
7974 				 * destination is unreachable.
7975 				 * We do not IRE_REFHOLD first_sire.
7976 				 */
7977 				if (first_sire == NULL) {
7978 					first_sire = sire;
7979 				}
7980 			}
7981 		}
7982 		if (ire == NULL) {
7983 			if (ip_debug > 3) {
7984 				/* ip2dbg */
7985 				pr_addr_dbg("ip_newroute: "
7986 				    "can't resolve %s\n", AF_INET, &dst);
7987 			}
7988 			ip3dbg(("ip_newroute: "
7989 			    "ire %p, sire %p, first_sire %p\n",
7990 			    (void *)ire, (void *)sire, (void *)first_sire));
7991 
7992 			if (sire != NULL) {
7993 				ire_refrele(sire);
7994 				sire = NULL;
7995 			}
7996 
7997 			if (first_sire != NULL) {
7998 				/*
7999 				 * At least one multirt route has been found
8000 				 * in the same call to ip_newroute();
8001 				 * there is no need to report an ICMP error.
8002 				 * first_sire was not IRE_REFHOLDed.
8003 				 */
8004 				MULTIRT_DEBUG_UNTAG(first_mp);
8005 				freemsg(first_mp);
8006 				return;
8007 			}
8008 			ip_rts_change(RTM_MISS, dst, 0, 0, 0, 0, 0, 0,
8009 			    RTA_DST, ipst);
8010 			if (attach_ill != NULL)
8011 				ill_refrele(attach_ill);
8012 			goto icmp_err_ret;
8013 		}
8014 
8015 		/*
8016 		 * Verify that the returned IRE does not have either
8017 		 * the RTF_REJECT or RTF_BLACKHOLE flags set and that the IRE is
8018 		 * either an IRE_CACHE, IRE_IF_NORESOLVER or IRE_IF_RESOLVER.
8019 		 */
8020 		if ((ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) ||
8021 		    (ire->ire_type & (IRE_CACHE | IRE_INTERFACE)) == 0) {
8022 			if (attach_ill != NULL)
8023 				ill_refrele(attach_ill);
8024 			goto icmp_err_ret;
8025 		}
8026 		/*
8027 		 * Increment the ire_ob_pkt_count field for ire if it is an
8028 		 * INTERFACE (IF_RESOLVER or IF_NORESOLVER) IRE type, and
8029 		 * increment the same for the parent IRE, sire, if it is some
8030 		 * sort of prefix IRE (which includes DEFAULT, PREFIX, and HOST)
8031 		 */
8032 		if ((ire->ire_type & IRE_INTERFACE) != 0) {
8033 			UPDATE_OB_PKT_COUNT(ire);
8034 			ire->ire_last_used_time = lbolt;
8035 		}
8036 
8037 		if (sire != NULL) {
8038 			gw = sire->ire_gateway_addr;
8039 			ASSERT((sire->ire_type & (IRE_CACHETABLE |
8040 			    IRE_INTERFACE)) == 0);
8041 			UPDATE_OB_PKT_COUNT(sire);
8042 			sire->ire_last_used_time = lbolt;
8043 		}
8044 		/*
8045 		 * We have a route to reach the destination.
8046 		 *
8047 		 * 1) If the interface is part of ill group, try to get a new
8048 		 *    ill taking load spreading into account.
8049 		 *
8050 		 * 2) After selecting the ill, get a source address that
8051 		 *    might create good inbound load spreading.
8052 		 *    ipif_select_source does this for us.
8053 		 *
8054 		 * If the application specified the ill (ifindex), we still
8055 		 * load spread. Only if the packets needs to go out
8056 		 * specifically on a given ill e.g. binding to
8057 		 * IPIF_NOFAILOVER address, then we don't try to use a
8058 		 * different ill for load spreading.
8059 		 */
8060 		if (attach_ill == NULL) {
8061 			/*
8062 			 * Don't perform outbound load spreading in the
8063 			 * case of an RTF_MULTIRT route, as we actually
8064 			 * typically want to replicate outgoing packets
8065 			 * through particular interfaces.
8066 			 */
8067 			if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8068 				dst_ill = ire->ire_ipif->ipif_ill;
8069 				/* for uniformity */
8070 				ill_refhold(dst_ill);
8071 			} else {
8072 				/*
8073 				 * If we are here trying to create an IRE_CACHE
8074 				 * for an offlink destination and have the
8075 				 * IRE_CACHE for the next hop and the latter is
8076 				 * using virtual IP source address selection i.e
8077 				 * it's ire->ire_ipif is pointing to a virtual
8078 				 * network interface (vni) then
8079 				 * ip_newroute_get_dst_ll() will return the vni
8080 				 * interface as the dst_ill. Since the vni is
8081 				 * virtual i.e not associated with any physical
8082 				 * interface, it cannot be the dst_ill, hence
8083 				 * in such a case call ip_newroute_get_dst_ll()
8084 				 * with the stq_ill instead of the ire_ipif ILL.
8085 				 * The function returns a refheld ill.
8086 				 */
8087 				if ((ire->ire_type == IRE_CACHE) &&
8088 				    IS_VNI(ire->ire_ipif->ipif_ill))
8089 					dst_ill = ip_newroute_get_dst_ill(
8090 					    ire->ire_stq->q_ptr);
8091 				else
8092 					dst_ill = ip_newroute_get_dst_ill(
8093 					    ire->ire_ipif->ipif_ill);
8094 			}
8095 			if (dst_ill == NULL) {
8096 				if (ip_debug > 2) {
8097 					pr_addr_dbg("ip_newroute: "
8098 					    "no dst ill for dst"
8099 					    " %s\n", AF_INET, &dst);
8100 				}
8101 				goto icmp_err_ret;
8102 			}
8103 		} else {
8104 			dst_ill = ire->ire_ipif->ipif_ill;
8105 			/* for uniformity */
8106 			ill_refhold(dst_ill);
8107 			/*
8108 			 * We should have found a route matching ill as we
8109 			 * called ire_ftable_lookup with MATCH_IRE_ILL.
8110 			 * Rather than asserting, when there is a mismatch,
8111 			 * we just drop the packet.
8112 			 */
8113 			if (dst_ill != attach_ill) {
8114 				ip0dbg(("ip_newroute: Packet dropped as "
8115 				    "IPIF_NOFAILOVER ill is %s, "
8116 				    "ire->ire_ipif->ipif_ill is %s\n",
8117 				    attach_ill->ill_name,
8118 				    dst_ill->ill_name));
8119 				ill_refrele(attach_ill);
8120 				goto icmp_err_ret;
8121 			}
8122 		}
8123 		/* attach_ill can't go in loop. IPMP and CGTP are disjoint */
8124 		if (attach_ill != NULL) {
8125 			ill_refrele(attach_ill);
8126 			attach_ill = NULL;
8127 			do_attach_ill = B_TRUE;
8128 		}
8129 		ASSERT(dst_ill != NULL);
8130 		ip2dbg(("ip_newroute: dst_ill %s\n", dst_ill->ill_name));
8131 
8132 		/*
8133 		 * Pick the best source address from dst_ill.
8134 		 *
8135 		 * 1) If it is part of a multipathing group, we would
8136 		 *    like to spread the inbound packets across different
8137 		 *    interfaces. ipif_select_source picks a random source
8138 		 *    across the different ills in the group.
8139 		 *
8140 		 * 2) If it is not part of a multipathing group, we try
8141 		 *    to pick the source address from the destination
8142 		 *    route. Clustering assumes that when we have multiple
8143 		 *    prefixes hosted on an interface, the prefix of the
8144 		 *    source address matches the prefix of the destination
8145 		 *    route. We do this only if the address is not
8146 		 *    DEPRECATED.
8147 		 *
8148 		 * 3) If the conn is in a different zone than the ire, we
8149 		 *    need to pick a source address from the right zone.
8150 		 *
8151 		 * NOTE : If we hit case (1) above, the prefix of the source
8152 		 *	  address picked may not match the prefix of the
8153 		 *	  destination routes prefix as ipif_select_source
8154 		 *	  does not look at "dst" while picking a source
8155 		 *	  address.
8156 		 *	  If we want the same behavior as (2), we will need
8157 		 *	  to change the behavior of ipif_select_source.
8158 		 */
8159 		ASSERT(src_ipif == NULL);
8160 		if ((sire != NULL) && (sire->ire_flags & RTF_SETSRC)) {
8161 			/*
8162 			 * The RTF_SETSRC flag is set in the parent ire (sire).
8163 			 * Check that the ipif matching the requested source
8164 			 * address still exists.
8165 			 */
8166 			src_ipif = ipif_lookup_addr(sire->ire_src_addr, NULL,
8167 			    zoneid, NULL, NULL, NULL, NULL, ipst);
8168 		}
8169 
8170 		unspec_src = (connp != NULL && connp->conn_unspec_src);
8171 
8172 		if (src_ipif == NULL &&
8173 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
8174 			ire_marks |= IRE_MARK_USESRC_CHECK;
8175 			if ((dst_ill->ill_group != NULL) ||
8176 			    (ire->ire_ipif->ipif_flags & IPIF_DEPRECATED) ||
8177 			    (connp != NULL && ire->ire_zoneid != zoneid &&
8178 			    ire->ire_zoneid != ALL_ZONES) ||
8179 			    (dst_ill->ill_usesrc_ifindex != 0)) {
8180 				/*
8181 				 * If the destination is reachable via a
8182 				 * given gateway, the selected source address
8183 				 * should be in the same subnet as the gateway.
8184 				 * Otherwise, the destination is not reachable.
8185 				 *
8186 				 * If there are no interfaces on the same subnet
8187 				 * as the destination, ipif_select_source gives
8188 				 * first non-deprecated interface which might be
8189 				 * on a different subnet than the gateway.
8190 				 * This is not desirable. Hence pass the dst_ire
8191 				 * source address to ipif_select_source.
8192 				 * It is sure that the destination is reachable
8193 				 * with the dst_ire source address subnet.
8194 				 * So passing dst_ire source address to
8195 				 * ipif_select_source will make sure that the
8196 				 * selected source will be on the same subnet
8197 				 * as dst_ire source address.
8198 				 */
8199 				ipaddr_t saddr = ire->ire_ipif->ipif_src_addr;
8200 				src_ipif = ipif_select_source(dst_ill, saddr,
8201 				    zoneid);
8202 				if (src_ipif == NULL) {
8203 					if (ip_debug > 2) {
8204 						pr_addr_dbg("ip_newroute: "
8205 						    "no src for dst %s ",
8206 						    AF_INET, &dst);
8207 						printf("through interface %s\n",
8208 						    dst_ill->ill_name);
8209 					}
8210 					goto icmp_err_ret;
8211 				}
8212 			} else {
8213 				src_ipif = ire->ire_ipif;
8214 				ASSERT(src_ipif != NULL);
8215 				/* hold src_ipif for uniformity */
8216 				ipif_refhold(src_ipif);
8217 			}
8218 		}
8219 
8220 		/*
8221 		 * Assign a source address while we have the conn.
8222 		 * We can't have ip_wput_ire pick a source address when the
8223 		 * packet returns from arp since we need to look at
8224 		 * conn_unspec_src and conn_zoneid, and we lose the conn when
8225 		 * going through arp.
8226 		 *
8227 		 * NOTE : ip_newroute_v6 does not have this piece of code as
8228 		 *	  it uses ip6i to store this information.
8229 		 */
8230 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
8231 			ipha->ipha_src = src_ipif->ipif_src_addr;
8232 
8233 		if (ip_debug > 3) {
8234 			/* ip2dbg */
8235 			pr_addr_dbg("ip_newroute: first hop %s\n",
8236 			    AF_INET, &gw);
8237 		}
8238 		ip2dbg(("\tire type %s (%d)\n",
8239 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type), ire->ire_type));
8240 
8241 		/*
8242 		 * The TTL of multirouted packets is bounded by the
8243 		 * ip_multirt_ttl ndd variable.
8244 		 */
8245 		if ((sire != NULL) && (sire->ire_flags & RTF_MULTIRT)) {
8246 			/* Force TTL of multirouted packets */
8247 			if ((ipst->ips_ip_multirt_ttl > 0) &&
8248 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
8249 				ip2dbg(("ip_newroute: forcing multirt TTL "
8250 				    "to %d (was %d), dst 0x%08x\n",
8251 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
8252 				    ntohl(sire->ire_addr)));
8253 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
8254 			}
8255 		}
8256 		/*
8257 		 * At this point in ip_newroute(), ire is either the
8258 		 * IRE_CACHE of the next-hop gateway for an off-subnet
8259 		 * destination or an IRE_INTERFACE type that should be used
8260 		 * to resolve an on-subnet destination or an on-subnet
8261 		 * next-hop gateway.
8262 		 *
8263 		 * In the IRE_CACHE case, we have the following :
8264 		 *
8265 		 * 1) src_ipif - used for getting a source address.
8266 		 *
8267 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8268 		 *    means packets using this IRE_CACHE will go out on
8269 		 *    dst_ill.
8270 		 *
8271 		 * 3) The IRE sire will point to the prefix that is the
8272 		 *    longest  matching route for the destination. These
8273 		 *    prefix types include IRE_DEFAULT, IRE_PREFIX, IRE_HOST.
8274 		 *
8275 		 *    The newly created IRE_CACHE entry for the off-subnet
8276 		 *    destination is tied to both the prefix route and the
8277 		 *    interface route used to resolve the next-hop gateway
8278 		 *    via the ire_phandle and ire_ihandle fields,
8279 		 *    respectively.
8280 		 *
8281 		 * In the IRE_INTERFACE case, we have the following :
8282 		 *
8283 		 * 1) src_ipif - used for getting a source address.
8284 		 *
8285 		 * 2) dst_ill - from which we derive ire_stq/ire_rfq. This
8286 		 *    means packets using the IRE_CACHE that we will build
8287 		 *    here will go out on dst_ill.
8288 		 *
8289 		 * 3) sire may or may not be NULL. But, the IRE_CACHE that is
8290 		 *    to be created will only be tied to the IRE_INTERFACE
8291 		 *    that was derived from the ire_ihandle field.
8292 		 *
8293 		 *    If sire is non-NULL, it means the destination is
8294 		 *    off-link and we will first create the IRE_CACHE for the
8295 		 *    gateway. Next time through ip_newroute, we will create
8296 		 *    the IRE_CACHE for the final destination as described
8297 		 *    above.
8298 		 *
8299 		 * In both cases, after the current resolution has been
8300 		 * completed (or possibly initialised, in the IRE_INTERFACE
8301 		 * case), the loop may be re-entered to attempt the resolution
8302 		 * of another RTF_MULTIRT route.
8303 		 *
8304 		 * When an IRE_CACHE entry for the off-subnet destination is
8305 		 * created, RTF_SETSRC and RTF_MULTIRT are inherited from sire,
8306 		 * for further processing in emission loops.
8307 		 */
8308 		save_ire = ire;
8309 		switch (ire->ire_type) {
8310 		case IRE_CACHE: {
8311 			ire_t	*ipif_ire;
8312 
8313 			ASSERT(save_ire->ire_nce->nce_state == ND_REACHABLE);
8314 			if (gw == 0)
8315 				gw = ire->ire_gateway_addr;
8316 			/*
8317 			 * We need 3 ire's to create a new cache ire for an
8318 			 * off-link destination from the cache ire of the
8319 			 * gateway.
8320 			 *
8321 			 *	1. The prefix ire 'sire' (Note that this does
8322 			 *	   not apply to the conn_nexthop_set case)
8323 			 *	2. The cache ire of the gateway 'ire'
8324 			 *	3. The interface ire 'ipif_ire'
8325 			 *
8326 			 * We have (1) and (2). We lookup (3) below.
8327 			 *
8328 			 * If there is no interface route to the gateway,
8329 			 * it is a race condition, where we found the cache
8330 			 * but the interface route has been deleted.
8331 			 */
8332 			if (ip_nexthop) {
8333 				ipif_ire = ire_ihandle_lookup_onlink(ire);
8334 			} else {
8335 				ipif_ire =
8336 				    ire_ihandle_lookup_offlink(ire, sire);
8337 			}
8338 			if (ipif_ire == NULL) {
8339 				ip1dbg(("ip_newroute: "
8340 				    "ire_ihandle_lookup_offlink failed\n"));
8341 				goto icmp_err_ret;
8342 			}
8343 
8344 			/*
8345 			 * Check cached gateway IRE for any security
8346 			 * attributes; if found, associate the gateway
8347 			 * credentials group to the destination IRE.
8348 			 */
8349 			if ((attrp = save_ire->ire_gw_secattr) != NULL) {
8350 				mutex_enter(&attrp->igsa_lock);
8351 				if ((gcgrp = attrp->igsa_gcgrp) != NULL)
8352 					GCGRP_REFHOLD(gcgrp);
8353 				mutex_exit(&attrp->igsa_lock);
8354 			}
8355 
8356 			/*
8357 			 * XXX For the source of the resolver mp,
8358 			 * we are using the same DL_UNITDATA_REQ
8359 			 * (from save_ire->ire_nce->nce_res_mp)
8360 			 * though the save_ire is not pointing at the same ill.
8361 			 * This is incorrect. We need to send it up to the
8362 			 * resolver to get the right res_mp. For ethernets
8363 			 * this may be okay (ill_type == DL_ETHER).
8364 			 */
8365 
8366 			ire = ire_create(
8367 			    (uchar_t *)&dst,		/* dest address */
8368 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8369 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8370 			    (uchar_t *)&gw,		/* gateway address */
8371 			    &save_ire->ire_max_frag,
8372 			    save_ire->ire_nce,		/* src nce */
8373 			    dst_ill->ill_rq,		/* recv-from queue */
8374 			    dst_ill->ill_wq,		/* send-to queue */
8375 			    IRE_CACHE,			/* IRE type */
8376 			    src_ipif,
8377 			    (sire != NULL) ?
8378 			    sire->ire_mask : 0, 	/* Parent mask */
8379 			    (sire != NULL) ?
8380 			    sire->ire_phandle : 0,	/* Parent handle */
8381 			    ipif_ire->ire_ihandle,	/* Interface handle */
8382 			    (sire != NULL) ? (sire->ire_flags &
8383 			    (RTF_SETSRC | RTF_MULTIRT)) : 0, /* flags */
8384 			    (sire != NULL) ?
8385 			    &(sire->ire_uinfo) : &(save_ire->ire_uinfo),
8386 			    NULL,
8387 			    gcgrp,
8388 			    ipst);
8389 
8390 			if (ire == NULL) {
8391 				if (gcgrp != NULL) {
8392 					GCGRP_REFRELE(gcgrp);
8393 					gcgrp = NULL;
8394 				}
8395 				ire_refrele(ipif_ire);
8396 				ire_refrele(save_ire);
8397 				break;
8398 			}
8399 
8400 			/* reference now held by IRE */
8401 			gcgrp = NULL;
8402 
8403 			ire->ire_marks |= ire_marks;
8404 
8405 			/*
8406 			 * Prevent sire and ipif_ire from getting deleted.
8407 			 * The newly created ire is tied to both of them via
8408 			 * the phandle and ihandle respectively.
8409 			 */
8410 			if (sire != NULL) {
8411 				IRB_REFHOLD(sire->ire_bucket);
8412 				/* Has it been removed already ? */
8413 				if (sire->ire_marks & IRE_MARK_CONDEMNED) {
8414 					IRB_REFRELE(sire->ire_bucket);
8415 					ire_refrele(ipif_ire);
8416 					ire_refrele(save_ire);
8417 					break;
8418 				}
8419 			}
8420 
8421 			IRB_REFHOLD(ipif_ire->ire_bucket);
8422 			/* Has it been removed already ? */
8423 			if (ipif_ire->ire_marks & IRE_MARK_CONDEMNED) {
8424 				IRB_REFRELE(ipif_ire->ire_bucket);
8425 				if (sire != NULL)
8426 					IRB_REFRELE(sire->ire_bucket);
8427 				ire_refrele(ipif_ire);
8428 				ire_refrele(save_ire);
8429 				break;
8430 			}
8431 
8432 			xmit_mp = first_mp;
8433 			/*
8434 			 * In the case of multirouting, a copy
8435 			 * of the packet is done before its sending.
8436 			 * The copy is used to attempt another
8437 			 * route resolution, in a next loop.
8438 			 */
8439 			if (ire->ire_flags & RTF_MULTIRT) {
8440 				copy_mp = copymsg(first_mp);
8441 				if (copy_mp != NULL) {
8442 					xmit_mp = copy_mp;
8443 					MULTIRT_DEBUG_TAG(first_mp);
8444 				}
8445 			}
8446 			ire_add_then_send(q, ire, xmit_mp);
8447 			ire_refrele(save_ire);
8448 
8449 			/* Assert that sire is not deleted yet. */
8450 			if (sire != NULL) {
8451 				ASSERT(sire->ire_ptpn != NULL);
8452 				IRB_REFRELE(sire->ire_bucket);
8453 			}
8454 
8455 			/* Assert that ipif_ire is not deleted yet. */
8456 			ASSERT(ipif_ire->ire_ptpn != NULL);
8457 			IRB_REFRELE(ipif_ire->ire_bucket);
8458 			ire_refrele(ipif_ire);
8459 
8460 			/*
8461 			 * If copy_mp is not NULL, multirouting was
8462 			 * requested. We loop to initiate a next
8463 			 * route resolution attempt, starting from sire.
8464 			 */
8465 			if (copy_mp != NULL) {
8466 				/*
8467 				 * Search for the next unresolved
8468 				 * multirt route.
8469 				 */
8470 				copy_mp = NULL;
8471 				ipif_ire = NULL;
8472 				ire = NULL;
8473 				multirt_resolve_next = B_TRUE;
8474 				continue;
8475 			}
8476 			if (sire != NULL)
8477 				ire_refrele(sire);
8478 			ipif_refrele(src_ipif);
8479 			ill_refrele(dst_ill);
8480 			return;
8481 		}
8482 		case IRE_IF_NORESOLVER: {
8483 
8484 			if (dst_ill->ill_phys_addr_length != IP_ADDR_LEN &&
8485 			    dst_ill->ill_resolver_mp == NULL) {
8486 				ip1dbg(("ip_newroute: dst_ill %p "
8487 				    "for IRE_IF_NORESOLVER ire %p has "
8488 				    "no ill_resolver_mp\n",
8489 				    (void *)dst_ill, (void *)ire));
8490 				break;
8491 			}
8492 
8493 			/*
8494 			 * TSol note: We are creating the ire cache for the
8495 			 * destination 'dst'. If 'dst' is offlink, going
8496 			 * through the first hop 'gw', the security attributes
8497 			 * of 'dst' must be set to point to the gateway
8498 			 * credentials of gateway 'gw'. If 'dst' is onlink, it
8499 			 * is possible that 'dst' is a potential gateway that is
8500 			 * referenced by some route that has some security
8501 			 * attributes. Thus in the former case, we need to do a
8502 			 * gcgrp_lookup of 'gw' while in the latter case we
8503 			 * need to do gcgrp_lookup of 'dst' itself.
8504 			 */
8505 			ga.ga_af = AF_INET;
8506 			IN6_IPADDR_TO_V4MAPPED(gw != INADDR_ANY ? gw : dst,
8507 			    &ga.ga_addr);
8508 			gcgrp = gcgrp_lookup(&ga, B_FALSE);
8509 
8510 			ire = ire_create(
8511 			    (uchar_t *)&dst,		/* dest address */
8512 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8513 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8514 			    (uchar_t *)&gw,		/* gateway address */
8515 			    &save_ire->ire_max_frag,
8516 			    NULL,			/* no src nce */
8517 			    dst_ill->ill_rq,		/* recv-from queue */
8518 			    dst_ill->ill_wq,		/* send-to queue */
8519 			    IRE_CACHE,
8520 			    src_ipif,
8521 			    save_ire->ire_mask,		/* Parent mask */
8522 			    (sire != NULL) ?		/* Parent handle */
8523 			    sire->ire_phandle : 0,
8524 			    save_ire->ire_ihandle,	/* Interface handle */
8525 			    (sire != NULL) ? sire->ire_flags &
8526 			    (RTF_SETSRC | RTF_MULTIRT) : 0, /* flags */
8527 			    &(save_ire->ire_uinfo),
8528 			    NULL,
8529 			    gcgrp,
8530 			    ipst);
8531 
8532 			if (ire == NULL) {
8533 				if (gcgrp != NULL) {
8534 					GCGRP_REFRELE(gcgrp);
8535 					gcgrp = NULL;
8536 				}
8537 				ire_refrele(save_ire);
8538 				break;
8539 			}
8540 
8541 			/* reference now held by IRE */
8542 			gcgrp = NULL;
8543 
8544 			ire->ire_marks |= ire_marks;
8545 
8546 			/* Prevent save_ire from getting deleted */
8547 			IRB_REFHOLD(save_ire->ire_bucket);
8548 			/* Has it been removed already ? */
8549 			if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
8550 				IRB_REFRELE(save_ire->ire_bucket);
8551 				ire_refrele(save_ire);
8552 				break;
8553 			}
8554 
8555 			/*
8556 			 * In the case of multirouting, a copy
8557 			 * of the packet is made before it is sent.
8558 			 * The copy is used in the next
8559 			 * loop to attempt another resolution.
8560 			 */
8561 			xmit_mp = first_mp;
8562 			if ((sire != NULL) &&
8563 			    (sire->ire_flags & RTF_MULTIRT)) {
8564 				copy_mp = copymsg(first_mp);
8565 				if (copy_mp != NULL) {
8566 					xmit_mp = copy_mp;
8567 					MULTIRT_DEBUG_TAG(first_mp);
8568 				}
8569 			}
8570 			ire_add_then_send(q, ire, xmit_mp);
8571 
8572 			/* Assert that it is not deleted yet. */
8573 			ASSERT(save_ire->ire_ptpn != NULL);
8574 			IRB_REFRELE(save_ire->ire_bucket);
8575 			ire_refrele(save_ire);
8576 
8577 			if (copy_mp != NULL) {
8578 				/*
8579 				 * If we found a (no)resolver, we ignore any
8580 				 * trailing top priority IRE_CACHE in further
8581 				 * loops. This ensures that we do not omit any
8582 				 * (no)resolver.
8583 				 * This IRE_CACHE, if any, will be processed
8584 				 * by another thread entering ip_newroute().
8585 				 * IRE_CACHE entries, if any, will be processed
8586 				 * by another thread entering ip_newroute(),
8587 				 * (upon resolver response, for instance).
8588 				 * This aims to force parallel multirt
8589 				 * resolutions as soon as a packet must be sent.
8590 				 * In the best case, after the tx of only one
8591 				 * packet, all reachable routes are resolved.
8592 				 * Otherwise, the resolution of all RTF_MULTIRT
8593 				 * routes would require several emissions.
8594 				 */
8595 				multirt_flags &= ~MULTIRT_CACHEGW;
8596 
8597 				/*
8598 				 * Search for the next unresolved multirt
8599 				 * route.
8600 				 */
8601 				copy_mp = NULL;
8602 				save_ire = NULL;
8603 				ire = NULL;
8604 				multirt_resolve_next = B_TRUE;
8605 				continue;
8606 			}
8607 
8608 			/*
8609 			 * Don't need sire anymore
8610 			 */
8611 			if (sire != NULL)
8612 				ire_refrele(sire);
8613 
8614 			ipif_refrele(src_ipif);
8615 			ill_refrele(dst_ill);
8616 			return;
8617 		}
8618 		case IRE_IF_RESOLVER:
8619 			/*
8620 			 * We can't build an IRE_CACHE yet, but at least we
8621 			 * found a resolver that can help.
8622 			 */
8623 			res_mp = dst_ill->ill_resolver_mp;
8624 			if (!OK_RESOLVER_MP(res_mp))
8625 				break;
8626 
8627 			/*
8628 			 * To be at this point in the code with a non-zero gw
8629 			 * means that dst is reachable through a gateway that
8630 			 * we have never resolved.  By changing dst to the gw
8631 			 * addr we resolve the gateway first.
8632 			 * When ire_add_then_send() tries to put the IP dg
8633 			 * to dst, it will reenter ip_newroute() at which
8634 			 * time we will find the IRE_CACHE for the gw and
8635 			 * create another IRE_CACHE in case IRE_CACHE above.
8636 			 */
8637 			if (gw != INADDR_ANY) {
8638 				/*
8639 				 * The source ipif that was determined above was
8640 				 * relative to the destination address, not the
8641 				 * gateway's. If src_ipif was not taken out of
8642 				 * the IRE_IF_RESOLVER entry, we'll need to call
8643 				 * ipif_select_source() again.
8644 				 */
8645 				if (src_ipif != ire->ire_ipif) {
8646 					ipif_refrele(src_ipif);
8647 					src_ipif = ipif_select_source(dst_ill,
8648 					    gw, zoneid);
8649 					if (src_ipif == NULL) {
8650 						if (ip_debug > 2) {
8651 							pr_addr_dbg(
8652 							    "ip_newroute: no "
8653 							    "src for gw %s ",
8654 							    AF_INET, &gw);
8655 							printf("through "
8656 							    "interface %s\n",
8657 							    dst_ill->ill_name);
8658 						}
8659 						goto icmp_err_ret;
8660 					}
8661 				}
8662 				save_dst = dst;
8663 				dst = gw;
8664 				gw = INADDR_ANY;
8665 			}
8666 
8667 			/*
8668 			 * We obtain a partial IRE_CACHE which we will pass
8669 			 * along with the resolver query.  When the response
8670 			 * comes back it will be there ready for us to add.
8671 			 * The ire_max_frag is atomically set under the
8672 			 * irebucket lock in ire_add_v[46].
8673 			 */
8674 
8675 			ire = ire_create_mp(
8676 			    (uchar_t *)&dst,		/* dest address */
8677 			    (uchar_t *)&ip_g_all_ones,	/* mask */
8678 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
8679 			    (uchar_t *)&gw,		/* gateway address */
8680 			    NULL,			/* ire_max_frag */
8681 			    NULL,			/* no src nce */
8682 			    dst_ill->ill_rq,		/* recv-from queue */
8683 			    dst_ill->ill_wq,		/* send-to queue */
8684 			    IRE_CACHE,
8685 			    src_ipif,			/* Interface ipif */
8686 			    save_ire->ire_mask,		/* Parent mask */
8687 			    0,
8688 			    save_ire->ire_ihandle,	/* Interface handle */
8689 			    0,				/* flags if any */
8690 			    &(save_ire->ire_uinfo),
8691 			    NULL,
8692 			    NULL,
8693 			    ipst);
8694 
8695 			if (ire == NULL) {
8696 				ire_refrele(save_ire);
8697 				break;
8698 			}
8699 
8700 			if ((sire != NULL) &&
8701 			    (sire->ire_flags & RTF_MULTIRT)) {
8702 				copy_mp = copymsg(first_mp);
8703 				if (copy_mp != NULL)
8704 					MULTIRT_DEBUG_TAG(copy_mp);
8705 			}
8706 
8707 			ire->ire_marks |= ire_marks;
8708 
8709 			/*
8710 			 * Construct message chain for the resolver
8711 			 * of the form:
8712 			 * 	ARP_REQ_MBLK-->IRE_MBLK-->Packet
8713 			 * Packet could contain a IPSEC_OUT mp.
8714 			 *
8715 			 * NOTE : ire will be added later when the response
8716 			 * comes back from ARP. If the response does not
8717 			 * come back, ARP frees the packet. For this reason,
8718 			 * we can't REFHOLD the bucket of save_ire to prevent
8719 			 * deletions. We may not be able to REFRELE the bucket
8720 			 * if the response never comes back. Thus, before
8721 			 * adding the ire, ire_add_v4 will make sure that the
8722 			 * interface route does not get deleted. This is the
8723 			 * only case unlike ip_newroute_v6, ip_newroute_ipif_v6
8724 			 * where we can always prevent deletions because of
8725 			 * the synchronous nature of adding IRES i.e
8726 			 * ire_add_then_send is called after creating the IRE.
8727 			 */
8728 			ASSERT(ire->ire_mp != NULL);
8729 			ire->ire_mp->b_cont = first_mp;
8730 			/* Have saved_mp handy, for cleanup if canput fails */
8731 			saved_mp = mp;
8732 			mp = copyb(res_mp);
8733 			if (mp == NULL) {
8734 				/* Prepare for cleanup */
8735 				mp = saved_mp; /* pkt */
8736 				ire_delete(ire); /* ire_mp */
8737 				ire = NULL;
8738 				ire_refrele(save_ire);
8739 				if (copy_mp != NULL) {
8740 					MULTIRT_DEBUG_UNTAG(copy_mp);
8741 					freemsg(copy_mp);
8742 					copy_mp = NULL;
8743 				}
8744 				break;
8745 			}
8746 			linkb(mp, ire->ire_mp);
8747 
8748 			/*
8749 			 * Fill in the source and dest addrs for the resolver.
8750 			 * NOTE: this depends on memory layouts imposed by
8751 			 * ill_init().
8752 			 */
8753 			areq = (areq_t *)mp->b_rptr;
8754 			addrp = (ipaddr_t *)((char *)areq +
8755 			    areq->areq_sender_addr_offset);
8756 			if (do_attach_ill) {
8757 				/*
8758 				 * This is bind to no failover case.
8759 				 * arp packet also must go out on attach_ill.
8760 				 */
8761 				ASSERT(ipha->ipha_src != NULL);
8762 				*addrp = ipha->ipha_src;
8763 			} else {
8764 				*addrp = save_ire->ire_src_addr;
8765 			}
8766 
8767 			ire_refrele(save_ire);
8768 			addrp = (ipaddr_t *)((char *)areq +
8769 			    areq->areq_target_addr_offset);
8770 			*addrp = dst;
8771 			/* Up to the resolver. */
8772 			if (canputnext(dst_ill->ill_rq) &&
8773 			    !(dst_ill->ill_arp_closing)) {
8774 				putnext(dst_ill->ill_rq, mp);
8775 				ire = NULL;
8776 				if (copy_mp != NULL) {
8777 					/*
8778 					 * If we found a resolver, we ignore
8779 					 * any trailing top priority IRE_CACHE
8780 					 * in the further loops. This ensures
8781 					 * that we do not omit any resolver.
8782 					 * IRE_CACHE entries, if any, will be
8783 					 * processed next time we enter
8784 					 * ip_newroute().
8785 					 */
8786 					multirt_flags &= ~MULTIRT_CACHEGW;
8787 					/*
8788 					 * Search for the next unresolved
8789 					 * multirt route.
8790 					 */
8791 					first_mp = copy_mp;
8792 					copy_mp = NULL;
8793 					/* Prepare the next resolution loop. */
8794 					mp = first_mp;
8795 					EXTRACT_PKT_MP(mp, first_mp,
8796 					    mctl_present);
8797 					if (mctl_present)
8798 						io = (ipsec_out_t *)
8799 						    first_mp->b_rptr;
8800 					ipha = (ipha_t *)mp->b_rptr;
8801 
8802 					ASSERT(sire != NULL);
8803 
8804 					dst = save_dst;
8805 					multirt_resolve_next = B_TRUE;
8806 					continue;
8807 				}
8808 
8809 				if (sire != NULL)
8810 					ire_refrele(sire);
8811 
8812 				/*
8813 				 * The response will come back in ip_wput
8814 				 * with db_type IRE_DB_TYPE.
8815 				 */
8816 				ipif_refrele(src_ipif);
8817 				ill_refrele(dst_ill);
8818 				return;
8819 			} else {
8820 				/* Prepare for cleanup */
8821 				DTRACE_PROBE1(ip__newroute__drop, mblk_t *,
8822 				    mp);
8823 				mp->b_cont = NULL;
8824 				freeb(mp); /* areq */
8825 				/*
8826 				 * this is an ire that is not added to the
8827 				 * cache. ire_freemblk will handle the release
8828 				 * of any resources associated with the ire.
8829 				 */
8830 				ire_delete(ire); /* ire_mp */
8831 				mp = saved_mp; /* pkt */
8832 				ire = NULL;
8833 				if (copy_mp != NULL) {
8834 					MULTIRT_DEBUG_UNTAG(copy_mp);
8835 					freemsg(copy_mp);
8836 					copy_mp = NULL;
8837 				}
8838 				break;
8839 			}
8840 		default:
8841 			break;
8842 		}
8843 	} while (multirt_resolve_next);
8844 
8845 	ip1dbg(("ip_newroute: dropped\n"));
8846 	/* Did this packet originate externally? */
8847 	if (mp->b_prev) {
8848 		mp->b_next = NULL;
8849 		mp->b_prev = NULL;
8850 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInDiscards);
8851 	} else {
8852 		if (dst_ill != NULL) {
8853 			BUMP_MIB(dst_ill->ill_ip_mib, ipIfStatsOutDiscards);
8854 		} else {
8855 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
8856 		}
8857 	}
8858 	ASSERT(copy_mp == NULL);
8859 	MULTIRT_DEBUG_UNTAG(first_mp);
8860 	freemsg(first_mp);
8861 	if (ire != NULL)
8862 		ire_refrele(ire);
8863 	if (sire != NULL)
8864 		ire_refrele(sire);
8865 	if (src_ipif != NULL)
8866 		ipif_refrele(src_ipif);
8867 	if (dst_ill != NULL)
8868 		ill_refrele(dst_ill);
8869 	return;
8870 
8871 icmp_err_ret:
8872 	ip1dbg(("ip_newroute: no route\n"));
8873 	if (src_ipif != NULL)
8874 		ipif_refrele(src_ipif);
8875 	if (dst_ill != NULL)
8876 		ill_refrele(dst_ill);
8877 	if (sire != NULL)
8878 		ire_refrele(sire);
8879 	/* Did this packet originate externally? */
8880 	if (mp->b_prev) {
8881 		mp->b_next = NULL;
8882 		mp->b_prev = NULL;
8883 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsInNoRoutes);
8884 		q = WR(q);
8885 	} else {
8886 		/*
8887 		 * There is no outgoing ill, so just increment the
8888 		 * system MIB.
8889 		 */
8890 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
8891 		/*
8892 		 * Since ip_wput() isn't close to finished, we fill
8893 		 * in enough of the header for credible error reporting.
8894 		 */
8895 		if (ip_hdr_complete(ipha, zoneid, ipst)) {
8896 			/* Failed */
8897 			MULTIRT_DEBUG_UNTAG(first_mp);
8898 			freemsg(first_mp);
8899 			if (ire != NULL)
8900 				ire_refrele(ire);
8901 			return;
8902 		}
8903 	}
8904 
8905 	/*
8906 	 * At this point we will have ire only if RTF_BLACKHOLE
8907 	 * or RTF_REJECT flags are set on the IRE. It will not
8908 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
8909 	 */
8910 	if (ire != NULL) {
8911 		if (ire->ire_flags & RTF_BLACKHOLE) {
8912 			ire_refrele(ire);
8913 			MULTIRT_DEBUG_UNTAG(first_mp);
8914 			freemsg(first_mp);
8915 			return;
8916 		}
8917 		ire_refrele(ire);
8918 	}
8919 	if (ip_source_routed(ipha, ipst)) {
8920 		icmp_unreachable(q, first_mp, ICMP_SOURCE_ROUTE_FAILED,
8921 		    zoneid, ipst);
8922 		return;
8923 	}
8924 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
8925 }
8926 
8927 ip_opt_info_t zero_info;
8928 
8929 /*
8930  * IPv4 -
8931  * ip_newroute_ipif is called by ip_wput_multicast and
8932  * ip_rput_forward_multicast whenever we need to send
8933  * out a packet to a destination address for which we do not have specific
8934  * routing information. It is used when the packet will be sent out
8935  * on a specific interface. It is also called by ip_wput() when IP_BOUND_IF
8936  * socket option is set or icmp error message wants to go out on a particular
8937  * interface for a unicast packet.
8938  *
8939  * In most cases, the destination address is resolved thanks to the ipif
8940  * intrinsic resolver. However, there are some cases where the call to
8941  * ip_newroute_ipif must take into account the potential presence of
8942  * RTF_SETSRC and/or RTF_MULITRT flags in an IRE_OFFSUBNET ire
8943  * that uses the interface. This is specified through flags,
8944  * which can be a combination of:
8945  * - RTF_SETSRC: if an IRE_OFFSUBNET ire exists that has the RTF_SETSRC
8946  *   flag, the resulting ire will inherit the IRE_OFFSUBNET source address
8947  *   and flags. Additionally, the packet source address has to be set to
8948  *   the specified address. The caller is thus expected to set this flag
8949  *   if the packet has no specific source address yet.
8950  * - RTF_MULTIRT: if an IRE_OFFSUBNET ire exists that has the RTF_MULTIRT
8951  *   flag, the resulting ire will inherit the flag. All unresolved routes
8952  *   to the destination must be explored in the same call to
8953  *   ip_newroute_ipif().
8954  */
8955 static void
8956 ip_newroute_ipif(queue_t *q, mblk_t *mp, ipif_t *ipif, ipaddr_t dst,
8957     conn_t *connp, uint32_t flags, zoneid_t zoneid, ip_opt_info_t *infop)
8958 {
8959 	areq_t	*areq;
8960 	ire_t	*ire = NULL;
8961 	mblk_t	*res_mp;
8962 	ipaddr_t *addrp;
8963 	mblk_t *first_mp;
8964 	ire_t	*save_ire = NULL;
8965 	ill_t	*attach_ill = NULL;		/* Bind to IPIF_NOFAILOVER */
8966 	ipif_t	*src_ipif = NULL;
8967 	ushort_t ire_marks = 0;
8968 	ill_t	*dst_ill = NULL;
8969 	boolean_t mctl_present;
8970 	ipsec_out_t *io;
8971 	ipha_t *ipha;
8972 	int	ihandle = 0;
8973 	mblk_t	*saved_mp;
8974 	ire_t   *fire = NULL;
8975 	mblk_t  *copy_mp = NULL;
8976 	boolean_t multirt_resolve_next;
8977 	boolean_t unspec_src;
8978 	ipaddr_t ipha_dst;
8979 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
8980 
8981 	/*
8982 	 * CGTP goes in a loop which looks up a new ipif, do an ipif_refhold
8983 	 * here for uniformity
8984 	 */
8985 	ipif_refhold(ipif);
8986 
8987 	/*
8988 	 * This loop is run only once in most cases.
8989 	 * We loop to resolve further routes only when the destination
8990 	 * can be reached through multiple RTF_MULTIRT-flagged ires.
8991 	 */
8992 	do {
8993 		if (dst_ill != NULL) {
8994 			ill_refrele(dst_ill);
8995 			dst_ill = NULL;
8996 		}
8997 		if (src_ipif != NULL) {
8998 			ipif_refrele(src_ipif);
8999 			src_ipif = NULL;
9000 		}
9001 		multirt_resolve_next = B_FALSE;
9002 
9003 		ip1dbg(("ip_newroute_ipif: dst 0x%x, if %s\n", ntohl(dst),
9004 		    ipif->ipif_ill->ill_name));
9005 
9006 		EXTRACT_PKT_MP(mp, first_mp, mctl_present);
9007 		if (mctl_present)
9008 			io = (ipsec_out_t *)first_mp->b_rptr;
9009 
9010 		ipha = (ipha_t *)mp->b_rptr;
9011 
9012 		/*
9013 		 * Save the packet destination address, we may need it after
9014 		 * the packet has been consumed.
9015 		 */
9016 		ipha_dst = ipha->ipha_dst;
9017 
9018 		/*
9019 		 * If the interface is a pt-pt interface we look for an
9020 		 * IRE_IF_RESOLVER or IRE_IF_NORESOLVER that matches both the
9021 		 * local_address and the pt-pt destination address. Otherwise
9022 		 * we just match the local address.
9023 		 * NOTE: dst could be different than ipha->ipha_dst in case
9024 		 * of sending igmp multicast packets over a point-to-point
9025 		 * connection.
9026 		 * Thus we must be careful enough to check ipha_dst to be a
9027 		 * multicast address, otherwise it will take xmit_if path for
9028 		 * multicast packets resulting into kernel stack overflow by
9029 		 * repeated calls to ip_newroute_ipif from ire_send().
9030 		 */
9031 		if (CLASSD(ipha_dst) &&
9032 		    !(ipif->ipif_ill->ill_flags & ILLF_MULTICAST)) {
9033 			goto err_ret;
9034 		}
9035 
9036 		/*
9037 		 * We check if an IRE_OFFSUBNET for the addr that goes through
9038 		 * ipif exists. We need it to determine if the RTF_SETSRC and/or
9039 		 * RTF_MULTIRT flags must be honored. This IRE_OFFSUBNET ire may
9040 		 * propagate its flags to the new ire.
9041 		 */
9042 		if (CLASSD(ipha_dst) && (flags & (RTF_MULTIRT | RTF_SETSRC))) {
9043 			fire = ipif_lookup_multi_ire(ipif, ipha_dst);
9044 			ip2dbg(("ip_newroute_ipif: "
9045 			    "ipif_lookup_multi_ire("
9046 			    "ipif %p, dst %08x) = fire %p\n",
9047 			    (void *)ipif, ntohl(dst), (void *)fire));
9048 		}
9049 
9050 		if (mctl_present && io->ipsec_out_attach_if) {
9051 			attach_ill = ip_grab_attach_ill(NULL, first_mp,
9052 			    io->ipsec_out_ill_index, B_FALSE, ipst);
9053 
9054 			/* Failure case frees things for us. */
9055 			if (attach_ill == NULL) {
9056 				ipif_refrele(ipif);
9057 				if (fire != NULL)
9058 					ire_refrele(fire);
9059 				return;
9060 			}
9061 
9062 			/*
9063 			 * Check if we need an ire that will not be
9064 			 * looked up by anybody else i.e. HIDDEN.
9065 			 */
9066 			if (ill_is_probeonly(attach_ill)) {
9067 				ire_marks = IRE_MARK_HIDDEN;
9068 			}
9069 			/*
9070 			 * ip_wput passes the right ipif for IPIF_NOFAILOVER
9071 			 * case.
9072 			 */
9073 			dst_ill = ipif->ipif_ill;
9074 			/* attach_ill has been refheld by ip_grab_attach_ill */
9075 			ASSERT(dst_ill == attach_ill);
9076 		} else {
9077 			/*
9078 			 * If the interface belongs to an interface group,
9079 			 * make sure the next possible interface in the group
9080 			 * is used.  This encourages load spreading among
9081 			 * peers in an interface group.
9082 			 * Note: load spreading is disabled for RTF_MULTIRT
9083 			 * routes.
9084 			 */
9085 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9086 			    (fire->ire_flags & RTF_MULTIRT)) {
9087 				/*
9088 				 * Don't perform outbound load spreading
9089 				 * in the case of an RTF_MULTIRT issued route,
9090 				 * we actually typically want to replicate
9091 				 * outgoing packets through particular
9092 				 * interfaces.
9093 				 */
9094 				dst_ill = ipif->ipif_ill;
9095 				ill_refhold(dst_ill);
9096 			} else {
9097 				dst_ill = ip_newroute_get_dst_ill(
9098 				    ipif->ipif_ill);
9099 			}
9100 			if (dst_ill == NULL) {
9101 				if (ip_debug > 2) {
9102 					pr_addr_dbg("ip_newroute_ipif: "
9103 					    "no dst ill for dst %s\n",
9104 					    AF_INET, &dst);
9105 				}
9106 				goto err_ret;
9107 			}
9108 		}
9109 
9110 		/*
9111 		 * Pick a source address preferring non-deprecated ones.
9112 		 * Unlike ip_newroute, we don't do any source address
9113 		 * selection here since for multicast it really does not help
9114 		 * in inbound load spreading as in the unicast case.
9115 		 */
9116 		if ((flags & RTF_SETSRC) && (fire != NULL) &&
9117 		    (fire->ire_flags & RTF_SETSRC)) {
9118 			/*
9119 			 * As requested by flags, an IRE_OFFSUBNET was looked up
9120 			 * on that interface. This ire has RTF_SETSRC flag, so
9121 			 * the source address of the packet must be changed.
9122 			 * Check that the ipif matching the requested source
9123 			 * address still exists.
9124 			 */
9125 			src_ipif = ipif_lookup_addr(fire->ire_src_addr, NULL,
9126 			    zoneid, NULL, NULL, NULL, NULL, ipst);
9127 		}
9128 
9129 		unspec_src = (connp != NULL && connp->conn_unspec_src);
9130 
9131 		if (((!ipif->ipif_isv6 && ipif->ipif_lcl_addr == INADDR_ANY) ||
9132 		    (ipif->ipif_flags & (IPIF_DEPRECATED|IPIF_UP)) != IPIF_UP ||
9133 		    (connp != NULL && ipif->ipif_zoneid != zoneid &&
9134 		    ipif->ipif_zoneid != ALL_ZONES)) &&
9135 		    (src_ipif == NULL) &&
9136 		    (!unspec_src || ipha->ipha_src != INADDR_ANY)) {
9137 			src_ipif = ipif_select_source(dst_ill, dst, zoneid);
9138 			if (src_ipif == NULL) {
9139 				if (ip_debug > 2) {
9140 					/* ip1dbg */
9141 					pr_addr_dbg("ip_newroute_ipif: "
9142 					    "no src for dst %s",
9143 					    AF_INET, &dst);
9144 				}
9145 				ip1dbg((" through interface %s\n",
9146 				    dst_ill->ill_name));
9147 				goto err_ret;
9148 			}
9149 			ipif_refrele(ipif);
9150 			ipif = src_ipif;
9151 			ipif_refhold(ipif);
9152 		}
9153 		if (src_ipif == NULL) {
9154 			src_ipif = ipif;
9155 			ipif_refhold(src_ipif);
9156 		}
9157 
9158 		/*
9159 		 * Assign a source address while we have the conn.
9160 		 * We can't have ip_wput_ire pick a source address when the
9161 		 * packet returns from arp since conn_unspec_src might be set
9162 		 * and we lose the conn when going through arp.
9163 		 */
9164 		if (ipha->ipha_src == INADDR_ANY && !unspec_src)
9165 			ipha->ipha_src = src_ipif->ipif_src_addr;
9166 
9167 		/*
9168 		 * In the case of IP_BOUND_IF and IP_PKTINFO, it is possible
9169 		 * that the outgoing interface does not have an interface ire.
9170 		 */
9171 		if (CLASSD(ipha_dst) && (connp == NULL ||
9172 		    connp->conn_outgoing_ill == NULL) &&
9173 		    infop->ip_opt_ill_index == 0) {
9174 			/* ipif_to_ire returns an held ire */
9175 			ire = ipif_to_ire(ipif);
9176 			if (ire == NULL)
9177 				goto err_ret;
9178 			if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
9179 				goto err_ret;
9180 			/*
9181 			 * ihandle is needed when the ire is added to
9182 			 * cache table.
9183 			 */
9184 			save_ire = ire;
9185 			ihandle = save_ire->ire_ihandle;
9186 
9187 			ip2dbg(("ip_newroute_ipif: ire %p, ipif %p, "
9188 			    "flags %04x\n",
9189 			    (void *)ire, (void *)ipif, flags));
9190 			if ((flags & RTF_MULTIRT) && (fire != NULL) &&
9191 			    (fire->ire_flags & RTF_MULTIRT)) {
9192 				/*
9193 				 * As requested by flags, an IRE_OFFSUBNET was
9194 				 * looked up on that interface. This ire has
9195 				 * RTF_MULTIRT flag, so the resolution loop will
9196 				 * be re-entered to resolve additional routes on
9197 				 * other interfaces. For that purpose, a copy of
9198 				 * the packet is performed at this point.
9199 				 */
9200 				fire->ire_last_used_time = lbolt;
9201 				copy_mp = copymsg(first_mp);
9202 				if (copy_mp) {
9203 					MULTIRT_DEBUG_TAG(copy_mp);
9204 				}
9205 			}
9206 			if ((flags & RTF_SETSRC) && (fire != NULL) &&
9207 			    (fire->ire_flags & RTF_SETSRC)) {
9208 				/*
9209 				 * As requested by flags, an IRE_OFFSUBET was
9210 				 * looked up on that interface. This ire has
9211 				 * RTF_SETSRC flag, so the source address of the
9212 				 * packet must be changed.
9213 				 */
9214 				ipha->ipha_src = fire->ire_src_addr;
9215 			}
9216 		} else {
9217 			ASSERT((connp == NULL) ||
9218 			    (connp->conn_outgoing_ill != NULL) ||
9219 			    (connp->conn_dontroute) ||
9220 			    infop->ip_opt_ill_index != 0);
9221 			/*
9222 			 * The only ways we can come here are:
9223 			 * 1) IP_BOUND_IF socket option is set
9224 			 * 2) SO_DONTROUTE socket option is set
9225 			 * 3) IP_PKTINFO option is passed in as ancillary data.
9226 			 * In all cases, the new ire will not be added
9227 			 * into cache table.
9228 			 */
9229 			ire_marks |= IRE_MARK_NOADD;
9230 		}
9231 
9232 		switch (ipif->ipif_net_type) {
9233 		case IRE_IF_NORESOLVER: {
9234 			/* We have what we need to build an IRE_CACHE. */
9235 
9236 			if ((dst_ill->ill_phys_addr_length != IP_ADDR_LEN) &&
9237 			    (dst_ill->ill_resolver_mp == NULL)) {
9238 				ip1dbg(("ip_newroute_ipif: dst_ill %p "
9239 				    "for IRE_IF_NORESOLVER ire %p has "
9240 				    "no ill_resolver_mp\n",
9241 				    (void *)dst_ill, (void *)ire));
9242 				break;
9243 			}
9244 
9245 			/*
9246 			 * The new ire inherits the IRE_OFFSUBNET flags
9247 			 * and source address, if this was requested.
9248 			 */
9249 			ire = ire_create(
9250 			    (uchar_t *)&dst,		/* dest address */
9251 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9252 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9253 			    NULL,			/* gateway address */
9254 			    &ipif->ipif_mtu,
9255 			    NULL,			/* no src nce */
9256 			    dst_ill->ill_rq,		/* recv-from queue */
9257 			    dst_ill->ill_wq,		/* send-to queue */
9258 			    IRE_CACHE,
9259 			    src_ipif,
9260 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9261 			    (fire != NULL) ?		/* Parent handle */
9262 			    fire->ire_phandle : 0,
9263 			    ihandle,			/* Interface handle */
9264 			    (fire != NULL) ?
9265 			    (fire->ire_flags &
9266 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9267 			    (save_ire == NULL ? &ire_uinfo_null :
9268 			    &save_ire->ire_uinfo),
9269 			    NULL,
9270 			    NULL,
9271 			    ipst);
9272 
9273 			if (ire == NULL) {
9274 				if (save_ire != NULL)
9275 					ire_refrele(save_ire);
9276 				break;
9277 			}
9278 
9279 			ire->ire_marks |= ire_marks;
9280 
9281 			/*
9282 			 * If IRE_MARK_NOADD is set then we need to convert
9283 			 * the max_fragp to a useable value now. This is
9284 			 * normally done in ire_add_v[46]. We also need to
9285 			 * associate the ire with an nce (normally would be
9286 			 * done in ip_wput_nondata()).
9287 			 *
9288 			 * Note that IRE_MARK_NOADD packets created here
9289 			 * do not have a non-null ire_mp pointer. The null
9290 			 * value of ire_bucket indicates that they were
9291 			 * never added.
9292 			 */
9293 			if (ire->ire_marks & IRE_MARK_NOADD) {
9294 				uint_t  max_frag;
9295 
9296 				max_frag = *ire->ire_max_fragp;
9297 				ire->ire_max_fragp = NULL;
9298 				ire->ire_max_frag = max_frag;
9299 
9300 				if ((ire->ire_nce = ndp_lookup_v4(
9301 				    ire_to_ill(ire),
9302 				    (ire->ire_gateway_addr != INADDR_ANY ?
9303 				    &ire->ire_gateway_addr : &ire->ire_addr),
9304 				    B_FALSE)) == NULL) {
9305 					if (save_ire != NULL)
9306 						ire_refrele(save_ire);
9307 					break;
9308 				}
9309 				ASSERT(ire->ire_nce->nce_state ==
9310 				    ND_REACHABLE);
9311 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
9312 			}
9313 
9314 			/* Prevent save_ire from getting deleted */
9315 			if (save_ire != NULL) {
9316 				IRB_REFHOLD(save_ire->ire_bucket);
9317 				/* Has it been removed already ? */
9318 				if (save_ire->ire_marks & IRE_MARK_CONDEMNED) {
9319 					IRB_REFRELE(save_ire->ire_bucket);
9320 					ire_refrele(save_ire);
9321 					break;
9322 				}
9323 			}
9324 
9325 			ire_add_then_send(q, ire, first_mp);
9326 
9327 			/* Assert that save_ire is not deleted yet. */
9328 			if (save_ire != NULL) {
9329 				ASSERT(save_ire->ire_ptpn != NULL);
9330 				IRB_REFRELE(save_ire->ire_bucket);
9331 				ire_refrele(save_ire);
9332 				save_ire = NULL;
9333 			}
9334 			if (fire != NULL) {
9335 				ire_refrele(fire);
9336 				fire = NULL;
9337 			}
9338 
9339 			/*
9340 			 * the resolution loop is re-entered if this
9341 			 * was requested through flags and if we
9342 			 * actually are in a multirouting case.
9343 			 */
9344 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9345 				boolean_t need_resolve =
9346 				    ire_multirt_need_resolve(ipha_dst,
9347 				    MBLK_GETLABEL(copy_mp), ipst);
9348 				if (!need_resolve) {
9349 					MULTIRT_DEBUG_UNTAG(copy_mp);
9350 					freemsg(copy_mp);
9351 					copy_mp = NULL;
9352 				} else {
9353 					/*
9354 					 * ipif_lookup_group() calls
9355 					 * ire_lookup_multi() that uses
9356 					 * ire_ftable_lookup() to find
9357 					 * an IRE_INTERFACE for the group.
9358 					 * In the multirt case,
9359 					 * ire_lookup_multi() then invokes
9360 					 * ire_multirt_lookup() to find
9361 					 * the next resolvable ire.
9362 					 * As a result, we obtain an new
9363 					 * interface, derived from the
9364 					 * next ire.
9365 					 */
9366 					ipif_refrele(ipif);
9367 					ipif = ipif_lookup_group(ipha_dst,
9368 					    zoneid, ipst);
9369 					ip2dbg(("ip_newroute_ipif: "
9370 					    "multirt dst %08x, ipif %p\n",
9371 					    htonl(dst), (void *)ipif));
9372 					if (ipif != NULL) {
9373 						mp = copy_mp;
9374 						copy_mp = NULL;
9375 						multirt_resolve_next = B_TRUE;
9376 						continue;
9377 					} else {
9378 						freemsg(copy_mp);
9379 					}
9380 				}
9381 			}
9382 			if (ipif != NULL)
9383 				ipif_refrele(ipif);
9384 			ill_refrele(dst_ill);
9385 			ipif_refrele(src_ipif);
9386 			return;
9387 		}
9388 		case IRE_IF_RESOLVER:
9389 			/*
9390 			 * We can't build an IRE_CACHE yet, but at least
9391 			 * we found a resolver that can help.
9392 			 */
9393 			res_mp = dst_ill->ill_resolver_mp;
9394 			if (!OK_RESOLVER_MP(res_mp))
9395 				break;
9396 
9397 			/*
9398 			 * We obtain a partial IRE_CACHE which we will pass
9399 			 * along with the resolver query.  When the response
9400 			 * comes back it will be there ready for us to add.
9401 			 * The new ire inherits the IRE_OFFSUBNET flags
9402 			 * and source address, if this was requested.
9403 			 * The ire_max_frag is atomically set under the
9404 			 * irebucket lock in ire_add_v[46]. Only in the
9405 			 * case of IRE_MARK_NOADD, we set it here itself.
9406 			 */
9407 			ire = ire_create_mp(
9408 			    (uchar_t *)&dst,		/* dest address */
9409 			    (uchar_t *)&ip_g_all_ones,	/* mask */
9410 			    (uchar_t *)&src_ipif->ipif_src_addr, /* src addr */
9411 			    NULL,			/* gateway address */
9412 			    (ire_marks & IRE_MARK_NOADD) ?
9413 			    ipif->ipif_mtu : 0,		/* max_frag */
9414 			    NULL,			/* no src nce */
9415 			    dst_ill->ill_rq,		/* recv-from queue */
9416 			    dst_ill->ill_wq,		/* send-to queue */
9417 			    IRE_CACHE,
9418 			    src_ipif,
9419 			    (save_ire != NULL ? save_ire->ire_mask : 0),
9420 			    (fire != NULL) ?		/* Parent handle */
9421 			    fire->ire_phandle : 0,
9422 			    ihandle,			/* Interface handle */
9423 			    (fire != NULL) ?		/* flags if any */
9424 			    (fire->ire_flags &
9425 			    (RTF_SETSRC | RTF_MULTIRT)) : 0,
9426 			    (save_ire == NULL ? &ire_uinfo_null :
9427 			    &save_ire->ire_uinfo),
9428 			    NULL,
9429 			    NULL,
9430 			    ipst);
9431 
9432 			if (save_ire != NULL) {
9433 				ire_refrele(save_ire);
9434 				save_ire = NULL;
9435 			}
9436 			if (ire == NULL)
9437 				break;
9438 
9439 			ire->ire_marks |= ire_marks;
9440 			/*
9441 			 * Construct message chain for the resolver of the
9442 			 * form:
9443 			 *	ARP_REQ_MBLK-->IRE_MBLK-->Packet
9444 			 *
9445 			 * NOTE : ire will be added later when the response
9446 			 * comes back from ARP. If the response does not
9447 			 * come back, ARP frees the packet. For this reason,
9448 			 * we can't REFHOLD the bucket of save_ire to prevent
9449 			 * deletions. We may not be able to REFRELE the
9450 			 * bucket if the response never comes back.
9451 			 * Thus, before adding the ire, ire_add_v4 will make
9452 			 * sure that the interface route does not get deleted.
9453 			 * This is the only case unlike ip_newroute_v6,
9454 			 * ip_newroute_ipif_v6 where we can always prevent
9455 			 * deletions because ire_add_then_send is called after
9456 			 * creating the IRE.
9457 			 * If IRE_MARK_NOADD is set, then ire_add_then_send
9458 			 * does not add this IRE into the IRE CACHE.
9459 			 */
9460 			ASSERT(ire->ire_mp != NULL);
9461 			ire->ire_mp->b_cont = first_mp;
9462 			/* Have saved_mp handy, for cleanup if canput fails */
9463 			saved_mp = mp;
9464 			mp = copyb(res_mp);
9465 			if (mp == NULL) {
9466 				/* Prepare for cleanup */
9467 				mp = saved_mp; /* pkt */
9468 				ire_delete(ire); /* ire_mp */
9469 				ire = NULL;
9470 				if (copy_mp != NULL) {
9471 					MULTIRT_DEBUG_UNTAG(copy_mp);
9472 					freemsg(copy_mp);
9473 					copy_mp = NULL;
9474 				}
9475 				break;
9476 			}
9477 			linkb(mp, ire->ire_mp);
9478 
9479 			/*
9480 			 * Fill in the source and dest addrs for the resolver.
9481 			 * NOTE: this depends on memory layouts imposed by
9482 			 * ill_init().
9483 			 */
9484 			areq = (areq_t *)mp->b_rptr;
9485 			addrp = (ipaddr_t *)((char *)areq +
9486 			    areq->areq_sender_addr_offset);
9487 			*addrp = ire->ire_src_addr;
9488 			addrp = (ipaddr_t *)((char *)areq +
9489 			    areq->areq_target_addr_offset);
9490 			*addrp = dst;
9491 			/* Up to the resolver. */
9492 			if (canputnext(dst_ill->ill_rq) &&
9493 			    !(dst_ill->ill_arp_closing)) {
9494 				putnext(dst_ill->ill_rq, mp);
9495 				/*
9496 				 * The response will come back in ip_wput
9497 				 * with db_type IRE_DB_TYPE.
9498 				 */
9499 			} else {
9500 				mp->b_cont = NULL;
9501 				freeb(mp); /* areq */
9502 				ire_delete(ire); /* ire_mp */
9503 				saved_mp->b_next = NULL;
9504 				saved_mp->b_prev = NULL;
9505 				freemsg(first_mp); /* pkt */
9506 				ip2dbg(("ip_newroute_ipif: dropped\n"));
9507 			}
9508 
9509 			if (fire != NULL) {
9510 				ire_refrele(fire);
9511 				fire = NULL;
9512 			}
9513 
9514 
9515 			/*
9516 			 * The resolution loop is re-entered if this was
9517 			 * requested through flags and we actually are
9518 			 * in a multirouting case.
9519 			 */
9520 			if ((flags & RTF_MULTIRT) && (copy_mp != NULL)) {
9521 				boolean_t need_resolve =
9522 				    ire_multirt_need_resolve(ipha_dst,
9523 				    MBLK_GETLABEL(copy_mp), ipst);
9524 				if (!need_resolve) {
9525 					MULTIRT_DEBUG_UNTAG(copy_mp);
9526 					freemsg(copy_mp);
9527 					copy_mp = NULL;
9528 				} else {
9529 					/*
9530 					 * ipif_lookup_group() calls
9531 					 * ire_lookup_multi() that uses
9532 					 * ire_ftable_lookup() to find
9533 					 * an IRE_INTERFACE for the group.
9534 					 * In the multirt case,
9535 					 * ire_lookup_multi() then invokes
9536 					 * ire_multirt_lookup() to find
9537 					 * the next resolvable ire.
9538 					 * As a result, we obtain an new
9539 					 * interface, derived from the
9540 					 * next ire.
9541 					 */
9542 					ipif_refrele(ipif);
9543 					ipif = ipif_lookup_group(ipha_dst,
9544 					    zoneid, ipst);
9545 					if (ipif != NULL) {
9546 						mp = copy_mp;
9547 						copy_mp = NULL;
9548 						multirt_resolve_next = B_TRUE;
9549 						continue;
9550 					} else {
9551 						freemsg(copy_mp);
9552 					}
9553 				}
9554 			}
9555 			if (ipif != NULL)
9556 				ipif_refrele(ipif);
9557 			ill_refrele(dst_ill);
9558 			ipif_refrele(src_ipif);
9559 			return;
9560 		default:
9561 			break;
9562 		}
9563 	} while (multirt_resolve_next);
9564 
9565 err_ret:
9566 	ip2dbg(("ip_newroute_ipif: dropped\n"));
9567 	if (fire != NULL)
9568 		ire_refrele(fire);
9569 	ipif_refrele(ipif);
9570 	/* Did this packet originate externally? */
9571 	if (dst_ill != NULL)
9572 		ill_refrele(dst_ill);
9573 	if (src_ipif != NULL)
9574 		ipif_refrele(src_ipif);
9575 	if (mp->b_prev || mp->b_next) {
9576 		mp->b_next = NULL;
9577 		mp->b_prev = NULL;
9578 	} else {
9579 		/*
9580 		 * Since ip_wput() isn't close to finished, we fill
9581 		 * in enough of the header for credible error reporting.
9582 		 */
9583 		if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
9584 			/* Failed */
9585 			freemsg(first_mp);
9586 			if (ire != NULL)
9587 				ire_refrele(ire);
9588 			return;
9589 		}
9590 	}
9591 	/*
9592 	 * At this point we will have ire only if RTF_BLACKHOLE
9593 	 * or RTF_REJECT flags are set on the IRE. It will not
9594 	 * generate ICMP_HOST_UNREACHABLE if RTF_BLACKHOLE is set.
9595 	 */
9596 	if (ire != NULL) {
9597 		if (ire->ire_flags & RTF_BLACKHOLE) {
9598 			ire_refrele(ire);
9599 			freemsg(first_mp);
9600 			return;
9601 		}
9602 		ire_refrele(ire);
9603 	}
9604 	icmp_unreachable(q, first_mp, ICMP_HOST_UNREACHABLE, zoneid, ipst);
9605 }
9606 
9607 /* Name/Value Table Lookup Routine */
9608 char *
9609 ip_nv_lookup(nv_t *nv, int value)
9610 {
9611 	if (!nv)
9612 		return (NULL);
9613 	for (; nv->nv_name; nv++) {
9614 		if (nv->nv_value == value)
9615 			return (nv->nv_name);
9616 	}
9617 	return ("unknown");
9618 }
9619 
9620 /*
9621  * This is a module open, i.e. this is a control stream for access
9622  * to a DLPI device.  We allocate an ill_t as the instance data in
9623  * this case.
9624  */
9625 int
9626 ip_modopen(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9627 {
9628 	ill_t	*ill;
9629 	int	err;
9630 	zoneid_t zoneid;
9631 	netstack_t *ns;
9632 	ip_stack_t *ipst;
9633 
9634 	/*
9635 	 * Prevent unprivileged processes from pushing IP so that
9636 	 * they can't send raw IP.
9637 	 */
9638 	if (secpolicy_net_rawaccess(credp) != 0)
9639 		return (EPERM);
9640 
9641 	ns = netstack_find_by_cred(credp);
9642 	ASSERT(ns != NULL);
9643 	ipst = ns->netstack_ip;
9644 	ASSERT(ipst != NULL);
9645 
9646 	/*
9647 	 * For exclusive stacks we set the zoneid to zero
9648 	 * to make IP operate as if in the global zone.
9649 	 */
9650 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9651 		zoneid = GLOBAL_ZONEID;
9652 	else
9653 		zoneid = crgetzoneid(credp);
9654 
9655 	ill = (ill_t *)mi_open_alloc_sleep(sizeof (ill_t));
9656 	q->q_ptr = WR(q)->q_ptr = ill;
9657 	ill->ill_ipst = ipst;
9658 	ill->ill_zoneid = zoneid;
9659 
9660 	/*
9661 	 * ill_init initializes the ill fields and then sends down
9662 	 * down a DL_INFO_REQ after calling qprocson.
9663 	 */
9664 	err = ill_init(q, ill);
9665 	if (err != 0) {
9666 		mi_free(ill);
9667 		netstack_rele(ipst->ips_netstack);
9668 		q->q_ptr = NULL;
9669 		WR(q)->q_ptr = NULL;
9670 		return (err);
9671 	}
9672 
9673 	/* ill_init initializes the ipsq marking this thread as writer */
9674 	ipsq_exit(ill->ill_phyint->phyint_ipsq, B_TRUE, B_TRUE);
9675 	/* Wait for the DL_INFO_ACK */
9676 	mutex_enter(&ill->ill_lock);
9677 	while (ill->ill_state_flags & ILL_LL_SUBNET_PENDING) {
9678 		/*
9679 		 * Return value of 0 indicates a pending signal.
9680 		 */
9681 		err = cv_wait_sig(&ill->ill_cv, &ill->ill_lock);
9682 		if (err == 0) {
9683 			mutex_exit(&ill->ill_lock);
9684 			(void) ip_close(q, 0);
9685 			return (EINTR);
9686 		}
9687 	}
9688 	mutex_exit(&ill->ill_lock);
9689 
9690 	/*
9691 	 * ip_rput_other could have set an error  in ill_error on
9692 	 * receipt of M_ERROR.
9693 	 */
9694 
9695 	err = ill->ill_error;
9696 	if (err != 0) {
9697 		(void) ip_close(q, 0);
9698 		return (err);
9699 	}
9700 
9701 	ill->ill_credp = credp;
9702 	crhold(credp);
9703 
9704 	mutex_enter(&ipst->ips_ip_mi_lock);
9705 	err = mi_open_link(&ipst->ips_ip_g_head, (IDP)ill, devp, flag, sflag,
9706 	    credp);
9707 	mutex_exit(&ipst->ips_ip_mi_lock);
9708 	if (err) {
9709 		(void) ip_close(q, 0);
9710 		return (err);
9711 	}
9712 	return (0);
9713 }
9714 
9715 /* For /dev/ip aka AF_INET open */
9716 int
9717 ip_openv4(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9718 {
9719 	return (ip_open(q, devp, flag, sflag, credp, B_FALSE));
9720 }
9721 
9722 /* For /dev/ip6 aka AF_INET6 open */
9723 int
9724 ip_openv6(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp)
9725 {
9726 	return (ip_open(q, devp, flag, sflag, credp, B_TRUE));
9727 }
9728 
9729 /* IP open routine. */
9730 int
9731 ip_open(queue_t *q, dev_t *devp, int flag, int sflag, cred_t *credp,
9732     boolean_t isv6)
9733 {
9734 	conn_t 		*connp;
9735 	major_t		maj;
9736 	zoneid_t	zoneid;
9737 	netstack_t	*ns;
9738 	ip_stack_t	*ipst;
9739 
9740 	TRACE_1(TR_FAC_IP, TR_IP_OPEN, "ip_open: q %p", q);
9741 
9742 	/* Allow reopen. */
9743 	if (q->q_ptr != NULL)
9744 		return (0);
9745 
9746 	if (sflag & MODOPEN) {
9747 		/* This is a module open */
9748 		return (ip_modopen(q, devp, flag, sflag, credp));
9749 	}
9750 
9751 	ns = netstack_find_by_cred(credp);
9752 	ASSERT(ns != NULL);
9753 	ipst = ns->netstack_ip;
9754 	ASSERT(ipst != NULL);
9755 
9756 	/*
9757 	 * For exclusive stacks we set the zoneid to zero
9758 	 * to make IP operate as if in the global zone.
9759 	 */
9760 	if (ipst->ips_netstack->netstack_stackid != GLOBAL_NETSTACKID)
9761 		zoneid = GLOBAL_ZONEID;
9762 	else
9763 		zoneid = crgetzoneid(credp);
9764 
9765 	/*
9766 	 * We are opening as a device. This is an IP client stream, and we
9767 	 * allocate an conn_t as the instance data.
9768 	 */
9769 	connp = ipcl_conn_create(IPCL_IPCCONN, KM_SLEEP, ipst->ips_netstack);
9770 
9771 	/*
9772 	 * ipcl_conn_create did a netstack_hold. Undo the hold that was
9773 	 * done by netstack_find_by_cred()
9774 	 */
9775 	netstack_rele(ipst->ips_netstack);
9776 
9777 	connp->conn_zoneid = zoneid;
9778 
9779 	connp->conn_upq = q;
9780 	q->q_ptr = WR(q)->q_ptr = connp;
9781 
9782 	if (flag & SO_SOCKSTR)
9783 		connp->conn_flags |= IPCL_SOCKET;
9784 
9785 	/* Minor tells us which /dev entry was opened */
9786 	if (isv6) {
9787 		connp->conn_flags |= IPCL_ISV6;
9788 		connp->conn_af_isv6 = B_TRUE;
9789 		ip_setpktversion(connp, isv6, B_FALSE, ipst);
9790 		connp->conn_src_preferences = IPV6_PREFER_SRC_DEFAULT;
9791 	} else {
9792 		connp->conn_af_isv6 = B_FALSE;
9793 		connp->conn_pkt_isv6 = B_FALSE;
9794 	}
9795 
9796 	if ((ip_minor_arena_la != NULL) && (flag & SO_SOCKSTR) &&
9797 	    ((connp->conn_dev = inet_minor_alloc(ip_minor_arena_la)) != 0)) {
9798 		connp->conn_minor_arena = ip_minor_arena_la;
9799 	} else {
9800 		/*
9801 		 * Either minor numbers in the large arena were exhausted
9802 		 * or a non socket application is doing the open.
9803 		 * Try to allocate from the small arena.
9804 		 */
9805 		if ((connp->conn_dev =
9806 		    inet_minor_alloc(ip_minor_arena_sa)) == 0) {
9807 			/* CONN_DEC_REF takes care of netstack_rele() */
9808 			q->q_ptr = WR(q)->q_ptr = NULL;
9809 			CONN_DEC_REF(connp);
9810 			return (EBUSY);
9811 		}
9812 		connp->conn_minor_arena = ip_minor_arena_sa;
9813 	}
9814 
9815 	maj = getemajor(*devp);
9816 	*devp = makedevice(maj, (minor_t)connp->conn_dev);
9817 
9818 	/*
9819 	 * connp->conn_cred is crfree()ed in ipcl_conn_destroy()
9820 	 */
9821 	connp->conn_cred = credp;
9822 
9823 	/*
9824 	 * Handle IP_RTS_REQUEST and other ioctls which use conn_recv
9825 	 */
9826 	connp->conn_recv = ip_conn_input;
9827 
9828 	crhold(connp->conn_cred);
9829 
9830 	/*
9831 	 * If the caller has the process-wide flag set, then default to MAC
9832 	 * exempt mode.  This allows read-down to unlabeled hosts.
9833 	 */
9834 	if (getpflags(NET_MAC_AWARE, credp) != 0)
9835 		connp->conn_mac_exempt = B_TRUE;
9836 
9837 	connp->conn_rq = q;
9838 	connp->conn_wq = WR(q);
9839 
9840 	/* Non-zero default values */
9841 	connp->conn_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
9842 
9843 	/*
9844 	 * Make the conn globally visible to walkers
9845 	 */
9846 	ASSERT(connp->conn_ref == 1);
9847 	mutex_enter(&connp->conn_lock);
9848 	connp->conn_state_flags &= ~CONN_INCIPIENT;
9849 	mutex_exit(&connp->conn_lock);
9850 
9851 	qprocson(q);
9852 
9853 	return (0);
9854 }
9855 
9856 /*
9857  * Change the output format (IPv4 vs. IPv6) for a conn_t.
9858  * Note that there is no race since either ip_output function works - it
9859  * is just an optimization to enter the best ip_output routine directly.
9860  */
9861 void
9862 ip_setpktversion(conn_t *connp, boolean_t isv6, boolean_t bump_mib,
9863     ip_stack_t *ipst)
9864 {
9865 	if (isv6)  {
9866 		if (bump_mib) {
9867 			BUMP_MIB(&ipst->ips_ip6_mib,
9868 			    ipIfStatsOutSwitchIPVersion);
9869 		}
9870 		connp->conn_send = ip_output_v6;
9871 		connp->conn_pkt_isv6 = B_TRUE;
9872 	} else {
9873 		if (bump_mib) {
9874 			BUMP_MIB(&ipst->ips_ip_mib,
9875 			    ipIfStatsOutSwitchIPVersion);
9876 		}
9877 		connp->conn_send = ip_output;
9878 		connp->conn_pkt_isv6 = B_FALSE;
9879 	}
9880 
9881 }
9882 
9883 /*
9884  * See if IPsec needs loading because of the options in mp.
9885  */
9886 static boolean_t
9887 ipsec_opt_present(mblk_t *mp)
9888 {
9889 	uint8_t *optcp, *next_optcp, *opt_endcp;
9890 	struct opthdr *opt;
9891 	struct T_opthdr *topt;
9892 	int opthdr_len;
9893 	t_uscalar_t optname, optlevel;
9894 	struct T_optmgmt_req *tor = (struct T_optmgmt_req *)mp->b_rptr;
9895 	ipsec_req_t *ipsr;
9896 
9897 	/*
9898 	 * Walk through the mess, and find IP_SEC_OPT.  If it's there,
9899 	 * return TRUE.
9900 	 */
9901 
9902 	optcp = mi_offset_param(mp, tor->OPT_offset, tor->OPT_length);
9903 	opt_endcp = optcp + tor->OPT_length;
9904 	if (tor->PRIM_type == T_OPTMGMT_REQ) {
9905 		opthdr_len = sizeof (struct T_opthdr);
9906 	} else {		/* O_OPTMGMT_REQ */
9907 		ASSERT(tor->PRIM_type == T_SVR4_OPTMGMT_REQ);
9908 		opthdr_len = sizeof (struct opthdr);
9909 	}
9910 	for (; optcp < opt_endcp; optcp = next_optcp) {
9911 		if (optcp + opthdr_len > opt_endcp)
9912 			return (B_FALSE);	/* Not enough option header. */
9913 		if (tor->PRIM_type == T_OPTMGMT_REQ) {
9914 			topt = (struct T_opthdr *)optcp;
9915 			optlevel = topt->level;
9916 			optname = topt->name;
9917 			next_optcp = optcp + _TPI_ALIGN_TOPT(topt->len);
9918 		} else {
9919 			opt = (struct opthdr *)optcp;
9920 			optlevel = opt->level;
9921 			optname = opt->name;
9922 			next_optcp = optcp + opthdr_len +
9923 			    _TPI_ALIGN_OPT(opt->len);
9924 		}
9925 		if ((next_optcp < optcp) || /* wraparound pointer space */
9926 		    ((next_optcp >= opt_endcp) && /* last option bad len */
9927 		    ((next_optcp - opt_endcp) >= __TPI_ALIGN_SIZE)))
9928 			return (B_FALSE); /* bad option buffer */
9929 		if ((optlevel == IPPROTO_IP && optname == IP_SEC_OPT) ||
9930 		    (optlevel == IPPROTO_IPV6 && optname == IPV6_SEC_OPT)) {
9931 			/*
9932 			 * Check to see if it's an all-bypass or all-zeroes
9933 			 * IPsec request.  Don't bother loading IPsec if
9934 			 * the socket doesn't want to use it.  (A good example
9935 			 * is a bypass request.)
9936 			 *
9937 			 * Basically, if any of the non-NEVER bits are set,
9938 			 * load IPsec.
9939 			 */
9940 			ipsr = (ipsec_req_t *)(optcp + opthdr_len);
9941 			if ((ipsr->ipsr_ah_req & ~IPSEC_PREF_NEVER) != 0 ||
9942 			    (ipsr->ipsr_esp_req & ~IPSEC_PREF_NEVER) != 0 ||
9943 			    (ipsr->ipsr_self_encap_req & ~IPSEC_PREF_NEVER)
9944 			    != 0)
9945 				return (B_TRUE);
9946 		}
9947 	}
9948 	return (B_FALSE);
9949 }
9950 
9951 /*
9952  * If conn is is waiting for ipsec to finish loading, kick it.
9953  */
9954 /* ARGSUSED */
9955 static void
9956 conn_restart_ipsec_waiter(conn_t *connp, void *arg)
9957 {
9958 	t_scalar_t	optreq_prim;
9959 	mblk_t		*mp;
9960 	cred_t		*cr;
9961 	int		err = 0;
9962 
9963 	/*
9964 	 * This function is called, after ipsec loading is complete.
9965 	 * Since IP checks exclusively and atomically (i.e it prevents
9966 	 * ipsec load from completing until ip_optcom_req completes)
9967 	 * whether ipsec load is complete, there cannot be a race with IP
9968 	 * trying to set the CONN_IPSEC_LOAD_WAIT flag on any conn now.
9969 	 */
9970 	mutex_enter(&connp->conn_lock);
9971 	if (connp->conn_state_flags & CONN_IPSEC_LOAD_WAIT) {
9972 		ASSERT(connp->conn_ipsec_opt_mp != NULL);
9973 		mp = connp->conn_ipsec_opt_mp;
9974 		connp->conn_ipsec_opt_mp = NULL;
9975 		connp->conn_state_flags  &= ~CONN_IPSEC_LOAD_WAIT;
9976 		cr = DB_CREDDEF(mp, GET_QUEUE_CRED(CONNP_TO_WQ(connp)));
9977 		mutex_exit(&connp->conn_lock);
9978 
9979 		ASSERT(DB_TYPE(mp) == M_PROTO || DB_TYPE(mp) == M_PCPROTO);
9980 
9981 		optreq_prim = ((union T_primitives *)mp->b_rptr)->type;
9982 		if (optreq_prim == T_OPTMGMT_REQ) {
9983 			err = tpi_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9984 			    &ip_opt_obj, B_FALSE);
9985 		} else {
9986 			ASSERT(optreq_prim == T_SVR4_OPTMGMT_REQ);
9987 			err = svr4_optcom_req(CONNP_TO_WQ(connp), mp, cr,
9988 			    &ip_opt_obj, B_FALSE);
9989 		}
9990 		if (err != EINPROGRESS)
9991 			CONN_OPER_PENDING_DONE(connp);
9992 		return;
9993 	}
9994 	mutex_exit(&connp->conn_lock);
9995 }
9996 
9997 /*
9998  * Called from the ipsec_loader thread, outside any perimeter, to tell
9999  * ip qenable any of the queues waiting for the ipsec loader to
10000  * complete.
10001  */
10002 void
10003 ip_ipsec_load_complete(ipsec_stack_t *ipss)
10004 {
10005 	netstack_t *ns = ipss->ipsec_netstack;
10006 
10007 	ipcl_walk(conn_restart_ipsec_waiter, NULL, ns->netstack_ip);
10008 }
10009 
10010 /*
10011  * Can't be used. Need to call svr4* -> optset directly. the leaf routine
10012  * determines the grp on which it has to become exclusive, queues the mp
10013  * and sq draining restarts the optmgmt
10014  */
10015 static boolean_t
10016 ip_check_for_ipsec_opt(queue_t *q, mblk_t *mp)
10017 {
10018 	conn_t *connp = Q_TO_CONN(q);
10019 	ipsec_stack_t *ipss = connp->conn_netstack->netstack_ipsec;
10020 
10021 	/*
10022 	 * Take IPsec requests and treat them special.
10023 	 */
10024 	if (ipsec_opt_present(mp)) {
10025 		/* First check if IPsec is loaded. */
10026 		mutex_enter(&ipss->ipsec_loader_lock);
10027 		if (ipss->ipsec_loader_state != IPSEC_LOADER_WAIT) {
10028 			mutex_exit(&ipss->ipsec_loader_lock);
10029 			return (B_FALSE);
10030 		}
10031 		mutex_enter(&connp->conn_lock);
10032 		connp->conn_state_flags |= CONN_IPSEC_LOAD_WAIT;
10033 
10034 		ASSERT(connp->conn_ipsec_opt_mp == NULL);
10035 		connp->conn_ipsec_opt_mp = mp;
10036 		mutex_exit(&connp->conn_lock);
10037 		mutex_exit(&ipss->ipsec_loader_lock);
10038 
10039 		ipsec_loader_loadnow(ipss);
10040 		return (B_TRUE);
10041 	}
10042 	return (B_FALSE);
10043 }
10044 
10045 /*
10046  * Set IPsec policy from an ipsec_req_t. If the req is not "zero" and valid,
10047  * all of them are copied to the conn_t. If the req is "zero", the policy is
10048  * zeroed out. A "zero" policy has zero ipsr_{ah,req,self_encap}_req
10049  * fields.
10050  * We keep only the latest setting of the policy and thus policy setting
10051  * is not incremental/cumulative.
10052  *
10053  * Requests to set policies with multiple alternative actions will
10054  * go through a different API.
10055  */
10056 int
10057 ipsec_set_req(cred_t *cr, conn_t *connp, ipsec_req_t *req)
10058 {
10059 	uint_t ah_req = 0;
10060 	uint_t esp_req = 0;
10061 	uint_t se_req = 0;
10062 	ipsec_selkey_t sel;
10063 	ipsec_act_t *actp = NULL;
10064 	uint_t nact;
10065 	ipsec_policy_t *pin4 = NULL, *pout4 = NULL;
10066 	ipsec_policy_t *pin6 = NULL, *pout6 = NULL;
10067 	ipsec_policy_root_t *pr;
10068 	ipsec_policy_head_t *ph;
10069 	int fam;
10070 	boolean_t is_pol_reset;
10071 	int error = 0;
10072 	netstack_t	*ns = connp->conn_netstack;
10073 	ip_stack_t	*ipst = ns->netstack_ip;
10074 	ipsec_stack_t	*ipss = ns->netstack_ipsec;
10075 
10076 #define	REQ_MASK (IPSEC_PREF_REQUIRED|IPSEC_PREF_NEVER)
10077 
10078 	/*
10079 	 * The IP_SEC_OPT option does not allow variable length parameters,
10080 	 * hence a request cannot be NULL.
10081 	 */
10082 	if (req == NULL)
10083 		return (EINVAL);
10084 
10085 	ah_req = req->ipsr_ah_req;
10086 	esp_req = req->ipsr_esp_req;
10087 	se_req = req->ipsr_self_encap_req;
10088 
10089 	/* Don't allow setting self-encap without one or more of AH/ESP. */
10090 	if (se_req != 0 && esp_req == 0 && ah_req == 0)
10091 		return (EINVAL);
10092 
10093 	/*
10094 	 * Are we dealing with a request to reset the policy (i.e.
10095 	 * zero requests).
10096 	 */
10097 	is_pol_reset = ((ah_req & REQ_MASK) == 0 &&
10098 	    (esp_req & REQ_MASK) == 0 &&
10099 	    (se_req & REQ_MASK) == 0);
10100 
10101 	if (!is_pol_reset) {
10102 		/*
10103 		 * If we couldn't load IPsec, fail with "protocol
10104 		 * not supported".
10105 		 * IPsec may not have been loaded for a request with zero
10106 		 * policies, so we don't fail in this case.
10107 		 */
10108 		mutex_enter(&ipss->ipsec_loader_lock);
10109 		if (ipss->ipsec_loader_state != IPSEC_LOADER_SUCCEEDED) {
10110 			mutex_exit(&ipss->ipsec_loader_lock);
10111 			return (EPROTONOSUPPORT);
10112 		}
10113 		mutex_exit(&ipss->ipsec_loader_lock);
10114 
10115 		/*
10116 		 * Test for valid requests. Invalid algorithms
10117 		 * need to be tested by IPsec code because new
10118 		 * algorithms can be added dynamically.
10119 		 */
10120 		if ((ah_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10121 		    (esp_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0 ||
10122 		    (se_req & ~(REQ_MASK|IPSEC_PREF_UNIQUE)) != 0) {
10123 			return (EINVAL);
10124 		}
10125 
10126 		/*
10127 		 * Only privileged users can issue these
10128 		 * requests.
10129 		 */
10130 		if (((ah_req & IPSEC_PREF_NEVER) ||
10131 		    (esp_req & IPSEC_PREF_NEVER) ||
10132 		    (se_req & IPSEC_PREF_NEVER)) &&
10133 		    secpolicy_ip_config(cr, B_FALSE) != 0) {
10134 			return (EPERM);
10135 		}
10136 
10137 		/*
10138 		 * The IPSEC_PREF_REQUIRED and IPSEC_PREF_NEVER
10139 		 * are mutually exclusive.
10140 		 */
10141 		if (((ah_req & REQ_MASK) == REQ_MASK) ||
10142 		    ((esp_req & REQ_MASK) == REQ_MASK) ||
10143 		    ((se_req & REQ_MASK) == REQ_MASK)) {
10144 			/* Both of them are set */
10145 			return (EINVAL);
10146 		}
10147 	}
10148 
10149 	mutex_enter(&connp->conn_lock);
10150 
10151 	/*
10152 	 * If we have already cached policies in ip_bind_connected*(), don't
10153 	 * let them change now. We cache policies for connections
10154 	 * whose src,dst [addr, port] is known.
10155 	 */
10156 	if (connp->conn_policy_cached) {
10157 		mutex_exit(&connp->conn_lock);
10158 		return (EINVAL);
10159 	}
10160 
10161 	/*
10162 	 * We have a zero policies, reset the connection policy if already
10163 	 * set. This will cause the connection to inherit the
10164 	 * global policy, if any.
10165 	 */
10166 	if (is_pol_reset) {
10167 		if (connp->conn_policy != NULL) {
10168 			IPPH_REFRELE(connp->conn_policy, ipst->ips_netstack);
10169 			connp->conn_policy = NULL;
10170 		}
10171 		connp->conn_flags &= ~IPCL_CHECK_POLICY;
10172 		connp->conn_in_enforce_policy = B_FALSE;
10173 		connp->conn_out_enforce_policy = B_FALSE;
10174 		mutex_exit(&connp->conn_lock);
10175 		return (0);
10176 	}
10177 
10178 	ph = connp->conn_policy = ipsec_polhead_split(connp->conn_policy,
10179 	    ipst->ips_netstack);
10180 	if (ph == NULL)
10181 		goto enomem;
10182 
10183 	ipsec_actvec_from_req(req, &actp, &nact, ipst->ips_netstack);
10184 	if (actp == NULL)
10185 		goto enomem;
10186 
10187 	/*
10188 	 * Always allocate IPv4 policy entries, since they can also
10189 	 * apply to ipv6 sockets being used in ipv4-compat mode.
10190 	 */
10191 	bzero(&sel, sizeof (sel));
10192 	sel.ipsl_valid = IPSL_IPV4;
10193 
10194 	pin4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10195 	    ipst->ips_netstack);
10196 	if (pin4 == NULL)
10197 		goto enomem;
10198 
10199 	pout4 = ipsec_policy_create(&sel, actp, nact, IPSEC_PRIO_SOCKET, NULL,
10200 	    ipst->ips_netstack);
10201 	if (pout4 == NULL)
10202 		goto enomem;
10203 
10204 	if (connp->conn_af_isv6) {
10205 		/*
10206 		 * We're looking at a v6 socket, also allocate the
10207 		 * v6-specific entries...
10208 		 */
10209 		sel.ipsl_valid = IPSL_IPV6;
10210 		pin6 = ipsec_policy_create(&sel, actp, nact,
10211 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10212 		if (pin6 == NULL)
10213 			goto enomem;
10214 
10215 		pout6 = ipsec_policy_create(&sel, actp, nact,
10216 		    IPSEC_PRIO_SOCKET, NULL, ipst->ips_netstack);
10217 		if (pout6 == NULL)
10218 			goto enomem;
10219 
10220 		/*
10221 		 * .. and file them away in the right place.
10222 		 */
10223 		fam = IPSEC_AF_V6;
10224 		pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10225 		HASHLIST_INSERT(pin6, ipsp_hash, pr->ipr_nonhash[fam]);
10226 		ipsec_insert_always(&ph->iph_rulebyid, pin6);
10227 		pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10228 		HASHLIST_INSERT(pout6, ipsp_hash, pr->ipr_nonhash[fam]);
10229 		ipsec_insert_always(&ph->iph_rulebyid, pout6);
10230 	}
10231 
10232 	ipsec_actvec_free(actp, nact);
10233 
10234 	/*
10235 	 * File the v4 policies.
10236 	 */
10237 	fam = IPSEC_AF_V4;
10238 	pr = &ph->iph_root[IPSEC_TYPE_INBOUND];
10239 	HASHLIST_INSERT(pin4, ipsp_hash, pr->ipr_nonhash[fam]);
10240 	ipsec_insert_always(&ph->iph_rulebyid, pin4);
10241 
10242 	pr = &ph->iph_root[IPSEC_TYPE_OUTBOUND];
10243 	HASHLIST_INSERT(pout4, ipsp_hash, pr->ipr_nonhash[fam]);
10244 	ipsec_insert_always(&ph->iph_rulebyid, pout4);
10245 
10246 	/*
10247 	 * If the requests need security, set enforce_policy.
10248 	 * If the requests are IPSEC_PREF_NEVER, one should
10249 	 * still set conn_out_enforce_policy so that an ipsec_out
10250 	 * gets attached in ip_wput. This is needed so that
10251 	 * for connections that we don't cache policy in ip_bind,
10252 	 * if global policy matches in ip_wput_attach_policy, we
10253 	 * don't wrongly inherit global policy. Similarly, we need
10254 	 * to set conn_in_enforce_policy also so that we don't verify
10255 	 * policy wrongly.
10256 	 */
10257 	if ((ah_req & REQ_MASK) != 0 ||
10258 	    (esp_req & REQ_MASK) != 0 ||
10259 	    (se_req & REQ_MASK) != 0) {
10260 		connp->conn_in_enforce_policy = B_TRUE;
10261 		connp->conn_out_enforce_policy = B_TRUE;
10262 		connp->conn_flags |= IPCL_CHECK_POLICY;
10263 	}
10264 
10265 	mutex_exit(&connp->conn_lock);
10266 	return (error);
10267 #undef REQ_MASK
10268 
10269 	/*
10270 	 * Common memory-allocation-failure exit path.
10271 	 */
10272 enomem:
10273 	mutex_exit(&connp->conn_lock);
10274 	if (actp != NULL)
10275 		ipsec_actvec_free(actp, nact);
10276 	if (pin4 != NULL)
10277 		IPPOL_REFRELE(pin4, ipst->ips_netstack);
10278 	if (pout4 != NULL)
10279 		IPPOL_REFRELE(pout4, ipst->ips_netstack);
10280 	if (pin6 != NULL)
10281 		IPPOL_REFRELE(pin6, ipst->ips_netstack);
10282 	if (pout6 != NULL)
10283 		IPPOL_REFRELE(pout6, ipst->ips_netstack);
10284 	return (ENOMEM);
10285 }
10286 
10287 /*
10288  * Only for options that pass in an IP addr. Currently only V4 options
10289  * pass in an ipif. V6 options always pass an ifindex specifying the ill.
10290  * So this function assumes level is IPPROTO_IP
10291  */
10292 int
10293 ip_opt_set_ipif(conn_t *connp, ipaddr_t addr, boolean_t checkonly, int option,
10294     mblk_t *first_mp)
10295 {
10296 	ipif_t *ipif = NULL;
10297 	int error;
10298 	ill_t *ill;
10299 	int zoneid;
10300 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
10301 
10302 	ip2dbg(("ip_opt_set_ipif: ipaddr %X\n", addr));
10303 
10304 	if (addr != INADDR_ANY || checkonly) {
10305 		ASSERT(connp != NULL);
10306 		zoneid = IPCL_ZONEID(connp);
10307 		if (option == IP_NEXTHOP) {
10308 			ipif = ipif_lookup_onlink_addr(addr,
10309 			    connp->conn_zoneid, ipst);
10310 		} else {
10311 			ipif = ipif_lookup_addr(addr, NULL, zoneid,
10312 			    CONNP_TO_WQ(connp), first_mp, ip_restart_optmgmt,
10313 			    &error, ipst);
10314 		}
10315 		if (ipif == NULL) {
10316 			if (error == EINPROGRESS)
10317 				return (error);
10318 			else if ((option == IP_MULTICAST_IF) ||
10319 			    (option == IP_NEXTHOP))
10320 				return (EHOSTUNREACH);
10321 			else
10322 				return (EINVAL);
10323 		} else if (checkonly) {
10324 			if (option == IP_MULTICAST_IF) {
10325 				ill = ipif->ipif_ill;
10326 				/* not supported by the virtual network iface */
10327 				if (IS_VNI(ill)) {
10328 					ipif_refrele(ipif);
10329 					return (EINVAL);
10330 				}
10331 			}
10332 			ipif_refrele(ipif);
10333 			return (0);
10334 		}
10335 		ill = ipif->ipif_ill;
10336 		mutex_enter(&connp->conn_lock);
10337 		mutex_enter(&ill->ill_lock);
10338 		if ((ill->ill_state_flags & ILL_CONDEMNED) ||
10339 		    (ipif->ipif_state_flags & IPIF_CONDEMNED)) {
10340 			mutex_exit(&ill->ill_lock);
10341 			mutex_exit(&connp->conn_lock);
10342 			ipif_refrele(ipif);
10343 			return (option == IP_MULTICAST_IF ?
10344 			    EHOSTUNREACH : EINVAL);
10345 		}
10346 	} else {
10347 		mutex_enter(&connp->conn_lock);
10348 	}
10349 
10350 	/* None of the options below are supported on the VNI */
10351 	if (ipif != NULL && IS_VNI(ipif->ipif_ill)) {
10352 		mutex_exit(&ill->ill_lock);
10353 		mutex_exit(&connp->conn_lock);
10354 		ipif_refrele(ipif);
10355 		return (EINVAL);
10356 	}
10357 
10358 	switch (option) {
10359 	case IP_DONTFAILOVER_IF:
10360 		/*
10361 		 * This option is used by in.mpathd to ensure
10362 		 * that IPMP probe packets only go out on the
10363 		 * test interfaces. in.mpathd sets this option
10364 		 * on the non-failover interfaces.
10365 		 * For backward compatibility, this option
10366 		 * implicitly sets IP_MULTICAST_IF, as used
10367 		 * be done in bind(), so that ip_wput gets
10368 		 * this ipif to send mcast packets.
10369 		 */
10370 		if (ipif != NULL) {
10371 			ASSERT(addr != INADDR_ANY);
10372 			connp->conn_nofailover_ill = ipif->ipif_ill;
10373 			connp->conn_multicast_ipif = ipif;
10374 		} else {
10375 			ASSERT(addr == INADDR_ANY);
10376 			connp->conn_nofailover_ill = NULL;
10377 			connp->conn_multicast_ipif = NULL;
10378 		}
10379 		break;
10380 
10381 	case IP_MULTICAST_IF:
10382 		connp->conn_multicast_ipif = ipif;
10383 		break;
10384 	case IP_NEXTHOP:
10385 		connp->conn_nexthop_v4 = addr;
10386 		connp->conn_nexthop_set = B_TRUE;
10387 		break;
10388 	}
10389 
10390 	if (ipif != NULL) {
10391 		mutex_exit(&ill->ill_lock);
10392 		mutex_exit(&connp->conn_lock);
10393 		ipif_refrele(ipif);
10394 		return (0);
10395 	}
10396 	mutex_exit(&connp->conn_lock);
10397 	/* We succeded in cleared the option */
10398 	return (0);
10399 }
10400 
10401 /*
10402  * For options that pass in an ifindex specifying the ill. V6 options always
10403  * pass in an ill. Some v4 options also pass in ifindex specifying the ill.
10404  */
10405 int
10406 ip_opt_set_ill(conn_t *connp, int ifindex, boolean_t isv6, boolean_t checkonly,
10407     int level, int option, mblk_t *first_mp)
10408 {
10409 	ill_t *ill = NULL;
10410 	int error = 0;
10411 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10412 
10413 	ip2dbg(("ip_opt_set_ill: ifindex %d\n", ifindex));
10414 	if (ifindex != 0) {
10415 		ASSERT(connp != NULL);
10416 		ill = ill_lookup_on_ifindex(ifindex, isv6, CONNP_TO_WQ(connp),
10417 		    first_mp, ip_restart_optmgmt, &error, ipst);
10418 		if (ill != NULL) {
10419 			if (checkonly) {
10420 				/* not supported by the virtual network iface */
10421 				if (IS_VNI(ill)) {
10422 					ill_refrele(ill);
10423 					return (EINVAL);
10424 				}
10425 				ill_refrele(ill);
10426 				return (0);
10427 			}
10428 			if (!ipif_lookup_zoneid_group(ill, connp->conn_zoneid,
10429 			    0, NULL)) {
10430 				ill_refrele(ill);
10431 				ill = NULL;
10432 				mutex_enter(&connp->conn_lock);
10433 				goto setit;
10434 			}
10435 			mutex_enter(&connp->conn_lock);
10436 			mutex_enter(&ill->ill_lock);
10437 			if (ill->ill_state_flags & ILL_CONDEMNED) {
10438 				mutex_exit(&ill->ill_lock);
10439 				mutex_exit(&connp->conn_lock);
10440 				ill_refrele(ill);
10441 				ill = NULL;
10442 				mutex_enter(&connp->conn_lock);
10443 			}
10444 			goto setit;
10445 		} else if (error == EINPROGRESS) {
10446 			return (error);
10447 		} else {
10448 			error = 0;
10449 		}
10450 	}
10451 	mutex_enter(&connp->conn_lock);
10452 setit:
10453 	ASSERT((level == IPPROTO_IP || level == IPPROTO_IPV6));
10454 
10455 	/*
10456 	 * The options below assume that the ILL (if any) transmits and/or
10457 	 * receives traffic. Neither of which is true for the virtual network
10458 	 * interface, so fail setting these on a VNI.
10459 	 */
10460 	if (IS_VNI(ill)) {
10461 		ASSERT(ill != NULL);
10462 		mutex_exit(&ill->ill_lock);
10463 		mutex_exit(&connp->conn_lock);
10464 		ill_refrele(ill);
10465 		return (EINVAL);
10466 	}
10467 
10468 	if (level == IPPROTO_IP) {
10469 		switch (option) {
10470 		case IP_BOUND_IF:
10471 			connp->conn_incoming_ill = ill;
10472 			connp->conn_outgoing_ill = ill;
10473 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10474 			    0 : ifindex;
10475 			break;
10476 
10477 		case IP_MULTICAST_IF:
10478 			/*
10479 			 * This option is an internal special. The socket
10480 			 * level IP_MULTICAST_IF specifies an 'ipaddr' and
10481 			 * is handled in ip_opt_set_ipif. IPV6_MULTICAST_IF
10482 			 * specifies an ifindex and we try first on V6 ill's.
10483 			 * If we don't find one, we they try using on v4 ill's
10484 			 * intenally and we come here.
10485 			 */
10486 			if (!checkonly && ill != NULL) {
10487 				ipif_t	*ipif;
10488 				ipif = ill->ill_ipif;
10489 
10490 				if (ipif->ipif_state_flags & IPIF_CONDEMNED) {
10491 					mutex_exit(&ill->ill_lock);
10492 					mutex_exit(&connp->conn_lock);
10493 					ill_refrele(ill);
10494 					ill = NULL;
10495 					mutex_enter(&connp->conn_lock);
10496 				} else {
10497 					connp->conn_multicast_ipif = ipif;
10498 				}
10499 			}
10500 			break;
10501 
10502 		case IP_DHCPINIT_IF:
10503 			if (connp->conn_dhcpinit_ill != NULL) {
10504 				/*
10505 				 * We've locked the conn so conn_cleanup_ill()
10506 				 * cannot clear conn_dhcpinit_ill -- so it's
10507 				 * safe to access the ill.
10508 				 */
10509 				ill_t *oill = connp->conn_dhcpinit_ill;
10510 
10511 				ASSERT(oill->ill_dhcpinit != 0);
10512 				atomic_dec_32(&oill->ill_dhcpinit);
10513 				connp->conn_dhcpinit_ill = NULL;
10514 			}
10515 
10516 			if (ill != NULL) {
10517 				connp->conn_dhcpinit_ill = ill;
10518 				atomic_inc_32(&ill->ill_dhcpinit);
10519 			}
10520 			break;
10521 		}
10522 	} else {
10523 		switch (option) {
10524 		case IPV6_BOUND_IF:
10525 			connp->conn_incoming_ill = ill;
10526 			connp->conn_outgoing_ill = ill;
10527 			connp->conn_orig_bound_ifindex = (ill == NULL) ?
10528 			    0 : ifindex;
10529 			break;
10530 
10531 		case IPV6_BOUND_PIF:
10532 			/*
10533 			 * Limit all transmit to this ill.
10534 			 * Unlike IPV6_BOUND_IF, using this option
10535 			 * prevents load spreading and failover from
10536 			 * happening when the interface is part of the
10537 			 * group. That's why we don't need to remember
10538 			 * the ifindex in orig_bound_ifindex as in
10539 			 * IPV6_BOUND_IF.
10540 			 */
10541 			connp->conn_outgoing_pill = ill;
10542 			break;
10543 
10544 		case IPV6_DONTFAILOVER_IF:
10545 			/*
10546 			 * This option is used by in.mpathd to ensure
10547 			 * that IPMP probe packets only go out on the
10548 			 * test interfaces. in.mpathd sets this option
10549 			 * on the non-failover interfaces.
10550 			 */
10551 			connp->conn_nofailover_ill = ill;
10552 			/*
10553 			 * For backward compatibility, this option
10554 			 * implicitly sets ip_multicast_ill as used in
10555 			 * IPV6_MULTICAST_IF so that ip_wput gets
10556 			 * this ill to send mcast packets.
10557 			 */
10558 			connp->conn_multicast_ill = ill;
10559 			connp->conn_orig_multicast_ifindex = (ill == NULL) ?
10560 			    0 : ifindex;
10561 			break;
10562 
10563 		case IPV6_MULTICAST_IF:
10564 			/*
10565 			 * Set conn_multicast_ill to be the IPv6 ill.
10566 			 * Set conn_multicast_ipif to be an IPv4 ipif
10567 			 * for ifindex to make IPv4 mapped addresses
10568 			 * on PF_INET6 sockets honor IPV6_MULTICAST_IF.
10569 			 * Even if no IPv6 ill exists for the ifindex
10570 			 * we need to check for an IPv4 ifindex in order
10571 			 * for this to work with mapped addresses. In that
10572 			 * case only set conn_multicast_ipif.
10573 			 */
10574 			if (!checkonly) {
10575 				if (ifindex == 0) {
10576 					connp->conn_multicast_ill = NULL;
10577 					connp->conn_orig_multicast_ifindex = 0;
10578 					connp->conn_multicast_ipif = NULL;
10579 				} else if (ill != NULL) {
10580 					connp->conn_multicast_ill = ill;
10581 					connp->conn_orig_multicast_ifindex =
10582 					    ifindex;
10583 				}
10584 			}
10585 			break;
10586 		}
10587 	}
10588 
10589 	if (ill != NULL) {
10590 		mutex_exit(&ill->ill_lock);
10591 		mutex_exit(&connp->conn_lock);
10592 		ill_refrele(ill);
10593 		return (0);
10594 	}
10595 	mutex_exit(&connp->conn_lock);
10596 	/*
10597 	 * We succeeded in clearing the option (ifindex == 0) or failed to
10598 	 * locate the ill and could not set the option (ifindex != 0)
10599 	 */
10600 	return (ifindex == 0 ? 0 : EINVAL);
10601 }
10602 
10603 /* This routine sets socket options. */
10604 /* ARGSUSED */
10605 int
10606 ip_opt_set(queue_t *q, uint_t optset_context, int level, int name,
10607     uint_t inlen, uchar_t *invalp, uint_t *outlenp, uchar_t *outvalp,
10608     void *dummy, cred_t *cr, mblk_t *first_mp)
10609 {
10610 	int		*i1 = (int *)invalp;
10611 	conn_t		*connp = Q_TO_CONN(q);
10612 	int		error = 0;
10613 	boolean_t	checkonly;
10614 	ire_t		*ire;
10615 	boolean_t	found;
10616 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
10617 
10618 	switch (optset_context) {
10619 
10620 	case SETFN_OPTCOM_CHECKONLY:
10621 		checkonly = B_TRUE;
10622 		/*
10623 		 * Note: Implies T_CHECK semantics for T_OPTCOM_REQ
10624 		 * inlen != 0 implies value supplied and
10625 		 * 	we have to "pretend" to set it.
10626 		 * inlen == 0 implies that there is no
10627 		 * 	value part in T_CHECK request and just validation
10628 		 * done elsewhere should be enough, we just return here.
10629 		 */
10630 		if (inlen == 0) {
10631 			*outlenp = 0;
10632 			return (0);
10633 		}
10634 		break;
10635 	case SETFN_OPTCOM_NEGOTIATE:
10636 	case SETFN_UD_NEGOTIATE:
10637 	case SETFN_CONN_NEGOTIATE:
10638 		checkonly = B_FALSE;
10639 		break;
10640 	default:
10641 		/*
10642 		 * We should never get here
10643 		 */
10644 		*outlenp = 0;
10645 		return (EINVAL);
10646 	}
10647 
10648 	ASSERT((optset_context != SETFN_OPTCOM_CHECKONLY) ||
10649 	    (optset_context == SETFN_OPTCOM_CHECKONLY && inlen != 0));
10650 
10651 	/*
10652 	 * For fixed length options, no sanity check
10653 	 * of passed in length is done. It is assumed *_optcom_req()
10654 	 * routines do the right thing.
10655 	 */
10656 
10657 	switch (level) {
10658 	case SOL_SOCKET:
10659 		/*
10660 		 * conn_lock protects the bitfields, and is used to
10661 		 * set the fields atomically.
10662 		 */
10663 		switch (name) {
10664 		case SO_BROADCAST:
10665 			if (!checkonly) {
10666 				/* TODO: use value someplace? */
10667 				mutex_enter(&connp->conn_lock);
10668 				connp->conn_broadcast = *i1 ? 1 : 0;
10669 				mutex_exit(&connp->conn_lock);
10670 			}
10671 			break;	/* goto sizeof (int) option return */
10672 		case SO_USELOOPBACK:
10673 			if (!checkonly) {
10674 				/* TODO: use value someplace? */
10675 				mutex_enter(&connp->conn_lock);
10676 				connp->conn_loopback = *i1 ? 1 : 0;
10677 				mutex_exit(&connp->conn_lock);
10678 			}
10679 			break;	/* goto sizeof (int) option return */
10680 		case SO_DONTROUTE:
10681 			if (!checkonly) {
10682 				mutex_enter(&connp->conn_lock);
10683 				connp->conn_dontroute = *i1 ? 1 : 0;
10684 				mutex_exit(&connp->conn_lock);
10685 			}
10686 			break;	/* goto sizeof (int) option return */
10687 		case SO_REUSEADDR:
10688 			if (!checkonly) {
10689 				mutex_enter(&connp->conn_lock);
10690 				connp->conn_reuseaddr = *i1 ? 1 : 0;
10691 				mutex_exit(&connp->conn_lock);
10692 			}
10693 			break;	/* goto sizeof (int) option return */
10694 		case SO_PROTOTYPE:
10695 			if (!checkonly) {
10696 				mutex_enter(&connp->conn_lock);
10697 				connp->conn_proto = *i1;
10698 				mutex_exit(&connp->conn_lock);
10699 			}
10700 			break;	/* goto sizeof (int) option return */
10701 		case SO_ALLZONES:
10702 			if (!checkonly) {
10703 				mutex_enter(&connp->conn_lock);
10704 				if (IPCL_IS_BOUND(connp)) {
10705 					mutex_exit(&connp->conn_lock);
10706 					return (EINVAL);
10707 				}
10708 				connp->conn_allzones = *i1 != 0 ? 1 : 0;
10709 				mutex_exit(&connp->conn_lock);
10710 			}
10711 			break;	/* goto sizeof (int) option return */
10712 		case SO_ANON_MLP:
10713 			if (!checkonly) {
10714 				mutex_enter(&connp->conn_lock);
10715 				connp->conn_anon_mlp = *i1 != 0 ? 1 : 0;
10716 				mutex_exit(&connp->conn_lock);
10717 			}
10718 			break;	/* goto sizeof (int) option return */
10719 		case SO_MAC_EXEMPT:
10720 			if (secpolicy_net_mac_aware(cr) != 0 ||
10721 			    IPCL_IS_BOUND(connp))
10722 				return (EACCES);
10723 			if (!checkonly) {
10724 				mutex_enter(&connp->conn_lock);
10725 				connp->conn_mac_exempt = *i1 != 0 ? 1 : 0;
10726 				mutex_exit(&connp->conn_lock);
10727 			}
10728 			break;	/* goto sizeof (int) option return */
10729 		default:
10730 			/*
10731 			 * "soft" error (negative)
10732 			 * option not handled at this level
10733 			 * Note: Do not modify *outlenp
10734 			 */
10735 			return (-EINVAL);
10736 		}
10737 		break;
10738 	case IPPROTO_IP:
10739 		switch (name) {
10740 		case IP_NEXTHOP:
10741 			if (secpolicy_ip_config(cr, B_FALSE) != 0)
10742 				return (EPERM);
10743 			/* FALLTHRU */
10744 		case IP_MULTICAST_IF:
10745 		case IP_DONTFAILOVER_IF: {
10746 			ipaddr_t addr = *i1;
10747 
10748 			error = ip_opt_set_ipif(connp, addr, checkonly, name,
10749 			    first_mp);
10750 			if (error != 0)
10751 				return (error);
10752 			break;	/* goto sizeof (int) option return */
10753 		}
10754 
10755 		case IP_MULTICAST_TTL:
10756 			/* Recorded in transport above IP */
10757 			*outvalp = *invalp;
10758 			*outlenp = sizeof (uchar_t);
10759 			return (0);
10760 		case IP_MULTICAST_LOOP:
10761 			if (!checkonly) {
10762 				mutex_enter(&connp->conn_lock);
10763 				connp->conn_multicast_loop = *invalp ? 1 : 0;
10764 				mutex_exit(&connp->conn_lock);
10765 			}
10766 			*outvalp = *invalp;
10767 			*outlenp = sizeof (uchar_t);
10768 			return (0);
10769 		case IP_ADD_MEMBERSHIP:
10770 		case MCAST_JOIN_GROUP:
10771 		case IP_DROP_MEMBERSHIP:
10772 		case MCAST_LEAVE_GROUP: {
10773 			struct ip_mreq *mreqp;
10774 			struct group_req *greqp;
10775 			ire_t *ire;
10776 			boolean_t done = B_FALSE;
10777 			ipaddr_t group, ifaddr;
10778 			struct sockaddr_in *sin;
10779 			uint32_t *ifindexp;
10780 			boolean_t mcast_opt = B_TRUE;
10781 			mcast_record_t fmode;
10782 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10783 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10784 
10785 			switch (name) {
10786 			case IP_ADD_MEMBERSHIP:
10787 				mcast_opt = B_FALSE;
10788 				/* FALLTHRU */
10789 			case MCAST_JOIN_GROUP:
10790 				fmode = MODE_IS_EXCLUDE;
10791 				optfn = ip_opt_add_group;
10792 				break;
10793 
10794 			case IP_DROP_MEMBERSHIP:
10795 				mcast_opt = B_FALSE;
10796 				/* FALLTHRU */
10797 			case MCAST_LEAVE_GROUP:
10798 				fmode = MODE_IS_INCLUDE;
10799 				optfn = ip_opt_delete_group;
10800 				break;
10801 			}
10802 
10803 			if (mcast_opt) {
10804 				greqp = (struct group_req *)i1;
10805 				sin = (struct sockaddr_in *)&greqp->gr_group;
10806 				if (sin->sin_family != AF_INET) {
10807 					*outlenp = 0;
10808 					return (ENOPROTOOPT);
10809 				}
10810 				group = (ipaddr_t)sin->sin_addr.s_addr;
10811 				ifaddr = INADDR_ANY;
10812 				ifindexp = &greqp->gr_interface;
10813 			} else {
10814 				mreqp = (struct ip_mreq *)i1;
10815 				group = (ipaddr_t)mreqp->imr_multiaddr.s_addr;
10816 				ifaddr = (ipaddr_t)mreqp->imr_interface.s_addr;
10817 				ifindexp = NULL;
10818 			}
10819 
10820 			/*
10821 			 * In the multirouting case, we need to replicate
10822 			 * the request on all interfaces that will take part
10823 			 * in replication.  We do so because multirouting is
10824 			 * reflective, thus we will probably receive multi-
10825 			 * casts on those interfaces.
10826 			 * The ip_multirt_apply_membership() succeeds if the
10827 			 * operation succeeds on at least one interface.
10828 			 */
10829 			ire = ire_ftable_lookup(group, IP_HOST_MASK, 0,
10830 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10831 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10832 			if (ire != NULL) {
10833 				if (ire->ire_flags & RTF_MULTIRT) {
10834 					error = ip_multirt_apply_membership(
10835 					    optfn, ire, connp, checkonly, group,
10836 					    fmode, INADDR_ANY, first_mp);
10837 					done = B_TRUE;
10838 				}
10839 				ire_refrele(ire);
10840 			}
10841 			if (!done) {
10842 				error = optfn(connp, checkonly, group, ifaddr,
10843 				    ifindexp, fmode, INADDR_ANY, first_mp);
10844 			}
10845 			if (error) {
10846 				/*
10847 				 * EINPROGRESS is a soft error, needs retry
10848 				 * so don't make *outlenp zero.
10849 				 */
10850 				if (error != EINPROGRESS)
10851 					*outlenp = 0;
10852 				return (error);
10853 			}
10854 			/* OK return - copy input buffer into output buffer */
10855 			if (invalp != outvalp) {
10856 				/* don't trust bcopy for identical src/dst */
10857 				bcopy(invalp, outvalp, inlen);
10858 			}
10859 			*outlenp = inlen;
10860 			return (0);
10861 		}
10862 		case IP_BLOCK_SOURCE:
10863 		case IP_UNBLOCK_SOURCE:
10864 		case IP_ADD_SOURCE_MEMBERSHIP:
10865 		case IP_DROP_SOURCE_MEMBERSHIP:
10866 		case MCAST_BLOCK_SOURCE:
10867 		case MCAST_UNBLOCK_SOURCE:
10868 		case MCAST_JOIN_SOURCE_GROUP:
10869 		case MCAST_LEAVE_SOURCE_GROUP: {
10870 			struct ip_mreq_source *imreqp;
10871 			struct group_source_req *gsreqp;
10872 			in_addr_t grp, src, ifaddr = INADDR_ANY;
10873 			uint32_t ifindex = 0;
10874 			mcast_record_t fmode;
10875 			struct sockaddr_in *sin;
10876 			ire_t *ire;
10877 			boolean_t mcast_opt = B_TRUE, done = B_FALSE;
10878 			int (*optfn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
10879 			    uint_t *, mcast_record_t, ipaddr_t, mblk_t *);
10880 
10881 			switch (name) {
10882 			case IP_BLOCK_SOURCE:
10883 				mcast_opt = B_FALSE;
10884 				/* FALLTHRU */
10885 			case MCAST_BLOCK_SOURCE:
10886 				fmode = MODE_IS_EXCLUDE;
10887 				optfn = ip_opt_add_group;
10888 				break;
10889 
10890 			case IP_UNBLOCK_SOURCE:
10891 				mcast_opt = B_FALSE;
10892 				/* FALLTHRU */
10893 			case MCAST_UNBLOCK_SOURCE:
10894 				fmode = MODE_IS_EXCLUDE;
10895 				optfn = ip_opt_delete_group;
10896 				break;
10897 
10898 			case IP_ADD_SOURCE_MEMBERSHIP:
10899 				mcast_opt = B_FALSE;
10900 				/* FALLTHRU */
10901 			case MCAST_JOIN_SOURCE_GROUP:
10902 				fmode = MODE_IS_INCLUDE;
10903 				optfn = ip_opt_add_group;
10904 				break;
10905 
10906 			case IP_DROP_SOURCE_MEMBERSHIP:
10907 				mcast_opt = B_FALSE;
10908 				/* FALLTHRU */
10909 			case MCAST_LEAVE_SOURCE_GROUP:
10910 				fmode = MODE_IS_INCLUDE;
10911 				optfn = ip_opt_delete_group;
10912 				break;
10913 			}
10914 
10915 			if (mcast_opt) {
10916 				gsreqp = (struct group_source_req *)i1;
10917 				if (gsreqp->gsr_group.ss_family != AF_INET) {
10918 					*outlenp = 0;
10919 					return (ENOPROTOOPT);
10920 				}
10921 				sin = (struct sockaddr_in *)&gsreqp->gsr_group;
10922 				grp = (ipaddr_t)sin->sin_addr.s_addr;
10923 				sin = (struct sockaddr_in *)&gsreqp->gsr_source;
10924 				src = (ipaddr_t)sin->sin_addr.s_addr;
10925 				ifindex = gsreqp->gsr_interface;
10926 			} else {
10927 				imreqp = (struct ip_mreq_source *)i1;
10928 				grp = (ipaddr_t)imreqp->imr_multiaddr.s_addr;
10929 				src = (ipaddr_t)imreqp->imr_sourceaddr.s_addr;
10930 				ifaddr = (ipaddr_t)imreqp->imr_interface.s_addr;
10931 			}
10932 
10933 			/*
10934 			 * In the multirouting case, we need to replicate
10935 			 * the request as noted in the mcast cases above.
10936 			 */
10937 			ire = ire_ftable_lookup(grp, IP_HOST_MASK, 0,
10938 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
10939 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
10940 			if (ire != NULL) {
10941 				if (ire->ire_flags & RTF_MULTIRT) {
10942 					error = ip_multirt_apply_membership(
10943 					    optfn, ire, connp, checkonly, grp,
10944 					    fmode, src, first_mp);
10945 					done = B_TRUE;
10946 				}
10947 				ire_refrele(ire);
10948 			}
10949 			if (!done) {
10950 				error = optfn(connp, checkonly, grp, ifaddr,
10951 				    &ifindex, fmode, src, first_mp);
10952 			}
10953 			if (error != 0) {
10954 				/*
10955 				 * EINPROGRESS is a soft error, needs retry
10956 				 * so don't make *outlenp zero.
10957 				 */
10958 				if (error != EINPROGRESS)
10959 					*outlenp = 0;
10960 				return (error);
10961 			}
10962 			/* OK return - copy input buffer into output buffer */
10963 			if (invalp != outvalp) {
10964 				bcopy(invalp, outvalp, inlen);
10965 			}
10966 			*outlenp = inlen;
10967 			return (0);
10968 		}
10969 		case IP_SEC_OPT:
10970 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
10971 			if (error != 0) {
10972 				*outlenp = 0;
10973 				return (error);
10974 			}
10975 			break;
10976 		case IP_HDRINCL:
10977 		case IP_OPTIONS:
10978 		case T_IP_OPTIONS:
10979 		case IP_TOS:
10980 		case T_IP_TOS:
10981 		case IP_TTL:
10982 		case IP_RECVDSTADDR:
10983 		case IP_RECVOPTS:
10984 			/* OK return - copy input buffer into output buffer */
10985 			if (invalp != outvalp) {
10986 				/* don't trust bcopy for identical src/dst */
10987 				bcopy(invalp, outvalp, inlen);
10988 			}
10989 			*outlenp = inlen;
10990 			return (0);
10991 		case IP_RECVIF:
10992 			/* Retrieve the inbound interface index */
10993 			if (!checkonly) {
10994 				mutex_enter(&connp->conn_lock);
10995 				connp->conn_recvif = *i1 ? 1 : 0;
10996 				mutex_exit(&connp->conn_lock);
10997 			}
10998 			break;	/* goto sizeof (int) option return */
10999 		case IP_RECVPKTINFO:
11000 			if (!checkonly) {
11001 				mutex_enter(&connp->conn_lock);
11002 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11003 				mutex_exit(&connp->conn_lock);
11004 			}
11005 			break;	/* goto sizeof (int) option return */
11006 		case IP_RECVSLLA:
11007 			/* Retrieve the source link layer address */
11008 			if (!checkonly) {
11009 				mutex_enter(&connp->conn_lock);
11010 				connp->conn_recvslla = *i1 ? 1 : 0;
11011 				mutex_exit(&connp->conn_lock);
11012 			}
11013 			break;	/* goto sizeof (int) option return */
11014 		case MRT_INIT:
11015 		case MRT_DONE:
11016 		case MRT_ADD_VIF:
11017 		case MRT_DEL_VIF:
11018 		case MRT_ADD_MFC:
11019 		case MRT_DEL_MFC:
11020 		case MRT_ASSERT:
11021 			if ((error = secpolicy_ip_config(cr, B_FALSE)) != 0) {
11022 				*outlenp = 0;
11023 				return (error);
11024 			}
11025 			error = ip_mrouter_set((int)name, q, checkonly,
11026 			    (uchar_t *)invalp, inlen, first_mp);
11027 			if (error) {
11028 				*outlenp = 0;
11029 				return (error);
11030 			}
11031 			/* OK return - copy input buffer into output buffer */
11032 			if (invalp != outvalp) {
11033 				/* don't trust bcopy for identical src/dst */
11034 				bcopy(invalp, outvalp, inlen);
11035 			}
11036 			*outlenp = inlen;
11037 			return (0);
11038 		case IP_BOUND_IF:
11039 		case IP_DHCPINIT_IF:
11040 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11041 			    level, name, first_mp);
11042 			if (error != 0)
11043 				return (error);
11044 			break; 		/* goto sizeof (int) option return */
11045 
11046 		case IP_UNSPEC_SRC:
11047 			/* Allow sending with a zero source address */
11048 			if (!checkonly) {
11049 				mutex_enter(&connp->conn_lock);
11050 				connp->conn_unspec_src = *i1 ? 1 : 0;
11051 				mutex_exit(&connp->conn_lock);
11052 			}
11053 			break;	/* goto sizeof (int) option return */
11054 		default:
11055 			/*
11056 			 * "soft" error (negative)
11057 			 * option not handled at this level
11058 			 * Note: Do not modify *outlenp
11059 			 */
11060 			return (-EINVAL);
11061 		}
11062 		break;
11063 	case IPPROTO_IPV6:
11064 		switch (name) {
11065 		case IPV6_BOUND_IF:
11066 		case IPV6_BOUND_PIF:
11067 		case IPV6_DONTFAILOVER_IF:
11068 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11069 			    level, name, first_mp);
11070 			if (error != 0)
11071 				return (error);
11072 			break; 		/* goto sizeof (int) option return */
11073 
11074 		case IPV6_MULTICAST_IF:
11075 			/*
11076 			 * The only possible errors are EINPROGRESS and
11077 			 * EINVAL. EINPROGRESS will be restarted and is not
11078 			 * a hard error. We call this option on both V4 and V6
11079 			 * If both return EINVAL, then this call returns
11080 			 * EINVAL. If at least one of them succeeds we
11081 			 * return success.
11082 			 */
11083 			found = B_FALSE;
11084 			error = ip_opt_set_ill(connp, *i1, B_TRUE, checkonly,
11085 			    level, name, first_mp);
11086 			if (error == EINPROGRESS)
11087 				return (error);
11088 			if (error == 0)
11089 				found = B_TRUE;
11090 			error = ip_opt_set_ill(connp, *i1, B_FALSE, checkonly,
11091 			    IPPROTO_IP, IP_MULTICAST_IF, first_mp);
11092 			if (error == 0)
11093 				found = B_TRUE;
11094 			if (!found)
11095 				return (error);
11096 			break; 		/* goto sizeof (int) option return */
11097 
11098 		case IPV6_MULTICAST_HOPS:
11099 			/* Recorded in transport above IP */
11100 			break;	/* goto sizeof (int) option return */
11101 		case IPV6_MULTICAST_LOOP:
11102 			if (!checkonly) {
11103 				mutex_enter(&connp->conn_lock);
11104 				connp->conn_multicast_loop = *i1;
11105 				mutex_exit(&connp->conn_lock);
11106 			}
11107 			break;	/* goto sizeof (int) option return */
11108 		case IPV6_JOIN_GROUP:
11109 		case MCAST_JOIN_GROUP:
11110 		case IPV6_LEAVE_GROUP:
11111 		case MCAST_LEAVE_GROUP: {
11112 			struct ipv6_mreq *ip_mreqp;
11113 			struct group_req *greqp;
11114 			ire_t *ire;
11115 			boolean_t done = B_FALSE;
11116 			in6_addr_t groupv6;
11117 			uint32_t ifindex;
11118 			boolean_t mcast_opt = B_TRUE;
11119 			mcast_record_t fmode;
11120 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11121 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11122 
11123 			switch (name) {
11124 			case IPV6_JOIN_GROUP:
11125 				mcast_opt = B_FALSE;
11126 				/* FALLTHRU */
11127 			case MCAST_JOIN_GROUP:
11128 				fmode = MODE_IS_EXCLUDE;
11129 				optfn = ip_opt_add_group_v6;
11130 				break;
11131 
11132 			case IPV6_LEAVE_GROUP:
11133 				mcast_opt = B_FALSE;
11134 				/* FALLTHRU */
11135 			case MCAST_LEAVE_GROUP:
11136 				fmode = MODE_IS_INCLUDE;
11137 				optfn = ip_opt_delete_group_v6;
11138 				break;
11139 			}
11140 
11141 			if (mcast_opt) {
11142 				struct sockaddr_in *sin;
11143 				struct sockaddr_in6 *sin6;
11144 				greqp = (struct group_req *)i1;
11145 				if (greqp->gr_group.ss_family == AF_INET) {
11146 					sin = (struct sockaddr_in *)
11147 					    &(greqp->gr_group);
11148 					IN6_INADDR_TO_V4MAPPED(&sin->sin_addr,
11149 					    &groupv6);
11150 				} else {
11151 					sin6 = (struct sockaddr_in6 *)
11152 					    &(greqp->gr_group);
11153 					groupv6 = sin6->sin6_addr;
11154 				}
11155 				ifindex = greqp->gr_interface;
11156 			} else {
11157 				ip_mreqp = (struct ipv6_mreq *)i1;
11158 				groupv6 = ip_mreqp->ipv6mr_multiaddr;
11159 				ifindex = ip_mreqp->ipv6mr_interface;
11160 			}
11161 			/*
11162 			 * In the multirouting case, we need to replicate
11163 			 * the request on all interfaces that will take part
11164 			 * in replication.  We do so because multirouting is
11165 			 * reflective, thus we will probably receive multi-
11166 			 * casts on those interfaces.
11167 			 * The ip_multirt_apply_membership_v6() succeeds if
11168 			 * the operation succeeds on at least one interface.
11169 			 */
11170 			ire = ire_ftable_lookup_v6(&groupv6, &ipv6_all_ones, 0,
11171 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11172 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11173 			if (ire != NULL) {
11174 				if (ire->ire_flags & RTF_MULTIRT) {
11175 					error = ip_multirt_apply_membership_v6(
11176 					    optfn, ire, connp, checkonly,
11177 					    &groupv6, fmode, &ipv6_all_zeros,
11178 					    first_mp);
11179 					done = B_TRUE;
11180 				}
11181 				ire_refrele(ire);
11182 			}
11183 			if (!done) {
11184 				error = optfn(connp, checkonly, &groupv6,
11185 				    ifindex, fmode, &ipv6_all_zeros, first_mp);
11186 			}
11187 			if (error) {
11188 				/*
11189 				 * EINPROGRESS is a soft error, needs retry
11190 				 * so don't make *outlenp zero.
11191 				 */
11192 				if (error != EINPROGRESS)
11193 					*outlenp = 0;
11194 				return (error);
11195 			}
11196 			/* OK return - copy input buffer into output buffer */
11197 			if (invalp != outvalp) {
11198 				/* don't trust bcopy for identical src/dst */
11199 				bcopy(invalp, outvalp, inlen);
11200 			}
11201 			*outlenp = inlen;
11202 			return (0);
11203 		}
11204 		case MCAST_BLOCK_SOURCE:
11205 		case MCAST_UNBLOCK_SOURCE:
11206 		case MCAST_JOIN_SOURCE_GROUP:
11207 		case MCAST_LEAVE_SOURCE_GROUP: {
11208 			struct group_source_req *gsreqp;
11209 			in6_addr_t v6grp, v6src;
11210 			uint32_t ifindex;
11211 			mcast_record_t fmode;
11212 			ire_t *ire;
11213 			boolean_t done = B_FALSE;
11214 			int (*optfn)(conn_t *, boolean_t, const in6_addr_t *,
11215 			    int, mcast_record_t, const in6_addr_t *, mblk_t *);
11216 
11217 			switch (name) {
11218 			case MCAST_BLOCK_SOURCE:
11219 				fmode = MODE_IS_EXCLUDE;
11220 				optfn = ip_opt_add_group_v6;
11221 				break;
11222 			case MCAST_UNBLOCK_SOURCE:
11223 				fmode = MODE_IS_EXCLUDE;
11224 				optfn = ip_opt_delete_group_v6;
11225 				break;
11226 			case MCAST_JOIN_SOURCE_GROUP:
11227 				fmode = MODE_IS_INCLUDE;
11228 				optfn = ip_opt_add_group_v6;
11229 				break;
11230 			case MCAST_LEAVE_SOURCE_GROUP:
11231 				fmode = MODE_IS_INCLUDE;
11232 				optfn = ip_opt_delete_group_v6;
11233 				break;
11234 			}
11235 
11236 			gsreqp = (struct group_source_req *)i1;
11237 			ifindex = gsreqp->gsr_interface;
11238 			if (gsreqp->gsr_group.ss_family == AF_INET) {
11239 				struct sockaddr_in *s;
11240 				s = (struct sockaddr_in *)&gsreqp->gsr_group;
11241 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6grp);
11242 				s = (struct sockaddr_in *)&gsreqp->gsr_source;
11243 				IN6_INADDR_TO_V4MAPPED(&s->sin_addr, &v6src);
11244 			} else {
11245 				struct sockaddr_in6 *s6;
11246 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_group;
11247 				v6grp = s6->sin6_addr;
11248 				s6 = (struct sockaddr_in6 *)&gsreqp->gsr_source;
11249 				v6src = s6->sin6_addr;
11250 			}
11251 
11252 			/*
11253 			 * In the multirouting case, we need to replicate
11254 			 * the request as noted in the mcast cases above.
11255 			 */
11256 			ire = ire_ftable_lookup_v6(&v6grp, &ipv6_all_ones, 0,
11257 			    IRE_HOST, NULL, NULL, ALL_ZONES, 0, NULL,
11258 			    MATCH_IRE_MASK | MATCH_IRE_TYPE, ipst);
11259 			if (ire != NULL) {
11260 				if (ire->ire_flags & RTF_MULTIRT) {
11261 					error = ip_multirt_apply_membership_v6(
11262 					    optfn, ire, connp, checkonly,
11263 					    &v6grp, fmode, &v6src, first_mp);
11264 					done = B_TRUE;
11265 				}
11266 				ire_refrele(ire);
11267 			}
11268 			if (!done) {
11269 				error = optfn(connp, checkonly, &v6grp,
11270 				    ifindex, fmode, &v6src, first_mp);
11271 			}
11272 			if (error != 0) {
11273 				/*
11274 				 * EINPROGRESS is a soft error, needs retry
11275 				 * so don't make *outlenp zero.
11276 				 */
11277 				if (error != EINPROGRESS)
11278 					*outlenp = 0;
11279 				return (error);
11280 			}
11281 			/* OK return - copy input buffer into output buffer */
11282 			if (invalp != outvalp) {
11283 				bcopy(invalp, outvalp, inlen);
11284 			}
11285 			*outlenp = inlen;
11286 			return (0);
11287 		}
11288 		case IPV6_UNICAST_HOPS:
11289 			/* Recorded in transport above IP */
11290 			break;	/* goto sizeof (int) option return */
11291 		case IPV6_UNSPEC_SRC:
11292 			/* Allow sending with a zero source address */
11293 			if (!checkonly) {
11294 				mutex_enter(&connp->conn_lock);
11295 				connp->conn_unspec_src = *i1 ? 1 : 0;
11296 				mutex_exit(&connp->conn_lock);
11297 			}
11298 			break;	/* goto sizeof (int) option return */
11299 		case IPV6_RECVPKTINFO:
11300 			if (!checkonly) {
11301 				mutex_enter(&connp->conn_lock);
11302 				connp->conn_ip_recvpktinfo = *i1 ? 1 : 0;
11303 				mutex_exit(&connp->conn_lock);
11304 			}
11305 			break;	/* goto sizeof (int) option return */
11306 		case IPV6_RECVTCLASS:
11307 			if (!checkonly) {
11308 				if (*i1 < 0 || *i1 > 1) {
11309 					return (EINVAL);
11310 				}
11311 				mutex_enter(&connp->conn_lock);
11312 				connp->conn_ipv6_recvtclass = *i1;
11313 				mutex_exit(&connp->conn_lock);
11314 			}
11315 			break;
11316 		case IPV6_RECVPATHMTU:
11317 			if (!checkonly) {
11318 				if (*i1 < 0 || *i1 > 1) {
11319 					return (EINVAL);
11320 				}
11321 				mutex_enter(&connp->conn_lock);
11322 				connp->conn_ipv6_recvpathmtu = *i1;
11323 				mutex_exit(&connp->conn_lock);
11324 			}
11325 			break;
11326 		case IPV6_RECVHOPLIMIT:
11327 			if (!checkonly) {
11328 				mutex_enter(&connp->conn_lock);
11329 				connp->conn_ipv6_recvhoplimit = *i1 ? 1 : 0;
11330 				mutex_exit(&connp->conn_lock);
11331 			}
11332 			break;	/* goto sizeof (int) option return */
11333 		case IPV6_RECVHOPOPTS:
11334 			if (!checkonly) {
11335 				mutex_enter(&connp->conn_lock);
11336 				connp->conn_ipv6_recvhopopts = *i1 ? 1 : 0;
11337 				mutex_exit(&connp->conn_lock);
11338 			}
11339 			break;	/* goto sizeof (int) option return */
11340 		case IPV6_RECVDSTOPTS:
11341 			if (!checkonly) {
11342 				mutex_enter(&connp->conn_lock);
11343 				connp->conn_ipv6_recvdstopts = *i1 ? 1 : 0;
11344 				mutex_exit(&connp->conn_lock);
11345 			}
11346 			break;	/* goto sizeof (int) option return */
11347 		case IPV6_RECVRTHDR:
11348 			if (!checkonly) {
11349 				mutex_enter(&connp->conn_lock);
11350 				connp->conn_ipv6_recvrthdr = *i1 ? 1 : 0;
11351 				mutex_exit(&connp->conn_lock);
11352 			}
11353 			break;	/* goto sizeof (int) option return */
11354 		case IPV6_RECVRTHDRDSTOPTS:
11355 			if (!checkonly) {
11356 				mutex_enter(&connp->conn_lock);
11357 				connp->conn_ipv6_recvrtdstopts = *i1 ? 1 : 0;
11358 				mutex_exit(&connp->conn_lock);
11359 			}
11360 			break;	/* goto sizeof (int) option return */
11361 		case IPV6_PKTINFO:
11362 			if (inlen == 0)
11363 				return (-EINVAL);	/* clearing option */
11364 			error = ip6_set_pktinfo(cr, connp,
11365 			    (struct in6_pktinfo *)invalp, first_mp);
11366 			if (error != 0)
11367 				*outlenp = 0;
11368 			else
11369 				*outlenp = inlen;
11370 			return (error);
11371 		case IPV6_NEXTHOP: {
11372 			struct sockaddr_in6 *sin6;
11373 
11374 			/* Verify that the nexthop is reachable */
11375 			if (inlen == 0)
11376 				return (-EINVAL);	/* clearing option */
11377 
11378 			sin6 = (struct sockaddr_in6 *)invalp;
11379 			ire = ire_route_lookup_v6(&sin6->sin6_addr,
11380 			    0, 0, 0, NULL, NULL, connp->conn_zoneid,
11381 			    NULL, MATCH_IRE_DEFAULT, ipst);
11382 
11383 			if (ire == NULL) {
11384 				*outlenp = 0;
11385 				return (EHOSTUNREACH);
11386 			}
11387 			ire_refrele(ire);
11388 			return (-EINVAL);
11389 		}
11390 		case IPV6_SEC_OPT:
11391 			error = ipsec_set_req(cr, connp, (ipsec_req_t *)invalp);
11392 			if (error != 0) {
11393 				*outlenp = 0;
11394 				return (error);
11395 			}
11396 			break;
11397 		case IPV6_SRC_PREFERENCES: {
11398 			/*
11399 			 * This is implemented strictly in the ip module
11400 			 * (here and in tcp_opt_*() to accomodate tcp
11401 			 * sockets).  Modules above ip pass this option
11402 			 * down here since ip is the only one that needs to
11403 			 * be aware of source address preferences.
11404 			 *
11405 			 * This socket option only affects connected
11406 			 * sockets that haven't already bound to a specific
11407 			 * IPv6 address.  In other words, sockets that
11408 			 * don't call bind() with an address other than the
11409 			 * unspecified address and that call connect().
11410 			 * ip_bind_connected_v6() passes these preferences
11411 			 * to the ipif_select_source_v6() function.
11412 			 */
11413 			if (inlen != sizeof (uint32_t))
11414 				return (EINVAL);
11415 			error = ip6_set_src_preferences(connp,
11416 			    *(uint32_t *)invalp);
11417 			if (error != 0) {
11418 				*outlenp = 0;
11419 				return (error);
11420 			} else {
11421 				*outlenp = sizeof (uint32_t);
11422 			}
11423 			break;
11424 		}
11425 		case IPV6_V6ONLY:
11426 			if (*i1 < 0 || *i1 > 1) {
11427 				return (EINVAL);
11428 			}
11429 			mutex_enter(&connp->conn_lock);
11430 			connp->conn_ipv6_v6only = *i1;
11431 			mutex_exit(&connp->conn_lock);
11432 			break;
11433 		default:
11434 			return (-EINVAL);
11435 		}
11436 		break;
11437 	default:
11438 		/*
11439 		 * "soft" error (negative)
11440 		 * option not handled at this level
11441 		 * Note: Do not modify *outlenp
11442 		 */
11443 		return (-EINVAL);
11444 	}
11445 	/*
11446 	 * Common case of return from an option that is sizeof (int)
11447 	 */
11448 	*(int *)outvalp = *i1;
11449 	*outlenp = sizeof (int);
11450 	return (0);
11451 }
11452 
11453 /*
11454  * This routine gets default values of certain options whose default
11455  * values are maintained by protocol specific code
11456  */
11457 /* ARGSUSED */
11458 int
11459 ip_opt_default(queue_t *q, int level, int name, uchar_t *ptr)
11460 {
11461 	int *i1 = (int *)ptr;
11462 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
11463 
11464 	switch (level) {
11465 	case IPPROTO_IP:
11466 		switch (name) {
11467 		case IP_MULTICAST_TTL:
11468 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_TTL;
11469 			return (sizeof (uchar_t));
11470 		case IP_MULTICAST_LOOP:
11471 			*ptr = (uchar_t)IP_DEFAULT_MULTICAST_LOOP;
11472 			return (sizeof (uchar_t));
11473 		default:
11474 			return (-1);
11475 		}
11476 	case IPPROTO_IPV6:
11477 		switch (name) {
11478 		case IPV6_UNICAST_HOPS:
11479 			*i1 = ipst->ips_ipv6_def_hops;
11480 			return (sizeof (int));
11481 		case IPV6_MULTICAST_HOPS:
11482 			*i1 = IP_DEFAULT_MULTICAST_TTL;
11483 			return (sizeof (int));
11484 		case IPV6_MULTICAST_LOOP:
11485 			*i1 = IP_DEFAULT_MULTICAST_LOOP;
11486 			return (sizeof (int));
11487 		case IPV6_V6ONLY:
11488 			*i1 = 1;
11489 			return (sizeof (int));
11490 		default:
11491 			return (-1);
11492 		}
11493 	default:
11494 		return (-1);
11495 	}
11496 	/* NOTREACHED */
11497 }
11498 
11499 /*
11500  * Given a destination address and a pointer to where to put the information
11501  * this routine fills in the mtuinfo.
11502  */
11503 int
11504 ip_fill_mtuinfo(struct in6_addr *in6, in_port_t port,
11505     struct ip6_mtuinfo *mtuinfo, netstack_t *ns)
11506 {
11507 	ire_t *ire;
11508 	ip_stack_t	*ipst = ns->netstack_ip;
11509 
11510 	if (IN6_IS_ADDR_UNSPECIFIED(in6))
11511 		return (-1);
11512 
11513 	bzero(mtuinfo, sizeof (*mtuinfo));
11514 	mtuinfo->ip6m_addr.sin6_family = AF_INET6;
11515 	mtuinfo->ip6m_addr.sin6_port = port;
11516 	mtuinfo->ip6m_addr.sin6_addr = *in6;
11517 
11518 	ire = ire_cache_lookup_v6(in6, ALL_ZONES, NULL, ipst);
11519 	if (ire != NULL) {
11520 		mtuinfo->ip6m_mtu = ire->ire_max_frag;
11521 		ire_refrele(ire);
11522 	} else {
11523 		mtuinfo->ip6m_mtu = IPV6_MIN_MTU;
11524 	}
11525 	return (sizeof (struct ip6_mtuinfo));
11526 }
11527 
11528 /*
11529  * This routine gets socket options.  For MRT_VERSION and MRT_ASSERT, error
11530  * checking of GET_QUEUE_CRED(q) and that ip_g_mrouter is set should be done and
11531  * isn't.  This doesn't matter as the error checking is done properly for the
11532  * other MRT options coming in through ip_opt_set.
11533  */
11534 int
11535 ip_opt_get(queue_t *q, int level, int name, uchar_t *ptr)
11536 {
11537 	conn_t		*connp = Q_TO_CONN(q);
11538 	ipsec_req_t	*req = (ipsec_req_t *)ptr;
11539 
11540 	switch (level) {
11541 	case IPPROTO_IP:
11542 		switch (name) {
11543 		case MRT_VERSION:
11544 		case MRT_ASSERT:
11545 			(void) ip_mrouter_get(name, q, ptr);
11546 			return (sizeof (int));
11547 		case IP_SEC_OPT:
11548 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V4));
11549 		case IP_NEXTHOP:
11550 			if (connp->conn_nexthop_set) {
11551 				*(ipaddr_t *)ptr = connp->conn_nexthop_v4;
11552 				return (sizeof (ipaddr_t));
11553 			} else
11554 				return (0);
11555 		case IP_RECVPKTINFO:
11556 			*(int *)ptr = connp->conn_ip_recvpktinfo ? 1: 0;
11557 			return (sizeof (int));
11558 		default:
11559 			break;
11560 		}
11561 		break;
11562 	case IPPROTO_IPV6:
11563 		switch (name) {
11564 		case IPV6_SEC_OPT:
11565 			return (ipsec_req_from_conn(connp, req, IPSEC_AF_V6));
11566 		case IPV6_SRC_PREFERENCES: {
11567 			return (ip6_get_src_preferences(connp,
11568 			    (uint32_t *)ptr));
11569 		}
11570 		case IPV6_V6ONLY:
11571 			*(int *)ptr = connp->conn_ipv6_v6only ? 1 : 0;
11572 			return (sizeof (int));
11573 		case IPV6_PATHMTU:
11574 			return (ip_fill_mtuinfo(&connp->conn_remv6, 0,
11575 			    (struct ip6_mtuinfo *)ptr, connp->conn_netstack));
11576 		default:
11577 			break;
11578 		}
11579 		break;
11580 	default:
11581 		break;
11582 	}
11583 	return (-1);
11584 }
11585 
11586 /* Named Dispatch routine to get a current value out of our parameter table. */
11587 /* ARGSUSED */
11588 static int
11589 ip_param_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11590 {
11591 	ipparam_t *ippa = (ipparam_t *)cp;
11592 
11593 	(void) mi_mpprintf(mp, "%d", ippa->ip_param_value);
11594 	return (0);
11595 }
11596 
11597 /* ARGSUSED */
11598 static int
11599 ip_param_generic_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
11600 {
11601 
11602 	(void) mi_mpprintf(mp, "%d", *(int *)cp);
11603 	return (0);
11604 }
11605 
11606 /*
11607  * Set ip{,6}_forwarding values.  This means walking through all of the
11608  * ill's and toggling their forwarding values.
11609  */
11610 /* ARGSUSED */
11611 static int
11612 ip_forward_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11613 {
11614 	long new_value;
11615 	int *forwarding_value = (int *)cp;
11616 	ill_t *ill;
11617 	boolean_t isv6;
11618 	ill_walk_context_t ctx;
11619 	ip_stack_t *ipst = CONNQ_TO_IPST(q);
11620 
11621 	isv6 = (forwarding_value == &ipst->ips_ipv6_forward);
11622 
11623 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11624 	    new_value < 0 || new_value > 1) {
11625 		return (EINVAL);
11626 	}
11627 
11628 	*forwarding_value = new_value;
11629 
11630 	/*
11631 	 * Regardless of the current value of ip_forwarding, set all per-ill
11632 	 * values of ip_forwarding to the value being set.
11633 	 *
11634 	 * Bring all the ill's up to date with the new global value.
11635 	 */
11636 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
11637 
11638 	if (isv6)
11639 		ill = ILL_START_WALK_V6(&ctx, ipst);
11640 	else
11641 		ill = ILL_START_WALK_V4(&ctx, ipst);
11642 
11643 	for (; ill != NULL; ill = ill_next(&ctx, ill))
11644 		(void) ill_forward_set(ill, new_value != 0);
11645 
11646 	rw_exit(&ipst->ips_ill_g_lock);
11647 	return (0);
11648 }
11649 
11650 /*
11651  * Walk through the param array specified registering each element with the
11652  * Named Dispatch handler. This is called only during init. So it is ok
11653  * not to acquire any locks
11654  */
11655 static boolean_t
11656 ip_param_register(IDP *ndp, ipparam_t *ippa, size_t ippa_cnt,
11657     ipndp_t *ipnd, size_t ipnd_cnt)
11658 {
11659 	for (; ippa_cnt-- > 0; ippa++) {
11660 		if (ippa->ip_param_name && ippa->ip_param_name[0]) {
11661 			if (!nd_load(ndp, ippa->ip_param_name,
11662 			    ip_param_get, ip_param_set, (caddr_t)ippa)) {
11663 				nd_free(ndp);
11664 				return (B_FALSE);
11665 			}
11666 		}
11667 	}
11668 
11669 	for (; ipnd_cnt-- > 0; ipnd++) {
11670 		if (ipnd->ip_ndp_name && ipnd->ip_ndp_name[0]) {
11671 			if (!nd_load(ndp, ipnd->ip_ndp_name,
11672 			    ipnd->ip_ndp_getf, ipnd->ip_ndp_setf,
11673 			    ipnd->ip_ndp_data)) {
11674 				nd_free(ndp);
11675 				return (B_FALSE);
11676 			}
11677 		}
11678 	}
11679 
11680 	return (B_TRUE);
11681 }
11682 
11683 /* Named Dispatch routine to negotiate a new value for one of our parameters. */
11684 /* ARGSUSED */
11685 static int
11686 ip_param_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp, cred_t *ioc_cr)
11687 {
11688 	long		new_value;
11689 	ipparam_t	*ippa = (ipparam_t *)cp;
11690 
11691 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
11692 	    new_value < ippa->ip_param_min || new_value > ippa->ip_param_max) {
11693 		return (EINVAL);
11694 	}
11695 	ippa->ip_param_value = new_value;
11696 	return (0);
11697 }
11698 
11699 /*
11700  * Handles both IPv4 and IPv6 reassembly - doing the out-of-order cases,
11701  * When an ipf is passed here for the first time, if
11702  * we already have in-order fragments on the queue, we convert from the fast-
11703  * path reassembly scheme to the hard-case scheme.  From then on, additional
11704  * fragments are reassembled here.  We keep track of the start and end offsets
11705  * of each piece, and the number of holes in the chain.  When the hole count
11706  * goes to zero, we are done!
11707  *
11708  * The ipf_count will be updated to account for any mblk(s) added (pointed to
11709  * by mp) or subtracted (freeb()ed dups), upon return the caller must update
11710  * ipfb_count and ill_frag_count by the difference of ipf_count before and
11711  * after the call to ip_reassemble().
11712  */
11713 int
11714 ip_reassemble(mblk_t *mp, ipf_t *ipf, uint_t start, boolean_t more, ill_t *ill,
11715     size_t msg_len)
11716 {
11717 	uint_t	end;
11718 	mblk_t	*next_mp;
11719 	mblk_t	*mp1;
11720 	uint_t	offset;
11721 	boolean_t incr_dups = B_TRUE;
11722 	boolean_t offset_zero_seen = B_FALSE;
11723 	boolean_t pkt_boundary_checked = B_FALSE;
11724 
11725 	/* If start == 0 then ipf_nf_hdr_len has to be set. */
11726 	ASSERT(start != 0 || ipf->ipf_nf_hdr_len != 0);
11727 
11728 	/* Add in byte count */
11729 	ipf->ipf_count += msg_len;
11730 	if (ipf->ipf_end) {
11731 		/*
11732 		 * We were part way through in-order reassembly, but now there
11733 		 * is a hole.  We walk through messages already queued, and
11734 		 * mark them for hard case reassembly.  We know that up till
11735 		 * now they were in order starting from offset zero.
11736 		 */
11737 		offset = 0;
11738 		for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
11739 			IP_REASS_SET_START(mp1, offset);
11740 			if (offset == 0) {
11741 				ASSERT(ipf->ipf_nf_hdr_len != 0);
11742 				offset = -ipf->ipf_nf_hdr_len;
11743 			}
11744 			offset += mp1->b_wptr - mp1->b_rptr;
11745 			IP_REASS_SET_END(mp1, offset);
11746 		}
11747 		/* One hole at the end. */
11748 		ipf->ipf_hole_cnt = 1;
11749 		/* Brand it as a hard case, forever. */
11750 		ipf->ipf_end = 0;
11751 	}
11752 	/* Walk through all the new pieces. */
11753 	do {
11754 		end = start + (mp->b_wptr - mp->b_rptr);
11755 		/*
11756 		 * If start is 0, decrease 'end' only for the first mblk of
11757 		 * the fragment. Otherwise 'end' can get wrong value in the
11758 		 * second pass of the loop if first mblk is exactly the
11759 		 * size of ipf_nf_hdr_len.
11760 		 */
11761 		if (start == 0 && !offset_zero_seen) {
11762 			/* First segment */
11763 			ASSERT(ipf->ipf_nf_hdr_len != 0);
11764 			end -= ipf->ipf_nf_hdr_len;
11765 			offset_zero_seen = B_TRUE;
11766 		}
11767 		next_mp = mp->b_cont;
11768 		/*
11769 		 * We are checking to see if there is any interesing data
11770 		 * to process.  If there isn't and the mblk isn't the
11771 		 * one which carries the unfragmentable header then we
11772 		 * drop it.  It's possible to have just the unfragmentable
11773 		 * header come through without any data.  That needs to be
11774 		 * saved.
11775 		 *
11776 		 * If the assert at the top of this function holds then the
11777 		 * term "ipf->ipf_nf_hdr_len != 0" isn't needed.  This code
11778 		 * is infrequently traveled enough that the test is left in
11779 		 * to protect against future code changes which break that
11780 		 * invariant.
11781 		 */
11782 		if (start == end && start != 0 && ipf->ipf_nf_hdr_len != 0) {
11783 			/* Empty.  Blast it. */
11784 			IP_REASS_SET_START(mp, 0);
11785 			IP_REASS_SET_END(mp, 0);
11786 			/*
11787 			 * If the ipf points to the mblk we are about to free,
11788 			 * update ipf to point to the next mblk (or NULL
11789 			 * if none).
11790 			 */
11791 			if (ipf->ipf_mp->b_cont == mp)
11792 				ipf->ipf_mp->b_cont = next_mp;
11793 			freeb(mp);
11794 			continue;
11795 		}
11796 		mp->b_cont = NULL;
11797 		IP_REASS_SET_START(mp, start);
11798 		IP_REASS_SET_END(mp, end);
11799 		if (!ipf->ipf_tail_mp) {
11800 			ipf->ipf_tail_mp = mp;
11801 			ipf->ipf_mp->b_cont = mp;
11802 			if (start == 0 || !more) {
11803 				ipf->ipf_hole_cnt = 1;
11804 				/*
11805 				 * if the first fragment comes in more than one
11806 				 * mblk, this loop will be executed for each
11807 				 * mblk. Need to adjust hole count so exiting
11808 				 * this routine will leave hole count at 1.
11809 				 */
11810 				if (next_mp)
11811 					ipf->ipf_hole_cnt++;
11812 			} else
11813 				ipf->ipf_hole_cnt = 2;
11814 			continue;
11815 		} else if (ipf->ipf_last_frag_seen && !more &&
11816 		    !pkt_boundary_checked) {
11817 			/*
11818 			 * We check datagram boundary only if this fragment
11819 			 * claims to be the last fragment and we have seen a
11820 			 * last fragment in the past too. We do this only
11821 			 * once for a given fragment.
11822 			 *
11823 			 * start cannot be 0 here as fragments with start=0
11824 			 * and MF=0 gets handled as a complete packet. These
11825 			 * fragments should not reach here.
11826 			 */
11827 
11828 			if (start + msgdsize(mp) !=
11829 			    IP_REASS_END(ipf->ipf_tail_mp)) {
11830 				/*
11831 				 * We have two fragments both of which claim
11832 				 * to be the last fragment but gives conflicting
11833 				 * information about the whole datagram size.
11834 				 * Something fishy is going on. Drop the
11835 				 * fragment and free up the reassembly list.
11836 				 */
11837 				return (IP_REASS_FAILED);
11838 			}
11839 
11840 			/*
11841 			 * We shouldn't come to this code block again for this
11842 			 * particular fragment.
11843 			 */
11844 			pkt_boundary_checked = B_TRUE;
11845 		}
11846 
11847 		/* New stuff at or beyond tail? */
11848 		offset = IP_REASS_END(ipf->ipf_tail_mp);
11849 		if (start >= offset) {
11850 			if (ipf->ipf_last_frag_seen) {
11851 				/* current fragment is beyond last fragment */
11852 				return (IP_REASS_FAILED);
11853 			}
11854 			/* Link it on end. */
11855 			ipf->ipf_tail_mp->b_cont = mp;
11856 			ipf->ipf_tail_mp = mp;
11857 			if (more) {
11858 				if (start != offset)
11859 					ipf->ipf_hole_cnt++;
11860 			} else if (start == offset && next_mp == NULL)
11861 					ipf->ipf_hole_cnt--;
11862 			continue;
11863 		}
11864 		mp1 = ipf->ipf_mp->b_cont;
11865 		offset = IP_REASS_START(mp1);
11866 		/* New stuff at the front? */
11867 		if (start < offset) {
11868 			if (start == 0) {
11869 				if (end >= offset) {
11870 					/* Nailed the hole at the begining. */
11871 					ipf->ipf_hole_cnt--;
11872 				}
11873 			} else if (end < offset) {
11874 				/*
11875 				 * A hole, stuff, and a hole where there used
11876 				 * to be just a hole.
11877 				 */
11878 				ipf->ipf_hole_cnt++;
11879 			}
11880 			mp->b_cont = mp1;
11881 			/* Check for overlap. */
11882 			while (end > offset) {
11883 				if (end < IP_REASS_END(mp1)) {
11884 					mp->b_wptr -= end - offset;
11885 					IP_REASS_SET_END(mp, offset);
11886 					BUMP_MIB(ill->ill_ip_mib,
11887 					    ipIfStatsReasmPartDups);
11888 					break;
11889 				}
11890 				/* Did we cover another hole? */
11891 				if ((mp1->b_cont &&
11892 				    IP_REASS_END(mp1) !=
11893 				    IP_REASS_START(mp1->b_cont) &&
11894 				    end >= IP_REASS_START(mp1->b_cont)) ||
11895 				    (!ipf->ipf_last_frag_seen && !more)) {
11896 					ipf->ipf_hole_cnt--;
11897 				}
11898 				/* Clip out mp1. */
11899 				if ((mp->b_cont = mp1->b_cont) == NULL) {
11900 					/*
11901 					 * After clipping out mp1, this guy
11902 					 * is now hanging off the end.
11903 					 */
11904 					ipf->ipf_tail_mp = mp;
11905 				}
11906 				IP_REASS_SET_START(mp1, 0);
11907 				IP_REASS_SET_END(mp1, 0);
11908 				/* Subtract byte count */
11909 				ipf->ipf_count -= mp1->b_datap->db_lim -
11910 				    mp1->b_datap->db_base;
11911 				freeb(mp1);
11912 				BUMP_MIB(ill->ill_ip_mib,
11913 				    ipIfStatsReasmPartDups);
11914 				mp1 = mp->b_cont;
11915 				if (!mp1)
11916 					break;
11917 				offset = IP_REASS_START(mp1);
11918 			}
11919 			ipf->ipf_mp->b_cont = mp;
11920 			continue;
11921 		}
11922 		/*
11923 		 * The new piece starts somewhere between the start of the head
11924 		 * and before the end of the tail.
11925 		 */
11926 		for (; mp1; mp1 = mp1->b_cont) {
11927 			offset = IP_REASS_END(mp1);
11928 			if (start < offset) {
11929 				if (end <= offset) {
11930 					/* Nothing new. */
11931 					IP_REASS_SET_START(mp, 0);
11932 					IP_REASS_SET_END(mp, 0);
11933 					/* Subtract byte count */
11934 					ipf->ipf_count -= mp->b_datap->db_lim -
11935 					    mp->b_datap->db_base;
11936 					if (incr_dups) {
11937 						ipf->ipf_num_dups++;
11938 						incr_dups = B_FALSE;
11939 					}
11940 					freeb(mp);
11941 					BUMP_MIB(ill->ill_ip_mib,
11942 					    ipIfStatsReasmDuplicates);
11943 					break;
11944 				}
11945 				/*
11946 				 * Trim redundant stuff off beginning of new
11947 				 * piece.
11948 				 */
11949 				IP_REASS_SET_START(mp, offset);
11950 				mp->b_rptr += offset - start;
11951 				BUMP_MIB(ill->ill_ip_mib,
11952 				    ipIfStatsReasmPartDups);
11953 				start = offset;
11954 				if (!mp1->b_cont) {
11955 					/*
11956 					 * After trimming, this guy is now
11957 					 * hanging off the end.
11958 					 */
11959 					mp1->b_cont = mp;
11960 					ipf->ipf_tail_mp = mp;
11961 					if (!more) {
11962 						ipf->ipf_hole_cnt--;
11963 					}
11964 					break;
11965 				}
11966 			}
11967 			if (start >= IP_REASS_START(mp1->b_cont))
11968 				continue;
11969 			/* Fill a hole */
11970 			if (start > offset)
11971 				ipf->ipf_hole_cnt++;
11972 			mp->b_cont = mp1->b_cont;
11973 			mp1->b_cont = mp;
11974 			mp1 = mp->b_cont;
11975 			offset = IP_REASS_START(mp1);
11976 			if (end >= offset) {
11977 				ipf->ipf_hole_cnt--;
11978 				/* Check for overlap. */
11979 				while (end > offset) {
11980 					if (end < IP_REASS_END(mp1)) {
11981 						mp->b_wptr -= end - offset;
11982 						IP_REASS_SET_END(mp, offset);
11983 						/*
11984 						 * TODO we might bump
11985 						 * this up twice if there is
11986 						 * overlap at both ends.
11987 						 */
11988 						BUMP_MIB(ill->ill_ip_mib,
11989 						    ipIfStatsReasmPartDups);
11990 						break;
11991 					}
11992 					/* Did we cover another hole? */
11993 					if ((mp1->b_cont &&
11994 					    IP_REASS_END(mp1)
11995 					    != IP_REASS_START(mp1->b_cont) &&
11996 					    end >=
11997 					    IP_REASS_START(mp1->b_cont)) ||
11998 					    (!ipf->ipf_last_frag_seen &&
11999 					    !more)) {
12000 						ipf->ipf_hole_cnt--;
12001 					}
12002 					/* Clip out mp1. */
12003 					if ((mp->b_cont = mp1->b_cont) ==
12004 					    NULL) {
12005 						/*
12006 						 * After clipping out mp1,
12007 						 * this guy is now hanging
12008 						 * off the end.
12009 						 */
12010 						ipf->ipf_tail_mp = mp;
12011 					}
12012 					IP_REASS_SET_START(mp1, 0);
12013 					IP_REASS_SET_END(mp1, 0);
12014 					/* Subtract byte count */
12015 					ipf->ipf_count -=
12016 					    mp1->b_datap->db_lim -
12017 					    mp1->b_datap->db_base;
12018 					freeb(mp1);
12019 					BUMP_MIB(ill->ill_ip_mib,
12020 					    ipIfStatsReasmPartDups);
12021 					mp1 = mp->b_cont;
12022 					if (!mp1)
12023 						break;
12024 					offset = IP_REASS_START(mp1);
12025 				}
12026 			}
12027 			break;
12028 		}
12029 	} while (start = end, mp = next_mp);
12030 
12031 	/* Fragment just processed could be the last one. Remember this fact */
12032 	if (!more)
12033 		ipf->ipf_last_frag_seen = B_TRUE;
12034 
12035 	/* Still got holes? */
12036 	if (ipf->ipf_hole_cnt)
12037 		return (IP_REASS_PARTIAL);
12038 	/* Clean up overloaded fields to avoid upstream disasters. */
12039 	for (mp1 = ipf->ipf_mp->b_cont; mp1; mp1 = mp1->b_cont) {
12040 		IP_REASS_SET_START(mp1, 0);
12041 		IP_REASS_SET_END(mp1, 0);
12042 	}
12043 	return (IP_REASS_COMPLETE);
12044 }
12045 
12046 /*
12047  * ipsec processing for the fast path, used for input UDP Packets
12048  * Returns true if ready for passup to UDP.
12049  * Return false if packet is not passable to UDP (e.g. it failed IPsec policy,
12050  * was an ESP-in-UDP packet, etc.).
12051  */
12052 static boolean_t
12053 ip_udp_check(queue_t *q, conn_t *connp, ill_t *ill, ipha_t *ipha,
12054     mblk_t **mpp, mblk_t **first_mpp, boolean_t mctl_present, ire_t *ire)
12055 {
12056 	uint32_t	ill_index;
12057 	uint_t		in_flags;	/* IPF_RECVSLLA and/or IPF_RECVIF */
12058 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
12059 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12060 	udp_t		*udp = connp->conn_udp;
12061 
12062 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12063 	/* The ill_index of the incoming ILL */
12064 	ill_index = ((ill_t *)q->q_ptr)->ill_phyint->phyint_ifindex;
12065 
12066 	/* pass packet up to the transport */
12067 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
12068 		*first_mpp = ipsec_check_inbound_policy(*first_mpp, connp, ipha,
12069 		    NULL, mctl_present);
12070 		if (*first_mpp == NULL) {
12071 			return (B_FALSE);
12072 		}
12073 	}
12074 
12075 	/* Initiate IPPF processing for fastpath UDP */
12076 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
12077 		ip_process(IPP_LOCAL_IN, mpp, ill_index);
12078 		if (*mpp == NULL) {
12079 			ip2dbg(("ip_input_ipsec_process: UDP pkt "
12080 			    "deferred/dropped during IPPF processing\n"));
12081 			return (B_FALSE);
12082 		}
12083 	}
12084 	/*
12085 	 * Remove 0-spi if it's 0, or move everything behind
12086 	 * the UDP header over it and forward to ESP via
12087 	 * ip_proto_input().
12088 	 */
12089 	if (udp->udp_nat_t_endpoint) {
12090 		if (mctl_present) {
12091 			/* mctl_present *shouldn't* happen. */
12092 			ip_drop_packet(*first_mpp, B_TRUE, NULL,
12093 			    NULL, DROPPER(ipss, ipds_esp_nat_t_ipsec),
12094 			    &ipss->ipsec_dropper);
12095 			*first_mpp = NULL;
12096 			return (B_FALSE);
12097 		}
12098 
12099 		/* "ill" is "recv_ill" in actuality. */
12100 		if (!zero_spi_check(q, *mpp, ire, ill, ipss))
12101 			return (B_FALSE);
12102 
12103 		/* Else continue like a normal UDP packet. */
12104 	}
12105 
12106 	/*
12107 	 * We make the checks as below since we are in the fast path
12108 	 * and want to minimize the number of checks if the IP_RECVIF and/or
12109 	 * IP_RECVSLLA and/or IPV6_RECVPKTINFO options are not set
12110 	 */
12111 	if (connp->conn_recvif || connp->conn_recvslla ||
12112 	    connp->conn_ip_recvpktinfo) {
12113 		if (connp->conn_recvif) {
12114 			in_flags = IPF_RECVIF;
12115 		}
12116 		/*
12117 		 * UDP supports IP_RECVPKTINFO option for both v4 and v6
12118 		 * so the flag passed to ip_add_info is based on IP version
12119 		 * of connp.
12120 		 */
12121 		if (connp->conn_ip_recvpktinfo) {
12122 			if (connp->conn_af_isv6) {
12123 				/*
12124 				 * V6 only needs index
12125 				 */
12126 				in_flags |= IPF_RECVIF;
12127 			} else {
12128 				/*
12129 				 * V4 needs index + matching address.
12130 				 */
12131 				in_flags |= IPF_RECVADDR;
12132 			}
12133 		}
12134 		if (connp->conn_recvslla) {
12135 			in_flags |= IPF_RECVSLLA;
12136 		}
12137 		/*
12138 		 * since in_flags are being set ill will be
12139 		 * referenced in ip_add_info, so it better not
12140 		 * be NULL.
12141 		 */
12142 		/*
12143 		 * the actual data will be contained in b_cont
12144 		 * upon successful return of the following call.
12145 		 * If the call fails then the original mblk is
12146 		 * returned.
12147 		 */
12148 		*mpp = ip_add_info(*mpp, ill, in_flags, IPCL_ZONEID(connp),
12149 		    ipst);
12150 	}
12151 
12152 	return (B_TRUE);
12153 }
12154 
12155 /*
12156  * Fragmentation reassembly.  Each ILL has a hash table for
12157  * queuing packets undergoing reassembly for all IPIFs
12158  * associated with the ILL.  The hash is based on the packet
12159  * IP ident field.  The ILL frag hash table was allocated
12160  * as a timer block at the time the ILL was created.  Whenever
12161  * there is anything on the reassembly queue, the timer will
12162  * be running.  Returns B_TRUE if successful else B_FALSE;
12163  * frees mp on failure.
12164  */
12165 static boolean_t
12166 ip_rput_fragment(queue_t *q, mblk_t **mpp, ipha_t *ipha,
12167     uint32_t *cksum_val, uint16_t *cksum_flags)
12168 {
12169 	uint32_t	frag_offset_flags;
12170 	ill_t		*ill = (ill_t *)q->q_ptr;
12171 	mblk_t		*mp = *mpp;
12172 	mblk_t		*t_mp;
12173 	ipaddr_t	dst;
12174 	uint8_t		proto = ipha->ipha_protocol;
12175 	uint32_t	sum_val;
12176 	uint16_t	sum_flags;
12177 	ipf_t		*ipf;
12178 	ipf_t		**ipfp;
12179 	ipfb_t		*ipfb;
12180 	uint16_t	ident;
12181 	uint32_t	offset;
12182 	ipaddr_t	src;
12183 	uint_t		hdr_length;
12184 	uint32_t	end;
12185 	mblk_t		*mp1;
12186 	mblk_t		*tail_mp;
12187 	size_t		count;
12188 	size_t		msg_len;
12189 	uint8_t		ecn_info = 0;
12190 	uint32_t	packet_size;
12191 	boolean_t	pruned = B_FALSE;
12192 	ip_stack_t *ipst = ill->ill_ipst;
12193 
12194 	if (cksum_val != NULL)
12195 		*cksum_val = 0;
12196 	if (cksum_flags != NULL)
12197 		*cksum_flags = 0;
12198 
12199 	/*
12200 	 * Drop the fragmented as early as possible, if
12201 	 * we don't have resource(s) to re-assemble.
12202 	 */
12203 	if (ipst->ips_ip_reass_queue_bytes == 0) {
12204 		freemsg(mp);
12205 		return (B_FALSE);
12206 	}
12207 
12208 	/* Check for fragmentation offset; return if there's none */
12209 	if ((frag_offset_flags = ntohs(ipha->ipha_fragment_offset_and_flags) &
12210 	    (IPH_MF | IPH_OFFSET)) == 0)
12211 		return (B_TRUE);
12212 
12213 	/*
12214 	 * We utilize hardware computed checksum info only for UDP since
12215 	 * IP fragmentation is a normal occurence for the protocol.  In
12216 	 * addition, checksum offload support for IP fragments carrying
12217 	 * UDP payload is commonly implemented across network adapters.
12218 	 */
12219 	ASSERT(ill != NULL);
12220 	if (proto == IPPROTO_UDP && dohwcksum && ILL_HCKSUM_CAPABLE(ill) &&
12221 	    (DB_CKSUMFLAGS(mp) & (HCK_FULLCKSUM | HCK_PARTIALCKSUM))) {
12222 		mblk_t *mp1 = mp->b_cont;
12223 		int32_t len;
12224 
12225 		/* Record checksum information from the packet */
12226 		sum_val = (uint32_t)DB_CKSUM16(mp);
12227 		sum_flags = DB_CKSUMFLAGS(mp);
12228 
12229 		/* IP payload offset from beginning of mblk */
12230 		offset = ((uchar_t *)ipha + IPH_HDR_LENGTH(ipha)) - mp->b_rptr;
12231 
12232 		if ((sum_flags & HCK_PARTIALCKSUM) &&
12233 		    (mp1 == NULL || mp1->b_cont == NULL) &&
12234 		    offset >= DB_CKSUMSTART(mp) &&
12235 		    ((len = offset - DB_CKSUMSTART(mp)) & 1) == 0) {
12236 			uint32_t adj;
12237 			/*
12238 			 * Partial checksum has been calculated by hardware
12239 			 * and attached to the packet; in addition, any
12240 			 * prepended extraneous data is even byte aligned.
12241 			 * If any such data exists, we adjust the checksum;
12242 			 * this would also handle any postpended data.
12243 			 */
12244 			IP_ADJCKSUM_PARTIAL(mp->b_rptr + DB_CKSUMSTART(mp),
12245 			    mp, mp1, len, adj);
12246 
12247 			/* One's complement subtract extraneous checksum */
12248 			if (adj >= sum_val)
12249 				sum_val = ~(adj - sum_val) & 0xFFFF;
12250 			else
12251 				sum_val -= adj;
12252 		}
12253 	} else {
12254 		sum_val = 0;
12255 		sum_flags = 0;
12256 	}
12257 
12258 	/* Clear hardware checksumming flag */
12259 	DB_CKSUMFLAGS(mp) = 0;
12260 
12261 	ident = ipha->ipha_ident;
12262 	offset = (frag_offset_flags << 3) & 0xFFFF;
12263 	src = ipha->ipha_src;
12264 	dst = ipha->ipha_dst;
12265 	hdr_length = IPH_HDR_LENGTH(ipha);
12266 	end = ntohs(ipha->ipha_length) - hdr_length;
12267 
12268 	/* If end == 0 then we have a packet with no data, so just free it */
12269 	if (end == 0) {
12270 		freemsg(mp);
12271 		return (B_FALSE);
12272 	}
12273 
12274 	/* Record the ECN field info. */
12275 	ecn_info = (ipha->ipha_type_of_service & 0x3);
12276 	if (offset != 0) {
12277 		/*
12278 		 * If this isn't the first piece, strip the header, and
12279 		 * add the offset to the end value.
12280 		 */
12281 		mp->b_rptr += hdr_length;
12282 		end += offset;
12283 	}
12284 
12285 	msg_len = MBLKSIZE(mp);
12286 	tail_mp = mp;
12287 	while (tail_mp->b_cont != NULL) {
12288 		tail_mp = tail_mp->b_cont;
12289 		msg_len += MBLKSIZE(tail_mp);
12290 	}
12291 
12292 	/* If the reassembly list for this ILL will get too big, prune it */
12293 	if ((msg_len + sizeof (*ipf) + ill->ill_frag_count) >=
12294 	    ipst->ips_ip_reass_queue_bytes) {
12295 		ill_frag_prune(ill,
12296 		    (ipst->ips_ip_reass_queue_bytes < msg_len) ? 0 :
12297 		    (ipst->ips_ip_reass_queue_bytes - msg_len));
12298 		pruned = B_TRUE;
12299 	}
12300 
12301 	ipfb = &ill->ill_frag_hash_tbl[ILL_FRAG_HASH(src, ident)];
12302 	mutex_enter(&ipfb->ipfb_lock);
12303 
12304 	ipfp = &ipfb->ipfb_ipf;
12305 	/* Try to find an existing fragment queue for this packet. */
12306 	for (;;) {
12307 		ipf = ipfp[0];
12308 		if (ipf != NULL) {
12309 			/*
12310 			 * It has to match on ident and src/dst address.
12311 			 */
12312 			if (ipf->ipf_ident == ident &&
12313 			    ipf->ipf_src == src &&
12314 			    ipf->ipf_dst == dst &&
12315 			    ipf->ipf_protocol == proto) {
12316 				/*
12317 				 * If we have received too many
12318 				 * duplicate fragments for this packet
12319 				 * free it.
12320 				 */
12321 				if (ipf->ipf_num_dups > ip_max_frag_dups) {
12322 					ill_frag_free_pkts(ill, ipfb, ipf, 1);
12323 					freemsg(mp);
12324 					mutex_exit(&ipfb->ipfb_lock);
12325 					return (B_FALSE);
12326 				}
12327 				/* Found it. */
12328 				break;
12329 			}
12330 			ipfp = &ipf->ipf_hash_next;
12331 			continue;
12332 		}
12333 
12334 		/*
12335 		 * If we pruned the list, do we want to store this new
12336 		 * fragment?. We apply an optimization here based on the
12337 		 * fact that most fragments will be received in order.
12338 		 * So if the offset of this incoming fragment is zero,
12339 		 * it is the first fragment of a new packet. We will
12340 		 * keep it.  Otherwise drop the fragment, as we have
12341 		 * probably pruned the packet already (since the
12342 		 * packet cannot be found).
12343 		 */
12344 		if (pruned && offset != 0) {
12345 			mutex_exit(&ipfb->ipfb_lock);
12346 			freemsg(mp);
12347 			return (B_FALSE);
12348 		}
12349 
12350 		if (ipfb->ipfb_frag_pkts >= MAX_FRAG_PKTS(ipst))  {
12351 			/*
12352 			 * Too many fragmented packets in this hash
12353 			 * bucket. Free the oldest.
12354 			 */
12355 			ill_frag_free_pkts(ill, ipfb, ipfb->ipfb_ipf, 1);
12356 		}
12357 
12358 		/* New guy.  Allocate a frag message. */
12359 		mp1 = allocb(sizeof (*ipf), BPRI_MED);
12360 		if (mp1 == NULL) {
12361 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12362 			freemsg(mp);
12363 reass_done:
12364 			mutex_exit(&ipfb->ipfb_lock);
12365 			return (B_FALSE);
12366 		}
12367 
12368 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmReqds);
12369 		mp1->b_cont = mp;
12370 
12371 		/* Initialize the fragment header. */
12372 		ipf = (ipf_t *)mp1->b_rptr;
12373 		ipf->ipf_mp = mp1;
12374 		ipf->ipf_ptphn = ipfp;
12375 		ipfp[0] = ipf;
12376 		ipf->ipf_hash_next = NULL;
12377 		ipf->ipf_ident = ident;
12378 		ipf->ipf_protocol = proto;
12379 		ipf->ipf_src = src;
12380 		ipf->ipf_dst = dst;
12381 		ipf->ipf_nf_hdr_len = 0;
12382 		/* Record reassembly start time. */
12383 		ipf->ipf_timestamp = gethrestime_sec();
12384 		/* Record ipf generation and account for frag header */
12385 		ipf->ipf_gen = ill->ill_ipf_gen++;
12386 		ipf->ipf_count = MBLKSIZE(mp1);
12387 		ipf->ipf_last_frag_seen = B_FALSE;
12388 		ipf->ipf_ecn = ecn_info;
12389 		ipf->ipf_num_dups = 0;
12390 		ipfb->ipfb_frag_pkts++;
12391 		ipf->ipf_checksum = 0;
12392 		ipf->ipf_checksum_flags = 0;
12393 
12394 		/* Store checksum value in fragment header */
12395 		if (sum_flags != 0) {
12396 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12397 			sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12398 			ipf->ipf_checksum = sum_val;
12399 			ipf->ipf_checksum_flags = sum_flags;
12400 		}
12401 
12402 		/*
12403 		 * We handle reassembly two ways.  In the easy case,
12404 		 * where all the fragments show up in order, we do
12405 		 * minimal bookkeeping, and just clip new pieces on
12406 		 * the end.  If we ever see a hole, then we go off
12407 		 * to ip_reassemble which has to mark the pieces and
12408 		 * keep track of the number of holes, etc.  Obviously,
12409 		 * the point of having both mechanisms is so we can
12410 		 * handle the easy case as efficiently as possible.
12411 		 */
12412 		if (offset == 0) {
12413 			/* Easy case, in-order reassembly so far. */
12414 			ipf->ipf_count += msg_len;
12415 			ipf->ipf_tail_mp = tail_mp;
12416 			/*
12417 			 * Keep track of next expected offset in
12418 			 * ipf_end.
12419 			 */
12420 			ipf->ipf_end = end;
12421 			ipf->ipf_nf_hdr_len = hdr_length;
12422 		} else {
12423 			/* Hard case, hole at the beginning. */
12424 			ipf->ipf_tail_mp = NULL;
12425 			/*
12426 			 * ipf_end == 0 means that we have given up
12427 			 * on easy reassembly.
12428 			 */
12429 			ipf->ipf_end = 0;
12430 
12431 			/* Forget checksum offload from now on */
12432 			ipf->ipf_checksum_flags = 0;
12433 
12434 			/*
12435 			 * ipf_hole_cnt is set by ip_reassemble.
12436 			 * ipf_count is updated by ip_reassemble.
12437 			 * No need to check for return value here
12438 			 * as we don't expect reassembly to complete
12439 			 * or fail for the first fragment itself.
12440 			 */
12441 			(void) ip_reassemble(mp, ipf,
12442 			    (frag_offset_flags & IPH_OFFSET) << 3,
12443 			    (frag_offset_flags & IPH_MF), ill, msg_len);
12444 		}
12445 		/* Update per ipfb and ill byte counts */
12446 		ipfb->ipfb_count += ipf->ipf_count;
12447 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12448 		ill->ill_frag_count += ipf->ipf_count;
12449 		/* If the frag timer wasn't already going, start it. */
12450 		mutex_enter(&ill->ill_lock);
12451 		ill_frag_timer_start(ill);
12452 		mutex_exit(&ill->ill_lock);
12453 		goto reass_done;
12454 	}
12455 
12456 	/*
12457 	 * If the packet's flag has changed (it could be coming up
12458 	 * from an interface different than the previous, therefore
12459 	 * possibly different checksum capability), then forget about
12460 	 * any stored checksum states.  Otherwise add the value to
12461 	 * the existing one stored in the fragment header.
12462 	 */
12463 	if (sum_flags != 0 && sum_flags == ipf->ipf_checksum_flags) {
12464 		sum_val += ipf->ipf_checksum;
12465 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12466 		sum_val = (sum_val & 0xFFFF) + (sum_val >> 16);
12467 		ipf->ipf_checksum = sum_val;
12468 	} else if (ipf->ipf_checksum_flags != 0) {
12469 		/* Forget checksum offload from now on */
12470 		ipf->ipf_checksum_flags = 0;
12471 	}
12472 
12473 	/*
12474 	 * We have a new piece of a datagram which is already being
12475 	 * reassembled.  Update the ECN info if all IP fragments
12476 	 * are ECN capable.  If there is one which is not, clear
12477 	 * all the info.  If there is at least one which has CE
12478 	 * code point, IP needs to report that up to transport.
12479 	 */
12480 	if (ecn_info != IPH_ECN_NECT && ipf->ipf_ecn != IPH_ECN_NECT) {
12481 		if (ecn_info == IPH_ECN_CE)
12482 			ipf->ipf_ecn = IPH_ECN_CE;
12483 	} else {
12484 		ipf->ipf_ecn = IPH_ECN_NECT;
12485 	}
12486 	if (offset && ipf->ipf_end == offset) {
12487 		/* The new fragment fits at the end */
12488 		ipf->ipf_tail_mp->b_cont = mp;
12489 		/* Update the byte count */
12490 		ipf->ipf_count += msg_len;
12491 		/* Update per ipfb and ill byte counts */
12492 		ipfb->ipfb_count += msg_len;
12493 		ASSERT(ipfb->ipfb_count > 0);	/* Wraparound */
12494 		ill->ill_frag_count += msg_len;
12495 		if (frag_offset_flags & IPH_MF) {
12496 			/* More to come. */
12497 			ipf->ipf_end = end;
12498 			ipf->ipf_tail_mp = tail_mp;
12499 			goto reass_done;
12500 		}
12501 	} else {
12502 		/* Go do the hard cases. */
12503 		int ret;
12504 
12505 		if (offset == 0)
12506 			ipf->ipf_nf_hdr_len = hdr_length;
12507 
12508 		/* Save current byte count */
12509 		count = ipf->ipf_count;
12510 		ret = ip_reassemble(mp, ipf,
12511 		    (frag_offset_flags & IPH_OFFSET) << 3,
12512 		    (frag_offset_flags & IPH_MF), ill, msg_len);
12513 		/* Count of bytes added and subtracted (freeb()ed) */
12514 		count = ipf->ipf_count - count;
12515 		if (count) {
12516 			/* Update per ipfb and ill byte counts */
12517 			ipfb->ipfb_count += count;
12518 			ASSERT(ipfb->ipfb_count > 0); /* Wraparound */
12519 			ill->ill_frag_count += count;
12520 		}
12521 		if (ret == IP_REASS_PARTIAL) {
12522 			goto reass_done;
12523 		} else if (ret == IP_REASS_FAILED) {
12524 			/* Reassembly failed. Free up all resources */
12525 			ill_frag_free_pkts(ill, ipfb, ipf, 1);
12526 			for (t_mp = mp; t_mp != NULL; t_mp = t_mp->b_cont) {
12527 				IP_REASS_SET_START(t_mp, 0);
12528 				IP_REASS_SET_END(t_mp, 0);
12529 			}
12530 			freemsg(mp);
12531 			goto reass_done;
12532 		}
12533 		/* We will reach here iff 'ret' is IP_REASS_COMPLETE */
12534 	}
12535 	/*
12536 	 * We have completed reassembly.  Unhook the frag header from
12537 	 * the reassembly list.
12538 	 *
12539 	 * Before we free the frag header, record the ECN info
12540 	 * to report back to the transport.
12541 	 */
12542 	ecn_info = ipf->ipf_ecn;
12543 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsReasmOKs);
12544 	ipfp = ipf->ipf_ptphn;
12545 
12546 	/* We need to supply these to caller */
12547 	if ((sum_flags = ipf->ipf_checksum_flags) != 0)
12548 		sum_val = ipf->ipf_checksum;
12549 	else
12550 		sum_val = 0;
12551 
12552 	mp1 = ipf->ipf_mp;
12553 	count = ipf->ipf_count;
12554 	ipf = ipf->ipf_hash_next;
12555 	if (ipf != NULL)
12556 		ipf->ipf_ptphn = ipfp;
12557 	ipfp[0] = ipf;
12558 	ill->ill_frag_count -= count;
12559 	ASSERT(ipfb->ipfb_count >= count);
12560 	ipfb->ipfb_count -= count;
12561 	ipfb->ipfb_frag_pkts--;
12562 	mutex_exit(&ipfb->ipfb_lock);
12563 	/* Ditch the frag header. */
12564 	mp = mp1->b_cont;
12565 
12566 	freeb(mp1);
12567 
12568 	/* Restore original IP length in header. */
12569 	packet_size = (uint32_t)msgdsize(mp);
12570 	if (packet_size > IP_MAXPACKET) {
12571 		freemsg(mp);
12572 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
12573 		return (B_FALSE);
12574 	}
12575 
12576 	if (DB_REF(mp) > 1) {
12577 		mblk_t *mp2 = copymsg(mp);
12578 
12579 		freemsg(mp);
12580 		if (mp2 == NULL) {
12581 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12582 			return (B_FALSE);
12583 		}
12584 		mp = mp2;
12585 	}
12586 	ipha = (ipha_t *)mp->b_rptr;
12587 
12588 	ipha->ipha_length = htons((uint16_t)packet_size);
12589 	/* We're now complete, zip the frag state */
12590 	ipha->ipha_fragment_offset_and_flags = 0;
12591 	/* Record the ECN info. */
12592 	ipha->ipha_type_of_service &= 0xFC;
12593 	ipha->ipha_type_of_service |= ecn_info;
12594 	*mpp = mp;
12595 
12596 	/* Reassembly is successful; return checksum information if needed */
12597 	if (cksum_val != NULL)
12598 		*cksum_val = sum_val;
12599 	if (cksum_flags != NULL)
12600 		*cksum_flags = sum_flags;
12601 
12602 	return (B_TRUE);
12603 }
12604 
12605 /*
12606  * Perform ip header check sum update local options.
12607  * return B_TRUE if all is well, else return B_FALSE and release
12608  * the mp. caller is responsible for decrementing ire ref cnt.
12609  */
12610 static boolean_t
12611 ip_options_cksum(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12612     ip_stack_t *ipst)
12613 {
12614 	mblk_t		*first_mp;
12615 	boolean_t	mctl_present;
12616 	uint16_t	sum;
12617 
12618 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12619 	/*
12620 	 * Don't do the checksum if it has gone through AH/ESP
12621 	 * processing.
12622 	 */
12623 	if (!mctl_present) {
12624 		sum = ip_csum_hdr(ipha);
12625 		if (sum != 0) {
12626 			if (ill != NULL) {
12627 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12628 			} else {
12629 				BUMP_MIB(&ipst->ips_ip_mib,
12630 				    ipIfStatsInCksumErrs);
12631 			}
12632 			freemsg(first_mp);
12633 			return (B_FALSE);
12634 		}
12635 	}
12636 
12637 	if (!ip_rput_local_options(q, mp, ipha, ire, ipst)) {
12638 		if (mctl_present)
12639 			freeb(first_mp);
12640 		return (B_FALSE);
12641 	}
12642 
12643 	return (B_TRUE);
12644 }
12645 
12646 /*
12647  * All udp packet are delivered to the local host via this routine.
12648  */
12649 void
12650 ip_udp_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
12651     ill_t *recv_ill)
12652 {
12653 	uint32_t	sum;
12654 	uint32_t	u1;
12655 	boolean_t	mctl_present;
12656 	conn_t		*connp;
12657 	mblk_t		*first_mp;
12658 	uint16_t	*up;
12659 	ill_t		*ill = (ill_t *)q->q_ptr;
12660 	uint16_t	reass_hck_flags = 0;
12661 	ip_stack_t	*ipst;
12662 
12663 	ASSERT(recv_ill != NULL);
12664 	ipst = recv_ill->ill_ipst;
12665 
12666 #define	rptr    ((uchar_t *)ipha)
12667 
12668 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
12669 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
12670 	ASSERT(ipha->ipha_protocol == IPPROTO_UDP);
12671 	ASSERT(ill != NULL);
12672 
12673 	/*
12674 	 * FAST PATH for udp packets
12675 	 */
12676 
12677 	/* u1 is # words of IP options */
12678 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
12679 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12680 
12681 	/* IP options present */
12682 	if (u1 != 0)
12683 		goto ipoptions;
12684 
12685 	/* Check the IP header checksum.  */
12686 	if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12687 		/* Clear the IP header h/w cksum flag */
12688 		DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12689 	} else if (!mctl_present) {
12690 		/*
12691 		 * Don't verify header checksum if this packet is coming
12692 		 * back from AH/ESP as we already did it.
12693 		 */
12694 #define	uph	((uint16_t *)ipha)
12695 		sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] + uph[5] +
12696 		    uph[6] + uph[7] + uph[8] + uph[9];
12697 #undef	uph
12698 		/* finish doing IP checksum */
12699 		sum = (sum & 0xFFFF) + (sum >> 16);
12700 		sum = ~(sum + (sum >> 16)) & 0xFFFF;
12701 		if (sum != 0 && sum != 0xFFFF) {
12702 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
12703 			freemsg(first_mp);
12704 			return;
12705 		}
12706 	}
12707 
12708 	/*
12709 	 * Count for SNMP of inbound packets for ire.
12710 	 * if mctl is present this might be a secure packet and
12711 	 * has already been counted for in ip_proto_input().
12712 	 */
12713 	if (!mctl_present) {
12714 		UPDATE_IB_PKT_COUNT(ire);
12715 		ire->ire_last_used_time = lbolt;
12716 	}
12717 
12718 	/* packet part of fragmented IP packet? */
12719 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12720 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12721 		goto fragmented;
12722 	}
12723 
12724 	/* u1 = IP header length (20 bytes) */
12725 	u1 = IP_SIMPLE_HDR_LENGTH;
12726 
12727 	/* packet does not contain complete IP & UDP headers */
12728 	if ((mp->b_wptr - rptr) < (IP_SIMPLE_HDR_LENGTH + UDPH_SIZE))
12729 		goto udppullup;
12730 
12731 	/* up points to UDP header */
12732 	up = (uint16_t *)((uchar_t *)ipha + IP_SIMPLE_HDR_LENGTH);
12733 #define	iphs    ((uint16_t *)ipha)
12734 
12735 	/* if udp hdr cksum != 0, then need to checksum udp packet */
12736 	if (up[3] != 0) {
12737 		mblk_t *mp1 = mp->b_cont;
12738 		boolean_t cksum_err;
12739 		uint16_t hck_flags = 0;
12740 
12741 		/* Pseudo-header checksum */
12742 		u1 = IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12743 		    iphs[9] + up[2];
12744 
12745 		/*
12746 		 * Revert to software checksum calculation if the interface
12747 		 * isn't capable of checksum offload or if IPsec is present.
12748 		 */
12749 		if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
12750 			hck_flags = DB_CKSUMFLAGS(mp);
12751 
12752 		if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12753 			IP_STAT(ipst, ip_in_sw_cksum);
12754 
12755 		IP_CKSUM_RECV(hck_flags, u1,
12756 		    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
12757 		    (int32_t)((uchar_t *)up - rptr),
12758 		    mp, mp1, cksum_err);
12759 
12760 		if (cksum_err) {
12761 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12762 			if (hck_flags & HCK_FULLCKSUM)
12763 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12764 			else if (hck_flags & HCK_PARTIALCKSUM)
12765 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12766 			else
12767 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12768 
12769 			freemsg(first_mp);
12770 			return;
12771 		}
12772 	}
12773 
12774 	/* Non-fragmented broadcast or multicast packet? */
12775 	if (ire->ire_type == IRE_BROADCAST)
12776 		goto udpslowpath;
12777 
12778 	if ((connp = ipcl_classify_v4(mp, IPPROTO_UDP, IP_SIMPLE_HDR_LENGTH,
12779 	    ire->ire_zoneid, ipst)) != NULL) {
12780 		ASSERT(connp->conn_upq != NULL);
12781 		IP_STAT(ipst, ip_udp_fast_path);
12782 
12783 		if (CONN_UDP_FLOWCTLD(connp)) {
12784 			freemsg(mp);
12785 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInOverflows);
12786 		} else {
12787 			if (!mctl_present) {
12788 				BUMP_MIB(ill->ill_ip_mib,
12789 				    ipIfStatsHCInDelivers);
12790 			}
12791 			/*
12792 			 * mp and first_mp can change.
12793 			 */
12794 			if (ip_udp_check(q, connp, recv_ill,
12795 			    ipha, &mp, &first_mp, mctl_present, ire)) {
12796 				/* Send it upstream */
12797 				(connp->conn_recv)(connp, mp, NULL);
12798 			}
12799 		}
12800 		/*
12801 		 * freeb() cannot deal with null mblk being passed
12802 		 * in and first_mp can be set to null in the call
12803 		 * ipsec_input_fast_proc()->ipsec_check_inbound_policy.
12804 		 */
12805 		if (mctl_present && first_mp != NULL) {
12806 			freeb(first_mp);
12807 		}
12808 		CONN_DEC_REF(connp);
12809 		return;
12810 	}
12811 
12812 	/*
12813 	 * if we got here we know the packet is not fragmented and
12814 	 * has no options. The classifier could not find a conn_t and
12815 	 * most likely its an icmp packet so send it through slow path.
12816 	 */
12817 
12818 	goto udpslowpath;
12819 
12820 ipoptions:
12821 	if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
12822 		goto slow_done;
12823 	}
12824 
12825 	UPDATE_IB_PKT_COUNT(ire);
12826 	ire->ire_last_used_time = lbolt;
12827 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12828 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12829 fragmented:
12830 		/*
12831 		 * "sum" and "reass_hck_flags" are non-zero if the
12832 		 * reassembled packet has a valid hardware computed
12833 		 * checksum information associated with it.
12834 		 */
12835 		if (!ip_rput_fragment(q, &mp, ipha, &sum, &reass_hck_flags))
12836 			goto slow_done;
12837 		/*
12838 		 * Make sure that first_mp points back to mp as
12839 		 * the mp we came in with could have changed in
12840 		 * ip_rput_fragment().
12841 		 */
12842 		ASSERT(!mctl_present);
12843 		ipha = (ipha_t *)mp->b_rptr;
12844 		first_mp = mp;
12845 	}
12846 
12847 	/* Now we have a complete datagram, destined for this machine. */
12848 	u1 = IPH_HDR_LENGTH(ipha);
12849 	/* Pull up the UDP header, if necessary. */
12850 	if ((MBLKL(mp)) < (u1 + UDPH_SIZE)) {
12851 udppullup:
12852 		if (!pullupmsg(mp, u1 + UDPH_SIZE)) {
12853 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
12854 			freemsg(first_mp);
12855 			goto slow_done;
12856 		}
12857 		ipha = (ipha_t *)mp->b_rptr;
12858 	}
12859 
12860 	/*
12861 	 * Validate the checksum for the reassembled packet; for the
12862 	 * pullup case we calculate the payload checksum in software.
12863 	 */
12864 	up = (uint16_t *)((uchar_t *)ipha + u1 + UDP_PORTS_OFFSET);
12865 	if (up[3] != 0) {
12866 		boolean_t cksum_err;
12867 
12868 		if ((reass_hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
12869 			IP_STAT(ipst, ip_in_sw_cksum);
12870 
12871 		IP_CKSUM_RECV_REASS(reass_hck_flags,
12872 		    (int32_t)((uchar_t *)up - (uchar_t *)ipha),
12873 		    IP_UDP_CSUM_COMP + iphs[6] + iphs[7] + iphs[8] +
12874 		    iphs[9] + up[2], sum, cksum_err);
12875 
12876 		if (cksum_err) {
12877 			BUMP_MIB(ill->ill_ip_mib, udpIfStatsInCksumErrs);
12878 
12879 			if (reass_hck_flags & HCK_FULLCKSUM)
12880 				IP_STAT(ipst, ip_udp_in_full_hw_cksum_err);
12881 			else if (reass_hck_flags & HCK_PARTIALCKSUM)
12882 				IP_STAT(ipst, ip_udp_in_part_hw_cksum_err);
12883 			else
12884 				IP_STAT(ipst, ip_udp_in_sw_cksum_err);
12885 
12886 			freemsg(first_mp);
12887 			goto slow_done;
12888 		}
12889 	}
12890 udpslowpath:
12891 
12892 	/* Clear hardware checksum flag to be safe */
12893 	DB_CKSUMFLAGS(mp) = 0;
12894 
12895 	ip_fanout_udp(q, first_mp, ill, ipha, *(uint32_t *)up,
12896 	    (ire->ire_type == IRE_BROADCAST),
12897 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_IPINFO,
12898 	    mctl_present, B_TRUE, recv_ill, ire->ire_zoneid);
12899 
12900 slow_done:
12901 	IP_STAT(ipst, ip_udp_slow_path);
12902 	return;
12903 
12904 #undef  iphs
12905 #undef  rptr
12906 }
12907 
12908 /* ARGSUSED */
12909 static mblk_t *
12910 ip_tcp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
12911     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q,
12912     ill_rx_ring_t *ill_ring)
12913 {
12914 	conn_t		*connp;
12915 	uint32_t	sum;
12916 	uint32_t	u1;
12917 	uint16_t	*up;
12918 	int		offset;
12919 	ssize_t		len;
12920 	mblk_t		*mp1;
12921 	boolean_t	syn_present = B_FALSE;
12922 	tcph_t		*tcph;
12923 	uint_t		ip_hdr_len;
12924 	ill_t		*ill = (ill_t *)q->q_ptr;
12925 	zoneid_t	zoneid = ire->ire_zoneid;
12926 	boolean_t	cksum_err;
12927 	uint16_t	hck_flags = 0;
12928 	ip_stack_t	*ipst = recv_ill->ill_ipst;
12929 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
12930 
12931 #define	rptr	((uchar_t *)ipha)
12932 
12933 	ASSERT(ipha->ipha_protocol == IPPROTO_TCP);
12934 	ASSERT(ill != NULL);
12935 
12936 	/*
12937 	 * FAST PATH for tcp packets
12938 	 */
12939 
12940 	/* u1 is # words of IP options */
12941 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
12942 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
12943 
12944 	/* IP options present */
12945 	if (u1) {
12946 		goto ipoptions;
12947 	} else if (!mctl_present) {
12948 		/* Check the IP header checksum.  */
12949 		if (IS_IP_HDR_HWCKSUM(mctl_present, mp, ill)) {
12950 			/* Clear the IP header h/w cksum flag */
12951 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
12952 		} else if (!mctl_present) {
12953 			/*
12954 			 * Don't verify header checksum if this packet
12955 			 * is coming back from AH/ESP as we already did it.
12956 			 */
12957 #define	uph	((uint16_t *)ipha)
12958 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
12959 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
12960 #undef	uph
12961 			/* finish doing IP checksum */
12962 			sum = (sum & 0xFFFF) + (sum >> 16);
12963 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
12964 			if (sum != 0 && sum != 0xFFFF) {
12965 				BUMP_MIB(ill->ill_ip_mib,
12966 				    ipIfStatsInCksumErrs);
12967 				goto error;
12968 			}
12969 		}
12970 	}
12971 
12972 	if (!mctl_present) {
12973 		UPDATE_IB_PKT_COUNT(ire);
12974 		ire->ire_last_used_time = lbolt;
12975 	}
12976 
12977 	/* packet part of fragmented IP packet? */
12978 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
12979 	if (u1 & (IPH_MF | IPH_OFFSET)) {
12980 		goto fragmented;
12981 	}
12982 
12983 	/* u1 = IP header length (20 bytes) */
12984 	u1 = ip_hdr_len = IP_SIMPLE_HDR_LENGTH;
12985 
12986 	/* does packet contain IP+TCP headers? */
12987 	len = mp->b_wptr - rptr;
12988 	if (len < (IP_SIMPLE_HDR_LENGTH + TCP_MIN_HEADER_LENGTH)) {
12989 		IP_STAT(ipst, ip_tcppullup);
12990 		goto tcppullup;
12991 	}
12992 
12993 	/* TCP options present? */
12994 	offset = ((uchar_t *)ipha)[IP_SIMPLE_HDR_LENGTH + 12] >> 4;
12995 
12996 	/*
12997 	 * If options need to be pulled up, then goto tcpoptions.
12998 	 * otherwise we are still in the fast path
12999 	 */
13000 	if (len < (offset << 2) + IP_SIMPLE_HDR_LENGTH) {
13001 		IP_STAT(ipst, ip_tcpoptions);
13002 		goto tcpoptions;
13003 	}
13004 
13005 	/* multiple mblks of tcp data? */
13006 	if ((mp1 = mp->b_cont) != NULL) {
13007 		/* more then two? */
13008 		if (mp1->b_cont != NULL) {
13009 			IP_STAT(ipst, ip_multipkttcp);
13010 			goto multipkttcp;
13011 		}
13012 		len += mp1->b_wptr - mp1->b_rptr;
13013 	}
13014 
13015 	up = (uint16_t *)(rptr + IP_SIMPLE_HDR_LENGTH + TCP_PORTS_OFFSET);
13016 
13017 	/* part of pseudo checksum */
13018 
13019 	/* TCP datagram length */
13020 	u1 = len - IP_SIMPLE_HDR_LENGTH;
13021 
13022 #define	iphs    ((uint16_t *)ipha)
13023 
13024 #ifdef	_BIG_ENDIAN
13025 	u1 += IPPROTO_TCP;
13026 #else
13027 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13028 #endif
13029 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13030 
13031 	/*
13032 	 * Revert to software checksum calculation if the interface
13033 	 * isn't capable of checksum offload or if IPsec is present.
13034 	 */
13035 	if (ILL_HCKSUM_CAPABLE(ill) && !mctl_present && dohwcksum)
13036 		hck_flags = DB_CKSUMFLAGS(mp);
13037 
13038 	if ((hck_flags & (HCK_FULLCKSUM|HCK_PARTIALCKSUM)) == 0)
13039 		IP_STAT(ipst, ip_in_sw_cksum);
13040 
13041 	IP_CKSUM_RECV(hck_flags, u1,
13042 	    (uchar_t *)(rptr + DB_CKSUMSTART(mp)),
13043 	    (int32_t)((uchar_t *)up - rptr),
13044 	    mp, mp1, cksum_err);
13045 
13046 	if (cksum_err) {
13047 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13048 
13049 		if (hck_flags & HCK_FULLCKSUM)
13050 			IP_STAT(ipst, ip_tcp_in_full_hw_cksum_err);
13051 		else if (hck_flags & HCK_PARTIALCKSUM)
13052 			IP_STAT(ipst, ip_tcp_in_part_hw_cksum_err);
13053 		else
13054 			IP_STAT(ipst, ip_tcp_in_sw_cksum_err);
13055 
13056 		goto error;
13057 	}
13058 
13059 try_again:
13060 
13061 	if ((connp = ipcl_classify_v4(mp, IPPROTO_TCP, ip_hdr_len,
13062 	    zoneid, ipst)) == NULL) {
13063 		/* Send the TH_RST */
13064 		goto no_conn;
13065 	}
13066 
13067 	/*
13068 	 * TCP FAST PATH for AF_INET socket.
13069 	 *
13070 	 * TCP fast path to avoid extra work. An AF_INET socket type
13071 	 * does not have facility to receive extra information via
13072 	 * ip_process or ip_add_info. Also, when the connection was
13073 	 * established, we made a check if this connection is impacted
13074 	 * by any global IPsec policy or per connection policy (a
13075 	 * policy that comes in effect later will not apply to this
13076 	 * connection). Since all this can be determined at the
13077 	 * connection establishment time, a quick check of flags
13078 	 * can avoid extra work.
13079 	 */
13080 	if (IPCL_IS_TCP4_CONNECTED_NO_POLICY(connp) && !mctl_present &&
13081 	    !IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13082 		ASSERT(first_mp == mp);
13083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13084 		SET_SQUEUE(mp, tcp_rput_data, connp);
13085 		return (mp);
13086 	}
13087 
13088 	tcph = (tcph_t *)&mp->b_rptr[ip_hdr_len];
13089 	if ((tcph->th_flags[0] & (TH_SYN|TH_ACK|TH_RST|TH_URG)) == TH_SYN) {
13090 		if (IPCL_IS_TCP(connp)) {
13091 			mp->b_datap->db_struioflag |= STRUIO_EAGER;
13092 			DB_CKSUMSTART(mp) =
13093 			    (intptr_t)ip_squeue_get(ill_ring);
13094 			if (IPCL_IS_FULLY_BOUND(connp) && !mctl_present &&
13095 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13096 				BUMP_MIB(ill->ill_ip_mib,
13097 				    ipIfStatsHCInDelivers);
13098 				SET_SQUEUE(mp, connp->conn_recv, connp);
13099 				return (mp);
13100 			} else if (IPCL_IS_BOUND(connp) && !mctl_present &&
13101 			    !CONN_INBOUND_POLICY_PRESENT(connp, ipss)) {
13102 				BUMP_MIB(ill->ill_ip_mib,
13103 				    ipIfStatsHCInDelivers);
13104 				ip_squeue_enter_unbound++;
13105 				SET_SQUEUE(mp, tcp_conn_request_unbound,
13106 				    connp);
13107 				return (mp);
13108 			}
13109 			syn_present = B_TRUE;
13110 		}
13111 
13112 	}
13113 
13114 	if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp) && !syn_present) {
13115 		uint_t	flags = (unsigned int)tcph->th_flags[0] & 0xFF;
13116 
13117 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13118 		/* No need to send this packet to TCP */
13119 		if ((flags & TH_RST) || (flags & TH_URG)) {
13120 			CONN_DEC_REF(connp);
13121 			freemsg(first_mp);
13122 			return (NULL);
13123 		}
13124 		if (flags & TH_ACK) {
13125 			tcp_xmit_listeners_reset(first_mp, ip_hdr_len, zoneid,
13126 			    ipst->ips_netstack->netstack_tcp, connp);
13127 			CONN_DEC_REF(connp);
13128 			return (NULL);
13129 		}
13130 
13131 		CONN_DEC_REF(connp);
13132 		freemsg(first_mp);
13133 		return (NULL);
13134 	}
13135 
13136 	if (CONN_INBOUND_POLICY_PRESENT(connp, ipss) || mctl_present) {
13137 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
13138 		    ipha, NULL, mctl_present);
13139 		if (first_mp == NULL) {
13140 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13141 			CONN_DEC_REF(connp);
13142 			return (NULL);
13143 		}
13144 		if (IPCL_IS_TCP(connp) && IPCL_IS_BOUND(connp)) {
13145 			ASSERT(syn_present);
13146 			if (mctl_present) {
13147 				ASSERT(first_mp != mp);
13148 				first_mp->b_datap->db_struioflag |=
13149 				    STRUIO_POLICY;
13150 			} else {
13151 				ASSERT(first_mp == mp);
13152 				mp->b_datap->db_struioflag &= ~STRUIO_EAGER;
13153 				mp->b_datap->db_struioflag |= STRUIO_POLICY;
13154 			}
13155 		} else {
13156 			/*
13157 			 * Discard first_mp early since we're dealing with a
13158 			 * fully-connected conn_t and tcp doesn't do policy in
13159 			 * this case.
13160 			 */
13161 			if (mctl_present) {
13162 				freeb(first_mp);
13163 				mctl_present = B_FALSE;
13164 			}
13165 			first_mp = mp;
13166 		}
13167 	}
13168 
13169 	/* Initiate IPPF processing for fastpath */
13170 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13171 		uint32_t	ill_index;
13172 
13173 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13174 		ip_process(IPP_LOCAL_IN, &mp, ill_index);
13175 		if (mp == NULL) {
13176 			ip2dbg(("ip_input_ipsec_process: TCP pkt "
13177 			    "deferred/dropped during IPPF processing\n"));
13178 			CONN_DEC_REF(connp);
13179 			if (mctl_present)
13180 				freeb(first_mp);
13181 			return (NULL);
13182 		} else if (mctl_present) {
13183 			/*
13184 			 * ip_process might return a new mp.
13185 			 */
13186 			ASSERT(first_mp != mp);
13187 			first_mp->b_cont = mp;
13188 		} else {
13189 			first_mp = mp;
13190 		}
13191 
13192 	}
13193 
13194 	if (!syn_present && connp->conn_ip_recvpktinfo) {
13195 		/*
13196 		 * TCP does not support IP_RECVPKTINFO for v4 so lets
13197 		 * make sure IPF_RECVIF is passed to ip_add_info.
13198 		 */
13199 		mp = ip_add_info(mp, recv_ill, flags|IPF_RECVIF,
13200 		    IPCL_ZONEID(connp), ipst);
13201 		if (mp == NULL) {
13202 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13203 			CONN_DEC_REF(connp);
13204 			if (mctl_present)
13205 				freeb(first_mp);
13206 			return (NULL);
13207 		} else if (mctl_present) {
13208 			/*
13209 			 * ip_add_info might return a new mp.
13210 			 */
13211 			ASSERT(first_mp != mp);
13212 			first_mp->b_cont = mp;
13213 		} else {
13214 			first_mp = mp;
13215 		}
13216 	}
13217 
13218 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13219 	if (IPCL_IS_TCP(connp)) {
13220 		SET_SQUEUE(first_mp, connp->conn_recv, connp);
13221 		return (first_mp);
13222 	} else {
13223 		/* SOCK_RAW, IPPROTO_TCP case */
13224 		(connp->conn_recv)(connp, first_mp, NULL);
13225 		CONN_DEC_REF(connp);
13226 		return (NULL);
13227 	}
13228 
13229 no_conn:
13230 	/* Initiate IPPf processing, if needed. */
13231 	if (IPP_ENABLED(IPP_LOCAL_IN, ipst)) {
13232 		uint32_t ill_index;
13233 		ill_index = recv_ill->ill_phyint->phyint_ifindex;
13234 		ip_process(IPP_LOCAL_IN, &first_mp, ill_index);
13235 		if (first_mp == NULL) {
13236 			return (NULL);
13237 		}
13238 	}
13239 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13240 
13241 	tcp_xmit_listeners_reset(first_mp, IPH_HDR_LENGTH(mp->b_rptr), zoneid,
13242 	    ipst->ips_netstack->netstack_tcp, NULL);
13243 	return (NULL);
13244 ipoptions:
13245 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst)) {
13246 		goto slow_done;
13247 	}
13248 
13249 	UPDATE_IB_PKT_COUNT(ire);
13250 	ire->ire_last_used_time = lbolt;
13251 
13252 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13253 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13254 fragmented:
13255 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
13256 			if (mctl_present)
13257 				freeb(first_mp);
13258 			goto slow_done;
13259 		}
13260 		/*
13261 		 * Make sure that first_mp points back to mp as
13262 		 * the mp we came in with could have changed in
13263 		 * ip_rput_fragment().
13264 		 */
13265 		ASSERT(!mctl_present);
13266 		ipha = (ipha_t *)mp->b_rptr;
13267 		first_mp = mp;
13268 	}
13269 
13270 	/* Now we have a complete datagram, destined for this machine. */
13271 	u1 = ip_hdr_len = IPH_HDR_LENGTH(ipha);
13272 
13273 	len = mp->b_wptr - mp->b_rptr;
13274 	/* Pull up a minimal TCP header, if necessary. */
13275 	if (len < (u1 + 20)) {
13276 tcppullup:
13277 		if (!pullupmsg(mp, u1 + 20)) {
13278 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13279 			goto error;
13280 		}
13281 		ipha = (ipha_t *)mp->b_rptr;
13282 		len = mp->b_wptr - mp->b_rptr;
13283 	}
13284 
13285 	/*
13286 	 * Extract the offset field from the TCP header.  As usual, we
13287 	 * try to help the compiler more than the reader.
13288 	 */
13289 	offset = ((uchar_t *)ipha)[u1 + 12] >> 4;
13290 	if (offset != 5) {
13291 tcpoptions:
13292 		if (offset < 5) {
13293 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13294 			goto error;
13295 		}
13296 		/*
13297 		 * There must be TCP options.
13298 		 * Make sure we can grab them.
13299 		 */
13300 		offset <<= 2;
13301 		offset += u1;
13302 		if (len < offset) {
13303 			if (!pullupmsg(mp, offset)) {
13304 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13305 				goto error;
13306 			}
13307 			ipha = (ipha_t *)mp->b_rptr;
13308 			len = mp->b_wptr - rptr;
13309 		}
13310 	}
13311 
13312 	/* Get the total packet length in len, including headers. */
13313 	if (mp->b_cont) {
13314 multipkttcp:
13315 		len = msgdsize(mp);
13316 	}
13317 
13318 	/*
13319 	 * Check the TCP checksum by pulling together the pseudo-
13320 	 * header checksum, and passing it to ip_csum to be added in
13321 	 * with the TCP datagram.
13322 	 *
13323 	 * Since we are not using the hwcksum if available we must
13324 	 * clear the flag. We may come here via tcppullup or tcpoptions.
13325 	 * If either of these fails along the way the mblk is freed.
13326 	 * If this logic ever changes and mblk is reused to say send
13327 	 * ICMP's back, then this flag may need to be cleared in
13328 	 * other places as well.
13329 	 */
13330 	DB_CKSUMFLAGS(mp) = 0;
13331 
13332 	up = (uint16_t *)(rptr + u1 + TCP_PORTS_OFFSET);
13333 
13334 	u1 = (uint32_t)(len - u1);	/* TCP datagram length. */
13335 #ifdef	_BIG_ENDIAN
13336 	u1 += IPPROTO_TCP;
13337 #else
13338 	u1 = ((u1 >> 8) & 0xFF) + (((u1 & 0xFF) + IPPROTO_TCP) << 8);
13339 #endif
13340 	u1 += iphs[6] + iphs[7] + iphs[8] + iphs[9];
13341 	/*
13342 	 * Not M_DATA mblk or its a dup, so do the checksum now.
13343 	 */
13344 	IP_STAT(ipst, ip_in_sw_cksum);
13345 	if (IP_CSUM(mp, (int32_t)((uchar_t *)up - rptr), u1) != 0) {
13346 		BUMP_MIB(ill->ill_ip_mib, tcpIfStatsInErrs);
13347 		goto error;
13348 	}
13349 
13350 	IP_STAT(ipst, ip_tcp_slow_path);
13351 	goto try_again;
13352 #undef  iphs
13353 #undef  rptr
13354 
13355 error:
13356 	freemsg(first_mp);
13357 slow_done:
13358 	return (NULL);
13359 }
13360 
13361 /* ARGSUSED */
13362 static void
13363 ip_sctp_input(mblk_t *mp, ipha_t *ipha, ill_t *recv_ill, boolean_t mctl_present,
13364     ire_t *ire, mblk_t *first_mp, uint_t flags, queue_t *q, ipaddr_t dst)
13365 {
13366 	conn_t		*connp;
13367 	uint32_t	sum;
13368 	uint32_t	u1;
13369 	ssize_t		len;
13370 	sctp_hdr_t	*sctph;
13371 	zoneid_t	zoneid = ire->ire_zoneid;
13372 	uint32_t	pktsum;
13373 	uint32_t	calcsum;
13374 	uint32_t	ports;
13375 	in6_addr_t	map_src, map_dst;
13376 	ill_t		*ill = (ill_t *)q->q_ptr;
13377 	ip_stack_t	*ipst;
13378 	sctp_stack_t	*sctps;
13379 	boolean_t	sctp_csum_err = B_FALSE;
13380 
13381 	ASSERT(recv_ill != NULL);
13382 	ipst = recv_ill->ill_ipst;
13383 	sctps = ipst->ips_netstack->netstack_sctp;
13384 
13385 #define	rptr	((uchar_t *)ipha)
13386 
13387 	ASSERT(ipha->ipha_protocol == IPPROTO_SCTP);
13388 	ASSERT(ill != NULL);
13389 
13390 	/* u1 is # words of IP options */
13391 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4)
13392 	    + IP_SIMPLE_HDR_LENGTH_IN_WORDS);
13393 
13394 	/* IP options present */
13395 	if (u1 > 0) {
13396 		goto ipoptions;
13397 	} else {
13398 		/* Check the IP header checksum.  */
13399 		if (!IS_IP_HDR_HWCKSUM(mctl_present, mp, ill) &&
13400 		    !mctl_present) {
13401 #define	uph	((uint16_t *)ipha)
13402 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
13403 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
13404 #undef	uph
13405 			/* finish doing IP checksum */
13406 			sum = (sum & 0xFFFF) + (sum >> 16);
13407 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
13408 			/*
13409 			 * Don't verify header checksum if this packet
13410 			 * is coming back from AH/ESP as we already did it.
13411 			 */
13412 			if (sum != 0 && sum != 0xFFFF) {
13413 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
13414 				goto error;
13415 			}
13416 		}
13417 		/*
13418 		 * Since there is no SCTP h/w cksum support yet, just
13419 		 * clear the flag.
13420 		 */
13421 		DB_CKSUMFLAGS(mp) = 0;
13422 	}
13423 
13424 	/*
13425 	 * Don't verify header checksum if this packet is coming
13426 	 * back from AH/ESP as we already did it.
13427 	 */
13428 	if (!mctl_present) {
13429 		UPDATE_IB_PKT_COUNT(ire);
13430 		ire->ire_last_used_time = lbolt;
13431 	}
13432 
13433 	/* packet part of fragmented IP packet? */
13434 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13435 	if (u1 & (IPH_MF | IPH_OFFSET))
13436 		goto fragmented;
13437 
13438 	/* u1 = IP header length (20 bytes) */
13439 	u1 = IP_SIMPLE_HDR_LENGTH;
13440 
13441 find_sctp_client:
13442 	/* Pullup if we don't have the sctp common header. */
13443 	len = MBLKL(mp);
13444 	if (len < (u1 + SCTP_COMMON_HDR_LENGTH)) {
13445 		if (mp->b_cont == NULL ||
13446 		    !pullupmsg(mp, u1 + SCTP_COMMON_HDR_LENGTH)) {
13447 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13448 			goto error;
13449 		}
13450 		ipha = (ipha_t *)mp->b_rptr;
13451 		len = MBLKL(mp);
13452 	}
13453 
13454 	sctph = (sctp_hdr_t *)(rptr + u1);
13455 #ifdef	DEBUG
13456 	if (!skip_sctp_cksum) {
13457 #endif
13458 		pktsum = sctph->sh_chksum;
13459 		sctph->sh_chksum = 0;
13460 		calcsum = sctp_cksum(mp, u1);
13461 		sctph->sh_chksum = pktsum;
13462 		if (calcsum != pktsum)
13463 			sctp_csum_err = B_TRUE;
13464 #ifdef	DEBUG	/* skip_sctp_cksum */
13465 	}
13466 #endif
13467 	/* get the ports */
13468 	ports = *(uint32_t *)&sctph->sh_sport;
13469 
13470 	IRE_REFRELE(ire);
13471 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_dst, &map_dst);
13472 	IN6_IPADDR_TO_V4MAPPED(ipha->ipha_src, &map_src);
13473 	if (sctp_csum_err) {
13474 		/*
13475 		 * No potential sctp checksum errors go to the Sun
13476 		 * sctp stack however they might be Adler-32 summed
13477 		 * packets a userland stack bound to a raw IP socket
13478 		 * could reasonably use. Note though that Adler-32 is
13479 		 * a long deprecated algorithm and customer sctp
13480 		 * networks should eventually migrate to CRC-32 at
13481 		 * which time this facility should be removed.
13482 		 */
13483 		flags |= IP_FF_SCTP_CSUM_ERR;
13484 		goto no_conn;
13485 	}
13486 	if ((connp = sctp_fanout(&map_src, &map_dst, ports, zoneid, mp,
13487 	    sctps)) == NULL) {
13488 		/* Check for raw socket or OOTB handling */
13489 		goto no_conn;
13490 	}
13491 
13492 	/* Found a client; up it goes */
13493 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInDelivers);
13494 	sctp_input(connp, ipha, mp, first_mp, recv_ill, B_TRUE, mctl_present);
13495 	return;
13496 
13497 no_conn:
13498 	ip_fanout_sctp_raw(first_mp, recv_ill, ipha, B_TRUE,
13499 	    ports, mctl_present, flags, B_TRUE, zoneid);
13500 	return;
13501 
13502 ipoptions:
13503 	DB_CKSUMFLAGS(mp) = 0;
13504 	if (!ip_options_cksum(q, ill, first_mp, ipha, ire, ipst))
13505 		goto slow_done;
13506 
13507 	UPDATE_IB_PKT_COUNT(ire);
13508 	ire->ire_last_used_time = lbolt;
13509 
13510 	u1 = ntohs(ipha->ipha_fragment_offset_and_flags);
13511 	if (u1 & (IPH_MF | IPH_OFFSET)) {
13512 fragmented:
13513 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL))
13514 			goto slow_done;
13515 		/*
13516 		 * Make sure that first_mp points back to mp as
13517 		 * the mp we came in with could have changed in
13518 		 * ip_rput_fragment().
13519 		 */
13520 		ASSERT(!mctl_present);
13521 		ipha = (ipha_t *)mp->b_rptr;
13522 		first_mp = mp;
13523 	}
13524 
13525 	/* Now we have a complete datagram, destined for this machine. */
13526 	u1 = IPH_HDR_LENGTH(ipha);
13527 	goto find_sctp_client;
13528 #undef  iphs
13529 #undef  rptr
13530 
13531 error:
13532 	freemsg(first_mp);
13533 slow_done:
13534 	IRE_REFRELE(ire);
13535 }
13536 
13537 #define	VER_BITS	0xF0
13538 #define	VERSION_6	0x60
13539 
13540 static boolean_t
13541 ip_rput_multimblk_ipoptions(queue_t *q, ill_t *ill, mblk_t *mp, ipha_t **iphapp,
13542     ipaddr_t *dstp, ip_stack_t *ipst)
13543 {
13544 	uint_t	opt_len;
13545 	ipha_t *ipha;
13546 	ssize_t len;
13547 	uint_t	pkt_len;
13548 
13549 	ASSERT(ill != NULL);
13550 	IP_STAT(ipst, ip_ipoptions);
13551 	ipha = *iphapp;
13552 
13553 #define	rptr    ((uchar_t *)ipha)
13554 	/* Assume no IPv6 packets arrive over the IPv4 queue */
13555 	if (IPH_HDR_VERSION(ipha) == IPV6_VERSION) {
13556 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInWrongIPVersion);
13557 		freemsg(mp);
13558 		return (B_FALSE);
13559 	}
13560 
13561 	/* multiple mblk or too short */
13562 	pkt_len = ntohs(ipha->ipha_length);
13563 
13564 	/* Get the number of words of IP options in the IP header. */
13565 	opt_len = ipha->ipha_version_and_hdr_length - IP_SIMPLE_HDR_VERSION;
13566 	if (opt_len) {
13567 		/* IP Options present!  Validate and process. */
13568 		if (opt_len > (15 - IP_SIMPLE_HDR_LENGTH_IN_WORDS)) {
13569 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13570 			goto done;
13571 		}
13572 		/*
13573 		 * Recompute complete header length and make sure we
13574 		 * have access to all of it.
13575 		 */
13576 		len = ((size_t)opt_len + IP_SIMPLE_HDR_LENGTH_IN_WORDS) << 2;
13577 		if (len > (mp->b_wptr - rptr)) {
13578 			if (len > pkt_len) {
13579 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13580 				goto done;
13581 			}
13582 			if (!pullupmsg(mp, len)) {
13583 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13584 				goto done;
13585 			}
13586 			ipha = (ipha_t *)mp->b_rptr;
13587 		}
13588 		/*
13589 		 * Go off to ip_rput_options which returns the next hop
13590 		 * destination address, which may have been affected
13591 		 * by source routing.
13592 		 */
13593 		IP_STAT(ipst, ip_opt);
13594 		if (ip_rput_options(q, mp, ipha, dstp, ipst) == -1) {
13595 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13596 			return (B_FALSE);
13597 		}
13598 	}
13599 	*iphapp = ipha;
13600 	return (B_TRUE);
13601 done:
13602 	/* clear b_prev - used by ip_mroute_decap */
13603 	mp->b_prev = NULL;
13604 	freemsg(mp);
13605 	return (B_FALSE);
13606 #undef  rptr
13607 }
13608 
13609 /*
13610  * Deal with the fact that there is no ire for the destination.
13611  */
13612 static ire_t *
13613 ip_rput_noire(queue_t *q, mblk_t *mp, int ll_multicast, ipaddr_t dst)
13614 {
13615 	ipha_t	*ipha;
13616 	ill_t	*ill;
13617 	ire_t	*ire;
13618 	ip_stack_t *ipst;
13619 	enum	ire_forward_action ret_action;
13620 
13621 	ipha = (ipha_t *)mp->b_rptr;
13622 	ill = (ill_t *)q->q_ptr;
13623 
13624 	ASSERT(ill != NULL);
13625 	ipst = ill->ill_ipst;
13626 
13627 	/*
13628 	 * No IRE for this destination, so it can't be for us.
13629 	 * Unless we are forwarding, drop the packet.
13630 	 * We have to let source routed packets through
13631 	 * since we don't yet know if they are 'ping -l'
13632 	 * packets i.e. if they will go out over the
13633 	 * same interface as they came in on.
13634 	 */
13635 	if (ll_multicast) {
13636 		freemsg(mp);
13637 		return (NULL);
13638 	}
13639 	if (!(ill->ill_flags & ILLF_ROUTER) && !ip_source_routed(ipha, ipst)) {
13640 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13641 		freemsg(mp);
13642 		return (NULL);
13643 	}
13644 
13645 	/*
13646 	 * Mark this packet as having originated externally.
13647 	 *
13648 	 * For non-forwarding code path, ire_send later double
13649 	 * checks this interface to see if it is still exists
13650 	 * post-ARP resolution.
13651 	 *
13652 	 * Also, IPQOS uses this to differentiate between
13653 	 * IPP_FWD_OUT and IPP_LOCAL_OUT for post-ARP
13654 	 * QOS packet processing in ip_wput_attach_llhdr().
13655 	 * The QoS module can mark the b_band for a fastpath message
13656 	 * or the dl_priority field in a unitdata_req header for
13657 	 * CoS marking. This info can only be found in
13658 	 * ip_wput_attach_llhdr().
13659 	 */
13660 	mp->b_prev = (mblk_t *)(uintptr_t)ill->ill_phyint->phyint_ifindex;
13661 	/*
13662 	 * Clear the indication that this may have a hardware checksum
13663 	 * as we are not using it
13664 	 */
13665 	DB_CKSUMFLAGS(mp) = 0;
13666 
13667 	ire = ire_forward(dst, &ret_action, NULL, NULL,
13668 	    MBLK_GETLABEL(mp), ipst);
13669 
13670 	if (ire == NULL && ret_action == Forward_check_multirt) {
13671 		/* Let ip_newroute handle CGTP  */
13672 		ip_newroute(q, mp, dst, NULL, GLOBAL_ZONEID, ipst);
13673 		return (NULL);
13674 	}
13675 
13676 	if (ire != NULL)
13677 		return (ire);
13678 
13679 	mp->b_prev = mp->b_next = 0;
13680 
13681 	if (ret_action == Forward_blackhole) {
13682 		freemsg(mp);
13683 		return (NULL);
13684 	}
13685 	/* send icmp unreachable */
13686 	q = WR(q);
13687 	/* Sent by forwarding path, and router is global zone */
13688 	if (ip_source_routed(ipha, ipst)) {
13689 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED,
13690 		    GLOBAL_ZONEID, ipst);
13691 	} else {
13692 		icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, GLOBAL_ZONEID,
13693 		    ipst);
13694 	}
13695 
13696 	return (NULL);
13697 
13698 }
13699 
13700 /*
13701  * check ip header length and align it.
13702  */
13703 static boolean_t
13704 ip_check_and_align_header(queue_t *q, mblk_t *mp, ip_stack_t *ipst)
13705 {
13706 	ssize_t len;
13707 	ill_t *ill;
13708 	ipha_t	*ipha;
13709 
13710 	len = MBLKL(mp);
13711 
13712 	if (!OK_32PTR(mp->b_rptr) || len < IP_SIMPLE_HDR_LENGTH) {
13713 		ill = (ill_t *)q->q_ptr;
13714 
13715 		if (!OK_32PTR(mp->b_rptr))
13716 			IP_STAT(ipst, ip_notaligned1);
13717 		else
13718 			IP_STAT(ipst, ip_notaligned2);
13719 		/* Guard against bogus device drivers */
13720 		if (len < 0) {
13721 			/* clear b_prev - used by ip_mroute_decap */
13722 			mp->b_prev = NULL;
13723 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInHdrErrors);
13724 			freemsg(mp);
13725 			return (B_FALSE);
13726 		}
13727 
13728 		if (ip_rput_pullups++ == 0) {
13729 			ipha = (ipha_t *)mp->b_rptr;
13730 			(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
13731 			    "ip_check_and_align_header: %s forced us to "
13732 			    " pullup pkt, hdr len %ld, hdr addr %p",
13733 			    ill->ill_name, len, ipha);
13734 		}
13735 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
13736 			/* clear b_prev - used by ip_mroute_decap */
13737 			mp->b_prev = NULL;
13738 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13739 			freemsg(mp);
13740 			return (B_FALSE);
13741 		}
13742 	}
13743 	return (B_TRUE);
13744 }
13745 
13746 ire_t *
13747 ip_check_multihome(void *addr, ire_t *ire, ill_t *ill)
13748 {
13749 	ire_t		*new_ire;
13750 	ill_t		*ire_ill;
13751 	uint_t		ifindex;
13752 	ip_stack_t	*ipst = ill->ill_ipst;
13753 	boolean_t	strict_check = B_FALSE;
13754 
13755 	/*
13756 	 * This packet came in on an interface other than the one associated
13757 	 * with the first ire we found for the destination address. We do
13758 	 * another ire lookup here, using the ingress ill, to see if the
13759 	 * interface is in an interface group.
13760 	 * As long as the ills belong to the same group, we don't consider
13761 	 * them to be arriving on the wrong interface. Thus, if the switch
13762 	 * is doing inbound load spreading, we won't drop packets when the
13763 	 * ip*_strict_dst_multihoming switch is on. Note, the same holds true
13764 	 * for 'usesrc groups' where the destination address may belong to
13765 	 * another interface to allow multipathing to happen.
13766 	 * We also need to check for IPIF_UNNUMBERED point2point interfaces
13767 	 * where the local address may not be unique. In this case we were
13768 	 * at the mercy of the initial ire cache lookup and the IRE_LOCAL it
13769 	 * actually returned. The new lookup, which is more specific, should
13770 	 * only find the IRE_LOCAL associated with the ingress ill if one
13771 	 * exists.
13772 	 */
13773 
13774 	if (ire->ire_ipversion == IPV4_VERSION) {
13775 		if (ipst->ips_ip_strict_dst_multihoming)
13776 			strict_check = B_TRUE;
13777 		new_ire = ire_ctable_lookup(*((ipaddr_t *)addr), 0, IRE_LOCAL,
13778 		    ill->ill_ipif, ALL_ZONES, NULL,
13779 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13780 	} else {
13781 		ASSERT(!IN6_IS_ADDR_MULTICAST((in6_addr_t *)addr));
13782 		if (ipst->ips_ipv6_strict_dst_multihoming)
13783 			strict_check = B_TRUE;
13784 		new_ire = ire_ctable_lookup_v6((in6_addr_t *)addr, NULL,
13785 		    IRE_LOCAL, ill->ill_ipif, ALL_ZONES, NULL,
13786 		    (MATCH_IRE_TYPE|MATCH_IRE_ILL_GROUP), ipst);
13787 	}
13788 	/*
13789 	 * If the same ire that was returned in ip_input() is found then this
13790 	 * is an indication that interface groups are in use. The packet
13791 	 * arrived on a different ill in the group than the one associated with
13792 	 * the destination address.  If a different ire was found then the same
13793 	 * IP address must be hosted on multiple ills. This is possible with
13794 	 * unnumbered point2point interfaces. We switch to use this new ire in
13795 	 * order to have accurate interface statistics.
13796 	 */
13797 	if (new_ire != NULL) {
13798 		if ((new_ire != ire) && (new_ire->ire_rfq != NULL)) {
13799 			ire_refrele(ire);
13800 			ire = new_ire;
13801 		} else {
13802 			ire_refrele(new_ire);
13803 		}
13804 		return (ire);
13805 	} else if ((ire->ire_rfq == NULL) &&
13806 	    (ire->ire_ipversion == IPV4_VERSION)) {
13807 		/*
13808 		 * The best match could have been the original ire which
13809 		 * was created against an IRE_LOCAL on lo0. In the IPv4 case
13810 		 * the strict multihoming checks are irrelevant as we consider
13811 		 * local addresses hosted on lo0 to be interface agnostic. We
13812 		 * only expect a null ire_rfq on IREs which are associated with
13813 		 * lo0 hence we can return now.
13814 		 */
13815 		return (ire);
13816 	}
13817 
13818 	/*
13819 	 * Chase pointers once and store locally.
13820 	 */
13821 	ire_ill = (ire->ire_rfq == NULL) ? NULL :
13822 	    (ill_t *)(ire->ire_rfq->q_ptr);
13823 	ifindex = ill->ill_usesrc_ifindex;
13824 
13825 	/*
13826 	 * Check if it's a legal address on the 'usesrc' interface.
13827 	 */
13828 	if ((ifindex != 0) && (ire_ill != NULL) &&
13829 	    (ifindex == ire_ill->ill_phyint->phyint_ifindex)) {
13830 		return (ire);
13831 	}
13832 
13833 	/*
13834 	 * If the ip*_strict_dst_multihoming switch is on then we can
13835 	 * only accept this packet if the interface is marked as routing.
13836 	 */
13837 	if (!(strict_check))
13838 		return (ire);
13839 
13840 	if ((ill->ill_flags & ire->ire_ipif->ipif_ill->ill_flags &
13841 	    ILLF_ROUTER) != 0) {
13842 		return (ire);
13843 	}
13844 
13845 	ire_refrele(ire);
13846 	return (NULL);
13847 }
13848 
13849 ire_t *
13850 ip_fast_forward(ire_t *ire, ipaddr_t dst,  ill_t *ill, mblk_t *mp)
13851 {
13852 	ipha_t	*ipha;
13853 	ire_t	*src_ire;
13854 	ill_t	*stq_ill;
13855 	uint_t	hlen;
13856 	uint_t	pkt_len;
13857 	uint32_t sum;
13858 	queue_t	*dev_q;
13859 	ip_stack_t *ipst = ill->ill_ipst;
13860 	mblk_t *fpmp;
13861 	enum	ire_forward_action ret_action;
13862 
13863 	ipha = (ipha_t *)mp->b_rptr;
13864 
13865 	/*
13866 	 * Martian Address Filtering [RFC 1812, Section 5.3.7]
13867 	 * The loopback address check for both src and dst has already
13868 	 * been checked in ip_input
13869 	 */
13870 
13871 	if (dst == INADDR_ANY || CLASSD(ipha->ipha_src)) {
13872 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13873 		goto drop;
13874 	}
13875 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
13876 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
13877 
13878 	if (src_ire != NULL) {
13879 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
13880 		ire_refrele(src_ire);
13881 		goto drop;
13882 	}
13883 
13884 
13885 	/* No ire cache of nexthop. So first create one  */
13886 	if (ire == NULL) {
13887 
13888 		ire = ire_forward(dst, &ret_action, NULL, NULL,
13889 		    NULL, ipst);
13890 		/*
13891 		 * We only come to ip_fast_forward if ip_cgtp_filter
13892 		 * is not set. So ire_forward() should not return with
13893 		 * Forward_check_multirt as the next action.
13894 		 */
13895 		ASSERT(ret_action != Forward_check_multirt);
13896 		if (ire == NULL) {
13897 			/* An attempt was made to forward the packet */
13898 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13899 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
13900 			mp->b_prev = mp->b_next = 0;
13901 			/* send icmp unreachable */
13902 			/* Sent by forwarding path, and router is global zone */
13903 			if (ret_action == Forward_ret_icmp_err) {
13904 				if (ip_source_routed(ipha, ipst)) {
13905 					icmp_unreachable(ill->ill_wq, mp,
13906 					    ICMP_SOURCE_ROUTE_FAILED,
13907 					    GLOBAL_ZONEID, ipst);
13908 				} else {
13909 					icmp_unreachable(ill->ill_wq, mp,
13910 					    ICMP_HOST_UNREACHABLE,
13911 					    GLOBAL_ZONEID, ipst);
13912 				}
13913 			} else {
13914 				freemsg(mp);
13915 			}
13916 			return (NULL);
13917 		}
13918 	}
13919 
13920 	/*
13921 	 * Forwarding fastpath exception case:
13922 	 * If either of the follwoing case is true, we take
13923 	 * the slowpath
13924 	 *	o forwarding is not enabled
13925 	 *	o incoming and outgoing interface are the same, or the same
13926 	 *	  IPMP group
13927 	 *	o corresponding ire is in incomplete state
13928 	 *	o packet needs fragmentation
13929 	 *	o ARP cache is not resolved
13930 	 *
13931 	 * The codeflow from here on is thus:
13932 	 *	ip_rput_process_forward->ip_rput_forward->ip_xmit_v4
13933 	 */
13934 	pkt_len = ntohs(ipha->ipha_length);
13935 	stq_ill = (ill_t *)ire->ire_stq->q_ptr;
13936 	if (!(stq_ill->ill_flags & ILLF_ROUTER) ||
13937 	    !(ill->ill_flags & ILLF_ROUTER) ||
13938 	    (ill == stq_ill) ||
13939 	    (ill->ill_group != NULL && ill->ill_group == stq_ill->ill_group) ||
13940 	    (ire->ire_nce == NULL) ||
13941 	    (pkt_len > ire->ire_max_frag) ||
13942 	    ((fpmp = ire->ire_nce->nce_fp_mp) == NULL) ||
13943 	    ((hlen = MBLKL(fpmp)) > MBLKHEAD(mp)) ||
13944 	    ipha->ipha_ttl <= 1) {
13945 		ip_rput_process_forward(ill->ill_rq, mp, ire,
13946 		    ipha, ill, B_FALSE);
13947 		return (ire);
13948 	}
13949 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
13950 
13951 	DTRACE_PROBE4(ip4__forwarding__start,
13952 	    ill_t *, ill, ill_t *, stq_ill, ipha_t *, ipha, mblk_t *, mp);
13953 
13954 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
13955 	    ipst->ips_ipv4firewall_forwarding,
13956 	    ill, stq_ill, ipha, mp, mp, 0, ipst);
13957 
13958 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
13959 
13960 	if (mp == NULL)
13961 		goto drop;
13962 
13963 	mp->b_datap->db_struioun.cksum.flags = 0;
13964 	/* Adjust the checksum to reflect the ttl decrement. */
13965 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
13966 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
13967 	ipha->ipha_ttl--;
13968 
13969 	/*
13970 	 * Write the link layer header.  We can do this safely here,
13971 	 * because we have already tested to make sure that the IP
13972 	 * policy is not set, and that we have a fast path destination
13973 	 * header.
13974 	 */
13975 	mp->b_rptr -= hlen;
13976 	bcopy(fpmp->b_rptr, mp->b_rptr, hlen);
13977 
13978 	UPDATE_IB_PKT_COUNT(ire);
13979 	ire->ire_last_used_time = lbolt;
13980 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
13981 	BUMP_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
13982 	UPDATE_MIB(stq_ill->ill_ip_mib, ipIfStatsHCOutOctets, pkt_len);
13983 
13984 	dev_q = ire->ire_stq->q_next;
13985 	if ((dev_q->q_next != NULL || dev_q->q_first != NULL) &&
13986 	    !canputnext(ire->ire_stq)) {
13987 		goto indiscard;
13988 	}
13989 	if (ILL_DLS_CAPABLE(stq_ill)) {
13990 		/*
13991 		 * Send the packet directly to DLD, where it
13992 		 * may be queued depending on the availability
13993 		 * of transmit resources at the media layer.
13994 		 */
13995 		IP_DLS_ILL_TX(stq_ill, ipha, mp, ipst);
13996 	} else {
13997 		DTRACE_PROBE4(ip4__physical__out__start,
13998 		    ill_t *, NULL, ill_t *, stq_ill,
13999 		    ipha_t *, ipha, mblk_t *, mp);
14000 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
14001 		    ipst->ips_ipv4firewall_physical_out,
14002 		    NULL, stq_ill, ipha, mp, mp, 0, ipst);
14003 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
14004 		if (mp == NULL)
14005 			goto drop;
14006 		putnext(ire->ire_stq, mp);
14007 	}
14008 	return (ire);
14009 
14010 indiscard:
14011 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14012 drop:
14013 	if (mp != NULL)
14014 		freemsg(mp);
14015 	return (ire);
14016 
14017 }
14018 
14019 /*
14020  * This function is called in the forwarding slowpath, when
14021  * either the ire lacks the link-layer address, or the packet needs
14022  * further processing(eg. fragmentation), before transmission.
14023  */
14024 
14025 static void
14026 ip_rput_process_forward(queue_t *q, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14027     ill_t *ill, boolean_t ll_multicast)
14028 {
14029 	ill_group_t	*ill_group;
14030 	ill_group_t	*ire_group;
14031 	queue_t		*dev_q;
14032 	ire_t		*src_ire;
14033 	ip_stack_t	*ipst = ill->ill_ipst;
14034 
14035 	ASSERT(ire->ire_stq != NULL);
14036 
14037 	mp->b_prev = NULL; /* ip_rput_noire sets incoming interface here */
14038 	mp->b_next = NULL; /* ip_rput_noire sets dst here */
14039 
14040 	if (ll_multicast != 0) {
14041 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14042 		goto drop_pkt;
14043 	}
14044 
14045 	/*
14046 	 * check if ipha_src is a broadcast address. Note that this
14047 	 * check is redundant when we get here from ip_fast_forward()
14048 	 * which has already done this check. However, since we can
14049 	 * also get here from ip_rput_process_broadcast() or, for
14050 	 * for the slow path through ip_fast_forward(), we perform
14051 	 * the check again for code-reusability
14052 	 */
14053 	src_ire = ire_ctable_lookup(ipha->ipha_src, 0, IRE_BROADCAST, NULL,
14054 	    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
14055 	if (src_ire != NULL || ipha->ipha_dst == INADDR_ANY) {
14056 		if (src_ire != NULL)
14057 			ire_refrele(src_ire);
14058 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14059 		ip2dbg(("ip_rput_process_forward: Received packet with"
14060 		    " bad src/dst address on %s\n", ill->ill_name));
14061 		goto drop_pkt;
14062 	}
14063 
14064 	ill_group = ill->ill_group;
14065 	ire_group = ((ill_t *)(ire->ire_rfq)->q_ptr)->ill_group;
14066 	/*
14067 	 * Check if we want to forward this one at this time.
14068 	 * We allow source routed packets on a host provided that
14069 	 * they go out the same interface or same interface group
14070 	 * as they came in on.
14071 	 *
14072 	 * XXX To be quicker, we may wish to not chase pointers to
14073 	 * get the ILLF_ROUTER flag and instead store the
14074 	 * forwarding policy in the ire.  An unfortunate
14075 	 * side-effect of that would be requiring an ire flush
14076 	 * whenever the ILLF_ROUTER flag changes.
14077 	 */
14078 	if (((ill->ill_flags &
14079 	    ((ill_t *)ire->ire_stq->q_ptr)->ill_flags &
14080 	    ILLF_ROUTER) == 0) &&
14081 	    !(ip_source_routed(ipha, ipst) && (ire->ire_rfq == q ||
14082 	    (ill_group != NULL && ill_group == ire_group)))) {
14083 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsForwProhibits);
14084 		if (ip_source_routed(ipha, ipst)) {
14085 			q = WR(q);
14086 			/*
14087 			 * Clear the indication that this may have
14088 			 * hardware checksum as we are not using it.
14089 			 */
14090 			DB_CKSUMFLAGS(mp) = 0;
14091 			/* Sent by forwarding path, and router is global zone */
14092 			icmp_unreachable(q, mp,
14093 			    ICMP_SOURCE_ROUTE_FAILED, GLOBAL_ZONEID, ipst);
14094 			return;
14095 		}
14096 		goto drop_pkt;
14097 	}
14098 
14099 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInForwDatagrams);
14100 
14101 	/* Packet is being forwarded. Turning off hwcksum flag. */
14102 	DB_CKSUMFLAGS(mp) = 0;
14103 	if (ipst->ips_ip_g_send_redirects) {
14104 		/*
14105 		 * Check whether the incoming interface and outgoing
14106 		 * interface is part of the same group. If so,
14107 		 * send redirects.
14108 		 *
14109 		 * Check the source address to see if it originated
14110 		 * on the same logical subnet it is going back out on.
14111 		 * If so, we should be able to send it a redirect.
14112 		 * Avoid sending a redirect if the destination
14113 		 * is directly connected (i.e., ipha_dst is the same
14114 		 * as ire_gateway_addr or the ire_addr of the
14115 		 * nexthop IRE_CACHE ), or if the packet was source
14116 		 * routed out this interface.
14117 		 */
14118 		ipaddr_t src, nhop;
14119 		mblk_t	*mp1;
14120 		ire_t	*nhop_ire = NULL;
14121 
14122 		/*
14123 		 * Check whether ire_rfq and q are from the same ill
14124 		 * or if they are not same, they at least belong
14125 		 * to the same group. If so, send redirects.
14126 		 */
14127 		if ((ire->ire_rfq == q ||
14128 		    (ill_group != NULL && ill_group == ire_group)) &&
14129 		    !ip_source_routed(ipha, ipst)) {
14130 
14131 			nhop = (ire->ire_gateway_addr != 0 ?
14132 			    ire->ire_gateway_addr : ire->ire_addr);
14133 
14134 			if (ipha->ipha_dst == nhop) {
14135 				/*
14136 				 * We avoid sending a redirect if the
14137 				 * destination is directly connected
14138 				 * because it is possible that multiple
14139 				 * IP subnets may have been configured on
14140 				 * the link, and the source may not
14141 				 * be on the same subnet as ip destination,
14142 				 * even though they are on the same
14143 				 * physical link.
14144 				 */
14145 				goto sendit;
14146 			}
14147 
14148 			src = ipha->ipha_src;
14149 
14150 			/*
14151 			 * We look up the interface ire for the nexthop,
14152 			 * to see if ipha_src is in the same subnet
14153 			 * as the nexthop.
14154 			 *
14155 			 * Note that, if, in the future, IRE_CACHE entries
14156 			 * are obsoleted,  this lookup will not be needed,
14157 			 * as the ire passed to this function will be the
14158 			 * same as the nhop_ire computed below.
14159 			 */
14160 			nhop_ire = ire_ftable_lookup(nhop, 0, 0,
14161 			    IRE_INTERFACE, NULL, NULL, ALL_ZONES,
14162 			    0, NULL, MATCH_IRE_TYPE, ipst);
14163 
14164 			if (nhop_ire != NULL) {
14165 				if ((src & nhop_ire->ire_mask) ==
14166 				    (nhop & nhop_ire->ire_mask)) {
14167 					/*
14168 					 * The source is directly connected.
14169 					 * Just copy the ip header (which is
14170 					 * in the first mblk)
14171 					 */
14172 					mp1 = copyb(mp);
14173 					if (mp1 != NULL) {
14174 						icmp_send_redirect(WR(q), mp1,
14175 						    nhop, ipst);
14176 					}
14177 				}
14178 				ire_refrele(nhop_ire);
14179 			}
14180 		}
14181 	}
14182 sendit:
14183 	dev_q = ire->ire_stq->q_next;
14184 	if ((dev_q->q_next || dev_q->q_first) && !canput(dev_q)) {
14185 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14186 		freemsg(mp);
14187 		return;
14188 	}
14189 
14190 	ip_rput_forward(ire, ipha, mp, ill);
14191 	return;
14192 
14193 drop_pkt:
14194 	ip2dbg(("ip_rput_process_forward: drop pkt\n"));
14195 	freemsg(mp);
14196 }
14197 
14198 ire_t *
14199 ip_rput_process_broadcast(queue_t **qp, mblk_t *mp, ire_t *ire, ipha_t *ipha,
14200     ill_t *ill, ipaddr_t dst, int cgtp_flt_pkt, int ll_multicast)
14201 {
14202 	queue_t		*q;
14203 	uint16_t	hcksumflags;
14204 	ip_stack_t	*ipst = ill->ill_ipst;
14205 
14206 	q = *qp;
14207 
14208 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInBcastPkts);
14209 
14210 	/*
14211 	 * Clear the indication that this may have hardware
14212 	 * checksum as we are not using it for forwarding.
14213 	 */
14214 	hcksumflags = DB_CKSUMFLAGS(mp);
14215 	DB_CKSUMFLAGS(mp) = 0;
14216 
14217 	/*
14218 	 * Directed broadcast forwarding: if the packet came in over a
14219 	 * different interface then it is routed out over we can forward it.
14220 	 */
14221 	if (ipha->ipha_protocol == IPPROTO_TCP) {
14222 		ire_refrele(ire);
14223 		freemsg(mp);
14224 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14225 		return (NULL);
14226 	}
14227 	/*
14228 	 * For multicast we have set dst to be INADDR_BROADCAST
14229 	 * for delivering to all STREAMS. IRE_MARK_NORECV is really
14230 	 * only for broadcast packets.
14231 	 */
14232 	if (!CLASSD(ipha->ipha_dst)) {
14233 		ire_t *new_ire;
14234 		ipif_t *ipif;
14235 		/*
14236 		 * For ill groups, as the switch duplicates broadcasts
14237 		 * across all the ports, we need to filter out and
14238 		 * send up only one copy. There is one copy for every
14239 		 * broadcast address on each ill. Thus, we look for a
14240 		 * specific IRE on this ill and look at IRE_MARK_NORECV
14241 		 * later to see whether this ill is eligible to receive
14242 		 * them or not. ill_nominate_bcast_rcv() nominates only
14243 		 * one set of IREs for receiving.
14244 		 */
14245 
14246 		ipif = ipif_get_next_ipif(NULL, ill);
14247 		if (ipif == NULL) {
14248 			ire_refrele(ire);
14249 			freemsg(mp);
14250 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14251 			return (NULL);
14252 		}
14253 		new_ire = ire_ctable_lookup(dst, 0, 0,
14254 		    ipif, ALL_ZONES, NULL, MATCH_IRE_ILL, ipst);
14255 		ipif_refrele(ipif);
14256 
14257 		if (new_ire != NULL) {
14258 			if (new_ire->ire_marks & IRE_MARK_NORECV) {
14259 				ire_refrele(ire);
14260 				ire_refrele(new_ire);
14261 				freemsg(mp);
14262 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14263 				return (NULL);
14264 			}
14265 			/*
14266 			 * In the special case of multirouted broadcast
14267 			 * packets, we unconditionally need to "gateway"
14268 			 * them to the appropriate interface here.
14269 			 * In the normal case, this cannot happen, because
14270 			 * there is no broadcast IRE tagged with the
14271 			 * RTF_MULTIRT flag.
14272 			 */
14273 			if (new_ire->ire_flags & RTF_MULTIRT) {
14274 				ire_refrele(new_ire);
14275 				if (ire->ire_rfq != NULL) {
14276 					q = ire->ire_rfq;
14277 					*qp = q;
14278 				}
14279 			} else {
14280 				ire_refrele(ire);
14281 				ire = new_ire;
14282 			}
14283 		} else if (cgtp_flt_pkt == CGTP_IP_PKT_NOT_CGTP) {
14284 			if (!ipst->ips_ip_g_forward_directed_bcast) {
14285 				/*
14286 				 * Free the message if
14287 				 * ip_g_forward_directed_bcast is turned
14288 				 * off for non-local broadcast.
14289 				 */
14290 				ire_refrele(ire);
14291 				freemsg(mp);
14292 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14293 				return (NULL);
14294 			}
14295 		} else {
14296 			/*
14297 			 * This CGTP packet successfully passed the
14298 			 * CGTP filter, but the related CGTP
14299 			 * broadcast IRE has not been found,
14300 			 * meaning that the redundant ipif is
14301 			 * probably down. However, if we discarded
14302 			 * this packet, its duplicate would be
14303 			 * filtered out by the CGTP filter so none
14304 			 * of them would get through. So we keep
14305 			 * going with this one.
14306 			 */
14307 			ASSERT(cgtp_flt_pkt == CGTP_IP_PKT_PREMIUM);
14308 			if (ire->ire_rfq != NULL) {
14309 				q = ire->ire_rfq;
14310 				*qp = q;
14311 			}
14312 		}
14313 	}
14314 	if (ipst->ips_ip_g_forward_directed_bcast && ll_multicast == 0) {
14315 		/*
14316 		 * Verify that there are not more then one
14317 		 * IRE_BROADCAST with this broadcast address which
14318 		 * has ire_stq set.
14319 		 * TODO: simplify, loop over all IRE's
14320 		 */
14321 		ire_t	*ire1;
14322 		int	num_stq = 0;
14323 		mblk_t	*mp1;
14324 
14325 		/* Find the first one with ire_stq set */
14326 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
14327 		for (ire1 = ire; ire1 &&
14328 		    !ire1->ire_stq && ire1->ire_addr == ire->ire_addr;
14329 		    ire1 = ire1->ire_next)
14330 			;
14331 		if (ire1) {
14332 			ire_refrele(ire);
14333 			ire = ire1;
14334 			IRE_REFHOLD(ire);
14335 		}
14336 
14337 		/* Check if there are additional ones with stq set */
14338 		for (ire1 = ire; ire1; ire1 = ire1->ire_next) {
14339 			if (ire->ire_addr != ire1->ire_addr)
14340 				break;
14341 			if (ire1->ire_stq) {
14342 				num_stq++;
14343 				break;
14344 			}
14345 		}
14346 		rw_exit(&ire->ire_bucket->irb_lock);
14347 		if (num_stq == 1 && ire->ire_stq != NULL) {
14348 			ip1dbg(("ip_rput_process_broadcast: directed "
14349 			    "broadcast to 0x%x\n",
14350 			    ntohl(ire->ire_addr)));
14351 			mp1 = copymsg(mp);
14352 			if (mp1) {
14353 				switch (ipha->ipha_protocol) {
14354 				case IPPROTO_UDP:
14355 					ip_udp_input(q, mp1, ipha, ire, ill);
14356 					break;
14357 				default:
14358 					ip_proto_input(q, mp1, ipha, ire, ill,
14359 					    B_FALSE);
14360 					break;
14361 				}
14362 			}
14363 			/*
14364 			 * Adjust ttl to 2 (1+1 - the forward engine
14365 			 * will decrement it by one.
14366 			 */
14367 			if (ip_csum_hdr(ipha)) {
14368 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
14369 				ip2dbg(("ip_rput_broadcast:drop pkt\n"));
14370 				freemsg(mp);
14371 				ire_refrele(ire);
14372 				return (NULL);
14373 			}
14374 			ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl + 1;
14375 			ipha->ipha_hdr_checksum = 0;
14376 			ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
14377 			ip_rput_process_forward(q, mp, ire, ipha,
14378 			    ill, ll_multicast);
14379 			ire_refrele(ire);
14380 			return (NULL);
14381 		}
14382 		ip1dbg(("ip_rput: NO directed broadcast to 0x%x\n",
14383 		    ntohl(ire->ire_addr)));
14384 	}
14385 
14386 
14387 	/* Restore any hardware checksum flags */
14388 	DB_CKSUMFLAGS(mp) = hcksumflags;
14389 	return (ire);
14390 }
14391 
14392 /* ARGSUSED */
14393 static boolean_t
14394 ip_rput_process_multicast(queue_t *q, mblk_t *mp, ill_t *ill, ipha_t *ipha,
14395     int *ll_multicast, ipaddr_t *dstp)
14396 {
14397 	ip_stack_t	*ipst = ill->ill_ipst;
14398 
14399 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastPkts);
14400 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInMcastOctets,
14401 	    ntohs(ipha->ipha_length));
14402 
14403 	/*
14404 	 * Forward packets only if we have joined the allmulti
14405 	 * group on this interface.
14406 	 */
14407 	if (ipst->ips_ip_g_mrouter && ill->ill_join_allmulti) {
14408 		int retval;
14409 
14410 		/*
14411 		 * Clear the indication that this may have hardware
14412 		 * checksum as we are not using it.
14413 		 */
14414 		DB_CKSUMFLAGS(mp) = 0;
14415 		retval = ip_mforward(ill, ipha, mp);
14416 		/* ip_mforward updates mib variables if needed */
14417 		/* clear b_prev - used by ip_mroute_decap */
14418 		mp->b_prev = NULL;
14419 
14420 		switch (retval) {
14421 		case 0:
14422 			/*
14423 			 * pkt is okay and arrived on phyint.
14424 			 *
14425 			 * If we are running as a multicast router
14426 			 * we need to see all IGMP and/or PIM packets.
14427 			 */
14428 			if ((ipha->ipha_protocol == IPPROTO_IGMP) ||
14429 			    (ipha->ipha_protocol == IPPROTO_PIM)) {
14430 				goto done;
14431 			}
14432 			break;
14433 		case -1:
14434 			/* pkt is mal-formed, toss it */
14435 			goto drop_pkt;
14436 		case 1:
14437 			/* pkt is okay and arrived on a tunnel */
14438 			/*
14439 			 * If we are running a multicast router
14440 			 *  we need to see all igmp packets.
14441 			 */
14442 			if (ipha->ipha_protocol == IPPROTO_IGMP) {
14443 				*dstp = INADDR_BROADCAST;
14444 				*ll_multicast = 1;
14445 				return (B_FALSE);
14446 			}
14447 
14448 			goto drop_pkt;
14449 		}
14450 	}
14451 
14452 	ILM_WALKER_HOLD(ill);
14453 	if (ilm_lookup_ill(ill, *dstp, ALL_ZONES) == NULL) {
14454 		/*
14455 		 * This might just be caused by the fact that
14456 		 * multiple IP Multicast addresses map to the same
14457 		 * link layer multicast - no need to increment counter!
14458 		 */
14459 		ILM_WALKER_RELE(ill);
14460 		freemsg(mp);
14461 		return (B_TRUE);
14462 	}
14463 	ILM_WALKER_RELE(ill);
14464 done:
14465 	ip2dbg(("ip_rput: multicast for us: 0x%x\n", ntohl(*dstp)));
14466 	/*
14467 	 * This assumes the we deliver to all streams for multicast
14468 	 * and broadcast packets.
14469 	 */
14470 	*dstp = INADDR_BROADCAST;
14471 	*ll_multicast = 1;
14472 	return (B_FALSE);
14473 drop_pkt:
14474 	ip2dbg(("ip_rput: drop pkt\n"));
14475 	freemsg(mp);
14476 	return (B_TRUE);
14477 }
14478 
14479 /*
14480  * This function is used to both return an indication of whether or not
14481  * the packet received is a non-unicast packet (by way of the DL_UNITDATA_IND)
14482  * and in doing so, determine whether or not it is broadcast vs multicast.
14483  * For it to be a broadcast packet, we must have the appropriate mblk_t
14484  * hanging off the ill_t.  If this is either not present or doesn't match
14485  * the destination mac address in the DL_UNITDATA_IND, the packet is deemed
14486  * to be multicast.  Thus NICs that have no broadcast address (or no
14487  * capability for one, such as point to point links) cannot return as
14488  * the packet being broadcast.  The use of HPE_BROADCAST/HPE_MULTICAST as
14489  * the return values simplifies the current use of the return value of this
14490  * function, which is to pass through the multicast/broadcast characteristic
14491  * to consumers of the netinfo/pfhooks API.  While this is not cast in stone,
14492  * changing the return value to some other symbol demands the appropriate
14493  * "translation" when hpe_flags is set prior to calling hook_run() for
14494  * packet events.
14495  */
14496 int
14497 ip_get_dlpi_mbcast(ill_t *ill, mblk_t *mb)
14498 {
14499 	dl_unitdata_ind_t *ind = (dl_unitdata_ind_t *)mb->b_rptr;
14500 	mblk_t *bmp;
14501 
14502 	if (ind->dl_group_address) {
14503 		if (ind->dl_dest_addr_offset > sizeof (*ind) &&
14504 		    ind->dl_dest_addr_offset + ind->dl_dest_addr_length <
14505 		    MBLKL(mb) &&
14506 		    (bmp = ill->ill_bcast_mp) != NULL) {
14507 			dl_unitdata_req_t *dlur;
14508 			uint8_t *bphys_addr;
14509 
14510 			dlur = (dl_unitdata_req_t *)bmp->b_rptr;
14511 			if (ill->ill_sap_length < 0)
14512 				bphys_addr = (uchar_t *)dlur +
14513 				    dlur->dl_dest_addr_offset;
14514 			else
14515 				bphys_addr = (uchar_t *)dlur +
14516 				    dlur->dl_dest_addr_offset +
14517 				    ill->ill_sap_length;
14518 
14519 			if (bcmp(mb->b_rptr + ind->dl_dest_addr_offset,
14520 			    bphys_addr, ind->dl_dest_addr_length) == 0) {
14521 				return (HPE_BROADCAST);
14522 			}
14523 			return (HPE_MULTICAST);
14524 		}
14525 		return (HPE_MULTICAST);
14526 	}
14527 	return (0);
14528 }
14529 
14530 static boolean_t
14531 ip_rput_process_notdata(queue_t *q, mblk_t **first_mpp, ill_t *ill,
14532     int *ll_multicast, mblk_t **mpp)
14533 {
14534 	mblk_t *mp1, *from_mp, *to_mp, *mp, *first_mp;
14535 	boolean_t must_copy = B_FALSE;
14536 	struct iocblk   *iocp;
14537 	ipha_t		*ipha;
14538 	ip_stack_t	*ipst = ill->ill_ipst;
14539 
14540 #define	rptr    ((uchar_t *)ipha)
14541 
14542 	first_mp = *first_mpp;
14543 	mp = *mpp;
14544 
14545 	ASSERT(first_mp == mp);
14546 
14547 	/*
14548 	 * if db_ref > 1 then copymsg and free original. Packet may be
14549 	 * changed and do not want other entity who has a reference to this
14550 	 * message to trip over the changes. This is a blind change because
14551 	 * trying to catch all places that might change packet is too
14552 	 * difficult (since it may be a module above this one)
14553 	 *
14554 	 * This corresponds to the non-fast path case. We walk down the full
14555 	 * chain in this case, and check the db_ref count of all the dblks,
14556 	 * and do a copymsg if required. It is possible that the db_ref counts
14557 	 * of the data blocks in the mblk chain can be different.
14558 	 * For Example, we can get a DL_UNITDATA_IND(M_PROTO) with a db_ref
14559 	 * count of 1, followed by a M_DATA block with a ref count of 2, if
14560 	 * 'snoop' is running.
14561 	 */
14562 	for (mp1 = mp; mp1 != NULL; mp1 = mp1->b_cont) {
14563 		if (mp1->b_datap->db_ref > 1) {
14564 			must_copy = B_TRUE;
14565 			break;
14566 		}
14567 	}
14568 
14569 	if (must_copy) {
14570 		mp1 = copymsg(mp);
14571 		if (mp1 == NULL) {
14572 			for (mp1 = mp; mp1 != NULL;
14573 			    mp1 = mp1->b_cont) {
14574 				mp1->b_next = NULL;
14575 				mp1->b_prev = NULL;
14576 			}
14577 			freemsg(mp);
14578 			if (ill != NULL) {
14579 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14580 			} else {
14581 				BUMP_MIB(&ipst->ips_ip_mib,
14582 				    ipIfStatsInDiscards);
14583 			}
14584 			return (B_TRUE);
14585 		}
14586 		for (from_mp = mp, to_mp = mp1; from_mp != NULL;
14587 		    from_mp = from_mp->b_cont, to_mp = to_mp->b_cont) {
14588 			/* Copy b_prev - used by ip_mroute_decap */
14589 			to_mp->b_prev = from_mp->b_prev;
14590 			from_mp->b_prev = NULL;
14591 		}
14592 		*first_mpp = first_mp = mp1;
14593 		freemsg(mp);
14594 		mp = mp1;
14595 		*mpp = mp1;
14596 	}
14597 
14598 	ipha = (ipha_t *)mp->b_rptr;
14599 
14600 	/*
14601 	 * previous code has a case for M_DATA.
14602 	 * We want to check how that happens.
14603 	 */
14604 	ASSERT(first_mp->b_datap->db_type != M_DATA);
14605 	switch (first_mp->b_datap->db_type) {
14606 	case M_PROTO:
14607 	case M_PCPROTO:
14608 		if (((dl_unitdata_ind_t *)rptr)->dl_primitive !=
14609 		    DL_UNITDATA_IND) {
14610 			/* Go handle anything other than data elsewhere. */
14611 			ip_rput_dlpi(q, mp);
14612 			return (B_TRUE);
14613 		}
14614 
14615 		*ll_multicast = ip_get_dlpi_mbcast(ill, mp);
14616 		/* Ditch the DLPI header. */
14617 		mp1 = mp->b_cont;
14618 		ASSERT(first_mp == mp);
14619 		*first_mpp = mp1;
14620 		freeb(mp);
14621 		*mpp = mp1;
14622 		return (B_FALSE);
14623 	case M_IOCACK:
14624 		ip1dbg(("got iocack "));
14625 		iocp = (struct iocblk *)mp->b_rptr;
14626 		switch (iocp->ioc_cmd) {
14627 		case DL_IOC_HDR_INFO:
14628 			ill = (ill_t *)q->q_ptr;
14629 			ill_fastpath_ack(ill, mp);
14630 			return (B_TRUE);
14631 		case SIOCSTUNPARAM:
14632 		case OSIOCSTUNPARAM:
14633 			/* Go through qwriter_ip */
14634 			break;
14635 		case SIOCGTUNPARAM:
14636 		case OSIOCGTUNPARAM:
14637 			ip_rput_other(NULL, q, mp, NULL);
14638 			return (B_TRUE);
14639 		default:
14640 			putnext(q, mp);
14641 			return (B_TRUE);
14642 		}
14643 		/* FALLTHRU */
14644 	case M_ERROR:
14645 	case M_HANGUP:
14646 		/*
14647 		 * Since this is on the ill stream we unconditionally
14648 		 * bump up the refcount
14649 		 */
14650 		ill_refhold(ill);
14651 		qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14652 		return (B_TRUE);
14653 	case M_CTL:
14654 		if ((MBLKL(first_mp) >= sizeof (da_ipsec_t)) &&
14655 		    (((da_ipsec_t *)first_mp->b_rptr)->da_type ==
14656 		    IPHADA_M_CTL)) {
14657 			/*
14658 			 * It's an IPsec accelerated packet.
14659 			 * Make sure that the ill from which we received the
14660 			 * packet has enabled IPsec hardware acceleration.
14661 			 */
14662 			if (!(ill->ill_capabilities &
14663 			    (ILL_CAPAB_AH|ILL_CAPAB_ESP))) {
14664 				/* IPsec kstats: bean counter */
14665 				freemsg(mp);
14666 				return (B_TRUE);
14667 			}
14668 
14669 			/*
14670 			 * Make mp point to the mblk following the M_CTL,
14671 			 * then process according to type of mp.
14672 			 * After this processing, first_mp will point to
14673 			 * the data-attributes and mp to the pkt following
14674 			 * the M_CTL.
14675 			 */
14676 			mp = first_mp->b_cont;
14677 			if (mp == NULL) {
14678 				freemsg(first_mp);
14679 				return (B_TRUE);
14680 			}
14681 			/*
14682 			 * A Hardware Accelerated packet can only be M_DATA
14683 			 * ESP or AH packet.
14684 			 */
14685 			if (mp->b_datap->db_type != M_DATA) {
14686 				/* non-M_DATA IPsec accelerated packet */
14687 				IPSECHW_DEBUG(IPSECHW_PKT,
14688 				    ("non-M_DATA IPsec accelerated pkt\n"));
14689 				freemsg(first_mp);
14690 				return (B_TRUE);
14691 			}
14692 			ipha = (ipha_t *)mp->b_rptr;
14693 			if (ipha->ipha_protocol != IPPROTO_AH &&
14694 			    ipha->ipha_protocol != IPPROTO_ESP) {
14695 				IPSECHW_DEBUG(IPSECHW_PKT,
14696 				    ("non-M_DATA IPsec accelerated pkt\n"));
14697 				freemsg(first_mp);
14698 				return (B_TRUE);
14699 			}
14700 			*mpp = mp;
14701 			return (B_FALSE);
14702 		}
14703 		putnext(q, mp);
14704 		return (B_TRUE);
14705 	case M_IOCNAK:
14706 		ip1dbg(("got iocnak "));
14707 		iocp = (struct iocblk *)mp->b_rptr;
14708 		switch (iocp->ioc_cmd) {
14709 		case SIOCSTUNPARAM:
14710 		case OSIOCSTUNPARAM:
14711 			/*
14712 			 * Since this is on the ill stream we unconditionally
14713 			 * bump up the refcount
14714 			 */
14715 			ill_refhold(ill);
14716 			qwriter_ip(ill, q, mp, ip_rput_other, CUR_OP, B_FALSE);
14717 			return (B_TRUE);
14718 		case DL_IOC_HDR_INFO:
14719 		case SIOCGTUNPARAM:
14720 		case OSIOCGTUNPARAM:
14721 			ip_rput_other(NULL, q, mp, NULL);
14722 			return (B_TRUE);
14723 		default:
14724 			break;
14725 		}
14726 		/* FALLTHRU */
14727 	default:
14728 		putnext(q, mp);
14729 		return (B_TRUE);
14730 	}
14731 }
14732 
14733 /* Read side put procedure.  Packets coming from the wire arrive here. */
14734 void
14735 ip_rput(queue_t *q, mblk_t *mp)
14736 {
14737 	ill_t	*ill;
14738 	union DL_primitives *dl;
14739 
14740 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_rput_start: q %p", q);
14741 
14742 	ill = (ill_t *)q->q_ptr;
14743 
14744 	if (ill->ill_state_flags & (ILL_CONDEMNED | ILL_LL_SUBNET_PENDING)) {
14745 		/*
14746 		 * If things are opening or closing, only accept high-priority
14747 		 * DLPI messages.  (On open ill->ill_ipif has not yet been
14748 		 * created; on close, things hanging off the ill may have been
14749 		 * freed already.)
14750 		 */
14751 		dl = (union DL_primitives *)mp->b_rptr;
14752 		if (DB_TYPE(mp) != M_PCPROTO ||
14753 		    dl->dl_primitive == DL_UNITDATA_IND) {
14754 			/*
14755 			 * SIOC[GS]TUNPARAM ioctls can come here.
14756 			 */
14757 			inet_freemsg(mp);
14758 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14759 			    "ip_rput_end: q %p (%S)", q, "uninit");
14760 			return;
14761 		}
14762 	}
14763 
14764 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
14765 	    "ip_rput_end: q %p (%S)", q, "end");
14766 
14767 	ip_input(ill, NULL, mp, NULL);
14768 }
14769 
14770 static mblk_t *
14771 ip_fix_dbref(ill_t *ill, mblk_t *mp)
14772 {
14773 	mblk_t *mp1;
14774 	boolean_t adjusted = B_FALSE;
14775 	ip_stack_t *ipst = ill->ill_ipst;
14776 
14777 	IP_STAT(ipst, ip_db_ref);
14778 	/*
14779 	 * The IP_RECVSLLA option depends on having the
14780 	 * link layer header. First check that:
14781 	 * a> the underlying device is of type ether,
14782 	 * since this option is currently supported only
14783 	 * over ethernet.
14784 	 * b> there is enough room to copy over the link
14785 	 * layer header.
14786 	 *
14787 	 * Once the checks are done, adjust rptr so that
14788 	 * the link layer header will be copied via
14789 	 * copymsg. Note that, IFT_ETHER may be returned
14790 	 * by some non-ethernet drivers but in this case
14791 	 * the second check will fail.
14792 	 */
14793 	if (ill->ill_type == IFT_ETHER &&
14794 	    (mp->b_rptr - mp->b_datap->db_base) >=
14795 	    sizeof (struct ether_header)) {
14796 		mp->b_rptr -= sizeof (struct ether_header);
14797 		adjusted = B_TRUE;
14798 	}
14799 	mp1 = copymsg(mp);
14800 
14801 	if (mp1 == NULL) {
14802 		mp->b_next = NULL;
14803 		/* clear b_prev - used by ip_mroute_decap */
14804 		mp->b_prev = NULL;
14805 		freemsg(mp);
14806 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
14807 		return (NULL);
14808 	}
14809 
14810 	if (adjusted) {
14811 		/*
14812 		 * Copy is done. Restore the pointer in
14813 		 * the _new_ mblk
14814 		 */
14815 		mp1->b_rptr += sizeof (struct ether_header);
14816 	}
14817 
14818 	/* Copy b_prev - used by ip_mroute_decap */
14819 	mp1->b_prev = mp->b_prev;
14820 	mp->b_prev = NULL;
14821 
14822 	/* preserve the hardware checksum flags and data, if present */
14823 	if (DB_CKSUMFLAGS(mp) != 0) {
14824 		DB_CKSUMFLAGS(mp1) = DB_CKSUMFLAGS(mp);
14825 		DB_CKSUMSTART(mp1) = DB_CKSUMSTART(mp);
14826 		DB_CKSUMSTUFF(mp1) = DB_CKSUMSTUFF(mp);
14827 		DB_CKSUMEND(mp1) = DB_CKSUMEND(mp);
14828 		DB_CKSUM16(mp1) = DB_CKSUM16(mp);
14829 	}
14830 
14831 	freemsg(mp);
14832 	return (mp1);
14833 }
14834 
14835 /*
14836  * Direct read side procedure capable of dealing with chains. GLDv3 based
14837  * drivers call this function directly with mblk chains while STREAMS
14838  * read side procedure ip_rput() calls this for single packet with ip_ring
14839  * set to NULL to process one packet at a time.
14840  *
14841  * The ill will always be valid if this function is called directly from
14842  * the driver.
14843  *
14844  * If ip_input() is called from GLDv3:
14845  *
14846  *   - This must be a non-VLAN IP stream.
14847  *   - 'mp' is either an untagged or a special priority-tagged packet.
14848  *   - Any VLAN tag that was in the MAC header has been stripped.
14849  *
14850  * If the IP header in packet is not 32-bit aligned, every message in the
14851  * chain will be aligned before further operations. This is required on SPARC
14852  * platform.
14853  */
14854 /* ARGSUSED */
14855 void
14856 ip_input(ill_t *ill, ill_rx_ring_t *ip_ring, mblk_t *mp_chain,
14857     struct mac_header_info_s *mhip)
14858 {
14859 	ipaddr_t		dst = NULL;
14860 	ipaddr_t		prev_dst;
14861 	ire_t			*ire = NULL;
14862 	ipha_t			*ipha;
14863 	uint_t			pkt_len;
14864 	ssize_t			len;
14865 	uint_t			opt_len;
14866 	int			ll_multicast;
14867 	int			cgtp_flt_pkt;
14868 	queue_t			*q = ill->ill_rq;
14869 	squeue_t		*curr_sqp = NULL;
14870 	mblk_t 			*head = NULL;
14871 	mblk_t			*tail = NULL;
14872 	mblk_t			*first_mp;
14873 	mblk_t 			*mp;
14874 	mblk_t			*dmp;
14875 	int			cnt = 0;
14876 	ip_stack_t		*ipst = ill->ill_ipst;
14877 
14878 	ASSERT(mp_chain != NULL);
14879 	ASSERT(ill != NULL);
14880 
14881 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_START, "ip_input_start: q %p", q);
14882 
14883 #define	rptr	((uchar_t *)ipha)
14884 
14885 	while (mp_chain != NULL) {
14886 		first_mp = mp = mp_chain;
14887 		mp_chain = mp_chain->b_next;
14888 		mp->b_next = NULL;
14889 		ll_multicast = 0;
14890 
14891 		/*
14892 		 * We do ire caching from one iteration to
14893 		 * another. In the event the packet chain contains
14894 		 * all packets from the same dst, this caching saves
14895 		 * an ire_cache_lookup for each of the succeeding
14896 		 * packets in a packet chain.
14897 		 */
14898 		prev_dst = dst;
14899 
14900 		/*
14901 		 * if db_ref > 1 then copymsg and free original. Packet
14902 		 * may be changed and we do not want the other entity
14903 		 * who has a reference to this message to trip over the
14904 		 * changes. This is a blind change because trying to
14905 		 * catch all places that might change the packet is too
14906 		 * difficult.
14907 		 *
14908 		 * This corresponds to the fast path case, where we have
14909 		 * a chain of M_DATA mblks.  We check the db_ref count
14910 		 * of only the 1st data block in the mblk chain. There
14911 		 * doesn't seem to be a reason why a device driver would
14912 		 * send up data with varying db_ref counts in the mblk
14913 		 * chain. In any case the Fast path is a private
14914 		 * interface, and our drivers don't do such a thing.
14915 		 * Given the above assumption, there is no need to walk
14916 		 * down the entire mblk chain (which could have a
14917 		 * potential performance problem)
14918 		 */
14919 
14920 		if (DB_REF(mp) > 1) {
14921 			if ((mp = ip_fix_dbref(ill, mp)) == NULL)
14922 				continue;
14923 		}
14924 
14925 		/*
14926 		 * Check and align the IP header.
14927 		 */
14928 		first_mp = mp;
14929 		if (DB_TYPE(mp) == M_DATA) {
14930 			dmp = mp;
14931 		} else if (DB_TYPE(mp) == M_PROTO &&
14932 		    *(t_uscalar_t *)mp->b_rptr == DL_UNITDATA_IND) {
14933 			dmp = mp->b_cont;
14934 		} else {
14935 			dmp = NULL;
14936 		}
14937 		if (dmp != NULL) {
14938 			/*
14939 			 * IP header ptr not aligned?
14940 			 * OR IP header not complete in first mblk
14941 			 */
14942 			if (!OK_32PTR(dmp->b_rptr) ||
14943 			    MBLKL(dmp) < IP_SIMPLE_HDR_LENGTH) {
14944 				if (!ip_check_and_align_header(q, dmp, ipst))
14945 					continue;
14946 			}
14947 		}
14948 
14949 		/*
14950 		 * ip_input fast path
14951 		 */
14952 
14953 		/* mblk type is not M_DATA */
14954 		if (DB_TYPE(mp) != M_DATA) {
14955 			if (ip_rput_process_notdata(q, &first_mp, ill,
14956 			    &ll_multicast, &mp))
14957 				continue;
14958 
14959 			/*
14960 			 * The only way we can get here is if we had a
14961 			 * packet that was either a DL_UNITDATA_IND or
14962 			 * an M_CTL for an IPsec accelerated packet.
14963 			 *
14964 			 * In either case, the first_mp will point to
14965 			 * the leading M_PROTO or M_CTL.
14966 			 */
14967 			ASSERT(first_mp != NULL);
14968 		} else if (mhip != NULL) {
14969 			/*
14970 			 * ll_multicast is set here so that it is ready
14971 			 * for easy use with FW_HOOKS().  ip_get_dlpi_mbcast
14972 			 * manipulates ll_multicast in the same fashion when
14973 			 * called from ip_rput_process_notdata.
14974 			 */
14975 			switch (mhip->mhi_dsttype) {
14976 			case MAC_ADDRTYPE_MULTICAST :
14977 				ll_multicast = HPE_MULTICAST;
14978 				break;
14979 			case MAC_ADDRTYPE_BROADCAST :
14980 				ll_multicast = HPE_BROADCAST;
14981 				break;
14982 			default :
14983 				break;
14984 			}
14985 		}
14986 
14987 		/* Make sure its an M_DATA and that its aligned */
14988 		ASSERT(DB_TYPE(mp) == M_DATA);
14989 		ASSERT(DB_REF(mp) == 1 && OK_32PTR(mp->b_rptr));
14990 
14991 		ipha = (ipha_t *)mp->b_rptr;
14992 		len = mp->b_wptr - rptr;
14993 		pkt_len = ntohs(ipha->ipha_length);
14994 
14995 		/*
14996 		 * We must count all incoming packets, even if they end
14997 		 * up being dropped later on.
14998 		 */
14999 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCInReceives);
15000 		UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCInOctets, pkt_len);
15001 
15002 		/* multiple mblk or too short */
15003 		len -= pkt_len;
15004 		if (len != 0) {
15005 			/*
15006 			 * Make sure we have data length consistent
15007 			 * with the IP header.
15008 			 */
15009 			if (mp->b_cont == NULL) {
15010 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15011 					BUMP_MIB(ill->ill_ip_mib,
15012 					    ipIfStatsInHdrErrors);
15013 					ip2dbg(("ip_input: drop pkt\n"));
15014 					freemsg(mp);
15015 					continue;
15016 				}
15017 				mp->b_wptr = rptr + pkt_len;
15018 			} else if ((len += msgdsize(mp->b_cont)) != 0) {
15019 				if (len < 0 || pkt_len < IP_SIMPLE_HDR_LENGTH) {
15020 					BUMP_MIB(ill->ill_ip_mib,
15021 					    ipIfStatsInHdrErrors);
15022 					ip2dbg(("ip_input: drop pkt\n"));
15023 					freemsg(mp);
15024 					continue;
15025 				}
15026 				(void) adjmsg(mp, -len);
15027 				IP_STAT(ipst, ip_multimblk3);
15028 			}
15029 		}
15030 
15031 		/* Obtain the dst of the current packet */
15032 		dst = ipha->ipha_dst;
15033 
15034 		/*
15035 		 * The following test for loopback is faster than
15036 		 * IP_LOOPBACK_ADDR(), because it avoids any bitwise
15037 		 * operations.
15038 		 * Note that these addresses are always in network byte order
15039 		 */
15040 		if (((*(uchar_t *)&ipha->ipha_dst) == 127) ||
15041 		    ((*(uchar_t *)&ipha->ipha_src) == 127)) {
15042 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInAddrErrors);
15043 			freemsg(mp);
15044 			continue;
15045 		}
15046 
15047 		/*
15048 		 * The event for packets being received from a 'physical'
15049 		 * interface is placed after validation of the source and/or
15050 		 * destination address as being local so that packets can be
15051 		 * redirected to loopback addresses using ipnat.
15052 		 */
15053 		DTRACE_PROBE4(ip4__physical__in__start,
15054 		    ill_t *, ill, ill_t *, NULL,
15055 		    ipha_t *, ipha, mblk_t *, first_mp);
15056 
15057 		FW_HOOKS(ipst->ips_ip4_physical_in_event,
15058 		    ipst->ips_ipv4firewall_physical_in,
15059 		    ill, NULL, ipha, first_mp, mp, ll_multicast, ipst);
15060 
15061 		DTRACE_PROBE1(ip4__physical__in__end, mblk_t *, first_mp);
15062 
15063 		if (first_mp == NULL) {
15064 			continue;
15065 		}
15066 		dst = ipha->ipha_dst;
15067 
15068 		/*
15069 		 * Attach any necessary label information to
15070 		 * this packet
15071 		 */
15072 		if (is_system_labeled() &&
15073 		    !tsol_get_pkt_label(mp, IPV4_VERSION)) {
15074 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
15075 			freemsg(mp);
15076 			continue;
15077 		}
15078 
15079 		/*
15080 		 * Reuse the cached ire only if the ipha_dst of the previous
15081 		 * packet is the same as the current packet AND it is not
15082 		 * INADDR_ANY.
15083 		 */
15084 		if (!(dst == prev_dst && dst != INADDR_ANY) &&
15085 		    (ire != NULL)) {
15086 			ire_refrele(ire);
15087 			ire = NULL;
15088 		}
15089 		opt_len = ipha->ipha_version_and_hdr_length -
15090 		    IP_SIMPLE_HDR_VERSION;
15091 
15092 		/*
15093 		 * Check to see if we can take the fastpath.
15094 		 * That is possible if the following conditions are met
15095 		 *	o Tsol disabled
15096 		 *	o CGTP disabled
15097 		 *	o ipp_action_count is 0
15098 		 *	o no options in the packet
15099 		 *	o not a RSVP packet
15100 		 * 	o not a multicast packet
15101 		 *	o ill not in IP_DHCPINIT_IF mode
15102 		 */
15103 		if (!is_system_labeled() &&
15104 		    !ipst->ips_ip_cgtp_filter && ipp_action_count == 0 &&
15105 		    opt_len == 0 && ipha->ipha_protocol != IPPROTO_RSVP &&
15106 		    !ll_multicast && !CLASSD(dst) && ill->ill_dhcpinit == 0) {
15107 			if (ire == NULL)
15108 				ire = ire_cache_lookup(dst, ALL_ZONES, NULL,
15109 				    ipst);
15110 
15111 			/* incoming packet is for forwarding */
15112 			if (ire == NULL || (ire->ire_type & IRE_CACHE)) {
15113 				ire = ip_fast_forward(ire, dst, ill, mp);
15114 				continue;
15115 			}
15116 			/* incoming packet is for local consumption */
15117 			if (ire->ire_type & IRE_LOCAL)
15118 				goto local;
15119 		}
15120 
15121 		/*
15122 		 * Disable ire caching for anything more complex
15123 		 * than the simple fast path case we checked for above.
15124 		 */
15125 		if (ire != NULL) {
15126 			ire_refrele(ire);
15127 			ire = NULL;
15128 		}
15129 
15130 		/*
15131 		 * Brutal hack for DHCPv4 unicast: RFC2131 allows a DHCP
15132 		 * server to unicast DHCP packets to a DHCP client using the
15133 		 * IP address it is offering to the client.  This can be
15134 		 * disabled through the "broadcast bit", but not all DHCP
15135 		 * servers honor that bit.  Therefore, to interoperate with as
15136 		 * many DHCP servers as possible, the DHCP client allows the
15137 		 * server to unicast, but we treat those packets as broadcast
15138 		 * here.  Note that we don't rewrite the packet itself since
15139 		 * (a) that would mess up the checksums and (b) the DHCP
15140 		 * client conn is bound to INADDR_ANY so ip_fanout_udp() will
15141 		 * hand it the packet regardless.
15142 		 */
15143 		if (ill->ill_dhcpinit != 0 &&
15144 		    IS_SIMPLE_IPH(ipha) && ipha->ipha_protocol == IPPROTO_UDP &&
15145 		    pullupmsg(mp, sizeof (ipha_t) + sizeof (udpha_t)) == 1) {
15146 			udpha_t *udpha;
15147 
15148 			/*
15149 			 * Reload ipha since pullupmsg() can change b_rptr.
15150 			 */
15151 			ipha = (ipha_t *)mp->b_rptr;
15152 			udpha = (udpha_t *)&ipha[1];
15153 
15154 			if (ntohs(udpha->uha_dst_port) == IPPORT_BOOTPC) {
15155 				DTRACE_PROBE2(ip4__dhcpinit__pkt, ill_t *, ill,
15156 				    mblk_t *, mp);
15157 				dst = INADDR_BROADCAST;
15158 			}
15159 		}
15160 
15161 		/* Full-blown slow path */
15162 		if (opt_len != 0) {
15163 			if (len != 0)
15164 				IP_STAT(ipst, ip_multimblk4);
15165 			else
15166 				IP_STAT(ipst, ip_ipoptions);
15167 			if (!ip_rput_multimblk_ipoptions(q, ill, mp, &ipha,
15168 			    &dst, ipst))
15169 				continue;
15170 		}
15171 
15172 		/*
15173 		 * Invoke the CGTP (multirouting) filtering module to process
15174 		 * the incoming packet. Packets identified as duplicates
15175 		 * must be discarded. Filtering is active only if the
15176 		 * the ip_cgtp_filter ndd variable is non-zero.
15177 		 */
15178 		cgtp_flt_pkt = CGTP_IP_PKT_NOT_CGTP;
15179 		if (ipst->ips_ip_cgtp_filter &&
15180 		    ipst->ips_ip_cgtp_filter_ops != NULL) {
15181 			netstackid_t stackid;
15182 
15183 			stackid = ipst->ips_netstack->netstack_stackid;
15184 			cgtp_flt_pkt =
15185 			    ipst->ips_ip_cgtp_filter_ops->cfo_filter(stackid,
15186 			    ill->ill_phyint->phyint_ifindex, mp);
15187 			if (cgtp_flt_pkt == CGTP_IP_PKT_DUPLICATE) {
15188 				freemsg(first_mp);
15189 				continue;
15190 			}
15191 		}
15192 
15193 		/*
15194 		 * If rsvpd is running, let RSVP daemon handle its processing
15195 		 * and forwarding of RSVP multicast/unicast packets.
15196 		 * If rsvpd is not running but mrouted is running, RSVP
15197 		 * multicast packets are forwarded as multicast traffic
15198 		 * and RSVP unicast packets are forwarded by unicast router.
15199 		 * If neither rsvpd nor mrouted is running, RSVP multicast
15200 		 * packets are not forwarded, but the unicast packets are
15201 		 * forwarded like unicast traffic.
15202 		 */
15203 		if (ipha->ipha_protocol == IPPROTO_RSVP &&
15204 		    ipst->ips_ipcl_proto_fanout[IPPROTO_RSVP].connf_head !=
15205 		    NULL) {
15206 			/* RSVP packet and rsvpd running. Treat as ours */
15207 			ip2dbg(("ip_input: RSVP for us: 0x%x\n", ntohl(dst)));
15208 			/*
15209 			 * This assumes that we deliver to all streams for
15210 			 * multicast and broadcast packets.
15211 			 * We have to force ll_multicast to 1 to handle the
15212 			 * M_DATA messages passed in from ip_mroute_decap.
15213 			 */
15214 			dst = INADDR_BROADCAST;
15215 			ll_multicast = 1;
15216 		} else if (CLASSD(dst)) {
15217 			/* packet is multicast */
15218 			mp->b_next = NULL;
15219 			if (ip_rput_process_multicast(q, mp, ill, ipha,
15220 			    &ll_multicast, &dst))
15221 				continue;
15222 		}
15223 
15224 		if (ire == NULL) {
15225 			ire = ire_cache_lookup(dst, ALL_ZONES,
15226 			    MBLK_GETLABEL(mp), ipst);
15227 		}
15228 
15229 		if (ire == NULL) {
15230 			/*
15231 			 * No IRE for this destination, so it can't be for us.
15232 			 * Unless we are forwarding, drop the packet.
15233 			 * We have to let source routed packets through
15234 			 * since we don't yet know if they are 'ping -l'
15235 			 * packets i.e. if they will go out over the
15236 			 * same interface as they came in on.
15237 			 */
15238 			ire = ip_rput_noire(q, mp, ll_multicast, dst);
15239 			if (ire == NULL)
15240 				continue;
15241 		}
15242 
15243 		/*
15244 		 * Broadcast IRE may indicate either broadcast or
15245 		 * multicast packet
15246 		 */
15247 		if (ire->ire_type == IRE_BROADCAST) {
15248 			/*
15249 			 * Skip broadcast checks if packet is UDP multicast;
15250 			 * we'd rather not enter ip_rput_process_broadcast()
15251 			 * unless the packet is broadcast for real, since
15252 			 * that routine is a no-op for multicast.
15253 			 */
15254 			if (ipha->ipha_protocol != IPPROTO_UDP ||
15255 			    !CLASSD(ipha->ipha_dst)) {
15256 				ire = ip_rput_process_broadcast(&q, mp,
15257 				    ire, ipha, ill, dst, cgtp_flt_pkt,
15258 				    ll_multicast);
15259 				if (ire == NULL)
15260 					continue;
15261 			}
15262 		} else if (ire->ire_stq != NULL) {
15263 			/* fowarding? */
15264 			ip_rput_process_forward(q, mp, ire, ipha, ill,
15265 			    ll_multicast);
15266 			/* ip_rput_process_forward consumed the packet */
15267 			continue;
15268 		}
15269 
15270 local:
15271 		/*
15272 		 * If the queue in the ire is different to the ingress queue
15273 		 * then we need to check to see if we can accept the packet.
15274 		 * Note that for multicast packets and broadcast packets sent
15275 		 * to a broadcast address which is shared between multiple
15276 		 * interfaces we should not do this since we just got a random
15277 		 * broadcast ire.
15278 		 */
15279 		if ((ire->ire_rfq != q) && (ire->ire_type != IRE_BROADCAST)) {
15280 			if ((ire = ip_check_multihome(&ipha->ipha_dst, ire,
15281 			    ill)) == NULL) {
15282 				/* Drop packet */
15283 				BUMP_MIB(ill->ill_ip_mib,
15284 				    ipIfStatsForwProhibits);
15285 				freemsg(mp);
15286 				continue;
15287 			}
15288 			if (ire->ire_rfq != NULL)
15289 				q = ire->ire_rfq;
15290 		}
15291 
15292 		switch (ipha->ipha_protocol) {
15293 		case IPPROTO_TCP:
15294 			ASSERT(first_mp == mp);
15295 			if ((mp = ip_tcp_input(mp, ipha, ill, B_FALSE, ire,
15296 			    mp, 0, q, ip_ring)) != NULL) {
15297 				if (curr_sqp == NULL) {
15298 					curr_sqp = GET_SQUEUE(mp);
15299 					ASSERT(cnt == 0);
15300 					cnt++;
15301 					head = tail = mp;
15302 				} else if (curr_sqp == GET_SQUEUE(mp)) {
15303 					ASSERT(tail != NULL);
15304 					cnt++;
15305 					tail->b_next = mp;
15306 					tail = mp;
15307 				} else {
15308 					/*
15309 					 * A different squeue. Send the
15310 					 * chain for the previous squeue on
15311 					 * its way. This shouldn't happen
15312 					 * often unless interrupt binding
15313 					 * changes.
15314 					 */
15315 					IP_STAT(ipst, ip_input_multi_squeue);
15316 					squeue_enter_chain(curr_sqp, head,
15317 					    tail, cnt, SQTAG_IP_INPUT);
15318 					curr_sqp = GET_SQUEUE(mp);
15319 					head = mp;
15320 					tail = mp;
15321 					cnt = 1;
15322 				}
15323 			}
15324 			continue;
15325 		case IPPROTO_UDP:
15326 			ASSERT(first_mp == mp);
15327 			ip_udp_input(q, mp, ipha, ire, ill);
15328 			continue;
15329 		case IPPROTO_SCTP:
15330 			ASSERT(first_mp == mp);
15331 			ip_sctp_input(mp, ipha, ill, B_FALSE, ire, mp, 0,
15332 			    q, dst);
15333 			/* ire has been released by ip_sctp_input */
15334 			ire = NULL;
15335 			continue;
15336 		default:
15337 			ip_proto_input(q, first_mp, ipha, ire, ill, B_FALSE);
15338 			continue;
15339 		}
15340 	}
15341 
15342 	if (ire != NULL)
15343 		ire_refrele(ire);
15344 
15345 	if (head != NULL)
15346 		squeue_enter_chain(curr_sqp, head, tail, cnt, SQTAG_IP_INPUT);
15347 
15348 	/*
15349 	 * This code is there just to make netperf/ttcp look good.
15350 	 *
15351 	 * Its possible that after being in polling mode (and having cleared
15352 	 * the backlog), squeues have turned the interrupt frequency higher
15353 	 * to improve latency at the expense of more CPU utilization (less
15354 	 * packets per interrupts or more number of interrupts). Workloads
15355 	 * like ttcp/netperf do manage to tickle polling once in a while
15356 	 * but for the remaining time, stay in higher interrupt mode since
15357 	 * their packet arrival rate is pretty uniform and this shows up
15358 	 * as higher CPU utilization. Since people care about CPU utilization
15359 	 * while running netperf/ttcp, turn the interrupt frequency back to
15360 	 * normal/default if polling has not been used in ip_poll_normal_ticks.
15361 	 */
15362 	if (ip_ring != NULL && (ip_ring->rr_poll_state & ILL_POLLING)) {
15363 		if (lbolt >= (ip_ring->rr_poll_time + ip_poll_normal_ticks)) {
15364 			ip_ring->rr_poll_state &= ~ILL_POLLING;
15365 			ip_ring->rr_blank(ip_ring->rr_handle,
15366 			    ip_ring->rr_normal_blank_time,
15367 			    ip_ring->rr_normal_pkt_cnt);
15368 		}
15369 		}
15370 
15371 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_END,
15372 	    "ip_input_end: q %p (%S)", q, "end");
15373 #undef  rptr
15374 }
15375 
15376 static void
15377 ip_dlpi_error(ill_t *ill, t_uscalar_t prim, t_uscalar_t dl_err,
15378     t_uscalar_t err)
15379 {
15380 	if (dl_err == DL_SYSERR) {
15381 		(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15382 		    "%s: %s failed: DL_SYSERR (errno %u)\n",
15383 		    ill->ill_name, dl_primstr(prim), err);
15384 		return;
15385 	}
15386 
15387 	(void) mi_strlog(ill->ill_rq, 1, SL_CONSOLE|SL_ERROR|SL_TRACE,
15388 	    "%s: %s failed: %s\n", ill->ill_name, dl_primstr(prim),
15389 	    dl_errstr(dl_err));
15390 }
15391 
15392 /*
15393  * ip_rput_dlpi is called by ip_rput to handle all DLPI messages other
15394  * than DL_UNITDATA_IND messages. If we need to process this message
15395  * exclusively, we call qwriter_ip, in which case we also need to call
15396  * ill_refhold before that, since qwriter_ip does an ill_refrele.
15397  */
15398 void
15399 ip_rput_dlpi(queue_t *q, mblk_t *mp)
15400 {
15401 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15402 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15403 	ill_t		*ill = (ill_t *)q->q_ptr;
15404 	boolean_t	pending;
15405 
15406 	ip1dbg(("ip_rput_dlpi"));
15407 	if (dloa->dl_primitive == DL_ERROR_ACK) {
15408 		ip2dbg(("ip_rput_dlpi(%s): DL_ERROR_ACK %s (0x%x): "
15409 		    "%s (0x%x), unix %u\n", ill->ill_name,
15410 		    dl_primstr(dlea->dl_error_primitive),
15411 		    dlea->dl_error_primitive,
15412 		    dl_errstr(dlea->dl_errno),
15413 		    dlea->dl_errno,
15414 		    dlea->dl_unix_errno));
15415 	}
15416 
15417 	/*
15418 	 * If we received an ACK but didn't send a request for it, then it
15419 	 * can't be part of any pending operation; discard up-front.
15420 	 */
15421 	switch (dloa->dl_primitive) {
15422 	case DL_NOTIFY_IND:
15423 		pending = B_TRUE;
15424 		break;
15425 	case DL_ERROR_ACK:
15426 		pending = ill_dlpi_pending(ill, dlea->dl_error_primitive);
15427 		break;
15428 	case DL_OK_ACK:
15429 		pending = ill_dlpi_pending(ill, dloa->dl_correct_primitive);
15430 		break;
15431 	case DL_INFO_ACK:
15432 		pending = ill_dlpi_pending(ill, DL_INFO_REQ);
15433 		break;
15434 	case DL_BIND_ACK:
15435 		pending = ill_dlpi_pending(ill, DL_BIND_REQ);
15436 		break;
15437 	case DL_PHYS_ADDR_ACK:
15438 		pending = ill_dlpi_pending(ill, DL_PHYS_ADDR_REQ);
15439 		break;
15440 	case DL_NOTIFY_ACK:
15441 		pending = ill_dlpi_pending(ill, DL_NOTIFY_REQ);
15442 		break;
15443 	case DL_CONTROL_ACK:
15444 		pending = ill_dlpi_pending(ill, DL_CONTROL_REQ);
15445 		break;
15446 	case DL_CAPABILITY_ACK:
15447 		pending = ill_dlpi_pending(ill, DL_CAPABILITY_REQ);
15448 		break;
15449 	default:
15450 		/* Not a DLPI message we support or were expecting */
15451 		freemsg(mp);
15452 		return;
15453 	}
15454 
15455 	if (!pending) {
15456 		freemsg(mp);
15457 		return;
15458 	}
15459 
15460 	switch (dloa->dl_primitive) {
15461 	case DL_ERROR_ACK:
15462 		if (dlea->dl_error_primitive == DL_UNBIND_REQ) {
15463 			mutex_enter(&ill->ill_lock);
15464 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15465 			cv_signal(&ill->ill_cv);
15466 			mutex_exit(&ill->ill_lock);
15467 		}
15468 		break;
15469 
15470 	case DL_OK_ACK:
15471 		ip1dbg(("ip_rput: DL_OK_ACK for %s\n",
15472 		    dl_primstr((int)dloa->dl_correct_primitive)));
15473 		switch (dloa->dl_correct_primitive) {
15474 		case DL_UNBIND_REQ:
15475 			mutex_enter(&ill->ill_lock);
15476 			ill->ill_state_flags &= ~ILL_DL_UNBIND_IN_PROGRESS;
15477 			cv_signal(&ill->ill_cv);
15478 			mutex_exit(&ill->ill_lock);
15479 			break;
15480 
15481 		case DL_ENABMULTI_REQ:
15482 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15483 				ill->ill_dlpi_multicast_state = IDS_OK;
15484 			break;
15485 		}
15486 		break;
15487 	default:
15488 		break;
15489 	}
15490 
15491 	/*
15492 	 * We know the message is one we're waiting for (or DL_NOTIFY_IND),
15493 	 * and we need to become writer to continue to process it. If it's not
15494 	 * a DL_NOTIFY_IND, we assume we're in the middle of an exclusive
15495 	 * operation and pass CUR_OP.  If this isn't true, we'll end up doing
15496 	 * some work as part of the current exclusive operation that actually
15497 	 * is not part of it -- which is wrong, but better than the
15498 	 * alternative of deadlock (if NEW_OP is always used).  Someday, we
15499 	 * should track which DLPI requests have ACKs that we wait on
15500 	 * synchronously so we can know whether to use CUR_OP or NEW_OP.
15501 	 *
15502 	 * As required by qwriter_ip(), we refhold the ill; it will refrele.
15503 	 * Since this is on the ill stream we unconditionally bump up the
15504 	 * refcount without doing ILL_CAN_LOOKUP().
15505 	 */
15506 	ill_refhold(ill);
15507 	if (dloa->dl_primitive == DL_NOTIFY_IND)
15508 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, NEW_OP, B_FALSE);
15509 	else
15510 		qwriter_ip(ill, q, mp, ip_rput_dlpi_writer, CUR_OP, B_FALSE);
15511 }
15512 
15513 /*
15514  * Handling of DLPI messages that require exclusive access to the ipsq.
15515  *
15516  * Need to do ill_pending_mp_release on ioctl completion, which could
15517  * happen here. (along with mi_copy_done)
15518  */
15519 /* ARGSUSED */
15520 static void
15521 ip_rput_dlpi_writer(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
15522 {
15523 	dl_ok_ack_t	*dloa = (dl_ok_ack_t *)mp->b_rptr;
15524 	dl_error_ack_t	*dlea = (dl_error_ack_t *)dloa;
15525 	int		err = 0;
15526 	ill_t		*ill;
15527 	ipif_t		*ipif = NULL;
15528 	mblk_t		*mp1 = NULL;
15529 	conn_t		*connp = NULL;
15530 	t_uscalar_t	paddrreq;
15531 	mblk_t		*mp_hw;
15532 	boolean_t	success;
15533 	boolean_t	ioctl_aborted = B_FALSE;
15534 	boolean_t	log = B_TRUE;
15535 	ip_stack_t		*ipst;
15536 
15537 	ip1dbg(("ip_rput_dlpi_writer .."));
15538 	ill = (ill_t *)q->q_ptr;
15539 	ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
15540 
15541 	ASSERT(IAM_WRITER_ILL(ill));
15542 
15543 	ipst = ill->ill_ipst;
15544 
15545 	/*
15546 	 * ipsq_pending_mp and ipsq_pending_ipif track each other. i.e.
15547 	 * both are null or non-null. However we can assert that only
15548 	 * after grabbing the ipsq_lock. So we don't make any assertion
15549 	 * here and in other places in the code.
15550 	 */
15551 	ipif = ipsq->ipsq_pending_ipif;
15552 	/*
15553 	 * The current ioctl could have been aborted by the user and a new
15554 	 * ioctl to bring up another ill could have started. We could still
15555 	 * get a response from the driver later.
15556 	 */
15557 	if (ipif != NULL && ipif->ipif_ill != ill)
15558 		ioctl_aborted = B_TRUE;
15559 
15560 	switch (dloa->dl_primitive) {
15561 	case DL_ERROR_ACK:
15562 		ip1dbg(("ip_rput_dlpi_writer: got DL_ERROR_ACK for %s\n",
15563 		    dl_primstr(dlea->dl_error_primitive)));
15564 
15565 		switch (dlea->dl_error_primitive) {
15566 		case DL_PROMISCON_REQ:
15567 		case DL_PROMISCOFF_REQ:
15568 		case DL_DISABMULTI_REQ:
15569 		case DL_UNBIND_REQ:
15570 		case DL_ATTACH_REQ:
15571 		case DL_INFO_REQ:
15572 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15573 			break;
15574 		case DL_NOTIFY_REQ:
15575 			ill_dlpi_done(ill, DL_NOTIFY_REQ);
15576 			log = B_FALSE;
15577 			break;
15578 		case DL_PHYS_ADDR_REQ:
15579 			/*
15580 			 * For IPv6 only, there are two additional
15581 			 * phys_addr_req's sent to the driver to get the
15582 			 * IPv6 token and lla. This allows IP to acquire
15583 			 * the hardware address format for a given interface
15584 			 * without having built in knowledge of the hardware
15585 			 * address. ill_phys_addr_pend keeps track of the last
15586 			 * DL_PAR sent so we know which response we are
15587 			 * dealing with. ill_dlpi_done will update
15588 			 * ill_phys_addr_pend when it sends the next req.
15589 			 * We don't complete the IOCTL until all three DL_PARs
15590 			 * have been attempted, so set *_len to 0 and break.
15591 			 */
15592 			paddrreq = ill->ill_phys_addr_pend;
15593 			ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
15594 			if (paddrreq == DL_IPV6_TOKEN) {
15595 				ill->ill_token_length = 0;
15596 				log = B_FALSE;
15597 				break;
15598 			} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
15599 				ill->ill_nd_lla_len = 0;
15600 				log = B_FALSE;
15601 				break;
15602 			}
15603 			/*
15604 			 * Something went wrong with the DL_PHYS_ADDR_REQ.
15605 			 * We presumably have an IOCTL hanging out waiting
15606 			 * for completion. Find it and complete the IOCTL
15607 			 * with the error noted.
15608 			 * However, ill_dl_phys was called on an ill queue
15609 			 * (from SIOCSLIFNAME), thus conn_pending_ill is not
15610 			 * set. But the ioctl is known to be pending on ill_wq.
15611 			 */
15612 			if (!ill->ill_ifname_pending)
15613 				break;
15614 			ill->ill_ifname_pending = 0;
15615 			if (!ioctl_aborted)
15616 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15617 			if (mp1 != NULL) {
15618 				/*
15619 				 * This operation (SIOCSLIFNAME) must have
15620 				 * happened on the ill. Assert there is no conn
15621 				 */
15622 				ASSERT(connp == NULL);
15623 				q = ill->ill_wq;
15624 			}
15625 			break;
15626 		case DL_BIND_REQ:
15627 			ill_dlpi_done(ill, DL_BIND_REQ);
15628 			if (ill->ill_ifname_pending)
15629 				break;
15630 			/*
15631 			 * Something went wrong with the bind.  We presumably
15632 			 * have an IOCTL hanging out waiting for completion.
15633 			 * Find it, take down the interface that was coming
15634 			 * up, and complete the IOCTL with the error noted.
15635 			 */
15636 			if (!ioctl_aborted)
15637 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15638 			if (mp1 != NULL) {
15639 				/*
15640 				 * This operation (SIOCSLIFFLAGS) must have
15641 				 * happened from a conn.
15642 				 */
15643 				ASSERT(connp != NULL);
15644 				q = CONNP_TO_WQ(connp);
15645 				if (ill->ill_move_in_progress) {
15646 					ILL_CLEAR_MOVE(ill);
15647 				}
15648 				(void) ipif_down(ipif, NULL, NULL);
15649 				/* error is set below the switch */
15650 			}
15651 			break;
15652 		case DL_ENABMULTI_REQ:
15653 			ill_dlpi_done(ill, DL_ENABMULTI_REQ);
15654 
15655 			if (ill->ill_dlpi_multicast_state == IDS_INPROGRESS)
15656 				ill->ill_dlpi_multicast_state = IDS_FAILED;
15657 			if (ill->ill_dlpi_multicast_state == IDS_FAILED) {
15658 				ipif_t *ipif;
15659 
15660 				printf("ip: joining multicasts failed (%d)"
15661 				    " on %s - will use link layer "
15662 				    "broadcasts for multicast\n",
15663 				    dlea->dl_errno, ill->ill_name);
15664 
15665 				/*
15666 				 * Set up the multicast mapping alone.
15667 				 * writer, so ok to access ill->ill_ipif
15668 				 * without any lock.
15669 				 */
15670 				ipif = ill->ill_ipif;
15671 				mutex_enter(&ill->ill_phyint->phyint_lock);
15672 				ill->ill_phyint->phyint_flags |=
15673 				    PHYI_MULTI_BCAST;
15674 				mutex_exit(&ill->ill_phyint->phyint_lock);
15675 
15676 				if (!ill->ill_isv6) {
15677 					(void) ipif_arp_setup_multicast(ipif,
15678 					    NULL);
15679 				} else {
15680 					(void) ipif_ndp_setup_multicast(ipif,
15681 					    NULL);
15682 				}
15683 			}
15684 			freemsg(mp);	/* Don't want to pass this up */
15685 			return;
15686 
15687 		case DL_CAPABILITY_REQ:
15688 		case DL_CONTROL_REQ:
15689 			ill_dlpi_done(ill, dlea->dl_error_primitive);
15690 			ill->ill_dlpi_capab_state = IDS_FAILED;
15691 			freemsg(mp);
15692 			return;
15693 		}
15694 		/*
15695 		 * Note the error for IOCTL completion (mp1 is set when
15696 		 * ready to complete ioctl). If ill_ifname_pending_err is
15697 		 * set, an error occured during plumbing (ill_ifname_pending),
15698 		 * so we want to report that error.
15699 		 *
15700 		 * NOTE: there are two addtional DL_PHYS_ADDR_REQ's
15701 		 * (DL_IPV6_TOKEN and DL_IPV6_LINK_LAYER_ADDR) that are
15702 		 * expected to get errack'd if the driver doesn't support
15703 		 * these flags (e.g. ethernet). log will be set to B_FALSE
15704 		 * if these error conditions are encountered.
15705 		 */
15706 		if (mp1 != NULL) {
15707 			if (ill->ill_ifname_pending_err != 0)  {
15708 				err = ill->ill_ifname_pending_err;
15709 				ill->ill_ifname_pending_err = 0;
15710 			} else {
15711 				err = dlea->dl_unix_errno ?
15712 				    dlea->dl_unix_errno : ENXIO;
15713 			}
15714 		/*
15715 		 * If we're plumbing an interface and an error hasn't already
15716 		 * been saved, set ill_ifname_pending_err to the error passed
15717 		 * up. Ignore the error if log is B_FALSE (see comment above).
15718 		 */
15719 		} else if (log && ill->ill_ifname_pending &&
15720 		    ill->ill_ifname_pending_err == 0) {
15721 			ill->ill_ifname_pending_err = dlea->dl_unix_errno ?
15722 			    dlea->dl_unix_errno : ENXIO;
15723 		}
15724 
15725 		if (log)
15726 			ip_dlpi_error(ill, dlea->dl_error_primitive,
15727 			    dlea->dl_errno, dlea->dl_unix_errno);
15728 		break;
15729 	case DL_CAPABILITY_ACK:
15730 		/* Call a routine to handle this one. */
15731 		ill_dlpi_done(ill, DL_CAPABILITY_REQ);
15732 		ill_capability_ack(ill, mp);
15733 
15734 		/*
15735 		 * If the ack is due to renegotiation, we will need to send
15736 		 * a new CAPABILITY_REQ to start the renegotiation.
15737 		 */
15738 		if (ill->ill_capab_reneg) {
15739 			ill->ill_capab_reneg = B_FALSE;
15740 			ill_capability_probe(ill);
15741 		}
15742 		break;
15743 	case DL_CONTROL_ACK:
15744 		/* We treat all of these as "fire and forget" */
15745 		ill_dlpi_done(ill, DL_CONTROL_REQ);
15746 		break;
15747 	case DL_INFO_ACK:
15748 		/* Call a routine to handle this one. */
15749 		ill_dlpi_done(ill, DL_INFO_REQ);
15750 		ip_ll_subnet_defaults(ill, mp);
15751 		ASSERT(!MUTEX_HELD(&ill->ill_phyint->phyint_ipsq->ipsq_lock));
15752 		return;
15753 	case DL_BIND_ACK:
15754 		/*
15755 		 * We should have an IOCTL waiting on this unless
15756 		 * sent by ill_dl_phys, in which case just return
15757 		 */
15758 		ill_dlpi_done(ill, DL_BIND_REQ);
15759 		if (ill->ill_ifname_pending)
15760 			break;
15761 
15762 		if (!ioctl_aborted)
15763 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
15764 		if (mp1 == NULL)
15765 			break;
15766 		/*
15767 		 * Because mp1 was added by ill_dl_up(), and it always
15768 		 * passes a valid connp, connp must be valid here.
15769 		 */
15770 		ASSERT(connp != NULL);
15771 		q = CONNP_TO_WQ(connp);
15772 
15773 		/*
15774 		 * We are exclusive. So nothing can change even after
15775 		 * we get the pending mp. If need be we can put it back
15776 		 * and restart, as in calling ipif_arp_up()  below.
15777 		 */
15778 		ip1dbg(("ip_rput_dlpi: bind_ack %s\n", ill->ill_name));
15779 
15780 		mutex_enter(&ill->ill_lock);
15781 		ill->ill_dl_up = 1;
15782 		(void) ill_hook_event_create(ill, 0, NE_UP, NULL, 0);
15783 		mutex_exit(&ill->ill_lock);
15784 
15785 		/*
15786 		 * Now bring up the resolver; when that is complete, we'll
15787 		 * create IREs.  Note that we intentionally mirror what
15788 		 * ipif_up() would have done, because we got here by way of
15789 		 * ill_dl_up(), which stopped ipif_up()'s processing.
15790 		 */
15791 		if (ill->ill_isv6) {
15792 			/*
15793 			 * v6 interfaces.
15794 			 * Unlike ARP which has to do another bind
15795 			 * and attach, once we get here we are
15796 			 * done with NDP. Except in the case of
15797 			 * ILLF_XRESOLV, in which case we send an
15798 			 * AR_INTERFACE_UP to the external resolver.
15799 			 * If all goes well, the ioctl will complete
15800 			 * in ip_rput(). If there's an error, we
15801 			 * complete it here.
15802 			 */
15803 			if ((err = ipif_ndp_up(ipif)) == 0) {
15804 				if (ill->ill_flags & ILLF_XRESOLV) {
15805 					mutex_enter(&connp->conn_lock);
15806 					mutex_enter(&ill->ill_lock);
15807 					success = ipsq_pending_mp_add(
15808 					    connp, ipif, q, mp1, 0);
15809 					mutex_exit(&ill->ill_lock);
15810 					mutex_exit(&connp->conn_lock);
15811 					if (success) {
15812 						err = ipif_resolver_up(ipif,
15813 						    Res_act_initial);
15814 						if (err == EINPROGRESS) {
15815 							freemsg(mp);
15816 							return;
15817 						}
15818 						ASSERT(err != 0);
15819 						mp1 = ipsq_pending_mp_get(ipsq,
15820 						    &connp);
15821 						ASSERT(mp1 != NULL);
15822 					} else {
15823 						/* conn has started closing */
15824 						err = EINTR;
15825 					}
15826 				} else { /* Non XRESOLV interface */
15827 					(void) ipif_resolver_up(ipif,
15828 					    Res_act_initial);
15829 					err = ipif_up_done_v6(ipif);
15830 				}
15831 			}
15832 		} else if (ill->ill_net_type == IRE_IF_RESOLVER) {
15833 			/*
15834 			 * ARP and other v4 external resolvers.
15835 			 * Leave the pending mblk intact so that
15836 			 * the ioctl completes in ip_rput().
15837 			 */
15838 			mutex_enter(&connp->conn_lock);
15839 			mutex_enter(&ill->ill_lock);
15840 			success = ipsq_pending_mp_add(connp, ipif, q, mp1, 0);
15841 			mutex_exit(&ill->ill_lock);
15842 			mutex_exit(&connp->conn_lock);
15843 			if (success) {
15844 				err = ipif_resolver_up(ipif, Res_act_initial);
15845 				if (err == EINPROGRESS) {
15846 					freemsg(mp);
15847 					return;
15848 				}
15849 				ASSERT(err != 0);
15850 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
15851 			} else {
15852 				/* The conn has started closing */
15853 				err = EINTR;
15854 			}
15855 		} else {
15856 			/*
15857 			 * This one is complete. Reply to pending ioctl.
15858 			 */
15859 			(void) ipif_resolver_up(ipif, Res_act_initial);
15860 			err = ipif_up_done(ipif);
15861 		}
15862 
15863 		if ((err == 0) && (ill->ill_up_ipifs)) {
15864 			err = ill_up_ipifs(ill, q, mp1);
15865 			if (err == EINPROGRESS) {
15866 				freemsg(mp);
15867 				return;
15868 			}
15869 		}
15870 
15871 		if (ill->ill_up_ipifs) {
15872 			ill_group_cleanup(ill);
15873 		}
15874 
15875 		break;
15876 	case DL_NOTIFY_IND: {
15877 		dl_notify_ind_t *notify = (dl_notify_ind_t *)mp->b_rptr;
15878 		ire_t *ire;
15879 		boolean_t need_ire_walk_v4 = B_FALSE;
15880 		boolean_t need_ire_walk_v6 = B_FALSE;
15881 
15882 		switch (notify->dl_notification) {
15883 		case DL_NOTE_PHYS_ADDR:
15884 			err = ill_set_phys_addr(ill, mp);
15885 			break;
15886 
15887 		case DL_NOTE_FASTPATH_FLUSH:
15888 			ill_fastpath_flush(ill);
15889 			break;
15890 
15891 		case DL_NOTE_SDU_SIZE:
15892 			/*
15893 			 * Change the MTU size of the interface, of all
15894 			 * attached ipif's, and of all relevant ire's.  The
15895 			 * new value's a uint32_t at notify->dl_data.
15896 			 * Mtu change Vs. new ire creation - protocol below.
15897 			 *
15898 			 * a Mark the ipif as IPIF_CHANGING.
15899 			 * b Set the new mtu in the ipif.
15900 			 * c Change the ire_max_frag on all affected ires
15901 			 * d Unmark the IPIF_CHANGING
15902 			 *
15903 			 * To see how the protocol works, assume an interface
15904 			 * route is also being added simultaneously by
15905 			 * ip_rt_add and let 'ipif' be the ipif referenced by
15906 			 * the ire. If the ire is created before step a,
15907 			 * it will be cleaned up by step c. If the ire is
15908 			 * created after step d, it will see the new value of
15909 			 * ipif_mtu. Any attempt to create the ire between
15910 			 * steps a to d will fail because of the IPIF_CHANGING
15911 			 * flag. Note that ire_create() is passed a pointer to
15912 			 * the ipif_mtu, and not the value. During ire_add
15913 			 * under the bucket lock, the ire_max_frag of the
15914 			 * new ire being created is set from the ipif/ire from
15915 			 * which it is being derived.
15916 			 */
15917 			mutex_enter(&ill->ill_lock);
15918 			ill->ill_max_frag = (uint_t)notify->dl_data;
15919 
15920 			/*
15921 			 * If an SIOCSLIFLNKINFO has changed the ill_max_mtu
15922 			 * leave it alone
15923 			 */
15924 			if (ill->ill_mtu_userspecified) {
15925 				mutex_exit(&ill->ill_lock);
15926 				break;
15927 			}
15928 			ill->ill_max_mtu = ill->ill_max_frag;
15929 			if (ill->ill_isv6) {
15930 				if (ill->ill_max_mtu < IPV6_MIN_MTU)
15931 					ill->ill_max_mtu = IPV6_MIN_MTU;
15932 			} else {
15933 				if (ill->ill_max_mtu < IP_MIN_MTU)
15934 					ill->ill_max_mtu = IP_MIN_MTU;
15935 			}
15936 			for (ipif = ill->ill_ipif; ipif != NULL;
15937 			    ipif = ipif->ipif_next) {
15938 				/*
15939 				 * Don't override the mtu if the user
15940 				 * has explicitly set it.
15941 				 */
15942 				if (ipif->ipif_flags & IPIF_FIXEDMTU)
15943 					continue;
15944 				ipif->ipif_mtu = (uint_t)notify->dl_data;
15945 				if (ipif->ipif_isv6)
15946 					ire = ipif_to_ire_v6(ipif);
15947 				else
15948 					ire = ipif_to_ire(ipif);
15949 				if (ire != NULL) {
15950 					ire->ire_max_frag = ipif->ipif_mtu;
15951 					ire_refrele(ire);
15952 				}
15953 				if (ipif->ipif_flags & IPIF_UP) {
15954 					if (ill->ill_isv6)
15955 						need_ire_walk_v6 = B_TRUE;
15956 					else
15957 						need_ire_walk_v4 = B_TRUE;
15958 				}
15959 			}
15960 			mutex_exit(&ill->ill_lock);
15961 			if (need_ire_walk_v4)
15962 				ire_walk_v4(ill_mtu_change, (char *)ill,
15963 				    ALL_ZONES, ipst);
15964 			if (need_ire_walk_v6)
15965 				ire_walk_v6(ill_mtu_change, (char *)ill,
15966 				    ALL_ZONES, ipst);
15967 			break;
15968 		case DL_NOTE_LINK_UP:
15969 		case DL_NOTE_LINK_DOWN: {
15970 			/*
15971 			 * We are writer. ill / phyint / ipsq assocs stable.
15972 			 * The RUNNING flag reflects the state of the link.
15973 			 */
15974 			phyint_t *phyint = ill->ill_phyint;
15975 			uint64_t new_phyint_flags;
15976 			boolean_t changed = B_FALSE;
15977 			boolean_t went_up;
15978 
15979 			went_up = notify->dl_notification == DL_NOTE_LINK_UP;
15980 			mutex_enter(&phyint->phyint_lock);
15981 			new_phyint_flags = went_up ?
15982 			    phyint->phyint_flags | PHYI_RUNNING :
15983 			    phyint->phyint_flags & ~PHYI_RUNNING;
15984 			if (new_phyint_flags != phyint->phyint_flags) {
15985 				phyint->phyint_flags = new_phyint_flags;
15986 				changed = B_TRUE;
15987 			}
15988 			mutex_exit(&phyint->phyint_lock);
15989 			/*
15990 			 * ill_restart_dad handles the DAD restart and routing
15991 			 * socket notification logic.
15992 			 */
15993 			if (changed) {
15994 				ill_restart_dad(phyint->phyint_illv4, went_up);
15995 				ill_restart_dad(phyint->phyint_illv6, went_up);
15996 			}
15997 			break;
15998 		}
15999 		case DL_NOTE_PROMISC_ON_PHYS:
16000 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16001 			    "got a DL_NOTE_PROMISC_ON_PHYS\n"));
16002 			mutex_enter(&ill->ill_lock);
16003 			ill->ill_promisc_on_phys = B_TRUE;
16004 			mutex_exit(&ill->ill_lock);
16005 			break;
16006 		case DL_NOTE_PROMISC_OFF_PHYS:
16007 			IPSECHW_DEBUG(IPSECHW_PKT, ("ip_rput_dlpi_writer: "
16008 			    "got a DL_NOTE_PROMISC_OFF_PHYS\n"));
16009 			mutex_enter(&ill->ill_lock);
16010 			ill->ill_promisc_on_phys = B_FALSE;
16011 			mutex_exit(&ill->ill_lock);
16012 			break;
16013 		case DL_NOTE_CAPAB_RENEG:
16014 			/*
16015 			 * Something changed on the driver side.
16016 			 * It wants us to renegotiate the capabilities
16017 			 * on this ill. One possible cause is the aggregation
16018 			 * interface under us where a port got added or
16019 			 * went away.
16020 			 *
16021 			 * If the capability negotiation is already done
16022 			 * or is in progress, reset the capabilities and
16023 			 * mark the ill's ill_capab_reneg to be B_TRUE,
16024 			 * so that when the ack comes back, we can start
16025 			 * the renegotiation process.
16026 			 *
16027 			 * Note that if ill_capab_reneg is already B_TRUE
16028 			 * (ill_dlpi_capab_state is IDS_UNKNOWN in this case),
16029 			 * the capability resetting request has been sent
16030 			 * and the renegotiation has not been started yet;
16031 			 * nothing needs to be done in this case.
16032 			 */
16033 			if (ill->ill_dlpi_capab_state != IDS_UNKNOWN) {
16034 				ill_capability_reset(ill);
16035 				ill->ill_capab_reneg = B_TRUE;
16036 			}
16037 			break;
16038 		default:
16039 			ip0dbg(("ip_rput_dlpi_writer: unknown notification "
16040 			    "type 0x%x for DL_NOTIFY_IND\n",
16041 			    notify->dl_notification));
16042 			break;
16043 		}
16044 
16045 		/*
16046 		 * As this is an asynchronous operation, we
16047 		 * should not call ill_dlpi_done
16048 		 */
16049 		break;
16050 	}
16051 	case DL_NOTIFY_ACK: {
16052 		dl_notify_ack_t *noteack = (dl_notify_ack_t *)mp->b_rptr;
16053 
16054 		if (noteack->dl_notifications & DL_NOTE_LINK_UP)
16055 			ill->ill_note_link = 1;
16056 		ill_dlpi_done(ill, DL_NOTIFY_REQ);
16057 		break;
16058 	}
16059 	case DL_PHYS_ADDR_ACK: {
16060 		/*
16061 		 * As part of plumbing the interface via SIOCSLIFNAME,
16062 		 * ill_dl_phys() will queue a series of DL_PHYS_ADDR_REQs,
16063 		 * whose answers we receive here.  As each answer is received,
16064 		 * we call ill_dlpi_done() to dispatch the next request as
16065 		 * we're processing the current one.  Once all answers have
16066 		 * been received, we use ipsq_pending_mp_get() to dequeue the
16067 		 * outstanding IOCTL and reply to it.  (Because ill_dl_phys()
16068 		 * is invoked from an ill queue, conn_oper_pending_ill is not
16069 		 * available, but we know the ioctl is pending on ill_wq.)
16070 		 */
16071 		uint_t paddrlen, paddroff;
16072 
16073 		paddrreq = ill->ill_phys_addr_pend;
16074 		paddrlen = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_length;
16075 		paddroff = ((dl_phys_addr_ack_t *)mp->b_rptr)->dl_addr_offset;
16076 
16077 		ill_dlpi_done(ill, DL_PHYS_ADDR_REQ);
16078 		if (paddrreq == DL_IPV6_TOKEN) {
16079 			/*
16080 			 * bcopy to low-order bits of ill_token
16081 			 *
16082 			 * XXX Temporary hack - currently, all known tokens
16083 			 * are 64 bits, so I'll cheat for the moment.
16084 			 */
16085 			bcopy(mp->b_rptr + paddroff,
16086 			    &ill->ill_token.s6_addr32[2], paddrlen);
16087 			ill->ill_token_length = paddrlen;
16088 			break;
16089 		} else if (paddrreq == DL_IPV6_LINK_LAYER_ADDR) {
16090 			ASSERT(ill->ill_nd_lla_mp == NULL);
16091 			ill_set_ndmp(ill, mp, paddroff, paddrlen);
16092 			mp = NULL;
16093 			break;
16094 		}
16095 
16096 		ASSERT(paddrreq == DL_CURR_PHYS_ADDR);
16097 		ASSERT(ill->ill_phys_addr_mp == NULL);
16098 		if (!ill->ill_ifname_pending)
16099 			break;
16100 		ill->ill_ifname_pending = 0;
16101 		if (!ioctl_aborted)
16102 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16103 		if (mp1 != NULL) {
16104 			ASSERT(connp == NULL);
16105 			q = ill->ill_wq;
16106 		}
16107 		/*
16108 		 * If any error acks received during the plumbing sequence,
16109 		 * ill_ifname_pending_err will be set. Break out and send up
16110 		 * the error to the pending ioctl.
16111 		 */
16112 		if (ill->ill_ifname_pending_err != 0) {
16113 			err = ill->ill_ifname_pending_err;
16114 			ill->ill_ifname_pending_err = 0;
16115 			break;
16116 		}
16117 
16118 		ill->ill_phys_addr_mp = mp;
16119 		ill->ill_phys_addr = mp->b_rptr + paddroff;
16120 		mp = NULL;
16121 
16122 		/*
16123 		 * If paddrlen is zero, the DLPI provider doesn't support
16124 		 * physical addresses.  The other two tests were historical
16125 		 * workarounds for bugs in our former PPP implementation, but
16126 		 * now other things have grown dependencies on them -- e.g.,
16127 		 * the tun module specifies a dl_addr_length of zero in its
16128 		 * DL_BIND_ACK, but then specifies an incorrect value in its
16129 		 * DL_PHYS_ADDR_ACK.  These bogus checks need to be removed,
16130 		 * but only after careful testing ensures that all dependent
16131 		 * broken DLPI providers have been fixed.
16132 		 */
16133 		if (paddrlen == 0 || ill->ill_phys_addr_length == 0 ||
16134 		    ill->ill_phys_addr_length == IP_ADDR_LEN) {
16135 			ill->ill_phys_addr = NULL;
16136 		} else if (paddrlen != ill->ill_phys_addr_length) {
16137 			ip0dbg(("DL_PHYS_ADDR_ACK: got addrlen %d, expected %d",
16138 			    paddrlen, ill->ill_phys_addr_length));
16139 			err = EINVAL;
16140 			break;
16141 		}
16142 
16143 		if (ill->ill_nd_lla_mp == NULL) {
16144 			if ((mp_hw = copyb(ill->ill_phys_addr_mp)) == NULL) {
16145 				err = ENOMEM;
16146 				break;
16147 			}
16148 			ill_set_ndmp(ill, mp_hw, paddroff, paddrlen);
16149 		}
16150 
16151 		/*
16152 		 * Set the interface token.  If the zeroth interface address
16153 		 * is unspecified, then set it to the link local address.
16154 		 */
16155 		if (IN6_IS_ADDR_UNSPECIFIED(&ill->ill_token))
16156 			(void) ill_setdefaulttoken(ill);
16157 
16158 		ASSERT(ill->ill_ipif->ipif_id == 0);
16159 		if (ipif != NULL &&
16160 		    IN6_IS_ADDR_UNSPECIFIED(&ipif->ipif_v6lcl_addr)) {
16161 			(void) ipif_setlinklocal(ipif);
16162 		}
16163 		break;
16164 	}
16165 	case DL_OK_ACK:
16166 		ip2dbg(("DL_OK_ACK %s (0x%x)\n",
16167 		    dl_primstr((int)dloa->dl_correct_primitive),
16168 		    dloa->dl_correct_primitive));
16169 		switch (dloa->dl_correct_primitive) {
16170 		case DL_PROMISCON_REQ:
16171 		case DL_PROMISCOFF_REQ:
16172 		case DL_ENABMULTI_REQ:
16173 		case DL_DISABMULTI_REQ:
16174 		case DL_UNBIND_REQ:
16175 		case DL_ATTACH_REQ:
16176 			ill_dlpi_done(ill, dloa->dl_correct_primitive);
16177 			break;
16178 		}
16179 		break;
16180 	default:
16181 		break;
16182 	}
16183 
16184 	freemsg(mp);
16185 	if (mp1 != NULL) {
16186 		/*
16187 		 * The operation must complete without EINPROGRESS
16188 		 * since ipsq_pending_mp_get() has removed the mblk
16189 		 * from ipsq_pending_mp.  Otherwise, the operation
16190 		 * will be stuck forever in the ipsq.
16191 		 */
16192 		ASSERT(err != EINPROGRESS);
16193 
16194 		switch (ipsq->ipsq_current_ioctl) {
16195 		case 0:
16196 			ipsq_current_finish(ipsq);
16197 			break;
16198 
16199 		case SIOCLIFADDIF:
16200 		case SIOCSLIFNAME:
16201 			ip_ioctl_finish(q, mp1, err, COPYOUT, ipsq);
16202 			break;
16203 
16204 		default:
16205 			ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
16206 			break;
16207 		}
16208 	}
16209 }
16210 
16211 /*
16212  * ip_rput_other is called by ip_rput to handle messages modifying the global
16213  * state in IP. Normally called as writer. Exception SIOCGTUNPARAM (shared)
16214  */
16215 /* ARGSUSED */
16216 void
16217 ip_rput_other(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
16218 {
16219 	ill_t		*ill;
16220 	struct iocblk	*iocp;
16221 	mblk_t		*mp1;
16222 	conn_t		*connp = NULL;
16223 
16224 	ip1dbg(("ip_rput_other "));
16225 	ill = (ill_t *)q->q_ptr;
16226 	/*
16227 	 * This routine is not a writer in the case of SIOCGTUNPARAM
16228 	 * in which case ipsq is NULL.
16229 	 */
16230 	if (ipsq != NULL) {
16231 		ASSERT(IAM_WRITER_IPSQ(ipsq));
16232 		ASSERT(ipsq == ill->ill_phyint->phyint_ipsq);
16233 	}
16234 
16235 	switch (mp->b_datap->db_type) {
16236 	case M_ERROR:
16237 	case M_HANGUP:
16238 		/*
16239 		 * The device has a problem.  We force the ILL down.  It can
16240 		 * be brought up again manually using SIOCSIFFLAGS (via
16241 		 * ifconfig or equivalent).
16242 		 */
16243 		ASSERT(ipsq != NULL);
16244 		if (mp->b_rptr < mp->b_wptr)
16245 			ill->ill_error = (int)(*mp->b_rptr & 0xFF);
16246 		if (ill->ill_error == 0)
16247 			ill->ill_error = ENXIO;
16248 		if (!ill_down_start(q, mp))
16249 			return;
16250 		ipif_all_down_tail(ipsq, q, mp, NULL);
16251 		break;
16252 	case M_IOCACK:
16253 		iocp = (struct iocblk *)mp->b_rptr;
16254 		ASSERT(iocp->ioc_cmd != DL_IOC_HDR_INFO);
16255 		switch (iocp->ioc_cmd) {
16256 		case SIOCSTUNPARAM:
16257 		case OSIOCSTUNPARAM:
16258 			ASSERT(ipsq != NULL);
16259 			/*
16260 			 * Finish socket ioctl passed through to tun.
16261 			 * We should have an IOCTL waiting on this.
16262 			 */
16263 			mp1 = ipsq_pending_mp_get(ipsq, &connp);
16264 			if (ill->ill_isv6) {
16265 				struct iftun_req *ta;
16266 
16267 				/*
16268 				 * if a source or destination is
16269 				 * being set, try and set the link
16270 				 * local address for the tunnel
16271 				 */
16272 				ta = (struct iftun_req *)mp->b_cont->
16273 				    b_cont->b_rptr;
16274 				if (ta->ifta_flags & (IFTUN_SRC | IFTUN_DST)) {
16275 					ipif_set_tun_llink(ill, ta);
16276 				}
16277 
16278 			}
16279 			if (mp1 != NULL) {
16280 				/*
16281 				 * Now copy back the b_next/b_prev used by
16282 				 * mi code for the mi_copy* functions.
16283 				 * See ip_sioctl_tunparam() for the reason.
16284 				 * Also protect against missing b_cont.
16285 				 */
16286 				if (mp->b_cont != NULL) {
16287 					mp->b_cont->b_next =
16288 					    mp1->b_cont->b_next;
16289 					mp->b_cont->b_prev =
16290 					    mp1->b_cont->b_prev;
16291 				}
16292 				inet_freemsg(mp1);
16293 				ASSERT(connp != NULL);
16294 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16295 				    iocp->ioc_error, NO_COPYOUT, ipsq);
16296 			} else {
16297 				ASSERT(connp == NULL);
16298 				putnext(q, mp);
16299 			}
16300 			break;
16301 		case SIOCGTUNPARAM:
16302 		case OSIOCGTUNPARAM:
16303 			/*
16304 			 * This is really M_IOCDATA from the tunnel driver.
16305 			 * convert back and complete the ioctl.
16306 			 * We should have an IOCTL waiting on this.
16307 			 */
16308 			mp1 = ill_pending_mp_get(ill, &connp, iocp->ioc_id);
16309 			if (mp1) {
16310 				/*
16311 				 * Now copy back the b_next/b_prev used by
16312 				 * mi code for the mi_copy* functions.
16313 				 * See ip_sioctl_tunparam() for the reason.
16314 				 * Also protect against missing b_cont.
16315 				 */
16316 				if (mp->b_cont != NULL) {
16317 					mp->b_cont->b_next =
16318 					    mp1->b_cont->b_next;
16319 					mp->b_cont->b_prev =
16320 					    mp1->b_cont->b_prev;
16321 				}
16322 				inet_freemsg(mp1);
16323 				if (iocp->ioc_error == 0)
16324 					mp->b_datap->db_type = M_IOCDATA;
16325 				ASSERT(connp != NULL);
16326 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16327 				    iocp->ioc_error, COPYOUT, NULL);
16328 			} else {
16329 				ASSERT(connp == NULL);
16330 				putnext(q, mp);
16331 			}
16332 			break;
16333 		default:
16334 			break;
16335 		}
16336 		break;
16337 	case M_IOCNAK:
16338 		iocp = (struct iocblk *)mp->b_rptr;
16339 
16340 		switch (iocp->ioc_cmd) {
16341 		int mode;
16342 
16343 		case DL_IOC_HDR_INFO:
16344 			/*
16345 			 * If this was the first attempt turn of the
16346 			 * fastpath probing.
16347 			 */
16348 			mutex_enter(&ill->ill_lock);
16349 			if (ill->ill_dlpi_fastpath_state == IDS_INPROGRESS) {
16350 				ill->ill_dlpi_fastpath_state = IDS_FAILED;
16351 				mutex_exit(&ill->ill_lock);
16352 				ill_fastpath_nack(ill);
16353 				ip1dbg(("ip_rput: DLPI fastpath off on "
16354 				    "interface %s\n",
16355 				    ill->ill_name));
16356 			} else {
16357 				mutex_exit(&ill->ill_lock);
16358 			}
16359 			freemsg(mp);
16360 			break;
16361 		case SIOCSTUNPARAM:
16362 		case OSIOCSTUNPARAM:
16363 			ASSERT(ipsq != NULL);
16364 			/*
16365 			 * Finish socket ioctl passed through to tun
16366 			 * We should have an IOCTL waiting on this.
16367 			 */
16368 			/* FALLTHRU */
16369 		case SIOCGTUNPARAM:
16370 		case OSIOCGTUNPARAM:
16371 			/*
16372 			 * This is really M_IOCDATA from the tunnel driver.
16373 			 * convert back and complete the ioctl.
16374 			 * We should have an IOCTL waiting on this.
16375 			 */
16376 			if (iocp->ioc_cmd == SIOCGTUNPARAM ||
16377 			    iocp->ioc_cmd == OSIOCGTUNPARAM) {
16378 				mp1 = ill_pending_mp_get(ill, &connp,
16379 				    iocp->ioc_id);
16380 				mode = COPYOUT;
16381 				ipsq = NULL;
16382 			} else {
16383 				mp1 = ipsq_pending_mp_get(ipsq, &connp);
16384 				mode = NO_COPYOUT;
16385 			}
16386 			if (mp1 != NULL) {
16387 				/*
16388 				 * Now copy back the b_next/b_prev used by
16389 				 * mi code for the mi_copy* functions.
16390 				 * See ip_sioctl_tunparam() for the reason.
16391 				 * Also protect against missing b_cont.
16392 				 */
16393 				if (mp->b_cont != NULL) {
16394 					mp->b_cont->b_next =
16395 					    mp1->b_cont->b_next;
16396 					mp->b_cont->b_prev =
16397 					    mp1->b_cont->b_prev;
16398 				}
16399 				inet_freemsg(mp1);
16400 				if (iocp->ioc_error == 0)
16401 					iocp->ioc_error = EINVAL;
16402 				ASSERT(connp != NULL);
16403 				ip_ioctl_finish(CONNP_TO_WQ(connp), mp,
16404 				    iocp->ioc_error, mode, ipsq);
16405 			} else {
16406 				ASSERT(connp == NULL);
16407 				putnext(q, mp);
16408 			}
16409 			break;
16410 		default:
16411 			break;
16412 		}
16413 	default:
16414 		break;
16415 	}
16416 }
16417 
16418 /*
16419  * NOTE : This function does not ire_refrele the ire argument passed in.
16420  *
16421  * IPQoS notes
16422  * IP policy is invoked twice for a forwarded packet, once on the read side
16423  * and again on the write side if both, IPP_FWD_IN and IPP_FWD_OUT are
16424  * enabled. An additional parameter, in_ill, has been added for this purpose.
16425  * Note that in_ill could be NULL when called from ip_rput_forward_multicast
16426  * because ip_mroute drops this information.
16427  *
16428  */
16429 void
16430 ip_rput_forward(ire_t *ire, ipha_t *ipha, mblk_t *mp, ill_t *in_ill)
16431 {
16432 	uint32_t	old_pkt_len;
16433 	uint32_t	pkt_len;
16434 	queue_t	*q;
16435 	uint32_t	sum;
16436 #define	rptr	((uchar_t *)ipha)
16437 	uint32_t	max_frag;
16438 	uint32_t	ill_index;
16439 	ill_t		*out_ill;
16440 	mib2_ipIfStatsEntry_t *mibptr;
16441 	ip_stack_t	*ipst = ((ill_t *)(ire->ire_stq->q_ptr))->ill_ipst;
16442 
16443 	/* Get the ill_index of the incoming ILL */
16444 	ill_index = (in_ill != NULL) ? in_ill->ill_phyint->phyint_ifindex : 0;
16445 	mibptr = (in_ill != NULL) ? in_ill->ill_ip_mib : &ipst->ips_ip_mib;
16446 
16447 	/* Initiate Read side IPPF processing */
16448 	if (IPP_ENABLED(IPP_FWD_IN, ipst)) {
16449 		ip_process(IPP_FWD_IN, &mp, ill_index);
16450 		if (mp == NULL) {
16451 			ip2dbg(("ip_rput_forward: pkt dropped/deferred "\
16452 			    "during IPPF processing\n"));
16453 			return;
16454 		}
16455 	}
16456 
16457 	/* Adjust the checksum to reflect the ttl decrement. */
16458 	sum = (int)ipha->ipha_hdr_checksum + IP_HDR_CSUM_TTL_ADJUST;
16459 	ipha->ipha_hdr_checksum = (uint16_t)(sum + (sum >> 16));
16460 
16461 	if (ipha->ipha_ttl-- <= 1) {
16462 		if (ip_csum_hdr(ipha)) {
16463 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16464 			goto drop_pkt;
16465 		}
16466 		/*
16467 		 * Note: ire_stq this will be NULL for multicast
16468 		 * datagrams using the long path through arp (the IRE
16469 		 * is not an IRE_CACHE). This should not cause
16470 		 * problems since we don't generate ICMP errors for
16471 		 * multicast packets.
16472 		 */
16473 		BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16474 		q = ire->ire_stq;
16475 		if (q != NULL) {
16476 			/* Sent by forwarding path, and router is global zone */
16477 			icmp_time_exceeded(q, mp, ICMP_TTL_EXCEEDED,
16478 			    GLOBAL_ZONEID, ipst);
16479 		} else
16480 			freemsg(mp);
16481 		return;
16482 	}
16483 
16484 	/*
16485 	 * Don't forward if the interface is down
16486 	 */
16487 	if (ire->ire_ipif->ipif_ill->ill_ipif_up_count == 0) {
16488 		BUMP_MIB(mibptr, ipIfStatsInDiscards);
16489 		ip2dbg(("ip_rput_forward:interface is down\n"));
16490 		goto drop_pkt;
16491 	}
16492 
16493 	/* Get the ill_index of the outgoing ILL */
16494 	out_ill = ire_to_ill(ire);
16495 	ill_index = out_ill->ill_phyint->phyint_ifindex;
16496 
16497 	DTRACE_PROBE4(ip4__forwarding__start,
16498 	    ill_t *, in_ill, ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16499 
16500 	FW_HOOKS(ipst->ips_ip4_forwarding_event,
16501 	    ipst->ips_ipv4firewall_forwarding,
16502 	    in_ill, out_ill, ipha, mp, mp, 0, ipst);
16503 
16504 	DTRACE_PROBE1(ip4__forwarding__end, mblk_t *, mp);
16505 
16506 	if (mp == NULL)
16507 		return;
16508 	old_pkt_len = pkt_len = ntohs(ipha->ipha_length);
16509 
16510 	if (is_system_labeled()) {
16511 		mblk_t *mp1;
16512 
16513 		if ((mp1 = tsol_ip_forward(ire, mp)) == NULL) {
16514 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16515 			goto drop_pkt;
16516 		}
16517 		/* Size may have changed */
16518 		mp = mp1;
16519 		ipha = (ipha_t *)mp->b_rptr;
16520 		pkt_len = ntohs(ipha->ipha_length);
16521 	}
16522 
16523 	/* Check if there are options to update */
16524 	if (!IS_SIMPLE_IPH(ipha)) {
16525 		if (ip_csum_hdr(ipha)) {
16526 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16527 			goto drop_pkt;
16528 		}
16529 		if (ip_rput_forward_options(mp, ipha, ire, ipst)) {
16530 			BUMP_MIB(mibptr, ipIfStatsForwProhibits);
16531 			return;
16532 		}
16533 
16534 		ipha->ipha_hdr_checksum = 0;
16535 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
16536 	}
16537 	max_frag = ire->ire_max_frag;
16538 	if (pkt_len > max_frag) {
16539 		/*
16540 		 * It needs fragging on its way out.  We haven't
16541 		 * verified the header checksum yet.  Since we
16542 		 * are going to put a surely good checksum in the
16543 		 * outgoing header, we have to make sure that it
16544 		 * was good coming in.
16545 		 */
16546 		if (ip_csum_hdr(ipha)) {
16547 			BUMP_MIB(mibptr, ipIfStatsInCksumErrs);
16548 			goto drop_pkt;
16549 		}
16550 		/* Initiate Write side IPPF processing */
16551 		if (IPP_ENABLED(IPP_FWD_OUT, ipst)) {
16552 			ip_process(IPP_FWD_OUT, &mp, ill_index);
16553 			if (mp == NULL) {
16554 				ip2dbg(("ip_rput_forward: pkt dropped/deferred"\
16555 				    " during IPPF processing\n"));
16556 				return;
16557 			}
16558 		}
16559 		/*
16560 		 * Handle labeled packet resizing.
16561 		 *
16562 		 * If we have added a label, inform ip_wput_frag() of its
16563 		 * effect on the MTU for ICMP messages.
16564 		 */
16565 		if (pkt_len > old_pkt_len) {
16566 			uint32_t secopt_size;
16567 
16568 			secopt_size = pkt_len - old_pkt_len;
16569 			if (secopt_size < max_frag)
16570 				max_frag -= secopt_size;
16571 		}
16572 
16573 		ip_wput_frag(ire, mp, IB_PKT, max_frag, 0, GLOBAL_ZONEID, ipst);
16574 		ip2dbg(("ip_rput_forward:sent to ip_wput_frag\n"));
16575 		return;
16576 	}
16577 
16578 	DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
16579 	    ill_t *, out_ill, ipha_t *, ipha, mblk_t *, mp);
16580 	FW_HOOKS(ipst->ips_ip4_physical_out_event,
16581 	    ipst->ips_ipv4firewall_physical_out,
16582 	    NULL, out_ill, ipha, mp, mp, 0, ipst);
16583 	DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
16584 	if (mp == NULL)
16585 		return;
16586 
16587 	mp->b_prev = (mblk_t *)IPP_FWD_OUT;
16588 	ip1dbg(("ip_rput_forward: Calling ip_xmit_v4\n"));
16589 	(void) ip_xmit_v4(mp, ire, NULL, B_FALSE);
16590 	/* ip_xmit_v4 always consumes the packet */
16591 	return;
16592 
16593 drop_pkt:;
16594 	ip1dbg(("ip_rput_forward: drop pkt\n"));
16595 	freemsg(mp);
16596 #undef	rptr
16597 }
16598 
16599 void
16600 ip_rput_forward_multicast(ipaddr_t dst, mblk_t *mp, ipif_t *ipif)
16601 {
16602 	ire_t	*ire;
16603 	ip_stack_t *ipst = ipif->ipif_ill->ill_ipst;
16604 
16605 	ASSERT(!ipif->ipif_isv6);
16606 	/*
16607 	 * Find an IRE which matches the destination and the outgoing
16608 	 * queue in the cache table. All we need is an IRE_CACHE which
16609 	 * is pointing at ipif->ipif_ill. If it is part of some ill group,
16610 	 * then it is enough to have some IRE_CACHE in the group.
16611 	 */
16612 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
16613 		dst = ipif->ipif_pp_dst_addr;
16614 
16615 	ire = ire_ctable_lookup(dst, 0, 0, ipif, ALL_ZONES, MBLK_GETLABEL(mp),
16616 	    MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR, ipst);
16617 	if (ire == NULL) {
16618 		/*
16619 		 * Mark this packet to make it be delivered to
16620 		 * ip_rput_forward after the new ire has been
16621 		 * created.
16622 		 */
16623 		mp->b_prev = NULL;
16624 		mp->b_next = mp;
16625 		ip_newroute_ipif(ipif->ipif_ill->ill_wq, mp, ipif, dst,
16626 		    NULL, 0, GLOBAL_ZONEID, &zero_info);
16627 	} else {
16628 		ip_rput_forward(ire, (ipha_t *)mp->b_rptr, mp, NULL);
16629 		IRE_REFRELE(ire);
16630 	}
16631 }
16632 
16633 /* Update any source route, record route or timestamp options */
16634 static int
16635 ip_rput_forward_options(mblk_t *mp, ipha_t *ipha, ire_t *ire, ip_stack_t *ipst)
16636 {
16637 	ipoptp_t	opts;
16638 	uchar_t		*opt;
16639 	uint8_t		optval;
16640 	uint8_t		optlen;
16641 	ipaddr_t	dst;
16642 	uint32_t	ts;
16643 	ire_t		*dst_ire = NULL;
16644 	ire_t		*tmp_ire = NULL;
16645 	timestruc_t	now;
16646 
16647 	ip2dbg(("ip_rput_forward_options\n"));
16648 	dst = ipha->ipha_dst;
16649 	for (optval = ipoptp_first(&opts, ipha);
16650 	    optval != IPOPT_EOL;
16651 	    optval = ipoptp_next(&opts)) {
16652 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
16653 		opt = opts.ipoptp_cur;
16654 		optlen = opts.ipoptp_len;
16655 		ip2dbg(("ip_rput_forward_options: opt %d, len %d\n",
16656 		    optval, opts.ipoptp_len));
16657 		switch (optval) {
16658 			uint32_t off;
16659 		case IPOPT_SSRR:
16660 		case IPOPT_LSRR:
16661 			/* Check if adminstratively disabled */
16662 			if (!ipst->ips_ip_forward_src_routed) {
16663 				if (ire->ire_stq != NULL) {
16664 					/*
16665 					 * Sent by forwarding path, and router
16666 					 * is global zone
16667 					 */
16668 					icmp_unreachable(ire->ire_stq, mp,
16669 					    ICMP_SOURCE_ROUTE_FAILED,
16670 					    GLOBAL_ZONEID, ipst);
16671 				} else {
16672 					ip0dbg(("ip_rput_forward_options: "
16673 					    "unable to send unreach\n"));
16674 					freemsg(mp);
16675 				}
16676 				return (-1);
16677 			}
16678 
16679 			dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16680 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16681 			if (dst_ire == NULL) {
16682 				/*
16683 				 * Must be partial since ip_rput_options
16684 				 * checked for strict.
16685 				 */
16686 				break;
16687 			}
16688 			off = opt[IPOPT_OFFSET];
16689 			off--;
16690 		redo_srr:
16691 			if (optlen < IP_ADDR_LEN ||
16692 			    off > optlen - IP_ADDR_LEN) {
16693 				/* End of source route */
16694 				ip1dbg((
16695 				    "ip_rput_forward_options: end of SR\n"));
16696 				ire_refrele(dst_ire);
16697 				break;
16698 			}
16699 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16700 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16701 			    IP_ADDR_LEN);
16702 			ip1dbg(("ip_rput_forward_options: next hop 0x%x\n",
16703 			    ntohl(dst)));
16704 
16705 			/*
16706 			 * Check if our address is present more than
16707 			 * once as consecutive hops in source route.
16708 			 */
16709 			tmp_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
16710 			    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
16711 			if (tmp_ire != NULL) {
16712 				ire_refrele(tmp_ire);
16713 				off += IP_ADDR_LEN;
16714 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16715 				goto redo_srr;
16716 			}
16717 			ipha->ipha_dst = dst;
16718 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16719 			ire_refrele(dst_ire);
16720 			break;
16721 		case IPOPT_RR:
16722 			off = opt[IPOPT_OFFSET];
16723 			off--;
16724 			if (optlen < IP_ADDR_LEN ||
16725 			    off > optlen - IP_ADDR_LEN) {
16726 				/* No more room - ignore */
16727 				ip1dbg((
16728 				    "ip_rput_forward_options: end of RR\n"));
16729 				break;
16730 			}
16731 			bcopy(&ire->ire_src_addr, (char *)opt + off,
16732 			    IP_ADDR_LEN);
16733 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16734 			break;
16735 		case IPOPT_TS:
16736 			/* Insert timestamp if there is room */
16737 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16738 			case IPOPT_TS_TSONLY:
16739 				off = IPOPT_TS_TIMELEN;
16740 				break;
16741 			case IPOPT_TS_PRESPEC:
16742 			case IPOPT_TS_PRESPEC_RFC791:
16743 				/* Verify that the address matched */
16744 				off = opt[IPOPT_OFFSET] - 1;
16745 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
16746 				dst_ire = ire_ctable_lookup(dst, 0,
16747 				    IRE_LOCAL, NULL, ALL_ZONES, NULL,
16748 				    MATCH_IRE_TYPE, ipst);
16749 				if (dst_ire == NULL) {
16750 					/* Not for us */
16751 					break;
16752 				}
16753 				ire_refrele(dst_ire);
16754 				/* FALLTHRU */
16755 			case IPOPT_TS_TSANDADDR:
16756 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
16757 				break;
16758 			default:
16759 				/*
16760 				 * ip_*put_options should have already
16761 				 * dropped this packet.
16762 				 */
16763 				cmn_err(CE_PANIC, "ip_rput_forward_options: "
16764 				    "unknown IT - bug in ip_rput_options?\n");
16765 				return (0);	/* Keep "lint" happy */
16766 			}
16767 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
16768 				/* Increase overflow counter */
16769 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
16770 				opt[IPOPT_POS_OV_FLG] =
16771 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
16772 				    (off << 4));
16773 				break;
16774 			}
16775 			off = opt[IPOPT_OFFSET] - 1;
16776 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
16777 			case IPOPT_TS_PRESPEC:
16778 			case IPOPT_TS_PRESPEC_RFC791:
16779 			case IPOPT_TS_TSANDADDR:
16780 				bcopy(&ire->ire_src_addr,
16781 				    (char *)opt + off, IP_ADDR_LEN);
16782 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
16783 				/* FALLTHRU */
16784 			case IPOPT_TS_TSONLY:
16785 				off = opt[IPOPT_OFFSET] - 1;
16786 				/* Compute # of milliseconds since midnight */
16787 				gethrestime(&now);
16788 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
16789 				    now.tv_nsec / (NANOSEC / MILLISEC);
16790 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
16791 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
16792 				break;
16793 			}
16794 			break;
16795 		}
16796 	}
16797 	return (0);
16798 }
16799 
16800 /*
16801  * This is called after processing at least one of AH/ESP headers.
16802  *
16803  * NOTE: the ill corresponding to ipsec_in_ill_index may not be
16804  * the actual, physical interface on which the packet was received,
16805  * but, when ip_strict_dst_multihoming is set to 1, could be the
16806  * interface which had the ipha_dst configured when the packet went
16807  * through ip_rput. The ill_index corresponding to the recv_ill
16808  * is saved in ipsec_in_rill_index
16809  *
16810  * NOTE2: The "ire" argument is only used in IPv4 cases.  This function
16811  * cannot assume "ire" points to valid data for any IPv6 cases.
16812  */
16813 void
16814 ip_fanout_proto_again(mblk_t *ipsec_mp, ill_t *ill, ill_t *recv_ill, ire_t *ire)
16815 {
16816 	mblk_t *mp;
16817 	ipaddr_t dst;
16818 	in6_addr_t *v6dstp;
16819 	ipha_t *ipha;
16820 	ip6_t *ip6h;
16821 	ipsec_in_t *ii;
16822 	boolean_t ill_need_rele = B_FALSE;
16823 	boolean_t rill_need_rele = B_FALSE;
16824 	boolean_t ire_need_rele = B_FALSE;
16825 	netstack_t	*ns;
16826 	ip_stack_t	*ipst;
16827 
16828 	ii = (ipsec_in_t *)ipsec_mp->b_rptr;
16829 	ASSERT(ii->ipsec_in_ill_index != 0);
16830 	ns = ii->ipsec_in_ns;
16831 	ASSERT(ii->ipsec_in_ns != NULL);
16832 	ipst = ns->netstack_ip;
16833 
16834 	mp = ipsec_mp->b_cont;
16835 	ASSERT(mp != NULL);
16836 
16837 
16838 	if (ill == NULL) {
16839 		ASSERT(recv_ill == NULL);
16840 		/*
16841 		 * We need to get the original queue on which ip_rput_local
16842 		 * or ip_rput_data_v6 was called.
16843 		 */
16844 		ill = ill_lookup_on_ifindex(ii->ipsec_in_ill_index,
16845 		    !ii->ipsec_in_v4, NULL, NULL, NULL, NULL, ipst);
16846 		ill_need_rele = B_TRUE;
16847 
16848 		if (ii->ipsec_in_ill_index != ii->ipsec_in_rill_index) {
16849 			recv_ill = ill_lookup_on_ifindex(
16850 			    ii->ipsec_in_rill_index, !ii->ipsec_in_v4,
16851 			    NULL, NULL, NULL, NULL, ipst);
16852 			rill_need_rele = B_TRUE;
16853 		} else {
16854 			recv_ill = ill;
16855 		}
16856 
16857 		if ((ill == NULL) || (recv_ill == NULL)) {
16858 			ip0dbg(("ip_fanout_proto_again: interface "
16859 			    "disappeared\n"));
16860 			if (ill != NULL)
16861 				ill_refrele(ill);
16862 			if (recv_ill != NULL)
16863 				ill_refrele(recv_ill);
16864 			freemsg(ipsec_mp);
16865 			return;
16866 		}
16867 	}
16868 
16869 	ASSERT(ill != NULL && recv_ill != NULL);
16870 
16871 	if (mp->b_datap->db_type == M_CTL) {
16872 		/*
16873 		 * AH/ESP is returning the ICMP message after
16874 		 * removing their headers. Fanout again till
16875 		 * it gets to the right protocol.
16876 		 */
16877 		if (ii->ipsec_in_v4) {
16878 			icmph_t *icmph;
16879 			int iph_hdr_length;
16880 			int hdr_length;
16881 
16882 			ipha = (ipha_t *)mp->b_rptr;
16883 			iph_hdr_length = IPH_HDR_LENGTH(ipha);
16884 			icmph = (icmph_t *)&mp->b_rptr[iph_hdr_length];
16885 			ipha = (ipha_t *)&icmph[1];
16886 			hdr_length = IPH_HDR_LENGTH(ipha);
16887 			/*
16888 			 * icmp_inbound_error_fanout may need to do pullupmsg.
16889 			 * Reset the type to M_DATA.
16890 			 */
16891 			mp->b_datap->db_type = M_DATA;
16892 			icmp_inbound_error_fanout(ill->ill_rq, ill, ipsec_mp,
16893 			    icmph, ipha, iph_hdr_length, hdr_length, B_TRUE,
16894 			    B_FALSE, ill, ii->ipsec_in_zoneid);
16895 		} else {
16896 			icmp6_t *icmp6;
16897 			int hdr_length;
16898 
16899 			ip6h = (ip6_t *)mp->b_rptr;
16900 			/* Don't call hdr_length_v6() unless you have to. */
16901 			if (ip6h->ip6_nxt != IPPROTO_ICMPV6)
16902 				hdr_length = ip_hdr_length_v6(mp, ip6h);
16903 			else
16904 				hdr_length = IPV6_HDR_LEN;
16905 
16906 			icmp6 = (icmp6_t *)(&mp->b_rptr[hdr_length]);
16907 			/*
16908 			 * icmp_inbound_error_fanout_v6 may need to do
16909 			 * pullupmsg.  Reset the type to M_DATA.
16910 			 */
16911 			mp->b_datap->db_type = M_DATA;
16912 			icmp_inbound_error_fanout_v6(ill->ill_rq, ipsec_mp,
16913 			    ip6h, icmp6, ill, B_TRUE, ii->ipsec_in_zoneid);
16914 		}
16915 		if (ill_need_rele)
16916 			ill_refrele(ill);
16917 		if (rill_need_rele)
16918 			ill_refrele(recv_ill);
16919 		return;
16920 	}
16921 
16922 	if (ii->ipsec_in_v4) {
16923 		ipha = (ipha_t *)mp->b_rptr;
16924 		dst = ipha->ipha_dst;
16925 		if (CLASSD(dst)) {
16926 			/*
16927 			 * Multicast has to be delivered to all streams.
16928 			 */
16929 			dst = INADDR_BROADCAST;
16930 		}
16931 
16932 		if (ire == NULL) {
16933 			ire = ire_cache_lookup(dst, ii->ipsec_in_zoneid,
16934 			    MBLK_GETLABEL(mp), ipst);
16935 			if (ire == NULL) {
16936 				if (ill_need_rele)
16937 					ill_refrele(ill);
16938 				if (rill_need_rele)
16939 					ill_refrele(recv_ill);
16940 				ip1dbg(("ip_fanout_proto_again: "
16941 				    "IRE not found"));
16942 				freemsg(ipsec_mp);
16943 				return;
16944 			}
16945 			ire_need_rele = B_TRUE;
16946 		}
16947 
16948 		switch (ipha->ipha_protocol) {
16949 			case IPPROTO_UDP:
16950 				ip_udp_input(ill->ill_rq, ipsec_mp, ipha, ire,
16951 				    recv_ill);
16952 				if (ire_need_rele)
16953 					ire_refrele(ire);
16954 				break;
16955 			case IPPROTO_TCP:
16956 				if (!ire_need_rele)
16957 					IRE_REFHOLD(ire);
16958 				mp = ip_tcp_input(mp, ipha, ill, B_TRUE,
16959 				    ire, ipsec_mp, 0, ill->ill_rq, NULL);
16960 				IRE_REFRELE(ire);
16961 				if (mp != NULL)
16962 					squeue_enter_chain(GET_SQUEUE(mp), mp,
16963 					    mp, 1, SQTAG_IP_PROTO_AGAIN);
16964 				break;
16965 			case IPPROTO_SCTP:
16966 				if (!ire_need_rele)
16967 					IRE_REFHOLD(ire);
16968 				ip_sctp_input(mp, ipha, ill, B_TRUE, ire,
16969 				    ipsec_mp, 0, ill->ill_rq, dst);
16970 				break;
16971 			default:
16972 				ip_proto_input(ill->ill_rq, ipsec_mp, ipha, ire,
16973 				    recv_ill, B_FALSE);
16974 				if (ire_need_rele)
16975 					ire_refrele(ire);
16976 				break;
16977 		}
16978 	} else {
16979 		uint32_t rput_flags = 0;
16980 
16981 		ip6h = (ip6_t *)mp->b_rptr;
16982 		v6dstp = &ip6h->ip6_dst;
16983 		/*
16984 		 * XXX Assumes ip_rput_v6 sets ll_multicast  only for multicast
16985 		 * address.
16986 		 *
16987 		 * Currently, we don't store that state in the IPSEC_IN
16988 		 * message, and we may need to.
16989 		 */
16990 		rput_flags |= (IN6_IS_ADDR_MULTICAST(v6dstp) ?
16991 		    IP6_IN_LLMCAST : 0);
16992 		ip_rput_data_v6(ill->ill_rq, ill, ipsec_mp, ip6h, rput_flags,
16993 		    NULL, NULL);
16994 	}
16995 	if (ill_need_rele)
16996 		ill_refrele(ill);
16997 	if (rill_need_rele)
16998 		ill_refrele(recv_ill);
16999 }
17000 
17001 /*
17002  * Call ill_frag_timeout to do garbage collection. ill_frag_timeout
17003  * returns 'true' if there are still fragments left on the queue, in
17004  * which case we restart the timer.
17005  */
17006 void
17007 ill_frag_timer(void *arg)
17008 {
17009 	ill_t	*ill = (ill_t *)arg;
17010 	boolean_t frag_pending;
17011 	ip_stack_t	*ipst = ill->ill_ipst;
17012 
17013 	mutex_enter(&ill->ill_lock);
17014 	ASSERT(!ill->ill_fragtimer_executing);
17015 	if (ill->ill_state_flags & ILL_CONDEMNED) {
17016 		ill->ill_frag_timer_id = 0;
17017 		mutex_exit(&ill->ill_lock);
17018 		return;
17019 	}
17020 	ill->ill_fragtimer_executing = 1;
17021 	mutex_exit(&ill->ill_lock);
17022 
17023 	frag_pending = ill_frag_timeout(ill, ipst->ips_ip_g_frag_timeout);
17024 
17025 	/*
17026 	 * Restart the timer, if we have fragments pending or if someone
17027 	 * wanted us to be scheduled again.
17028 	 */
17029 	mutex_enter(&ill->ill_lock);
17030 	ill->ill_fragtimer_executing = 0;
17031 	ill->ill_frag_timer_id = 0;
17032 	if (frag_pending || ill->ill_fragtimer_needrestart)
17033 		ill_frag_timer_start(ill);
17034 	mutex_exit(&ill->ill_lock);
17035 }
17036 
17037 void
17038 ill_frag_timer_start(ill_t *ill)
17039 {
17040 	ip_stack_t	*ipst = ill->ill_ipst;
17041 
17042 	ASSERT(MUTEX_HELD(&ill->ill_lock));
17043 
17044 	/* If the ill is closing or opening don't proceed */
17045 	if (ill->ill_state_flags & ILL_CONDEMNED)
17046 		return;
17047 
17048 	if (ill->ill_fragtimer_executing) {
17049 		/*
17050 		 * ill_frag_timer is currently executing. Just record the
17051 		 * the fact that we want the timer to be restarted.
17052 		 * ill_frag_timer will post a timeout before it returns,
17053 		 * ensuring it will be called again.
17054 		 */
17055 		ill->ill_fragtimer_needrestart = 1;
17056 		return;
17057 	}
17058 
17059 	if (ill->ill_frag_timer_id == 0) {
17060 		/*
17061 		 * The timer is neither running nor is the timeout handler
17062 		 * executing. Post a timeout so that ill_frag_timer will be
17063 		 * called
17064 		 */
17065 		ill->ill_frag_timer_id = timeout(ill_frag_timer, ill,
17066 		    MSEC_TO_TICK(ipst->ips_ip_g_frag_timo_ms >> 1));
17067 		ill->ill_fragtimer_needrestart = 0;
17068 	}
17069 }
17070 
17071 /*
17072  * This routine is needed for loopback when forwarding multicasts.
17073  *
17074  * IPQoS Notes:
17075  * IPPF processing is done in fanout routines.
17076  * Policy processing is done only if IPP_lOCAL_IN is enabled. Further,
17077  * processing for IPsec packets is done when it comes back in clear.
17078  * NOTE : The callers of this function need to do the ire_refrele for the
17079  *	  ire that is being passed in.
17080  */
17081 void
17082 ip_proto_input(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17083     ill_t *recv_ill, boolean_t esp_in_udp_packet)
17084 {
17085 	ill_t	*ill = (ill_t *)q->q_ptr;
17086 	uint32_t	sum;
17087 	uint32_t	u1;
17088 	uint32_t	u2;
17089 	int		hdr_length;
17090 	boolean_t	mctl_present;
17091 	mblk_t		*first_mp = mp;
17092 	mblk_t		*hada_mp = NULL;
17093 	ipha_t		*inner_ipha;
17094 	ip_stack_t	*ipst;
17095 
17096 	ASSERT(recv_ill != NULL);
17097 	ipst = recv_ill->ill_ipst;
17098 
17099 	TRACE_1(TR_FAC_IP, TR_IP_RPUT_LOCL_START,
17100 	    "ip_rput_locl_start: q %p", q);
17101 
17102 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17103 	ASSERT(ill != NULL);
17104 
17105 
17106 #define	rptr	((uchar_t *)ipha)
17107 #define	iphs	((uint16_t *)ipha)
17108 
17109 	/*
17110 	 * no UDP or TCP packet should come here anymore.
17111 	 */
17112 	ASSERT(ipha->ipha_protocol != IPPROTO_TCP &&
17113 	    ipha->ipha_protocol != IPPROTO_UDP);
17114 
17115 	EXTRACT_PKT_MP(mp, first_mp, mctl_present);
17116 	if (mctl_present &&
17117 	    ((da_ipsec_t *)first_mp->b_rptr)->da_type == IPHADA_M_CTL) {
17118 		ASSERT(MBLKL(first_mp) >= sizeof (da_ipsec_t));
17119 
17120 		/*
17121 		 * It's an IPsec accelerated packet.
17122 		 * Keep a pointer to the data attributes around until
17123 		 * we allocate the ipsec_info_t.
17124 		 */
17125 		IPSECHW_DEBUG(IPSECHW_PKT,
17126 		    ("ip_rput_local: inbound HW accelerated IPsec pkt\n"));
17127 		hada_mp = first_mp;
17128 		hada_mp->b_cont = NULL;
17129 		/*
17130 		 * Since it is accelerated, it comes directly from
17131 		 * the ill and the data attributes is followed by
17132 		 * the packet data.
17133 		 */
17134 		ASSERT(mp->b_datap->db_type != M_CTL);
17135 		first_mp = mp;
17136 		mctl_present = B_FALSE;
17137 	}
17138 
17139 	/*
17140 	 * IF M_CTL is not present, then ipsec_in_is_secure
17141 	 * should return B_TRUE. There is a case where loopback
17142 	 * packets has an M_CTL in the front with all the
17143 	 * IPsec options set to IPSEC_PREF_NEVER - which means
17144 	 * ipsec_in_is_secure will return B_FALSE. As loopback
17145 	 * packets never comes here, it is safe to ASSERT the
17146 	 * following.
17147 	 */
17148 	ASSERT(!mctl_present || ipsec_in_is_secure(first_mp));
17149 
17150 	/*
17151 	 * Also, we should never have an mctl_present if this is an
17152 	 * ESP-in-UDP packet.
17153 	 */
17154 	ASSERT(!mctl_present || !esp_in_udp_packet);
17155 
17156 
17157 	/* u1 is # words of IP options */
17158 	u1 = ipha->ipha_version_and_hdr_length - (uchar_t)((IP_VERSION << 4) +
17159 	    IP_SIMPLE_HDR_LENGTH_IN_WORDS);
17160 
17161 	/*
17162 	 * Don't verify header checksum if we just removed UDP header or
17163 	 * packet is coming back from AH/ESP.
17164 	 */
17165 	if (!esp_in_udp_packet && !mctl_present) {
17166 		if (u1) {
17167 			if (!ip_options_cksum(q, ill, mp, ipha, ire, ipst)) {
17168 				if (hada_mp != NULL)
17169 					freemsg(hada_mp);
17170 				return;
17171 			}
17172 		} else {
17173 			/* Check the IP header checksum.  */
17174 #define	uph	((uint16_t *)ipha)
17175 			sum = uph[0] + uph[1] + uph[2] + uph[3] + uph[4] +
17176 			    uph[5] + uph[6] + uph[7] + uph[8] + uph[9];
17177 #undef  uph
17178 			/* finish doing IP checksum */
17179 			sum = (sum & 0xFFFF) + (sum >> 16);
17180 			sum = ~(sum + (sum >> 16)) & 0xFFFF;
17181 			if (sum && sum != 0xFFFF) {
17182 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInCksumErrs);
17183 				goto drop_pkt;
17184 			}
17185 		}
17186 	}
17187 
17188 	/*
17189 	 * Count for SNMP of inbound packets for ire. As ip_proto_input
17190 	 * might be called more than once for secure packets, count only
17191 	 * the first time.
17192 	 */
17193 	if (!mctl_present) {
17194 		UPDATE_IB_PKT_COUNT(ire);
17195 		ire->ire_last_used_time = lbolt;
17196 	}
17197 
17198 	/* Check for fragmentation offset. */
17199 	u2 = ntohs(ipha->ipha_fragment_offset_and_flags);
17200 	u1 = u2 & (IPH_MF | IPH_OFFSET);
17201 	if (u1) {
17202 		/*
17203 		 * We re-assemble fragments before we do the AH/ESP
17204 		 * processing. Thus, M_CTL should not be present
17205 		 * while we are re-assembling.
17206 		 */
17207 		ASSERT(!mctl_present);
17208 		ASSERT(first_mp == mp);
17209 		if (!ip_rput_fragment(q, &mp, ipha, NULL, NULL)) {
17210 			return;
17211 		}
17212 		/*
17213 		 * Make sure that first_mp points back to mp as
17214 		 * the mp we came in with could have changed in
17215 		 * ip_rput_fragment().
17216 		 */
17217 		ipha = (ipha_t *)mp->b_rptr;
17218 		first_mp = mp;
17219 	}
17220 
17221 	/*
17222 	 * Clear hardware checksumming flag as it is currently only
17223 	 * used by TCP and UDP.
17224 	 */
17225 	DB_CKSUMFLAGS(mp) = 0;
17226 
17227 	/* Now we have a complete datagram, destined for this machine. */
17228 	u1 = IPH_HDR_LENGTH(ipha);
17229 	switch (ipha->ipha_protocol) {
17230 	case IPPROTO_ICMP: {
17231 		ire_t		*ire_zone;
17232 		ilm_t		*ilm;
17233 		mblk_t		*mp1;
17234 		zoneid_t	last_zoneid;
17235 
17236 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(recv_ill)) {
17237 			ASSERT(ire->ire_type == IRE_BROADCAST);
17238 			/*
17239 			 * In the multicast case, applications may have joined
17240 			 * the group from different zones, so we need to deliver
17241 			 * the packet to each of them. Loop through the
17242 			 * multicast memberships structures (ilm) on the receive
17243 			 * ill and send a copy of the packet up each matching
17244 			 * one. However, we don't do this for multicasts sent on
17245 			 * the loopback interface (PHYI_LOOPBACK flag set) as
17246 			 * they must stay in the sender's zone.
17247 			 *
17248 			 * ilm_add_v6() ensures that ilms in the same zone are
17249 			 * contiguous in the ill_ilm list. We use this property
17250 			 * to avoid sending duplicates needed when two
17251 			 * applications in the same zone join the same group on
17252 			 * different logical interfaces: we ignore the ilm if
17253 			 * its zoneid is the same as the last matching one.
17254 			 * In addition, the sending of the packet for
17255 			 * ire_zoneid is delayed until all of the other ilms
17256 			 * have been exhausted.
17257 			 */
17258 			last_zoneid = -1;
17259 			ILM_WALKER_HOLD(recv_ill);
17260 			for (ilm = recv_ill->ill_ilm; ilm != NULL;
17261 			    ilm = ilm->ilm_next) {
17262 				if ((ilm->ilm_flags & ILM_DELETED) ||
17263 				    ipha->ipha_dst != ilm->ilm_addr ||
17264 				    ilm->ilm_zoneid == last_zoneid ||
17265 				    ilm->ilm_zoneid == ire->ire_zoneid ||
17266 				    ilm->ilm_zoneid == ALL_ZONES ||
17267 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
17268 					continue;
17269 				mp1 = ip_copymsg(first_mp);
17270 				if (mp1 == NULL)
17271 					continue;
17272 				icmp_inbound(q, mp1, B_TRUE, ill,
17273 				    0, sum, mctl_present, B_TRUE,
17274 				    recv_ill, ilm->ilm_zoneid);
17275 				last_zoneid = ilm->ilm_zoneid;
17276 			}
17277 			ILM_WALKER_RELE(recv_ill);
17278 		} else if (ire->ire_type == IRE_BROADCAST) {
17279 			/*
17280 			 * In the broadcast case, there may be many zones
17281 			 * which need a copy of the packet delivered to them.
17282 			 * There is one IRE_BROADCAST per broadcast address
17283 			 * and per zone; we walk those using a helper function.
17284 			 * In addition, the sending of the packet for ire is
17285 			 * delayed until all of the other ires have been
17286 			 * processed.
17287 			 */
17288 			IRB_REFHOLD(ire->ire_bucket);
17289 			ire_zone = NULL;
17290 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
17291 			    ire)) != NULL) {
17292 				mp1 = ip_copymsg(first_mp);
17293 				if (mp1 == NULL)
17294 					continue;
17295 
17296 				UPDATE_IB_PKT_COUNT(ire_zone);
17297 				ire_zone->ire_last_used_time = lbolt;
17298 				icmp_inbound(q, mp1, B_TRUE, ill,
17299 				    0, sum, mctl_present, B_TRUE,
17300 				    recv_ill, ire_zone->ire_zoneid);
17301 			}
17302 			IRB_REFRELE(ire->ire_bucket);
17303 		}
17304 		icmp_inbound(q, first_mp, (ire->ire_type == IRE_BROADCAST),
17305 		    ill, 0, sum, mctl_present, B_TRUE, recv_ill,
17306 		    ire->ire_zoneid);
17307 		TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17308 		    "ip_rput_locl_end: q %p (%S)", q, "icmp");
17309 		return;
17310 	}
17311 	case IPPROTO_IGMP:
17312 		/*
17313 		 * If we are not willing to accept IGMP packets in clear,
17314 		 * then check with global policy.
17315 		 */
17316 		if (ipst->ips_igmp_accept_clear_messages == 0) {
17317 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17318 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17319 			if (first_mp == NULL)
17320 				return;
17321 		}
17322 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17323 			freemsg(first_mp);
17324 			ip1dbg(("ip_proto_input: zone all cannot accept raw"));
17325 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17326 			return;
17327 		}
17328 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
17329 			/* Bad packet - discarded by igmp_input */
17330 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17331 			    "ip_rput_locl_end: q %p (%S)", q, "igmp");
17332 			if (mctl_present)
17333 				freeb(first_mp);
17334 			return;
17335 		}
17336 		/*
17337 		 * igmp_input() may have returned the pulled up message.
17338 		 * So first_mp and ipha need to be reinitialized.
17339 		 */
17340 		ipha = (ipha_t *)mp->b_rptr;
17341 		if (mctl_present)
17342 			first_mp->b_cont = mp;
17343 		else
17344 			first_mp = mp;
17345 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17346 		    connf_head != NULL) {
17347 			/* No user-level listener for IGMP packets */
17348 			goto drop_pkt;
17349 		}
17350 		/* deliver to local raw users */
17351 		break;
17352 	case IPPROTO_PIM:
17353 		/*
17354 		 * If we are not willing to accept PIM packets in clear,
17355 		 * then check with global policy.
17356 		 */
17357 		if (ipst->ips_pim_accept_clear_messages == 0) {
17358 			first_mp = ipsec_check_global_policy(first_mp, NULL,
17359 			    ipha, NULL, mctl_present, ipst->ips_netstack);
17360 			if (first_mp == NULL)
17361 				return;
17362 		}
17363 		if (is_system_labeled() && !tsol_can_accept_raw(mp, B_TRUE)) {
17364 			freemsg(first_mp);
17365 			ip1dbg(("ip_proto_input: zone all cannot accept PIM"));
17366 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17367 			return;
17368 		}
17369 		if (pim_input(q, mp, ill) != 0) {
17370 			/* Bad packet - discarded by pim_input */
17371 			TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17372 			    "ip_rput_locl_end: q %p (%S)", q, "pim");
17373 			if (mctl_present)
17374 				freeb(first_mp);
17375 			return;
17376 		}
17377 
17378 		/*
17379 		 * pim_input() may have pulled up the message so ipha needs to
17380 		 * be reinitialized.
17381 		 */
17382 		ipha = (ipha_t *)mp->b_rptr;
17383 		if (ipst->ips_ipcl_proto_fanout[ipha->ipha_protocol].
17384 		    connf_head != NULL) {
17385 			/* No user-level listener for PIM packets */
17386 			goto drop_pkt;
17387 		}
17388 		/* deliver to local raw users */
17389 		break;
17390 	case IPPROTO_ENCAP:
17391 		/*
17392 		 * Handle self-encapsulated packets (IP-in-IP where
17393 		 * the inner addresses == the outer addresses).
17394 		 */
17395 		hdr_length = IPH_HDR_LENGTH(ipha);
17396 		if ((uchar_t *)ipha + hdr_length + sizeof (ipha_t) >
17397 		    mp->b_wptr) {
17398 			if (!pullupmsg(mp, (uchar_t *)ipha + hdr_length +
17399 			    sizeof (ipha_t) - mp->b_rptr)) {
17400 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17401 				freemsg(first_mp);
17402 				return;
17403 			}
17404 			ipha = (ipha_t *)mp->b_rptr;
17405 		}
17406 		inner_ipha = (ipha_t *)((uchar_t *)ipha + hdr_length);
17407 		/*
17408 		 * Check the sanity of the inner IP header.
17409 		 */
17410 		if ((IPH_HDR_VERSION(inner_ipha) != IPV4_VERSION)) {
17411 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17412 			freemsg(first_mp);
17413 			return;
17414 		}
17415 		if (IPH_HDR_LENGTH(inner_ipha) < sizeof (ipha_t)) {
17416 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17417 			freemsg(first_mp);
17418 			return;
17419 		}
17420 		if (inner_ipha->ipha_src == ipha->ipha_src &&
17421 		    inner_ipha->ipha_dst == ipha->ipha_dst) {
17422 			ipsec_in_t *ii;
17423 
17424 			/*
17425 			 * Self-encapsulated tunnel packet. Remove
17426 			 * the outer IP header and fanout again.
17427 			 * We also need to make sure that the inner
17428 			 * header is pulled up until options.
17429 			 */
17430 			mp->b_rptr = (uchar_t *)inner_ipha;
17431 			ipha = inner_ipha;
17432 			hdr_length = IPH_HDR_LENGTH(ipha);
17433 			if ((uchar_t *)ipha + hdr_length > mp->b_wptr) {
17434 				if (!pullupmsg(mp, (uchar_t *)ipha +
17435 				    + hdr_length - mp->b_rptr)) {
17436 					freemsg(first_mp);
17437 					return;
17438 				}
17439 				ipha = (ipha_t *)mp->b_rptr;
17440 			}
17441 			if (hdr_length > sizeof (ipha_t)) {
17442 				/* We got options on the inner packet. */
17443 				ipaddr_t dst = ipha->ipha_dst;
17444 
17445 				if (ip_rput_options(q, mp, ipha, &dst, ipst) ==
17446 				    -1) {
17447 					/* Bad options! */
17448 					return;
17449 				}
17450 				if (dst != ipha->ipha_dst) {
17451 					/*
17452 					 * Someone put a source-route in
17453 					 * the inside header of a self-
17454 					 * encapsulated packet.  Drop it
17455 					 * with extreme prejudice and let
17456 					 * the sender know.
17457 					 */
17458 					icmp_unreachable(q, first_mp,
17459 					    ICMP_SOURCE_ROUTE_FAILED,
17460 					    recv_ill->ill_zoneid, ipst);
17461 					return;
17462 				}
17463 			}
17464 			if (!mctl_present) {
17465 				ASSERT(first_mp == mp);
17466 				/*
17467 				 * This means that somebody is sending
17468 				 * Self-encapsualted packets without AH/ESP.
17469 				 * If AH/ESP was present, we would have already
17470 				 * allocated the first_mp.
17471 				 *
17472 				 * Send this packet to find a tunnel endpoint.
17473 				 * if I can't find one, an ICMP
17474 				 * PROTOCOL_UNREACHABLE will get sent.
17475 				 */
17476 				goto fanout;
17477 			}
17478 			/*
17479 			 * We generally store the ill_index if we need to
17480 			 * do IPsec processing as we lose the ill queue when
17481 			 * we come back. But in this case, we never should
17482 			 * have to store the ill_index here as it should have
17483 			 * been stored previously when we processed the
17484 			 * AH/ESP header in this routine or for non-ipsec
17485 			 * cases, we still have the queue. But for some bad
17486 			 * packets from the wire, we can get to IPsec after
17487 			 * this and we better store the index for that case.
17488 			 */
17489 			ill = (ill_t *)q->q_ptr;
17490 			ii = (ipsec_in_t *)first_mp->b_rptr;
17491 			ii->ipsec_in_ill_index =
17492 			    ill->ill_phyint->phyint_ifindex;
17493 			ii->ipsec_in_rill_index =
17494 			    recv_ill->ill_phyint->phyint_ifindex;
17495 			if (ii->ipsec_in_decaps) {
17496 				/*
17497 				 * This packet is self-encapsulated multiple
17498 				 * times. We don't want to recurse infinitely.
17499 				 * To keep it simple, drop the packet.
17500 				 */
17501 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17502 				freemsg(first_mp);
17503 				return;
17504 			}
17505 			ii->ipsec_in_decaps = B_TRUE;
17506 			ip_fanout_proto_again(first_mp, recv_ill, recv_ill,
17507 			    ire);
17508 			return;
17509 		}
17510 		break;
17511 	case IPPROTO_AH:
17512 	case IPPROTO_ESP: {
17513 		ipsec_stack_t *ipss = ipst->ips_netstack->netstack_ipsec;
17514 
17515 		/*
17516 		 * Fast path for AH/ESP. If this is the first time
17517 		 * we are sending a datagram to AH/ESP, allocate
17518 		 * a IPSEC_IN message and prepend it. Otherwise,
17519 		 * just fanout.
17520 		 */
17521 
17522 		int ipsec_rc;
17523 		ipsec_in_t *ii;
17524 		netstack_t *ns = ipst->ips_netstack;
17525 
17526 		IP_STAT(ipst, ipsec_proto_ahesp);
17527 		if (!mctl_present) {
17528 			ASSERT(first_mp == mp);
17529 			first_mp = ipsec_in_alloc(B_TRUE, ns);
17530 			if (first_mp == NULL) {
17531 				ip1dbg(("ip_proto_input: IPSEC_IN "
17532 				    "allocation failure.\n"));
17533 				freemsg(hada_mp); /* okay ifnull */
17534 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17535 				freemsg(mp);
17536 				return;
17537 			}
17538 			/*
17539 			 * Store the ill_index so that when we come back
17540 			 * from IPsec we ride on the same queue.
17541 			 */
17542 			ill = (ill_t *)q->q_ptr;
17543 			ii = (ipsec_in_t *)first_mp->b_rptr;
17544 			ii->ipsec_in_ill_index =
17545 			    ill->ill_phyint->phyint_ifindex;
17546 			ii->ipsec_in_rill_index =
17547 			    recv_ill->ill_phyint->phyint_ifindex;
17548 			first_mp->b_cont = mp;
17549 			/*
17550 			 * Cache hardware acceleration info.
17551 			 */
17552 			if (hada_mp != NULL) {
17553 				IPSECHW_DEBUG(IPSECHW_PKT,
17554 				    ("ip_rput_local: caching data attr.\n"));
17555 				ii->ipsec_in_accelerated = B_TRUE;
17556 				ii->ipsec_in_da = hada_mp;
17557 				hada_mp = NULL;
17558 			}
17559 		} else {
17560 			ii = (ipsec_in_t *)first_mp->b_rptr;
17561 		}
17562 
17563 		if (!ipsec_loaded(ipss)) {
17564 			ip_proto_not_sup(q, first_mp, IP_FF_SEND_ICMP,
17565 			    ire->ire_zoneid, ipst);
17566 			return;
17567 		}
17568 
17569 		ns = ipst->ips_netstack;
17570 		/* select inbound SA and have IPsec process the pkt */
17571 		if (ipha->ipha_protocol == IPPROTO_ESP) {
17572 			esph_t *esph = ipsec_inbound_esp_sa(first_mp, ns);
17573 			boolean_t esp_in_udp_sa;
17574 			if (esph == NULL)
17575 				return;
17576 			ASSERT(ii->ipsec_in_esp_sa != NULL);
17577 			ASSERT(ii->ipsec_in_esp_sa->ipsa_input_func != NULL);
17578 			esp_in_udp_sa = ((ii->ipsec_in_esp_sa->ipsa_flags &
17579 			    IPSA_F_NATT) != 0);
17580 			/*
17581 			 * The following is a fancy, but quick, way of saying:
17582 			 * ESP-in-UDP SA and Raw ESP packet --> drop
17583 			 *    OR
17584 			 * ESP SA and ESP-in-UDP packet --> drop
17585 			 */
17586 			if (esp_in_udp_sa != esp_in_udp_packet) {
17587 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17588 				ip_drop_packet(first_mp, B_TRUE, ill, NULL,
17589 				    DROPPER(ns->netstack_ipsec, ipds_esp_no_sa),
17590 				    &ns->netstack_ipsec->ipsec_dropper);
17591 				return;
17592 			}
17593 			ipsec_rc = ii->ipsec_in_esp_sa->ipsa_input_func(
17594 			    first_mp, esph);
17595 		} else {
17596 			ah_t *ah = ipsec_inbound_ah_sa(first_mp, ns);
17597 			if (ah == NULL)
17598 				return;
17599 			ASSERT(ii->ipsec_in_ah_sa != NULL);
17600 			ASSERT(ii->ipsec_in_ah_sa->ipsa_input_func != NULL);
17601 			ipsec_rc = ii->ipsec_in_ah_sa->ipsa_input_func(
17602 			    first_mp, ah);
17603 		}
17604 
17605 		switch (ipsec_rc) {
17606 		case IPSEC_STATUS_SUCCESS:
17607 			break;
17608 		case IPSEC_STATUS_FAILED:
17609 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
17610 			/* FALLTHRU */
17611 		case IPSEC_STATUS_PENDING:
17612 			return;
17613 		}
17614 		/* we're done with IPsec processing, send it up */
17615 		ip_fanout_proto_again(first_mp, ill, recv_ill, ire);
17616 		return;
17617 	}
17618 	default:
17619 		break;
17620 	}
17621 	if (is_system_labeled() && !tsol_can_accept_raw(mp, B_FALSE)) {
17622 		ip1dbg(("ip_proto_input: zone %d cannot accept raw IP",
17623 		    ire->ire_zoneid));
17624 		goto drop_pkt;
17625 	}
17626 	/*
17627 	 * Handle protocols with which IP is less intimate.  There
17628 	 * can be more than one stream bound to a particular
17629 	 * protocol.  When this is the case, each one gets a copy
17630 	 * of any incoming packets.
17631 	 */
17632 fanout:
17633 	ip_fanout_proto(q, first_mp, ill, ipha,
17634 	    IP_FF_SEND_ICMP | IP_FF_CKSUM | IP_FF_RAWIP, mctl_present,
17635 	    B_TRUE, recv_ill, ire->ire_zoneid);
17636 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17637 	    "ip_rput_locl_end: q %p (%S)", q, "ip_fanout_proto");
17638 	return;
17639 
17640 drop_pkt:
17641 	freemsg(first_mp);
17642 	if (hada_mp != NULL)
17643 		freeb(hada_mp);
17644 	TRACE_2(TR_FAC_IP, TR_IP_RPUT_LOCL_END,
17645 	    "ip_rput_locl_end: q %p (%S)", q, "droppkt");
17646 #undef	rptr
17647 #undef  iphs
17648 
17649 }
17650 
17651 /*
17652  * Update any source route, record route or timestamp options.
17653  * Check that we are at end of strict source route.
17654  * The options have already been checked for sanity in ip_rput_options().
17655  */
17656 static boolean_t
17657 ip_rput_local_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ire_t *ire,
17658     ip_stack_t *ipst)
17659 {
17660 	ipoptp_t	opts;
17661 	uchar_t		*opt;
17662 	uint8_t		optval;
17663 	uint8_t		optlen;
17664 	ipaddr_t	dst;
17665 	uint32_t	ts;
17666 	ire_t		*dst_ire;
17667 	timestruc_t	now;
17668 	zoneid_t	zoneid;
17669 	ill_t		*ill;
17670 
17671 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
17672 
17673 	ip2dbg(("ip_rput_local_options\n"));
17674 
17675 	for (optval = ipoptp_first(&opts, ipha);
17676 	    optval != IPOPT_EOL;
17677 	    optval = ipoptp_next(&opts)) {
17678 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
17679 		opt = opts.ipoptp_cur;
17680 		optlen = opts.ipoptp_len;
17681 		ip2dbg(("ip_rput_local_options: opt %d, len %d\n",
17682 		    optval, optlen));
17683 		switch (optval) {
17684 			uint32_t off;
17685 		case IPOPT_SSRR:
17686 		case IPOPT_LSRR:
17687 			off = opt[IPOPT_OFFSET];
17688 			off--;
17689 			if (optlen < IP_ADDR_LEN ||
17690 			    off > optlen - IP_ADDR_LEN) {
17691 				/* End of source route */
17692 				ip1dbg(("ip_rput_local_options: end of SR\n"));
17693 				break;
17694 			}
17695 			/*
17696 			 * This will only happen if two consecutive entries
17697 			 * in the source route contains our address or if
17698 			 * it is a packet with a loose source route which
17699 			 * reaches us before consuming the whole source route
17700 			 */
17701 			ip1dbg(("ip_rput_local_options: not end of SR\n"));
17702 			if (optval == IPOPT_SSRR) {
17703 				goto bad_src_route;
17704 			}
17705 			/*
17706 			 * Hack: instead of dropping the packet truncate the
17707 			 * source route to what has been used by filling the
17708 			 * rest with IPOPT_NOP.
17709 			 */
17710 			opt[IPOPT_OLEN] = (uint8_t)off;
17711 			while (off < optlen) {
17712 				opt[off++] = IPOPT_NOP;
17713 			}
17714 			break;
17715 		case IPOPT_RR:
17716 			off = opt[IPOPT_OFFSET];
17717 			off--;
17718 			if (optlen < IP_ADDR_LEN ||
17719 			    off > optlen - IP_ADDR_LEN) {
17720 				/* No more room - ignore */
17721 				ip1dbg((
17722 				    "ip_rput_local_options: end of RR\n"));
17723 				break;
17724 			}
17725 			bcopy(&ire->ire_src_addr, (char *)opt + off,
17726 			    IP_ADDR_LEN);
17727 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17728 			break;
17729 		case IPOPT_TS:
17730 			/* Insert timestamp if there is romm */
17731 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17732 			case IPOPT_TS_TSONLY:
17733 				off = IPOPT_TS_TIMELEN;
17734 				break;
17735 			case IPOPT_TS_PRESPEC:
17736 			case IPOPT_TS_PRESPEC_RFC791:
17737 				/* Verify that the address matched */
17738 				off = opt[IPOPT_OFFSET] - 1;
17739 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17740 				dst_ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
17741 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
17742 				    ipst);
17743 				if (dst_ire == NULL) {
17744 					/* Not for us */
17745 					break;
17746 				}
17747 				ire_refrele(dst_ire);
17748 				/* FALLTHRU */
17749 			case IPOPT_TS_TSANDADDR:
17750 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17751 				break;
17752 			default:
17753 				/*
17754 				 * ip_*put_options should have already
17755 				 * dropped this packet.
17756 				 */
17757 				cmn_err(CE_PANIC, "ip_rput_local_options: "
17758 				    "unknown IT - bug in ip_rput_options?\n");
17759 				return (B_TRUE);	/* Keep "lint" happy */
17760 			}
17761 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
17762 				/* Increase overflow counter */
17763 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
17764 				opt[IPOPT_POS_OV_FLG] =
17765 				    (uint8_t)((opt[IPOPT_POS_OV_FLG] & 0x0F) |
17766 				    (off << 4));
17767 				break;
17768 			}
17769 			off = opt[IPOPT_OFFSET] - 1;
17770 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17771 			case IPOPT_TS_PRESPEC:
17772 			case IPOPT_TS_PRESPEC_RFC791:
17773 			case IPOPT_TS_TSANDADDR:
17774 				bcopy(&ire->ire_src_addr, (char *)opt + off,
17775 				    IP_ADDR_LEN);
17776 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
17777 				/* FALLTHRU */
17778 			case IPOPT_TS_TSONLY:
17779 				off = opt[IPOPT_OFFSET] - 1;
17780 				/* Compute # of milliseconds since midnight */
17781 				gethrestime(&now);
17782 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
17783 				    now.tv_nsec / (NANOSEC / MILLISEC);
17784 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
17785 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
17786 				break;
17787 			}
17788 			break;
17789 		}
17790 	}
17791 	return (B_TRUE);
17792 
17793 bad_src_route:
17794 	q = WR(q);
17795 	if (q->q_next != NULL)
17796 		ill = q->q_ptr;
17797 	else
17798 		ill = NULL;
17799 
17800 	/* make sure we clear any indication of a hardware checksum */
17801 	DB_CKSUMFLAGS(mp) = 0;
17802 	zoneid = ipif_lookup_addr_zoneid(ipha->ipha_dst, ill, ipst);
17803 	if (zoneid == ALL_ZONES)
17804 		freemsg(mp);
17805 	else
17806 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
17807 	return (B_FALSE);
17808 
17809 }
17810 
17811 /*
17812  * Process IP options in an inbound packet.  If an option affects the
17813  * effective destination address, return the next hop address via dstp.
17814  * Returns -1 if something fails in which case an ICMP error has been sent
17815  * and mp freed.
17816  */
17817 static int
17818 ip_rput_options(queue_t *q, mblk_t *mp, ipha_t *ipha, ipaddr_t *dstp,
17819     ip_stack_t *ipst)
17820 {
17821 	ipoptp_t	opts;
17822 	uchar_t		*opt;
17823 	uint8_t		optval;
17824 	uint8_t		optlen;
17825 	ipaddr_t	dst;
17826 	intptr_t	code = 0;
17827 	ire_t		*ire = NULL;
17828 	zoneid_t	zoneid;
17829 	ill_t		*ill;
17830 
17831 	ip2dbg(("ip_rput_options\n"));
17832 	dst = ipha->ipha_dst;
17833 	for (optval = ipoptp_first(&opts, ipha);
17834 	    optval != IPOPT_EOL;
17835 	    optval = ipoptp_next(&opts)) {
17836 		opt = opts.ipoptp_cur;
17837 		optlen = opts.ipoptp_len;
17838 		ip2dbg(("ip_rput_options: opt %d, len %d\n",
17839 		    optval, optlen));
17840 		/*
17841 		 * Note: we need to verify the checksum before we
17842 		 * modify anything thus this routine only extracts the next
17843 		 * hop dst from any source route.
17844 		 */
17845 		switch (optval) {
17846 			uint32_t off;
17847 		case IPOPT_SSRR:
17848 		case IPOPT_LSRR:
17849 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17850 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17851 			if (ire == NULL) {
17852 				if (optval == IPOPT_SSRR) {
17853 					ip1dbg(("ip_rput_options: not next"
17854 					    " strict source route 0x%x\n",
17855 					    ntohl(dst)));
17856 					code = (char *)&ipha->ipha_dst -
17857 					    (char *)ipha;
17858 					goto param_prob; /* RouterReq's */
17859 				}
17860 				ip2dbg(("ip_rput_options: "
17861 				    "not next source route 0x%x\n",
17862 				    ntohl(dst)));
17863 				break;
17864 			}
17865 			ire_refrele(ire);
17866 
17867 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17868 				ip1dbg((
17869 				    "ip_rput_options: bad option offset\n"));
17870 				code = (char *)&opt[IPOPT_OLEN] -
17871 				    (char *)ipha;
17872 				goto param_prob;
17873 			}
17874 			off = opt[IPOPT_OFFSET];
17875 			off--;
17876 		redo_srr:
17877 			if (optlen < IP_ADDR_LEN ||
17878 			    off > optlen - IP_ADDR_LEN) {
17879 				/* End of source route */
17880 				ip1dbg(("ip_rput_options: end of SR\n"));
17881 				break;
17882 			}
17883 			bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
17884 			ip1dbg(("ip_rput_options: next hop 0x%x\n",
17885 			    ntohl(dst)));
17886 
17887 			/*
17888 			 * Check if our address is present more than
17889 			 * once as consecutive hops in source route.
17890 			 * XXX verify per-interface ip_forwarding
17891 			 * for source route?
17892 			 */
17893 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
17894 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
17895 
17896 			if (ire != NULL) {
17897 				ire_refrele(ire);
17898 				off += IP_ADDR_LEN;
17899 				goto redo_srr;
17900 			}
17901 
17902 			if (dst == htonl(INADDR_LOOPBACK)) {
17903 				ip1dbg(("ip_rput_options: loopback addr in "
17904 				    "source route!\n"));
17905 				goto bad_src_route;
17906 			}
17907 			/*
17908 			 * For strict: verify that dst is directly
17909 			 * reachable.
17910 			 */
17911 			if (optval == IPOPT_SSRR) {
17912 				ire = ire_ftable_lookup(dst, 0, 0,
17913 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
17914 				    MBLK_GETLABEL(mp),
17915 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
17916 				if (ire == NULL) {
17917 					ip1dbg(("ip_rput_options: SSRR not "
17918 					    "directly reachable: 0x%x\n",
17919 					    ntohl(dst)));
17920 					goto bad_src_route;
17921 				}
17922 				ire_refrele(ire);
17923 			}
17924 			/*
17925 			 * Defer update of the offset and the record route
17926 			 * until the packet is forwarded.
17927 			 */
17928 			break;
17929 		case IPOPT_RR:
17930 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17931 				ip1dbg((
17932 				    "ip_rput_options: bad option offset\n"));
17933 				code = (char *)&opt[IPOPT_OLEN] -
17934 				    (char *)ipha;
17935 				goto param_prob;
17936 			}
17937 			break;
17938 		case IPOPT_TS:
17939 			/*
17940 			 * Verify that length >= 5 and that there is either
17941 			 * room for another timestamp or that the overflow
17942 			 * counter is not maxed out.
17943 			 */
17944 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
17945 			if (optlen < IPOPT_MINLEN_IT) {
17946 				goto param_prob;
17947 			}
17948 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
17949 				ip1dbg((
17950 				    "ip_rput_options: bad option offset\n"));
17951 				code = (char *)&opt[IPOPT_OFFSET] -
17952 				    (char *)ipha;
17953 				goto param_prob;
17954 			}
17955 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
17956 			case IPOPT_TS_TSONLY:
17957 				off = IPOPT_TS_TIMELEN;
17958 				break;
17959 			case IPOPT_TS_TSANDADDR:
17960 			case IPOPT_TS_PRESPEC:
17961 			case IPOPT_TS_PRESPEC_RFC791:
17962 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
17963 				break;
17964 			default:
17965 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
17966 				    (char *)ipha;
17967 				goto param_prob;
17968 			}
17969 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
17970 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
17971 				/*
17972 				 * No room and the overflow counter is 15
17973 				 * already.
17974 				 */
17975 				goto param_prob;
17976 			}
17977 			break;
17978 		}
17979 	}
17980 
17981 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0) {
17982 		*dstp = dst;
17983 		return (0);
17984 	}
17985 
17986 	ip1dbg(("ip_rput_options: error processing IP options."));
17987 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
17988 
17989 param_prob:
17990 	q = WR(q);
17991 	if (q->q_next != NULL)
17992 		ill = q->q_ptr;
17993 	else
17994 		ill = NULL;
17995 
17996 	/* make sure we clear any indication of a hardware checksum */
17997 	DB_CKSUMFLAGS(mp) = 0;
17998 	/* Don't know whether this is for non-global or global/forwarding */
17999 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18000 	if (zoneid == ALL_ZONES)
18001 		freemsg(mp);
18002 	else
18003 		icmp_param_problem(q, mp, (uint8_t)code, zoneid, ipst);
18004 	return (-1);
18005 
18006 bad_src_route:
18007 	q = WR(q);
18008 	if (q->q_next != NULL)
18009 		ill = q->q_ptr;
18010 	else
18011 		ill = NULL;
18012 
18013 	/* make sure we clear any indication of a hardware checksum */
18014 	DB_CKSUMFLAGS(mp) = 0;
18015 	zoneid = ipif_lookup_addr_zoneid(dst, ill, ipst);
18016 	if (zoneid == ALL_ZONES)
18017 		freemsg(mp);
18018 	else
18019 		icmp_unreachable(q, mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
18020 	return (-1);
18021 }
18022 
18023 /*
18024  * IP & ICMP info in >=14 msg's ...
18025  *  - ip fixed part (mib2_ip_t)
18026  *  - icmp fixed part (mib2_icmp_t)
18027  *  - ipAddrEntryTable (ip 20)		all IPv4 ipifs
18028  *  - ipRouteEntryTable (ip 21)		all IPv4 IREs
18029  *  - ipNetToMediaEntryTable (ip 22)	[filled in by the arp module]
18030  *  - ipRouteAttributeTable (ip 102)	labeled routes
18031  *  - ip multicast membership (ip_member_t)
18032  *  - ip multicast source filtering (ip_grpsrc_t)
18033  *  - igmp fixed part (struct igmpstat)
18034  *  - multicast routing stats (struct mrtstat)
18035  *  - multicast routing vifs (array of struct vifctl)
18036  *  - multicast routing routes (array of struct mfcctl)
18037  *  - ip6 fixed part (mib2_ipv6IfStatsEntry_t)
18038  *					One per ill plus one generic
18039  *  - icmp6 fixed part (mib2_ipv6IfIcmpEntry_t)
18040  *					One per ill plus one generic
18041  *  - ipv6RouteEntry			all IPv6 IREs
18042  *  - ipv6RouteAttributeTable (ip6 102)	labeled routes
18043  *  - ipv6NetToMediaEntry		all Neighbor Cache entries
18044  *  - ipv6AddrEntry			all IPv6 ipifs
18045  *  - ipv6 multicast membership (ipv6_member_t)
18046  *  - ipv6 multicast source filtering (ipv6_grpsrc_t)
18047  *
18048  * MIB2_IP_MEDIA is filled in by the arp module with ARP cache entries.
18049  *
18050  * NOTE: original mpctl is copied for msg's 2..N, since its ctl part is
18051  * already filled in by the caller.
18052  * Return value of 0 indicates that no messages were sent and caller
18053  * should free mpctl.
18054  */
18055 int
18056 ip_snmp_get(queue_t *q, mblk_t *mpctl, int level)
18057 {
18058 	ip_stack_t *ipst;
18059 	sctp_stack_t *sctps;
18060 
18061 	if (q->q_next != NULL) {
18062 		ipst = ILLQ_TO_IPST(q);
18063 	} else {
18064 		ipst = CONNQ_TO_IPST(q);
18065 	}
18066 	ASSERT(ipst != NULL);
18067 	sctps = ipst->ips_netstack->netstack_sctp;
18068 
18069 	if (mpctl == NULL || mpctl->b_cont == NULL) {
18070 		return (0);
18071 	}
18072 
18073 	/*
18074 	 * For the purposes of the (broken) packet shell use
18075 	 * of the level we make sure MIB2_TCP/MIB2_UDP can be used
18076 	 * to make TCP and UDP appear first in the list of mib items.
18077 	 * TBD: We could expand this and use it in netstat so that
18078 	 * the kernel doesn't have to produce large tables (connections,
18079 	 * routes, etc) when netstat only wants the statistics or a particular
18080 	 * table.
18081 	 */
18082 	if (!(level == MIB2_TCP || level == MIB2_UDP)) {
18083 		if ((mpctl = icmp_snmp_get(q, mpctl)) == NULL) {
18084 			return (1);
18085 		}
18086 	}
18087 
18088 	if (level != MIB2_TCP) {
18089 		if ((mpctl = udp_snmp_get(q, mpctl)) == NULL) {
18090 			return (1);
18091 		}
18092 	}
18093 
18094 	if (level != MIB2_UDP) {
18095 		if ((mpctl = tcp_snmp_get(q, mpctl)) == NULL) {
18096 			return (1);
18097 		}
18098 	}
18099 
18100 	if ((mpctl = ip_snmp_get_mib2_ip_traffic_stats(q, mpctl,
18101 	    ipst)) == NULL) {
18102 		return (1);
18103 	}
18104 
18105 	if ((mpctl = ip_snmp_get_mib2_ip6(q, mpctl, ipst)) == NULL) {
18106 		return (1);
18107 	}
18108 
18109 	if ((mpctl = ip_snmp_get_mib2_icmp(q, mpctl, ipst)) == NULL) {
18110 		return (1);
18111 	}
18112 
18113 	if ((mpctl = ip_snmp_get_mib2_icmp6(q, mpctl, ipst)) == NULL) {
18114 		return (1);
18115 	}
18116 
18117 	if ((mpctl = ip_snmp_get_mib2_igmp(q, mpctl, ipst)) == NULL) {
18118 		return (1);
18119 	}
18120 
18121 	if ((mpctl = ip_snmp_get_mib2_multi(q, mpctl, ipst)) == NULL) {
18122 		return (1);
18123 	}
18124 
18125 	if ((mpctl = ip_snmp_get_mib2_ip_addr(q, mpctl, ipst)) == NULL) {
18126 		return (1);
18127 	}
18128 
18129 	if ((mpctl = ip_snmp_get_mib2_ip6_addr(q, mpctl, ipst)) == NULL) {
18130 		return (1);
18131 	}
18132 
18133 	if ((mpctl = ip_snmp_get_mib2_ip_group_mem(q, mpctl, ipst)) == NULL) {
18134 		return (1);
18135 	}
18136 
18137 	if ((mpctl = ip_snmp_get_mib2_ip6_group_mem(q, mpctl, ipst)) == NULL) {
18138 		return (1);
18139 	}
18140 
18141 	if ((mpctl = ip_snmp_get_mib2_ip_group_src(q, mpctl, ipst)) == NULL) {
18142 		return (1);
18143 	}
18144 
18145 	if ((mpctl = ip_snmp_get_mib2_ip6_group_src(q, mpctl, ipst)) == NULL) {
18146 		return (1);
18147 	}
18148 
18149 	if ((mpctl = ip_snmp_get_mib2_virt_multi(q, mpctl, ipst)) == NULL) {
18150 		return (1);
18151 	}
18152 
18153 	if ((mpctl = ip_snmp_get_mib2_multi_rtable(q, mpctl, ipst)) == NULL) {
18154 		return (1);
18155 	}
18156 
18157 	if ((mpctl = ip_snmp_get_mib2_ip_route_media(q, mpctl, ipst)) == NULL) {
18158 		return (1);
18159 	}
18160 
18161 	mpctl = ip_snmp_get_mib2_ip6_route_media(q, mpctl, ipst);
18162 	if (mpctl == NULL) {
18163 		return (1);
18164 	}
18165 
18166 	if ((mpctl = sctp_snmp_get_mib2(q, mpctl, sctps)) == NULL) {
18167 		return (1);
18168 	}
18169 	freemsg(mpctl);
18170 	return (1);
18171 }
18172 
18173 
18174 /* Get global (legacy) IPv4 statistics */
18175 static mblk_t *
18176 ip_snmp_get_mib2_ip(queue_t *q, mblk_t *mpctl, mib2_ipIfStatsEntry_t *ipmib,
18177     ip_stack_t *ipst)
18178 {
18179 	mib2_ip_t		old_ip_mib;
18180 	struct opthdr		*optp;
18181 	mblk_t			*mp2ctl;
18182 
18183 	/*
18184 	 * make a copy of the original message
18185 	 */
18186 	mp2ctl = copymsg(mpctl);
18187 
18188 	/* fixed length IP structure... */
18189 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18190 	optp->level = MIB2_IP;
18191 	optp->name = 0;
18192 	SET_MIB(old_ip_mib.ipForwarding,
18193 	    (WE_ARE_FORWARDING(ipst) ? 1 : 2));
18194 	SET_MIB(old_ip_mib.ipDefaultTTL,
18195 	    (uint32_t)ipst->ips_ip_def_ttl);
18196 	SET_MIB(old_ip_mib.ipReasmTimeout,
18197 	    ipst->ips_ip_g_frag_timeout);
18198 	SET_MIB(old_ip_mib.ipAddrEntrySize,
18199 	    sizeof (mib2_ipAddrEntry_t));
18200 	SET_MIB(old_ip_mib.ipRouteEntrySize,
18201 	    sizeof (mib2_ipRouteEntry_t));
18202 	SET_MIB(old_ip_mib.ipNetToMediaEntrySize,
18203 	    sizeof (mib2_ipNetToMediaEntry_t));
18204 	SET_MIB(old_ip_mib.ipMemberEntrySize, sizeof (ip_member_t));
18205 	SET_MIB(old_ip_mib.ipGroupSourceEntrySize, sizeof (ip_grpsrc_t));
18206 	SET_MIB(old_ip_mib.ipRouteAttributeSize,
18207 	    sizeof (mib2_ipAttributeEntry_t));
18208 	SET_MIB(old_ip_mib.transportMLPSize, sizeof (mib2_transportMLPEntry_t));
18209 
18210 	/*
18211 	 * Grab the statistics from the new IP MIB
18212 	 */
18213 	SET_MIB(old_ip_mib.ipInReceives,
18214 	    (uint32_t)ipmib->ipIfStatsHCInReceives);
18215 	SET_MIB(old_ip_mib.ipInHdrErrors, ipmib->ipIfStatsInHdrErrors);
18216 	SET_MIB(old_ip_mib.ipInAddrErrors, ipmib->ipIfStatsInAddrErrors);
18217 	SET_MIB(old_ip_mib.ipForwDatagrams,
18218 	    (uint32_t)ipmib->ipIfStatsHCOutForwDatagrams);
18219 	SET_MIB(old_ip_mib.ipInUnknownProtos,
18220 	    ipmib->ipIfStatsInUnknownProtos);
18221 	SET_MIB(old_ip_mib.ipInDiscards, ipmib->ipIfStatsInDiscards);
18222 	SET_MIB(old_ip_mib.ipInDelivers,
18223 	    (uint32_t)ipmib->ipIfStatsHCInDelivers);
18224 	SET_MIB(old_ip_mib.ipOutRequests,
18225 	    (uint32_t)ipmib->ipIfStatsHCOutRequests);
18226 	SET_MIB(old_ip_mib.ipOutDiscards, ipmib->ipIfStatsOutDiscards);
18227 	SET_MIB(old_ip_mib.ipOutNoRoutes, ipmib->ipIfStatsOutNoRoutes);
18228 	SET_MIB(old_ip_mib.ipReasmReqds, ipmib->ipIfStatsReasmReqds);
18229 	SET_MIB(old_ip_mib.ipReasmOKs, ipmib->ipIfStatsReasmOKs);
18230 	SET_MIB(old_ip_mib.ipReasmFails, ipmib->ipIfStatsReasmFails);
18231 	SET_MIB(old_ip_mib.ipFragOKs, ipmib->ipIfStatsOutFragOKs);
18232 	SET_MIB(old_ip_mib.ipFragFails, ipmib->ipIfStatsOutFragFails);
18233 	SET_MIB(old_ip_mib.ipFragCreates, ipmib->ipIfStatsOutFragCreates);
18234 
18235 	/* ipRoutingDiscards is not being used */
18236 	SET_MIB(old_ip_mib.ipRoutingDiscards, 0);
18237 	SET_MIB(old_ip_mib.tcpInErrs, ipmib->tcpIfStatsInErrs);
18238 	SET_MIB(old_ip_mib.udpNoPorts, ipmib->udpIfStatsNoPorts);
18239 	SET_MIB(old_ip_mib.ipInCksumErrs, ipmib->ipIfStatsInCksumErrs);
18240 	SET_MIB(old_ip_mib.ipReasmDuplicates,
18241 	    ipmib->ipIfStatsReasmDuplicates);
18242 	SET_MIB(old_ip_mib.ipReasmPartDups, ipmib->ipIfStatsReasmPartDups);
18243 	SET_MIB(old_ip_mib.ipForwProhibits, ipmib->ipIfStatsForwProhibits);
18244 	SET_MIB(old_ip_mib.udpInCksumErrs, ipmib->udpIfStatsInCksumErrs);
18245 	SET_MIB(old_ip_mib.udpInOverflows, ipmib->udpIfStatsInOverflows);
18246 	SET_MIB(old_ip_mib.rawipInOverflows,
18247 	    ipmib->rawipIfStatsInOverflows);
18248 
18249 	SET_MIB(old_ip_mib.ipsecInSucceeded, ipmib->ipsecIfStatsInSucceeded);
18250 	SET_MIB(old_ip_mib.ipsecInFailed, ipmib->ipsecIfStatsInFailed);
18251 	SET_MIB(old_ip_mib.ipInIPv6, ipmib->ipIfStatsInWrongIPVersion);
18252 	SET_MIB(old_ip_mib.ipOutIPv6, ipmib->ipIfStatsOutWrongIPVersion);
18253 	SET_MIB(old_ip_mib.ipOutSwitchIPv6,
18254 	    ipmib->ipIfStatsOutSwitchIPVersion);
18255 
18256 	if (!snmp_append_data(mpctl->b_cont, (char *)&old_ip_mib,
18257 	    (int)sizeof (old_ip_mib))) {
18258 		ip1dbg(("ip_snmp_get_mib2_ip: failed to allocate %u bytes\n",
18259 		    (uint_t)sizeof (old_ip_mib)));
18260 	}
18261 
18262 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18263 	ip3dbg(("ip_snmp_get_mib2_ip: level %d, name %d, len %d\n",
18264 	    (int)optp->level, (int)optp->name, (int)optp->len));
18265 	qreply(q, mpctl);
18266 	return (mp2ctl);
18267 }
18268 
18269 /* Per interface IPv4 statistics */
18270 static mblk_t *
18271 ip_snmp_get_mib2_ip_traffic_stats(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18272 {
18273 	struct opthdr		*optp;
18274 	mblk_t			*mp2ctl;
18275 	ill_t			*ill;
18276 	ill_walk_context_t	ctx;
18277 	mblk_t			*mp_tail = NULL;
18278 	mib2_ipIfStatsEntry_t	global_ip_mib;
18279 
18280 	/*
18281 	 * Make a copy of the original message
18282 	 */
18283 	mp2ctl = copymsg(mpctl);
18284 
18285 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18286 	optp->level = MIB2_IP;
18287 	optp->name = MIB2_IP_TRAFFIC_STATS;
18288 	/* Include "unknown interface" ip_mib */
18289 	ipst->ips_ip_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv4;
18290 	ipst->ips_ip_mib.ipIfStatsIfIndex =
18291 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
18292 	SET_MIB(ipst->ips_ip_mib.ipIfStatsForwarding,
18293 	    (ipst->ips_ip_g_forward ? 1 : 2));
18294 	SET_MIB(ipst->ips_ip_mib.ipIfStatsDefaultTTL,
18295 	    (uint32_t)ipst->ips_ip_def_ttl);
18296 	SET_MIB(ipst->ips_ip_mib.ipIfStatsEntrySize,
18297 	    sizeof (mib2_ipIfStatsEntry_t));
18298 	SET_MIB(ipst->ips_ip_mib.ipIfStatsAddrEntrySize,
18299 	    sizeof (mib2_ipAddrEntry_t));
18300 	SET_MIB(ipst->ips_ip_mib.ipIfStatsRouteEntrySize,
18301 	    sizeof (mib2_ipRouteEntry_t));
18302 	SET_MIB(ipst->ips_ip_mib.ipIfStatsNetToMediaEntrySize,
18303 	    sizeof (mib2_ipNetToMediaEntry_t));
18304 	SET_MIB(ipst->ips_ip_mib.ipIfStatsMemberEntrySize,
18305 	    sizeof (ip_member_t));
18306 	SET_MIB(ipst->ips_ip_mib.ipIfStatsGroupSourceEntrySize,
18307 	    sizeof (ip_grpsrc_t));
18308 
18309 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18310 	    (char *)&ipst->ips_ip_mib, (int)sizeof (ipst->ips_ip_mib))) {
18311 		ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18312 		    "failed to allocate %u bytes\n",
18313 		    (uint_t)sizeof (ipst->ips_ip_mib)));
18314 	}
18315 
18316 	bcopy(&ipst->ips_ip_mib, &global_ip_mib, sizeof (global_ip_mib));
18317 
18318 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18319 	ill = ILL_START_WALK_V4(&ctx, ipst);
18320 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18321 		ill->ill_ip_mib->ipIfStatsIfIndex =
18322 		    ill->ill_phyint->phyint_ifindex;
18323 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
18324 		    (ipst->ips_ip_g_forward ? 1 : 2));
18325 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultTTL,
18326 		    (uint32_t)ipst->ips_ip_def_ttl);
18327 
18328 		ip_mib2_add_ip_stats(&global_ip_mib, ill->ill_ip_mib);
18329 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18330 		    (char *)ill->ill_ip_mib,
18331 		    (int)sizeof (*ill->ill_ip_mib))) {
18332 			ip1dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18333 			    "failed to allocate %u bytes\n",
18334 			    (uint_t)sizeof (*ill->ill_ip_mib)));
18335 		}
18336 	}
18337 	rw_exit(&ipst->ips_ill_g_lock);
18338 
18339 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18340 	ip3dbg(("ip_snmp_get_mib2_ip_traffic_stats: "
18341 	    "level %d, name %d, len %d\n",
18342 	    (int)optp->level, (int)optp->name, (int)optp->len));
18343 	qreply(q, mpctl);
18344 
18345 	if (mp2ctl == NULL)
18346 		return (NULL);
18347 
18348 	return (ip_snmp_get_mib2_ip(q, mp2ctl, &global_ip_mib, ipst));
18349 }
18350 
18351 /* Global IPv4 ICMP statistics */
18352 static mblk_t *
18353 ip_snmp_get_mib2_icmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18354 {
18355 	struct opthdr		*optp;
18356 	mblk_t			*mp2ctl;
18357 
18358 	/*
18359 	 * Make a copy of the original message
18360 	 */
18361 	mp2ctl = copymsg(mpctl);
18362 
18363 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18364 	optp->level = MIB2_ICMP;
18365 	optp->name = 0;
18366 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_icmp_mib,
18367 	    (int)sizeof (ipst->ips_icmp_mib))) {
18368 		ip1dbg(("ip_snmp_get_mib2_icmp: failed to allocate %u bytes\n",
18369 		    (uint_t)sizeof (ipst->ips_icmp_mib)));
18370 	}
18371 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18372 	ip3dbg(("ip_snmp_get_mib2_icmp: level %d, name %d, len %d\n",
18373 	    (int)optp->level, (int)optp->name, (int)optp->len));
18374 	qreply(q, mpctl);
18375 	return (mp2ctl);
18376 }
18377 
18378 /* Global IPv4 IGMP statistics */
18379 static mblk_t *
18380 ip_snmp_get_mib2_igmp(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18381 {
18382 	struct opthdr		*optp;
18383 	mblk_t			*mp2ctl;
18384 
18385 	/*
18386 	 * make a copy of the original message
18387 	 */
18388 	mp2ctl = copymsg(mpctl);
18389 
18390 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18391 	optp->level = EXPER_IGMP;
18392 	optp->name = 0;
18393 	if (!snmp_append_data(mpctl->b_cont, (char *)&ipst->ips_igmpstat,
18394 	    (int)sizeof (ipst->ips_igmpstat))) {
18395 		ip1dbg(("ip_snmp_get_mib2_igmp: failed to allocate %u bytes\n",
18396 		    (uint_t)sizeof (ipst->ips_igmpstat)));
18397 	}
18398 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18399 	ip3dbg(("ip_snmp_get_mib2_igmp: level %d, name %d, len %d\n",
18400 	    (int)optp->level, (int)optp->name, (int)optp->len));
18401 	qreply(q, mpctl);
18402 	return (mp2ctl);
18403 }
18404 
18405 /* Global IPv4 Multicast Routing statistics */
18406 static mblk_t *
18407 ip_snmp_get_mib2_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18408 {
18409 	struct opthdr		*optp;
18410 	mblk_t			*mp2ctl;
18411 
18412 	/*
18413 	 * make a copy of the original message
18414 	 */
18415 	mp2ctl = copymsg(mpctl);
18416 
18417 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18418 	optp->level = EXPER_DVMRP;
18419 	optp->name = 0;
18420 	if (!ip_mroute_stats(mpctl->b_cont, ipst)) {
18421 		ip0dbg(("ip_mroute_stats: failed\n"));
18422 	}
18423 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18424 	ip3dbg(("ip_snmp_get_mib2_multi: level %d, name %d, len %d\n",
18425 	    (int)optp->level, (int)optp->name, (int)optp->len));
18426 	qreply(q, mpctl);
18427 	return (mp2ctl);
18428 }
18429 
18430 /* IPv4 address information */
18431 static mblk_t *
18432 ip_snmp_get_mib2_ip_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18433 {
18434 	struct opthdr		*optp;
18435 	mblk_t			*mp2ctl;
18436 	mblk_t			*mp_tail = NULL;
18437 	ill_t			*ill;
18438 	ipif_t			*ipif;
18439 	uint_t			bitval;
18440 	mib2_ipAddrEntry_t	mae;
18441 	zoneid_t		zoneid;
18442 	ill_walk_context_t ctx;
18443 
18444 	/*
18445 	 * make a copy of the original message
18446 	 */
18447 	mp2ctl = copymsg(mpctl);
18448 
18449 	/* ipAddrEntryTable */
18450 
18451 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18452 	optp->level = MIB2_IP;
18453 	optp->name = MIB2_IP_ADDR;
18454 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18455 
18456 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18457 	ill = ILL_START_WALK_V4(&ctx, ipst);
18458 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18459 		for (ipif = ill->ill_ipif; ipif != NULL;
18460 		    ipif = ipif->ipif_next) {
18461 			if (ipif->ipif_zoneid != zoneid &&
18462 			    ipif->ipif_zoneid != ALL_ZONES)
18463 				continue;
18464 			mae.ipAdEntInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18465 			mae.ipAdEntInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18466 			mae.ipAdEntInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18467 
18468 			ipif_get_name(ipif, mae.ipAdEntIfIndex.o_bytes,
18469 			    OCTET_LENGTH);
18470 			mae.ipAdEntIfIndex.o_length =
18471 			    mi_strlen(mae.ipAdEntIfIndex.o_bytes);
18472 			mae.ipAdEntAddr = ipif->ipif_lcl_addr;
18473 			mae.ipAdEntNetMask = ipif->ipif_net_mask;
18474 			mae.ipAdEntInfo.ae_subnet = ipif->ipif_subnet;
18475 			mae.ipAdEntInfo.ae_subnet_len =
18476 			    ip_mask_to_plen(ipif->ipif_net_mask);
18477 			mae.ipAdEntInfo.ae_src_addr = ipif->ipif_src_addr;
18478 			for (bitval = 1;
18479 			    bitval &&
18480 			    !(bitval & ipif->ipif_brd_addr);
18481 			    bitval <<= 1)
18482 				noop;
18483 			mae.ipAdEntBcastAddr = bitval;
18484 			mae.ipAdEntReasmMaxSize = IP_MAXPACKET;
18485 			mae.ipAdEntInfo.ae_mtu = ipif->ipif_mtu;
18486 			mae.ipAdEntInfo.ae_metric  = ipif->ipif_metric;
18487 			mae.ipAdEntInfo.ae_broadcast_addr =
18488 			    ipif->ipif_brd_addr;
18489 			mae.ipAdEntInfo.ae_pp_dst_addr =
18490 			    ipif->ipif_pp_dst_addr;
18491 			mae.ipAdEntInfo.ae_flags = ipif->ipif_flags |
18492 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18493 			mae.ipAdEntRetransmitTime = AR_EQ_DEFAULT_XMIT_INTERVAL;
18494 
18495 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18496 			    (char *)&mae, (int)sizeof (mib2_ipAddrEntry_t))) {
18497 				ip1dbg(("ip_snmp_get_mib2_ip_addr: failed to "
18498 				    "allocate %u bytes\n",
18499 				    (uint_t)sizeof (mib2_ipAddrEntry_t)));
18500 			}
18501 		}
18502 	}
18503 	rw_exit(&ipst->ips_ill_g_lock);
18504 
18505 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18506 	ip3dbg(("ip_snmp_get_mib2_ip_addr: level %d, name %d, len %d\n",
18507 	    (int)optp->level, (int)optp->name, (int)optp->len));
18508 	qreply(q, mpctl);
18509 	return (mp2ctl);
18510 }
18511 
18512 /* IPv6 address information */
18513 static mblk_t *
18514 ip_snmp_get_mib2_ip6_addr(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18515 {
18516 	struct opthdr		*optp;
18517 	mblk_t			*mp2ctl;
18518 	mblk_t			*mp_tail = NULL;
18519 	ill_t			*ill;
18520 	ipif_t			*ipif;
18521 	mib2_ipv6AddrEntry_t	mae6;
18522 	zoneid_t		zoneid;
18523 	ill_walk_context_t	ctx;
18524 
18525 	/*
18526 	 * make a copy of the original message
18527 	 */
18528 	mp2ctl = copymsg(mpctl);
18529 
18530 	/* ipv6AddrEntryTable */
18531 
18532 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18533 	optp->level = MIB2_IP6;
18534 	optp->name = MIB2_IP6_ADDR;
18535 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18536 
18537 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18538 	ill = ILL_START_WALK_V6(&ctx, ipst);
18539 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18540 		for (ipif = ill->ill_ipif; ipif != NULL;
18541 		    ipif = ipif->ipif_next) {
18542 			if (ipif->ipif_zoneid != zoneid &&
18543 			    ipif->ipif_zoneid != ALL_ZONES)
18544 				continue;
18545 			mae6.ipv6AddrInfo.ae_ibcnt = ipif->ipif_ib_pkt_count;
18546 			mae6.ipv6AddrInfo.ae_obcnt = ipif->ipif_ob_pkt_count;
18547 			mae6.ipv6AddrInfo.ae_focnt = ipif->ipif_fo_pkt_count;
18548 
18549 			ipif_get_name(ipif, mae6.ipv6AddrIfIndex.o_bytes,
18550 			    OCTET_LENGTH);
18551 			mae6.ipv6AddrIfIndex.o_length =
18552 			    mi_strlen(mae6.ipv6AddrIfIndex.o_bytes);
18553 			mae6.ipv6AddrAddress = ipif->ipif_v6lcl_addr;
18554 			mae6.ipv6AddrPfxLength =
18555 			    ip_mask_to_plen_v6(&ipif->ipif_v6net_mask);
18556 			mae6.ipv6AddrInfo.ae_subnet = ipif->ipif_v6subnet;
18557 			mae6.ipv6AddrInfo.ae_subnet_len =
18558 			    mae6.ipv6AddrPfxLength;
18559 			mae6.ipv6AddrInfo.ae_src_addr = ipif->ipif_v6src_addr;
18560 
18561 			/* Type: stateless(1), stateful(2), unknown(3) */
18562 			if (ipif->ipif_flags & IPIF_ADDRCONF)
18563 				mae6.ipv6AddrType = 1;
18564 			else
18565 				mae6.ipv6AddrType = 2;
18566 			/* Anycast: true(1), false(2) */
18567 			if (ipif->ipif_flags & IPIF_ANYCAST)
18568 				mae6.ipv6AddrAnycastFlag = 1;
18569 			else
18570 				mae6.ipv6AddrAnycastFlag = 2;
18571 
18572 			/*
18573 			 * Address status: preferred(1), deprecated(2),
18574 			 * invalid(3), inaccessible(4), unknown(5)
18575 			 */
18576 			if (ipif->ipif_flags & IPIF_NOLOCAL)
18577 				mae6.ipv6AddrStatus = 3;
18578 			else if (ipif->ipif_flags & IPIF_DEPRECATED)
18579 				mae6.ipv6AddrStatus = 2;
18580 			else
18581 				mae6.ipv6AddrStatus = 1;
18582 			mae6.ipv6AddrInfo.ae_mtu = ipif->ipif_mtu;
18583 			mae6.ipv6AddrInfo.ae_metric  = ipif->ipif_metric;
18584 			mae6.ipv6AddrInfo.ae_pp_dst_addr =
18585 			    ipif->ipif_v6pp_dst_addr;
18586 			mae6.ipv6AddrInfo.ae_flags = ipif->ipif_flags |
18587 			    ill->ill_flags | ill->ill_phyint->phyint_flags;
18588 			mae6.ipv6AddrReasmMaxSize = IP_MAXPACKET;
18589 			mae6.ipv6AddrIdentifier = ill->ill_token;
18590 			mae6.ipv6AddrIdentifierLen = ill->ill_token_length;
18591 			mae6.ipv6AddrReachableTime = ill->ill_reachable_time;
18592 			mae6.ipv6AddrRetransmitTime =
18593 			    ill->ill_reachable_retrans_time;
18594 			if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18595 			    (char *)&mae6,
18596 			    (int)sizeof (mib2_ipv6AddrEntry_t))) {
18597 				ip1dbg(("ip_snmp_get_mib2_ip6_addr: failed to "
18598 				    "allocate %u bytes\n",
18599 				    (uint_t)sizeof (mib2_ipv6AddrEntry_t)));
18600 			}
18601 		}
18602 	}
18603 	rw_exit(&ipst->ips_ill_g_lock);
18604 
18605 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18606 	ip3dbg(("ip_snmp_get_mib2_ip6_addr: level %d, name %d, len %d\n",
18607 	    (int)optp->level, (int)optp->name, (int)optp->len));
18608 	qreply(q, mpctl);
18609 	return (mp2ctl);
18610 }
18611 
18612 /* IPv4 multicast group membership. */
18613 static mblk_t *
18614 ip_snmp_get_mib2_ip_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18615 {
18616 	struct opthdr		*optp;
18617 	mblk_t			*mp2ctl;
18618 	ill_t			*ill;
18619 	ipif_t			*ipif;
18620 	ilm_t			*ilm;
18621 	ip_member_t		ipm;
18622 	mblk_t			*mp_tail = NULL;
18623 	ill_walk_context_t	ctx;
18624 	zoneid_t		zoneid;
18625 
18626 	/*
18627 	 * make a copy of the original message
18628 	 */
18629 	mp2ctl = copymsg(mpctl);
18630 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18631 
18632 	/* ipGroupMember table */
18633 	optp = (struct opthdr *)&mpctl->b_rptr[
18634 	    sizeof (struct T_optmgmt_ack)];
18635 	optp->level = MIB2_IP;
18636 	optp->name = EXPER_IP_GROUP_MEMBERSHIP;
18637 
18638 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18639 	ill = ILL_START_WALK_V4(&ctx, ipst);
18640 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18641 		ILM_WALKER_HOLD(ill);
18642 		for (ipif = ill->ill_ipif; ipif != NULL;
18643 		    ipif = ipif->ipif_next) {
18644 			if (ipif->ipif_zoneid != zoneid &&
18645 			    ipif->ipif_zoneid != ALL_ZONES)
18646 				continue;	/* not this zone */
18647 			ipif_get_name(ipif, ipm.ipGroupMemberIfIndex.o_bytes,
18648 			    OCTET_LENGTH);
18649 			ipm.ipGroupMemberIfIndex.o_length =
18650 			    mi_strlen(ipm.ipGroupMemberIfIndex.o_bytes);
18651 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18652 				ASSERT(ilm->ilm_ipif != NULL);
18653 				ASSERT(ilm->ilm_ill == NULL);
18654 				if (ilm->ilm_ipif != ipif)
18655 					continue;
18656 				ipm.ipGroupMemberAddress = ilm->ilm_addr;
18657 				ipm.ipGroupMemberRefCnt = ilm->ilm_refcnt;
18658 				ipm.ipGroupMemberFilterMode = ilm->ilm_fmode;
18659 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18660 				    (char *)&ipm, (int)sizeof (ipm))) {
18661 					ip1dbg(("ip_snmp_get_mib2_ip_group: "
18662 					    "failed to allocate %u bytes\n",
18663 					    (uint_t)sizeof (ipm)));
18664 				}
18665 			}
18666 		}
18667 		ILM_WALKER_RELE(ill);
18668 	}
18669 	rw_exit(&ipst->ips_ill_g_lock);
18670 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18671 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18672 	    (int)optp->level, (int)optp->name, (int)optp->len));
18673 	qreply(q, mpctl);
18674 	return (mp2ctl);
18675 }
18676 
18677 /* IPv6 multicast group membership. */
18678 static mblk_t *
18679 ip_snmp_get_mib2_ip6_group_mem(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18680 {
18681 	struct opthdr		*optp;
18682 	mblk_t			*mp2ctl;
18683 	ill_t			*ill;
18684 	ilm_t			*ilm;
18685 	ipv6_member_t		ipm6;
18686 	mblk_t			*mp_tail = NULL;
18687 	ill_walk_context_t	ctx;
18688 	zoneid_t		zoneid;
18689 
18690 	/*
18691 	 * make a copy of the original message
18692 	 */
18693 	mp2ctl = copymsg(mpctl);
18694 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18695 
18696 	/* ip6GroupMember table */
18697 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18698 	optp->level = MIB2_IP6;
18699 	optp->name = EXPER_IP6_GROUP_MEMBERSHIP;
18700 
18701 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18702 	ill = ILL_START_WALK_V6(&ctx, ipst);
18703 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18704 		ILM_WALKER_HOLD(ill);
18705 		ipm6.ipv6GroupMemberIfIndex = ill->ill_phyint->phyint_ifindex;
18706 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18707 			ASSERT(ilm->ilm_ipif == NULL);
18708 			ASSERT(ilm->ilm_ill != NULL);
18709 			if (ilm->ilm_zoneid != zoneid)
18710 				continue;	/* not this zone */
18711 			ipm6.ipv6GroupMemberAddress = ilm->ilm_v6addr;
18712 			ipm6.ipv6GroupMemberRefCnt = ilm->ilm_refcnt;
18713 			ipm6.ipv6GroupMemberFilterMode = ilm->ilm_fmode;
18714 			if (!snmp_append_data2(mpctl->b_cont,
18715 			    &mp_tail,
18716 			    (char *)&ipm6, (int)sizeof (ipm6))) {
18717 				ip1dbg(("ip_snmp_get_mib2_ip6_group: "
18718 				    "failed to allocate %u bytes\n",
18719 				    (uint_t)sizeof (ipm6)));
18720 			}
18721 		}
18722 		ILM_WALKER_RELE(ill);
18723 	}
18724 	rw_exit(&ipst->ips_ill_g_lock);
18725 
18726 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18727 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18728 	    (int)optp->level, (int)optp->name, (int)optp->len));
18729 	qreply(q, mpctl);
18730 	return (mp2ctl);
18731 }
18732 
18733 /* IP multicast filtered sources */
18734 static mblk_t *
18735 ip_snmp_get_mib2_ip_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18736 {
18737 	struct opthdr		*optp;
18738 	mblk_t			*mp2ctl;
18739 	ill_t			*ill;
18740 	ipif_t			*ipif;
18741 	ilm_t			*ilm;
18742 	ip_grpsrc_t		ips;
18743 	mblk_t			*mp_tail = NULL;
18744 	ill_walk_context_t	ctx;
18745 	zoneid_t		zoneid;
18746 	int			i;
18747 	slist_t			*sl;
18748 
18749 	/*
18750 	 * make a copy of the original message
18751 	 */
18752 	mp2ctl = copymsg(mpctl);
18753 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18754 
18755 	/* ipGroupSource table */
18756 	optp = (struct opthdr *)&mpctl->b_rptr[
18757 	    sizeof (struct T_optmgmt_ack)];
18758 	optp->level = MIB2_IP;
18759 	optp->name = EXPER_IP_GROUP_SOURCES;
18760 
18761 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18762 	ill = ILL_START_WALK_V4(&ctx, ipst);
18763 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18764 		ILM_WALKER_HOLD(ill);
18765 		for (ipif = ill->ill_ipif; ipif != NULL;
18766 		    ipif = ipif->ipif_next) {
18767 			if (ipif->ipif_zoneid != zoneid)
18768 				continue;	/* not this zone */
18769 			ipif_get_name(ipif, ips.ipGroupSourceIfIndex.o_bytes,
18770 			    OCTET_LENGTH);
18771 			ips.ipGroupSourceIfIndex.o_length =
18772 			    mi_strlen(ips.ipGroupSourceIfIndex.o_bytes);
18773 			for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18774 				ASSERT(ilm->ilm_ipif != NULL);
18775 				ASSERT(ilm->ilm_ill == NULL);
18776 				sl = ilm->ilm_filter;
18777 				if (ilm->ilm_ipif != ipif || SLIST_IS_EMPTY(sl))
18778 					continue;
18779 				ips.ipGroupSourceGroup = ilm->ilm_addr;
18780 				for (i = 0; i < sl->sl_numsrc; i++) {
18781 					if (!IN6_IS_ADDR_V4MAPPED(
18782 					    &sl->sl_addr[i]))
18783 						continue;
18784 					IN6_V4MAPPED_TO_IPADDR(&sl->sl_addr[i],
18785 					    ips.ipGroupSourceAddress);
18786 					if (snmp_append_data2(mpctl->b_cont,
18787 					    &mp_tail, (char *)&ips,
18788 					    (int)sizeof (ips)) == 0) {
18789 						ip1dbg(("ip_snmp_get_mib2_"
18790 						    "ip_group_src: failed to "
18791 						    "allocate %u bytes\n",
18792 						    (uint_t)sizeof (ips)));
18793 					}
18794 				}
18795 			}
18796 		}
18797 		ILM_WALKER_RELE(ill);
18798 	}
18799 	rw_exit(&ipst->ips_ill_g_lock);
18800 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18801 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18802 	    (int)optp->level, (int)optp->name, (int)optp->len));
18803 	qreply(q, mpctl);
18804 	return (mp2ctl);
18805 }
18806 
18807 /* IPv6 multicast filtered sources. */
18808 static mblk_t *
18809 ip_snmp_get_mib2_ip6_group_src(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18810 {
18811 	struct opthdr		*optp;
18812 	mblk_t			*mp2ctl;
18813 	ill_t			*ill;
18814 	ilm_t			*ilm;
18815 	ipv6_grpsrc_t		ips6;
18816 	mblk_t			*mp_tail = NULL;
18817 	ill_walk_context_t	ctx;
18818 	zoneid_t		zoneid;
18819 	int			i;
18820 	slist_t			*sl;
18821 
18822 	/*
18823 	 * make a copy of the original message
18824 	 */
18825 	mp2ctl = copymsg(mpctl);
18826 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18827 
18828 	/* ip6GroupMember table */
18829 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18830 	optp->level = MIB2_IP6;
18831 	optp->name = EXPER_IP6_GROUP_SOURCES;
18832 
18833 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
18834 	ill = ILL_START_WALK_V6(&ctx, ipst);
18835 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
18836 		ILM_WALKER_HOLD(ill);
18837 		ips6.ipv6GroupSourceIfIndex = ill->ill_phyint->phyint_ifindex;
18838 		for (ilm = ill->ill_ilm; ilm; ilm = ilm->ilm_next) {
18839 			ASSERT(ilm->ilm_ipif == NULL);
18840 			ASSERT(ilm->ilm_ill != NULL);
18841 			sl = ilm->ilm_filter;
18842 			if (ilm->ilm_zoneid != zoneid || SLIST_IS_EMPTY(sl))
18843 				continue;
18844 			ips6.ipv6GroupSourceGroup = ilm->ilm_v6addr;
18845 			for (i = 0; i < sl->sl_numsrc; i++) {
18846 				ips6.ipv6GroupSourceAddress = sl->sl_addr[i];
18847 				if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
18848 				    (char *)&ips6, (int)sizeof (ips6))) {
18849 					ip1dbg(("ip_snmp_get_mib2_ip6_"
18850 					    "group_src: failed to allocate "
18851 					    "%u bytes\n",
18852 					    (uint_t)sizeof (ips6)));
18853 				}
18854 			}
18855 		}
18856 		ILM_WALKER_RELE(ill);
18857 	}
18858 	rw_exit(&ipst->ips_ill_g_lock);
18859 
18860 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18861 	ip3dbg(("ip_snmp_get: level %d, name %d, len %d\n",
18862 	    (int)optp->level, (int)optp->name, (int)optp->len));
18863 	qreply(q, mpctl);
18864 	return (mp2ctl);
18865 }
18866 
18867 /* Multicast routing virtual interface table. */
18868 static mblk_t *
18869 ip_snmp_get_mib2_virt_multi(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18870 {
18871 	struct opthdr		*optp;
18872 	mblk_t			*mp2ctl;
18873 
18874 	/*
18875 	 * make a copy of the original message
18876 	 */
18877 	mp2ctl = copymsg(mpctl);
18878 
18879 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18880 	optp->level = EXPER_DVMRP;
18881 	optp->name = EXPER_DVMRP_VIF;
18882 	if (!ip_mroute_vif(mpctl->b_cont, ipst)) {
18883 		ip0dbg(("ip_mroute_vif: failed\n"));
18884 	}
18885 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18886 	ip3dbg(("ip_snmp_get_mib2_virt_multi: level %d, name %d, len %d\n",
18887 	    (int)optp->level, (int)optp->name, (int)optp->len));
18888 	qreply(q, mpctl);
18889 	return (mp2ctl);
18890 }
18891 
18892 /* Multicast routing table. */
18893 static mblk_t *
18894 ip_snmp_get_mib2_multi_rtable(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18895 {
18896 	struct opthdr		*optp;
18897 	mblk_t			*mp2ctl;
18898 
18899 	/*
18900 	 * make a copy of the original message
18901 	 */
18902 	mp2ctl = copymsg(mpctl);
18903 
18904 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18905 	optp->level = EXPER_DVMRP;
18906 	optp->name = EXPER_DVMRP_MRT;
18907 	if (!ip_mroute_mrt(mpctl->b_cont, ipst)) {
18908 		ip0dbg(("ip_mroute_mrt: failed\n"));
18909 	}
18910 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
18911 	ip3dbg(("ip_snmp_get_mib2_multi_rtable: level %d, name %d, len %d\n",
18912 	    (int)optp->level, (int)optp->name, (int)optp->len));
18913 	qreply(q, mpctl);
18914 	return (mp2ctl);
18915 }
18916 
18917 /*
18918  * Return ipRouteEntryTable, ipNetToMediaEntryTable, and ipRouteAttributeTable
18919  * in one IRE walk.
18920  */
18921 static mblk_t *
18922 ip_snmp_get_mib2_ip_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18923 {
18924 	struct opthdr	*optp;
18925 	mblk_t		*mp2ctl;	/* Returned */
18926 	mblk_t		*mp3ctl;	/* nettomedia */
18927 	mblk_t		*mp4ctl;	/* routeattrs */
18928 	iproutedata_t	ird;
18929 	zoneid_t	zoneid;
18930 
18931 	/*
18932 	 * make copies of the original message
18933 	 *	- mp2ctl is returned unchanged to the caller for his use
18934 	 *	- mpctl is sent upstream as ipRouteEntryTable
18935 	 *	- mp3ctl is sent upstream as ipNetToMediaEntryTable
18936 	 *	- mp4ctl is sent upstream as ipRouteAttributeTable
18937 	 */
18938 	mp2ctl = copymsg(mpctl);
18939 	mp3ctl = copymsg(mpctl);
18940 	mp4ctl = copymsg(mpctl);
18941 	if (mp3ctl == NULL || mp4ctl == NULL) {
18942 		freemsg(mp4ctl);
18943 		freemsg(mp3ctl);
18944 		freemsg(mp2ctl);
18945 		freemsg(mpctl);
18946 		return (NULL);
18947 	}
18948 
18949 	bzero(&ird, sizeof (ird));
18950 
18951 	ird.ird_route.lp_head = mpctl->b_cont;
18952 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
18953 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
18954 
18955 	zoneid = Q_TO_CONN(q)->conn_zoneid;
18956 	ire_walk_v4(ip_snmp_get2_v4, &ird, zoneid, ipst);
18957 
18958 	/* ipRouteEntryTable in mpctl */
18959 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18960 	optp->level = MIB2_IP;
18961 	optp->name = MIB2_IP_ROUTE;
18962 	optp->len = msgdsize(ird.ird_route.lp_head);
18963 	ip3dbg(("ip_snmp_get_mib2_ip_route_media: level %d, name %d, len %d\n",
18964 	    (int)optp->level, (int)optp->name, (int)optp->len));
18965 	qreply(q, mpctl);
18966 
18967 	/* ipNetToMediaEntryTable in mp3ctl */
18968 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18969 	optp->level = MIB2_IP;
18970 	optp->name = MIB2_IP_MEDIA;
18971 	optp->len = msgdsize(ird.ird_netmedia.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, mp3ctl);
18975 
18976 	/* ipRouteAttributeTable in mp4ctl */
18977 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
18978 	optp->level = MIB2_IP;
18979 	optp->name = EXPER_IP_RTATTR;
18980 	optp->len = msgdsize(ird.ird_attrs.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 	if (optp->len == 0)
18984 		freemsg(mp4ctl);
18985 	else
18986 		qreply(q, mp4ctl);
18987 
18988 	return (mp2ctl);
18989 }
18990 
18991 /*
18992  * Return ipv6RouteEntryTable and ipv6RouteAttributeTable in one IRE walk, and
18993  * ipv6NetToMediaEntryTable in an NDP walk.
18994  */
18995 static mblk_t *
18996 ip_snmp_get_mib2_ip6_route_media(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
18997 {
18998 	struct opthdr	*optp;
18999 	mblk_t		*mp2ctl;	/* Returned */
19000 	mblk_t		*mp3ctl;	/* nettomedia */
19001 	mblk_t		*mp4ctl;	/* routeattrs */
19002 	iproutedata_t	ird;
19003 	zoneid_t	zoneid;
19004 
19005 	/*
19006 	 * make copies of the original message
19007 	 *	- mp2ctl is returned unchanged to the caller for his use
19008 	 *	- mpctl is sent upstream as ipv6RouteEntryTable
19009 	 *	- mp3ctl is sent upstream as ipv6NetToMediaEntryTable
19010 	 *	- mp4ctl is sent upstream as ipv6RouteAttributeTable
19011 	 */
19012 	mp2ctl = copymsg(mpctl);
19013 	mp3ctl = copymsg(mpctl);
19014 	mp4ctl = copymsg(mpctl);
19015 	if (mp3ctl == NULL || mp4ctl == NULL) {
19016 		freemsg(mp4ctl);
19017 		freemsg(mp3ctl);
19018 		freemsg(mp2ctl);
19019 		freemsg(mpctl);
19020 		return (NULL);
19021 	}
19022 
19023 	bzero(&ird, sizeof (ird));
19024 
19025 	ird.ird_route.lp_head = mpctl->b_cont;
19026 	ird.ird_netmedia.lp_head = mp3ctl->b_cont;
19027 	ird.ird_attrs.lp_head = mp4ctl->b_cont;
19028 
19029 	zoneid = Q_TO_CONN(q)->conn_zoneid;
19030 	ire_walk_v6(ip_snmp_get2_v6_route, &ird, zoneid, ipst);
19031 
19032 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19033 	optp->level = MIB2_IP6;
19034 	optp->name = MIB2_IP6_ROUTE;
19035 	optp->len = msgdsize(ird.ird_route.lp_head);
19036 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19037 	    (int)optp->level, (int)optp->name, (int)optp->len));
19038 	qreply(q, mpctl);
19039 
19040 	/* ipv6NetToMediaEntryTable in mp3ctl */
19041 	ndp_walk(NULL, ip_snmp_get2_v6_media, &ird, ipst);
19042 
19043 	optp = (struct opthdr *)&mp3ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19044 	optp->level = MIB2_IP6;
19045 	optp->name = MIB2_IP6_MEDIA;
19046 	optp->len = msgdsize(ird.ird_netmedia.lp_head);
19047 	ip3dbg(("ip_snmp_get_mib2_ip6_route_media: level %d, name %d, len %d\n",
19048 	    (int)optp->level, (int)optp->name, (int)optp->len));
19049 	qreply(q, mp3ctl);
19050 
19051 	/* ipv6RouteAttributeTable in mp4ctl */
19052 	optp = (struct opthdr *)&mp4ctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19053 	optp->level = MIB2_IP6;
19054 	optp->name = EXPER_IP_RTATTR;
19055 	optp->len = msgdsize(ird.ird_attrs.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 	if (optp->len == 0)
19059 		freemsg(mp4ctl);
19060 	else
19061 		qreply(q, mp4ctl);
19062 
19063 	return (mp2ctl);
19064 }
19065 
19066 /*
19067  * IPv6 mib: One per ill
19068  */
19069 static mblk_t *
19070 ip_snmp_get_mib2_ip6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19071 {
19072 	struct opthdr		*optp;
19073 	mblk_t			*mp2ctl;
19074 	ill_t			*ill;
19075 	ill_walk_context_t	ctx;
19076 	mblk_t			*mp_tail = NULL;
19077 
19078 	/*
19079 	 * Make a copy of the original message
19080 	 */
19081 	mp2ctl = copymsg(mpctl);
19082 
19083 	/* fixed length IPv6 structure ... */
19084 
19085 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19086 	optp->level = MIB2_IP6;
19087 	optp->name = 0;
19088 	/* Include "unknown interface" ip6_mib */
19089 	ipst->ips_ip6_mib.ipIfStatsIPVersion = MIB2_INETADDRESSTYPE_ipv6;
19090 	ipst->ips_ip6_mib.ipIfStatsIfIndex =
19091 	    MIB2_UNKNOWN_INTERFACE; /* Flag to netstat */
19092 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsForwarding,
19093 	    ipst->ips_ipv6_forward ? 1 : 2);
19094 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsDefaultHopLimit,
19095 	    ipst->ips_ipv6_def_hops);
19096 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsEntrySize,
19097 	    sizeof (mib2_ipIfStatsEntry_t));
19098 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsAddrEntrySize,
19099 	    sizeof (mib2_ipv6AddrEntry_t));
19100 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsRouteEntrySize,
19101 	    sizeof (mib2_ipv6RouteEntry_t));
19102 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsNetToMediaEntrySize,
19103 	    sizeof (mib2_ipv6NetToMediaEntry_t));
19104 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsMemberEntrySize,
19105 	    sizeof (ipv6_member_t));
19106 	SET_MIB(ipst->ips_ip6_mib.ipIfStatsGroupSourceEntrySize,
19107 	    sizeof (ipv6_grpsrc_t));
19108 
19109 	/*
19110 	 * Synchronize 64- and 32-bit counters
19111 	 */
19112 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInReceives,
19113 	    ipIfStatsHCInReceives);
19114 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInDelivers,
19115 	    ipIfStatsHCInDelivers);
19116 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutRequests,
19117 	    ipIfStatsHCOutRequests);
19118 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutForwDatagrams,
19119 	    ipIfStatsHCOutForwDatagrams);
19120 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsOutMcastPkts,
19121 	    ipIfStatsHCOutMcastPkts);
19122 	SYNC32_MIB(&ipst->ips_ip6_mib, ipIfStatsInMcastPkts,
19123 	    ipIfStatsHCInMcastPkts);
19124 
19125 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19126 	    (char *)&ipst->ips_ip6_mib, (int)sizeof (ipst->ips_ip6_mib))) {
19127 		ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate %u bytes\n",
19128 		    (uint_t)sizeof (ipst->ips_ip6_mib)));
19129 	}
19130 
19131 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19132 	ill = ILL_START_WALK_V6(&ctx, ipst);
19133 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19134 		ill->ill_ip_mib->ipIfStatsIfIndex =
19135 		    ill->ill_phyint->phyint_ifindex;
19136 		SET_MIB(ill->ill_ip_mib->ipIfStatsForwarding,
19137 		    ipst->ips_ipv6_forward ? 1 : 2);
19138 		SET_MIB(ill->ill_ip_mib->ipIfStatsDefaultHopLimit,
19139 		    ill->ill_max_hops);
19140 
19141 		/*
19142 		 * Synchronize 64- and 32-bit counters
19143 		 */
19144 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInReceives,
19145 		    ipIfStatsHCInReceives);
19146 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInDelivers,
19147 		    ipIfStatsHCInDelivers);
19148 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutRequests,
19149 		    ipIfStatsHCOutRequests);
19150 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutForwDatagrams,
19151 		    ipIfStatsHCOutForwDatagrams);
19152 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsOutMcastPkts,
19153 		    ipIfStatsHCOutMcastPkts);
19154 		SYNC32_MIB(ill->ill_ip_mib, ipIfStatsInMcastPkts,
19155 		    ipIfStatsHCInMcastPkts);
19156 
19157 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19158 		    (char *)ill->ill_ip_mib,
19159 		    (int)sizeof (*ill->ill_ip_mib))) {
19160 			ip1dbg(("ip_snmp_get_mib2_ip6: failed to allocate "
19161 			"%u bytes\n", (uint_t)sizeof (*ill->ill_ip_mib)));
19162 		}
19163 	}
19164 	rw_exit(&ipst->ips_ill_g_lock);
19165 
19166 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19167 	ip3dbg(("ip_snmp_get_mib2_ip6: level %d, name %d, len %d\n",
19168 	    (int)optp->level, (int)optp->name, (int)optp->len));
19169 	qreply(q, mpctl);
19170 	return (mp2ctl);
19171 }
19172 
19173 /*
19174  * ICMPv6 mib: One per ill
19175  */
19176 static mblk_t *
19177 ip_snmp_get_mib2_icmp6(queue_t *q, mblk_t *mpctl, ip_stack_t *ipst)
19178 {
19179 	struct opthdr		*optp;
19180 	mblk_t			*mp2ctl;
19181 	ill_t			*ill;
19182 	ill_walk_context_t	ctx;
19183 	mblk_t			*mp_tail = NULL;
19184 	/*
19185 	 * Make a copy of the original message
19186 	 */
19187 	mp2ctl = copymsg(mpctl);
19188 
19189 	/* fixed length ICMPv6 structure ... */
19190 
19191 	optp = (struct opthdr *)&mpctl->b_rptr[sizeof (struct T_optmgmt_ack)];
19192 	optp->level = MIB2_ICMP6;
19193 	optp->name = 0;
19194 	/* Include "unknown interface" icmp6_mib */
19195 	ipst->ips_icmp6_mib.ipv6IfIcmpIfIndex =
19196 	    MIB2_UNKNOWN_INTERFACE; /* netstat flag */
19197 	ipst->ips_icmp6_mib.ipv6IfIcmpEntrySize =
19198 	    sizeof (mib2_ipv6IfIcmpEntry_t);
19199 	if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19200 	    (char *)&ipst->ips_icmp6_mib,
19201 	    (int)sizeof (ipst->ips_icmp6_mib))) {
19202 		ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate %u bytes\n",
19203 		    (uint_t)sizeof (ipst->ips_icmp6_mib)));
19204 	}
19205 
19206 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
19207 	ill = ILL_START_WALK_V6(&ctx, ipst);
19208 	for (; ill != NULL; ill = ill_next(&ctx, ill)) {
19209 		ill->ill_icmp6_mib->ipv6IfIcmpIfIndex =
19210 		    ill->ill_phyint->phyint_ifindex;
19211 		if (!snmp_append_data2(mpctl->b_cont, &mp_tail,
19212 		    (char *)ill->ill_icmp6_mib,
19213 		    (int)sizeof (*ill->ill_icmp6_mib))) {
19214 			ip1dbg(("ip_snmp_get_mib2_icmp6: failed to allocate "
19215 			    "%u bytes\n",
19216 			    (uint_t)sizeof (*ill->ill_icmp6_mib)));
19217 		}
19218 	}
19219 	rw_exit(&ipst->ips_ill_g_lock);
19220 
19221 	optp->len = (t_uscalar_t)msgdsize(mpctl->b_cont);
19222 	ip3dbg(("ip_snmp_get_mib2_icmp6: level %d, name %d, len %d\n",
19223 	    (int)optp->level, (int)optp->name, (int)optp->len));
19224 	qreply(q, mpctl);
19225 	return (mp2ctl);
19226 }
19227 
19228 /*
19229  * ire_walk routine to create both ipRouteEntryTable and
19230  * ipRouteAttributeTable in one IRE walk
19231  */
19232 static void
19233 ip_snmp_get2_v4(ire_t *ire, iproutedata_t *ird)
19234 {
19235 	ill_t				*ill;
19236 	ipif_t				*ipif;
19237 	mib2_ipRouteEntry_t		*re;
19238 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19239 	ipaddr_t			gw_addr;
19240 	tsol_ire_gw_secattr_t		*attrp;
19241 	tsol_gc_t			*gc = NULL;
19242 	tsol_gcgrp_t			*gcgrp = NULL;
19243 	uint_t				sacnt = 0;
19244 	int				i;
19245 
19246 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
19247 
19248 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19249 		return;
19250 
19251 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19252 		mutex_enter(&attrp->igsa_lock);
19253 		if ((gc = attrp->igsa_gc) != NULL) {
19254 			gcgrp = gc->gc_grp;
19255 			ASSERT(gcgrp != NULL);
19256 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19257 			sacnt = 1;
19258 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19259 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19260 			gc = gcgrp->gcgrp_head;
19261 			sacnt = gcgrp->gcgrp_count;
19262 		}
19263 		mutex_exit(&attrp->igsa_lock);
19264 
19265 		/* do nothing if there's no gc to report */
19266 		if (gc == NULL) {
19267 			ASSERT(sacnt == 0);
19268 			if (gcgrp != NULL) {
19269 				/* we might as well drop the lock now */
19270 				rw_exit(&gcgrp->gcgrp_rwlock);
19271 				gcgrp = NULL;
19272 			}
19273 			attrp = NULL;
19274 		}
19275 
19276 		ASSERT(gc == NULL || (gcgrp != NULL &&
19277 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19278 	}
19279 	ASSERT(sacnt == 0 || gc != NULL);
19280 
19281 	if (sacnt != 0 &&
19282 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19283 		kmem_free(re, sizeof (*re));
19284 		rw_exit(&gcgrp->gcgrp_rwlock);
19285 		return;
19286 	}
19287 
19288 	/*
19289 	 * Return all IRE types for route table... let caller pick and choose
19290 	 */
19291 	re->ipRouteDest = ire->ire_addr;
19292 	ipif = ire->ire_ipif;
19293 	re->ipRouteIfIndex.o_length = 0;
19294 	if (ire->ire_type == IRE_CACHE) {
19295 		ill = (ill_t *)ire->ire_stq->q_ptr;
19296 		re->ipRouteIfIndex.o_length =
19297 		    ill->ill_name_length == 0 ? 0 :
19298 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19299 		bcopy(ill->ill_name, re->ipRouteIfIndex.o_bytes,
19300 		    re->ipRouteIfIndex.o_length);
19301 	} else if (ipif != NULL) {
19302 		ipif_get_name(ipif, re->ipRouteIfIndex.o_bytes, OCTET_LENGTH);
19303 		re->ipRouteIfIndex.o_length =
19304 		    mi_strlen(re->ipRouteIfIndex.o_bytes);
19305 	}
19306 	re->ipRouteMetric1 = -1;
19307 	re->ipRouteMetric2 = -1;
19308 	re->ipRouteMetric3 = -1;
19309 	re->ipRouteMetric4 = -1;
19310 
19311 	gw_addr = ire->ire_gateway_addr;
19312 
19313 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK|IRE_BROADCAST))
19314 		re->ipRouteNextHop = ire->ire_src_addr;
19315 	else
19316 		re->ipRouteNextHop = gw_addr;
19317 	/* indirect(4), direct(3), or invalid(2) */
19318 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19319 		re->ipRouteType = 2;
19320 	else
19321 		re->ipRouteType = (gw_addr != 0) ? 4 : 3;
19322 	re->ipRouteProto = -1;
19323 	re->ipRouteAge = gethrestime_sec() - ire->ire_create_time;
19324 	re->ipRouteMask = ire->ire_mask;
19325 	re->ipRouteMetric5 = -1;
19326 	re->ipRouteInfo.re_max_frag	= ire->ire_max_frag;
19327 	re->ipRouteInfo.re_frag_flag	= ire->ire_frag_flag;
19328 	re->ipRouteInfo.re_rtt		= ire->ire_uinfo.iulp_rtt;
19329 	re->ipRouteInfo.re_ref		= ire->ire_refcnt;
19330 	re->ipRouteInfo.re_src_addr	= ire->ire_src_addr;
19331 	re->ipRouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19332 	re->ipRouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19333 	re->ipRouteInfo.re_flags	= ire->ire_flags;
19334 
19335 	if (ire->ire_flags & RTF_DYNAMIC) {
19336 		re->ipRouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19337 	} else {
19338 		re->ipRouteInfo.re_ire_type	= ire->ire_type;
19339 	}
19340 
19341 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19342 	    (char *)re, (int)sizeof (*re))) {
19343 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19344 		    (uint_t)sizeof (*re)));
19345 	}
19346 
19347 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19348 		iaeptr->iae_routeidx = ird->ird_idx;
19349 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19350 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19351 	}
19352 
19353 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19354 	    (char *)iae, sacnt * sizeof (*iae))) {
19355 		ip1dbg(("ip_snmp_get2_v4: failed to allocate %u bytes\n",
19356 		    (unsigned)(sacnt * sizeof (*iae))));
19357 	}
19358 
19359 	/* bump route index for next pass */
19360 	ird->ird_idx++;
19361 
19362 	kmem_free(re, sizeof (*re));
19363 	if (sacnt != 0)
19364 		kmem_free(iae, sacnt * sizeof (*iae));
19365 
19366 	if (gcgrp != NULL)
19367 		rw_exit(&gcgrp->gcgrp_rwlock);
19368 }
19369 
19370 /*
19371  * ire_walk routine to create ipv6RouteEntryTable and ipRouteEntryTable.
19372  */
19373 static void
19374 ip_snmp_get2_v6_route(ire_t *ire, iproutedata_t *ird)
19375 {
19376 	ill_t				*ill;
19377 	ipif_t				*ipif;
19378 	mib2_ipv6RouteEntry_t		*re;
19379 	mib2_ipAttributeEntry_t		*iae, *iaeptr;
19380 	in6_addr_t			gw_addr_v6;
19381 	tsol_ire_gw_secattr_t		*attrp;
19382 	tsol_gc_t			*gc = NULL;
19383 	tsol_gcgrp_t			*gcgrp = NULL;
19384 	uint_t				sacnt = 0;
19385 	int				i;
19386 
19387 	ASSERT(ire->ire_ipversion == IPV6_VERSION);
19388 
19389 	if ((re = kmem_zalloc(sizeof (*re), KM_NOSLEEP)) == NULL)
19390 		return;
19391 
19392 	if ((attrp = ire->ire_gw_secattr) != NULL) {
19393 		mutex_enter(&attrp->igsa_lock);
19394 		if ((gc = attrp->igsa_gc) != NULL) {
19395 			gcgrp = gc->gc_grp;
19396 			ASSERT(gcgrp != NULL);
19397 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19398 			sacnt = 1;
19399 		} else if ((gcgrp = attrp->igsa_gcgrp) != NULL) {
19400 			rw_enter(&gcgrp->gcgrp_rwlock, RW_READER);
19401 			gc = gcgrp->gcgrp_head;
19402 			sacnt = gcgrp->gcgrp_count;
19403 		}
19404 		mutex_exit(&attrp->igsa_lock);
19405 
19406 		/* do nothing if there's no gc to report */
19407 		if (gc == NULL) {
19408 			ASSERT(sacnt == 0);
19409 			if (gcgrp != NULL) {
19410 				/* we might as well drop the lock now */
19411 				rw_exit(&gcgrp->gcgrp_rwlock);
19412 				gcgrp = NULL;
19413 			}
19414 			attrp = NULL;
19415 		}
19416 
19417 		ASSERT(gc == NULL || (gcgrp != NULL &&
19418 		    RW_LOCK_HELD(&gcgrp->gcgrp_rwlock)));
19419 	}
19420 	ASSERT(sacnt == 0 || gc != NULL);
19421 
19422 	if (sacnt != 0 &&
19423 	    (iae = kmem_alloc(sacnt * sizeof (*iae), KM_NOSLEEP)) == NULL) {
19424 		kmem_free(re, sizeof (*re));
19425 		rw_exit(&gcgrp->gcgrp_rwlock);
19426 		return;
19427 	}
19428 
19429 	/*
19430 	 * Return all IRE types for route table... let caller pick and choose
19431 	 */
19432 	re->ipv6RouteDest = ire->ire_addr_v6;
19433 	re->ipv6RoutePfxLength = ip_mask_to_plen_v6(&ire->ire_mask_v6);
19434 	re->ipv6RouteIndex = 0;	/* Unique when multiple with same dest/plen */
19435 	re->ipv6RouteIfIndex.o_length = 0;
19436 	ipif = ire->ire_ipif;
19437 	if (ire->ire_type == IRE_CACHE) {
19438 		ill = (ill_t *)ire->ire_stq->q_ptr;
19439 		re->ipv6RouteIfIndex.o_length =
19440 		    ill->ill_name_length == 0 ? 0 :
19441 		    MIN(OCTET_LENGTH, ill->ill_name_length - 1);
19442 		bcopy(ill->ill_name, re->ipv6RouteIfIndex.o_bytes,
19443 		    re->ipv6RouteIfIndex.o_length);
19444 	} else if (ipif != NULL) {
19445 		ipif_get_name(ipif, re->ipv6RouteIfIndex.o_bytes, OCTET_LENGTH);
19446 		re->ipv6RouteIfIndex.o_length =
19447 		    mi_strlen(re->ipv6RouteIfIndex.o_bytes);
19448 	}
19449 
19450 	ASSERT(!(ire->ire_type & IRE_BROADCAST));
19451 
19452 	mutex_enter(&ire->ire_lock);
19453 	gw_addr_v6 = ire->ire_gateway_addr_v6;
19454 	mutex_exit(&ire->ire_lock);
19455 
19456 	if (ire->ire_type & (IRE_INTERFACE|IRE_LOOPBACK))
19457 		re->ipv6RouteNextHop = ire->ire_src_addr_v6;
19458 	else
19459 		re->ipv6RouteNextHop = gw_addr_v6;
19460 
19461 	/* remote(4), local(3), or discard(2) */
19462 	if (ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE))
19463 		re->ipv6RouteType = 2;
19464 	else if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6))
19465 		re->ipv6RouteType = 3;
19466 	else
19467 		re->ipv6RouteType = 4;
19468 
19469 	re->ipv6RouteProtocol	= -1;
19470 	re->ipv6RoutePolicy	= 0;
19471 	re->ipv6RouteAge	= gethrestime_sec() - ire->ire_create_time;
19472 	re->ipv6RouteNextHopRDI	= 0;
19473 	re->ipv6RouteWeight	= 0;
19474 	re->ipv6RouteMetric	= 0;
19475 	re->ipv6RouteInfo.re_max_frag	= ire->ire_max_frag;
19476 	re->ipv6RouteInfo.re_frag_flag	= ire->ire_frag_flag;
19477 	re->ipv6RouteInfo.re_rtt	= ire->ire_uinfo.iulp_rtt;
19478 	re->ipv6RouteInfo.re_src_addr	= ire->ire_src_addr_v6;
19479 	re->ipv6RouteInfo.re_obpkt	= ire->ire_ob_pkt_count;
19480 	re->ipv6RouteInfo.re_ibpkt	= ire->ire_ib_pkt_count;
19481 	re->ipv6RouteInfo.re_ref	= ire->ire_refcnt;
19482 	re->ipv6RouteInfo.re_flags	= ire->ire_flags;
19483 
19484 	if (ire->ire_flags & RTF_DYNAMIC) {
19485 		re->ipv6RouteInfo.re_ire_type	= IRE_HOST_REDIRECT;
19486 	} else {
19487 		re->ipv6RouteInfo.re_ire_type	= ire->ire_type;
19488 	}
19489 
19490 	if (!snmp_append_data2(ird->ird_route.lp_head, &ird->ird_route.lp_tail,
19491 	    (char *)re, (int)sizeof (*re))) {
19492 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19493 		    (uint_t)sizeof (*re)));
19494 	}
19495 
19496 	for (iaeptr = iae, i = 0; i < sacnt; i++, iaeptr++, gc = gc->gc_next) {
19497 		iaeptr->iae_routeidx = ird->ird_idx;
19498 		iaeptr->iae_doi = gc->gc_db->gcdb_doi;
19499 		iaeptr->iae_slrange = gc->gc_db->gcdb_slrange;
19500 	}
19501 
19502 	if (!snmp_append_data2(ird->ird_attrs.lp_head, &ird->ird_attrs.lp_tail,
19503 	    (char *)iae, sacnt * sizeof (*iae))) {
19504 		ip1dbg(("ip_snmp_get2_v6: failed to allocate %u bytes\n",
19505 		    (unsigned)(sacnt * sizeof (*iae))));
19506 	}
19507 
19508 	/* bump route index for next pass */
19509 	ird->ird_idx++;
19510 
19511 	kmem_free(re, sizeof (*re));
19512 	if (sacnt != 0)
19513 		kmem_free(iae, sacnt * sizeof (*iae));
19514 
19515 	if (gcgrp != NULL)
19516 		rw_exit(&gcgrp->gcgrp_rwlock);
19517 }
19518 
19519 /*
19520  * ndp_walk routine to create ipv6NetToMediaEntryTable
19521  */
19522 static int
19523 ip_snmp_get2_v6_media(nce_t *nce, iproutedata_t *ird)
19524 {
19525 	ill_t				*ill;
19526 	mib2_ipv6NetToMediaEntry_t	ntme;
19527 	dl_unitdata_req_t		*dl;
19528 
19529 	ill = nce->nce_ill;
19530 	if (ill->ill_isv6 == B_FALSE) /* skip arpce entry */
19531 		return (0);
19532 
19533 	/*
19534 	 * Neighbor cache entry attached to IRE with on-link
19535 	 * destination.
19536 	 */
19537 	ntme.ipv6NetToMediaIfIndex = ill->ill_phyint->phyint_ifindex;
19538 	ntme.ipv6NetToMediaNetAddress = nce->nce_addr;
19539 	if ((ill->ill_flags & ILLF_XRESOLV) &&
19540 	    (nce->nce_res_mp != NULL)) {
19541 		dl = (dl_unitdata_req_t *)(nce->nce_res_mp->b_rptr);
19542 		ntme.ipv6NetToMediaPhysAddress.o_length =
19543 		    dl->dl_dest_addr_length;
19544 	} else {
19545 		ntme.ipv6NetToMediaPhysAddress.o_length =
19546 		    ill->ill_phys_addr_length;
19547 	}
19548 	if (nce->nce_res_mp != NULL) {
19549 		bcopy((char *)nce->nce_res_mp->b_rptr +
19550 		    NCE_LL_ADDR_OFFSET(ill),
19551 		    ntme.ipv6NetToMediaPhysAddress.o_bytes,
19552 		    ntme.ipv6NetToMediaPhysAddress.o_length);
19553 	} else {
19554 		bzero(ntme.ipv6NetToMediaPhysAddress.o_bytes,
19555 		    ill->ill_phys_addr_length);
19556 	}
19557 	/*
19558 	 * Note: Returns ND_* states. Should be:
19559 	 * reachable(1), stale(2), delay(3), probe(4),
19560 	 * invalid(5), unknown(6)
19561 	 */
19562 	ntme.ipv6NetToMediaState = nce->nce_state;
19563 	ntme.ipv6NetToMediaLastUpdated = 0;
19564 
19565 	/* other(1), dynamic(2), static(3), local(4) */
19566 	if (IN6_IS_ADDR_LOOPBACK(&nce->nce_addr)) {
19567 		ntme.ipv6NetToMediaType = 4;
19568 	} else if (IN6_IS_ADDR_MULTICAST(&nce->nce_addr)) {
19569 		ntme.ipv6NetToMediaType = 1;
19570 	} else {
19571 		ntme.ipv6NetToMediaType = 2;
19572 	}
19573 
19574 	if (!snmp_append_data2(ird->ird_netmedia.lp_head,
19575 	    &ird->ird_netmedia.lp_tail, (char *)&ntme, sizeof (ntme))) {
19576 		ip1dbg(("ip_snmp_get2_v6_media: failed to allocate %u bytes\n",
19577 		    (uint_t)sizeof (ntme)));
19578 	}
19579 	return (0);
19580 }
19581 
19582 /*
19583  * return (0) if invalid set request, 1 otherwise, including non-tcp requests
19584  */
19585 /* ARGSUSED */
19586 int
19587 ip_snmp_set(queue_t *q, int level, int name, uchar_t *ptr, int len)
19588 {
19589 	switch (level) {
19590 	case MIB2_IP:
19591 	case MIB2_ICMP:
19592 		switch (name) {
19593 		default:
19594 			break;
19595 		}
19596 		return (1);
19597 	default:
19598 		return (1);
19599 	}
19600 }
19601 
19602 /*
19603  * When there exists both a 64- and 32-bit counter of a particular type
19604  * (i.e., InReceives), only the 64-bit counters are added.
19605  */
19606 void
19607 ip_mib2_add_ip_stats(mib2_ipIfStatsEntry_t *o1, mib2_ipIfStatsEntry_t *o2)
19608 {
19609 	UPDATE_MIB(o1, ipIfStatsInHdrErrors, o2->ipIfStatsInHdrErrors);
19610 	UPDATE_MIB(o1, ipIfStatsInTooBigErrors, o2->ipIfStatsInTooBigErrors);
19611 	UPDATE_MIB(o1, ipIfStatsInNoRoutes, o2->ipIfStatsInNoRoutes);
19612 	UPDATE_MIB(o1, ipIfStatsInAddrErrors, o2->ipIfStatsInAddrErrors);
19613 	UPDATE_MIB(o1, ipIfStatsInUnknownProtos, o2->ipIfStatsInUnknownProtos);
19614 	UPDATE_MIB(o1, ipIfStatsInTruncatedPkts, o2->ipIfStatsInTruncatedPkts);
19615 	UPDATE_MIB(o1, ipIfStatsInDiscards, o2->ipIfStatsInDiscards);
19616 	UPDATE_MIB(o1, ipIfStatsOutDiscards, o2->ipIfStatsOutDiscards);
19617 	UPDATE_MIB(o1, ipIfStatsOutFragOKs, o2->ipIfStatsOutFragOKs);
19618 	UPDATE_MIB(o1, ipIfStatsOutFragFails, o2->ipIfStatsOutFragFails);
19619 	UPDATE_MIB(o1, ipIfStatsOutFragCreates, o2->ipIfStatsOutFragCreates);
19620 	UPDATE_MIB(o1, ipIfStatsReasmReqds, o2->ipIfStatsReasmReqds);
19621 	UPDATE_MIB(o1, ipIfStatsReasmOKs, o2->ipIfStatsReasmOKs);
19622 	UPDATE_MIB(o1, ipIfStatsReasmFails, o2->ipIfStatsReasmFails);
19623 	UPDATE_MIB(o1, ipIfStatsOutNoRoutes, o2->ipIfStatsOutNoRoutes);
19624 	UPDATE_MIB(o1, ipIfStatsReasmDuplicates, o2->ipIfStatsReasmDuplicates);
19625 	UPDATE_MIB(o1, ipIfStatsReasmPartDups, o2->ipIfStatsReasmPartDups);
19626 	UPDATE_MIB(o1, ipIfStatsForwProhibits, o2->ipIfStatsForwProhibits);
19627 	UPDATE_MIB(o1, udpInCksumErrs, o2->udpInCksumErrs);
19628 	UPDATE_MIB(o1, udpInOverflows, o2->udpInOverflows);
19629 	UPDATE_MIB(o1, rawipInOverflows, o2->rawipInOverflows);
19630 	UPDATE_MIB(o1, ipIfStatsInWrongIPVersion,
19631 	    o2->ipIfStatsInWrongIPVersion);
19632 	UPDATE_MIB(o1, ipIfStatsOutWrongIPVersion,
19633 	    o2->ipIfStatsInWrongIPVersion);
19634 	UPDATE_MIB(o1, ipIfStatsOutSwitchIPVersion,
19635 	    o2->ipIfStatsOutSwitchIPVersion);
19636 	UPDATE_MIB(o1, ipIfStatsHCInReceives, o2->ipIfStatsHCInReceives);
19637 	UPDATE_MIB(o1, ipIfStatsHCInOctets, o2->ipIfStatsHCInOctets);
19638 	UPDATE_MIB(o1, ipIfStatsHCInForwDatagrams,
19639 	    o2->ipIfStatsHCInForwDatagrams);
19640 	UPDATE_MIB(o1, ipIfStatsHCInDelivers, o2->ipIfStatsHCInDelivers);
19641 	UPDATE_MIB(o1, ipIfStatsHCOutRequests, o2->ipIfStatsHCOutRequests);
19642 	UPDATE_MIB(o1, ipIfStatsHCOutForwDatagrams,
19643 	    o2->ipIfStatsHCOutForwDatagrams);
19644 	UPDATE_MIB(o1, ipIfStatsOutFragReqds, o2->ipIfStatsOutFragReqds);
19645 	UPDATE_MIB(o1, ipIfStatsHCOutTransmits, o2->ipIfStatsHCOutTransmits);
19646 	UPDATE_MIB(o1, ipIfStatsHCOutOctets, o2->ipIfStatsHCOutOctets);
19647 	UPDATE_MIB(o1, ipIfStatsHCInMcastPkts, o2->ipIfStatsHCInMcastPkts);
19648 	UPDATE_MIB(o1, ipIfStatsHCInMcastOctets, o2->ipIfStatsHCInMcastOctets);
19649 	UPDATE_MIB(o1, ipIfStatsHCOutMcastPkts, o2->ipIfStatsHCOutMcastPkts);
19650 	UPDATE_MIB(o1, ipIfStatsHCOutMcastOctets,
19651 	    o2->ipIfStatsHCOutMcastOctets);
19652 	UPDATE_MIB(o1, ipIfStatsHCInBcastPkts, o2->ipIfStatsHCInBcastPkts);
19653 	UPDATE_MIB(o1, ipIfStatsHCOutBcastPkts, o2->ipIfStatsHCOutBcastPkts);
19654 	UPDATE_MIB(o1, ipsecInSucceeded, o2->ipsecInSucceeded);
19655 	UPDATE_MIB(o1, ipsecInFailed, o2->ipsecInFailed);
19656 	UPDATE_MIB(o1, ipInCksumErrs, o2->ipInCksumErrs);
19657 	UPDATE_MIB(o1, tcpInErrs, o2->tcpInErrs);
19658 	UPDATE_MIB(o1, udpNoPorts, o2->udpNoPorts);
19659 }
19660 
19661 void
19662 ip_mib2_add_icmp6_stats(mib2_ipv6IfIcmpEntry_t *o1, mib2_ipv6IfIcmpEntry_t *o2)
19663 {
19664 	UPDATE_MIB(o1, ipv6IfIcmpInMsgs, o2->ipv6IfIcmpInMsgs);
19665 	UPDATE_MIB(o1, ipv6IfIcmpInErrors, o2->ipv6IfIcmpInErrors);
19666 	UPDATE_MIB(o1, ipv6IfIcmpInDestUnreachs, o2->ipv6IfIcmpInDestUnreachs);
19667 	UPDATE_MIB(o1, ipv6IfIcmpInAdminProhibs, o2->ipv6IfIcmpInAdminProhibs);
19668 	UPDATE_MIB(o1, ipv6IfIcmpInTimeExcds, o2->ipv6IfIcmpInTimeExcds);
19669 	UPDATE_MIB(o1, ipv6IfIcmpInParmProblems, o2->ipv6IfIcmpInParmProblems);
19670 	UPDATE_MIB(o1, ipv6IfIcmpInPktTooBigs, o2->ipv6IfIcmpInPktTooBigs);
19671 	UPDATE_MIB(o1, ipv6IfIcmpInEchos, o2->ipv6IfIcmpInEchos);
19672 	UPDATE_MIB(o1, ipv6IfIcmpInEchoReplies, o2->ipv6IfIcmpInEchoReplies);
19673 	UPDATE_MIB(o1, ipv6IfIcmpInRouterSolicits,
19674 	    o2->ipv6IfIcmpInRouterSolicits);
19675 	UPDATE_MIB(o1, ipv6IfIcmpInRouterAdvertisements,
19676 	    o2->ipv6IfIcmpInRouterAdvertisements);
19677 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborSolicits,
19678 	    o2->ipv6IfIcmpInNeighborSolicits);
19679 	UPDATE_MIB(o1, ipv6IfIcmpInNeighborAdvertisements,
19680 	    o2->ipv6IfIcmpInNeighborAdvertisements);
19681 	UPDATE_MIB(o1, ipv6IfIcmpInRedirects, o2->ipv6IfIcmpInRedirects);
19682 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembQueries,
19683 	    o2->ipv6IfIcmpInGroupMembQueries);
19684 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembResponses,
19685 	    o2->ipv6IfIcmpInGroupMembResponses);
19686 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembReductions,
19687 	    o2->ipv6IfIcmpInGroupMembReductions);
19688 	UPDATE_MIB(o1, ipv6IfIcmpOutMsgs, o2->ipv6IfIcmpOutMsgs);
19689 	UPDATE_MIB(o1, ipv6IfIcmpOutErrors, o2->ipv6IfIcmpOutErrors);
19690 	UPDATE_MIB(o1, ipv6IfIcmpOutDestUnreachs,
19691 	    o2->ipv6IfIcmpOutDestUnreachs);
19692 	UPDATE_MIB(o1, ipv6IfIcmpOutAdminProhibs,
19693 	    o2->ipv6IfIcmpOutAdminProhibs);
19694 	UPDATE_MIB(o1, ipv6IfIcmpOutTimeExcds, o2->ipv6IfIcmpOutTimeExcds);
19695 	UPDATE_MIB(o1, ipv6IfIcmpOutParmProblems,
19696 	    o2->ipv6IfIcmpOutParmProblems);
19697 	UPDATE_MIB(o1, ipv6IfIcmpOutPktTooBigs, o2->ipv6IfIcmpOutPktTooBigs);
19698 	UPDATE_MIB(o1, ipv6IfIcmpOutEchos, o2->ipv6IfIcmpOutEchos);
19699 	UPDATE_MIB(o1, ipv6IfIcmpOutEchoReplies, o2->ipv6IfIcmpOutEchoReplies);
19700 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterSolicits,
19701 	    o2->ipv6IfIcmpOutRouterSolicits);
19702 	UPDATE_MIB(o1, ipv6IfIcmpOutRouterAdvertisements,
19703 	    o2->ipv6IfIcmpOutRouterAdvertisements);
19704 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborSolicits,
19705 	    o2->ipv6IfIcmpOutNeighborSolicits);
19706 	UPDATE_MIB(o1, ipv6IfIcmpOutNeighborAdvertisements,
19707 	    o2->ipv6IfIcmpOutNeighborAdvertisements);
19708 	UPDATE_MIB(o1, ipv6IfIcmpOutRedirects, o2->ipv6IfIcmpOutRedirects);
19709 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembQueries,
19710 	    o2->ipv6IfIcmpOutGroupMembQueries);
19711 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembResponses,
19712 	    o2->ipv6IfIcmpOutGroupMembResponses);
19713 	UPDATE_MIB(o1, ipv6IfIcmpOutGroupMembReductions,
19714 	    o2->ipv6IfIcmpOutGroupMembReductions);
19715 	UPDATE_MIB(o1, ipv6IfIcmpInOverflows, o2->ipv6IfIcmpInOverflows);
19716 	UPDATE_MIB(o1, ipv6IfIcmpBadHoplimit, o2->ipv6IfIcmpBadHoplimit);
19717 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborAdvertisements,
19718 	    o2->ipv6IfIcmpInBadNeighborAdvertisements);
19719 	UPDATE_MIB(o1, ipv6IfIcmpInBadNeighborSolicitations,
19720 	    o2->ipv6IfIcmpInBadNeighborSolicitations);
19721 	UPDATE_MIB(o1, ipv6IfIcmpInBadRedirects, o2->ipv6IfIcmpInBadRedirects);
19722 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembTotal,
19723 	    o2->ipv6IfIcmpInGroupMembTotal);
19724 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadQueries,
19725 	    o2->ipv6IfIcmpInGroupMembBadQueries);
19726 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembBadReports,
19727 	    o2->ipv6IfIcmpInGroupMembBadReports);
19728 	UPDATE_MIB(o1, ipv6IfIcmpInGroupMembOurReports,
19729 	    o2->ipv6IfIcmpInGroupMembOurReports);
19730 }
19731 
19732 /*
19733  * Called before the options are updated to check if this packet will
19734  * be source routed from here.
19735  * This routine assumes that the options are well formed i.e. that they
19736  * have already been checked.
19737  */
19738 static boolean_t
19739 ip_source_routed(ipha_t *ipha, ip_stack_t *ipst)
19740 {
19741 	ipoptp_t	opts;
19742 	uchar_t		*opt;
19743 	uint8_t		optval;
19744 	uint8_t		optlen;
19745 	ipaddr_t	dst;
19746 	ire_t		*ire;
19747 
19748 	if (IS_SIMPLE_IPH(ipha)) {
19749 		ip2dbg(("not source routed\n"));
19750 		return (B_FALSE);
19751 	}
19752 	dst = ipha->ipha_dst;
19753 	for (optval = ipoptp_first(&opts, ipha);
19754 	    optval != IPOPT_EOL;
19755 	    optval = ipoptp_next(&opts)) {
19756 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
19757 		opt = opts.ipoptp_cur;
19758 		optlen = opts.ipoptp_len;
19759 		ip2dbg(("ip_source_routed: opt %d, len %d\n",
19760 		    optval, optlen));
19761 		switch (optval) {
19762 			uint32_t off;
19763 		case IPOPT_SSRR:
19764 		case IPOPT_LSRR:
19765 			/*
19766 			 * If dst is one of our addresses and there are some
19767 			 * entries left in the source route return (true).
19768 			 */
19769 			ire = ire_ctable_lookup(dst, 0, IRE_LOCAL, NULL,
19770 			    ALL_ZONES, NULL, MATCH_IRE_TYPE, ipst);
19771 			if (ire == NULL) {
19772 				ip2dbg(("ip_source_routed: not next"
19773 				    " source route 0x%x\n",
19774 				    ntohl(dst)));
19775 				return (B_FALSE);
19776 			}
19777 			ire_refrele(ire);
19778 			off = opt[IPOPT_OFFSET];
19779 			off--;
19780 			if (optlen < IP_ADDR_LEN ||
19781 			    off > optlen - IP_ADDR_LEN) {
19782 				/* End of source route */
19783 				ip1dbg(("ip_source_routed: end of SR\n"));
19784 				return (B_FALSE);
19785 			}
19786 			return (B_TRUE);
19787 		}
19788 	}
19789 	ip2dbg(("not source routed\n"));
19790 	return (B_FALSE);
19791 }
19792 
19793 /*
19794  * Check if the packet contains any source route.
19795  */
19796 static boolean_t
19797 ip_source_route_included(ipha_t *ipha)
19798 {
19799 	ipoptp_t	opts;
19800 	uint8_t		optval;
19801 
19802 	if (IS_SIMPLE_IPH(ipha))
19803 		return (B_FALSE);
19804 	for (optval = ipoptp_first(&opts, ipha);
19805 	    optval != IPOPT_EOL;
19806 	    optval = ipoptp_next(&opts)) {
19807 		switch (optval) {
19808 		case IPOPT_SSRR:
19809 		case IPOPT_LSRR:
19810 			return (B_TRUE);
19811 		}
19812 	}
19813 	return (B_FALSE);
19814 }
19815 
19816 /*
19817  * Called when the IRE expiration timer fires.
19818  */
19819 void
19820 ip_trash_timer_expire(void *args)
19821 {
19822 	int			flush_flag = 0;
19823 	ire_expire_arg_t	iea;
19824 	ip_stack_t		*ipst = (ip_stack_t *)args;
19825 
19826 	iea.iea_ipst = ipst;	/* No netstack_hold */
19827 
19828 	/*
19829 	 * ip_ire_expire_id is protected by ip_trash_timer_lock.
19830 	 * This lock makes sure that a new invocation of this function
19831 	 * that occurs due to an almost immediate timer firing will not
19832 	 * progress beyond this point until the current invocation is done
19833 	 */
19834 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19835 	ipst->ips_ip_ire_expire_id = 0;
19836 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19837 
19838 	/* Periodic timer */
19839 	if (ipst->ips_ip_ire_arp_time_elapsed >=
19840 	    ipst->ips_ip_ire_arp_interval) {
19841 		/*
19842 		 * Remove all IRE_CACHE entries since they might
19843 		 * contain arp information.
19844 		 */
19845 		flush_flag |= FLUSH_ARP_TIME;
19846 		ipst->ips_ip_ire_arp_time_elapsed = 0;
19847 		IP_STAT(ipst, ip_ire_arp_timer_expired);
19848 	}
19849 	if (ipst->ips_ip_ire_rd_time_elapsed >=
19850 	    ipst->ips_ip_ire_redir_interval) {
19851 		/* Remove all redirects */
19852 		flush_flag |= FLUSH_REDIRECT_TIME;
19853 		ipst->ips_ip_ire_rd_time_elapsed = 0;
19854 		IP_STAT(ipst, ip_ire_redirect_timer_expired);
19855 	}
19856 	if (ipst->ips_ip_ire_pmtu_time_elapsed >=
19857 	    ipst->ips_ip_ire_pathmtu_interval) {
19858 		/* Increase path mtu */
19859 		flush_flag |= FLUSH_MTU_TIME;
19860 		ipst->ips_ip_ire_pmtu_time_elapsed = 0;
19861 		IP_STAT(ipst, ip_ire_pmtu_timer_expired);
19862 	}
19863 
19864 	/*
19865 	 * Optimize for the case when there are no redirects in the
19866 	 * ftable, that is, no need to walk the ftable in that case.
19867 	 */
19868 	if (flush_flag & (FLUSH_MTU_TIME|FLUSH_ARP_TIME)) {
19869 		iea.iea_flush_flag = flush_flag;
19870 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_CACHETABLE, ire_expire,
19871 		    (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE, 0, NULL,
19872 		    ipst->ips_ip_cache_table_size, ipst->ips_ip_cache_table,
19873 		    NULL, ALL_ZONES, ipst);
19874 	}
19875 	if ((flush_flag & FLUSH_REDIRECT_TIME) &&
19876 	    ipst->ips_ip_redirect_cnt > 0) {
19877 		iea.iea_flush_flag = flush_flag;
19878 		ire_walk_ill_tables(MATCH_IRE_TYPE, IRE_FORWARDTABLE,
19879 		    ire_expire, (char *)(uintptr_t)&iea, IP_MASK_TABLE_SIZE,
19880 		    0, NULL, 0, NULL, NULL, ALL_ZONES, ipst);
19881 	}
19882 	if (flush_flag & FLUSH_MTU_TIME) {
19883 		/*
19884 		 * Walk all IPv6 IRE's and update them
19885 		 * Note that ARP and redirect timers are not
19886 		 * needed since NUD handles stale entries.
19887 		 */
19888 		flush_flag = FLUSH_MTU_TIME;
19889 		iea.iea_flush_flag = flush_flag;
19890 		ire_walk_v6(ire_expire, (char *)(uintptr_t)&iea,
19891 		    ALL_ZONES, ipst);
19892 	}
19893 
19894 	ipst->ips_ip_ire_arp_time_elapsed += ipst->ips_ip_timer_interval;
19895 	ipst->ips_ip_ire_rd_time_elapsed += ipst->ips_ip_timer_interval;
19896 	ipst->ips_ip_ire_pmtu_time_elapsed += ipst->ips_ip_timer_interval;
19897 
19898 	/*
19899 	 * Hold the lock to serialize timeout calls and prevent
19900 	 * stale values in ip_ire_expire_id. Otherwise it is possible
19901 	 * for the timer to fire and a new invocation of this function
19902 	 * to start before the return value of timeout has been stored
19903 	 * in ip_ire_expire_id by the current invocation.
19904 	 */
19905 	mutex_enter(&ipst->ips_ip_trash_timer_lock);
19906 	ipst->ips_ip_ire_expire_id = timeout(ip_trash_timer_expire,
19907 	    (void *)ipst, MSEC_TO_TICK(ipst->ips_ip_timer_interval));
19908 	mutex_exit(&ipst->ips_ip_trash_timer_lock);
19909 }
19910 
19911 /*
19912  * Called by the memory allocator subsystem directly, when the system
19913  * is running low on memory.
19914  */
19915 /* ARGSUSED */
19916 void
19917 ip_trash_ire_reclaim(void *args)
19918 {
19919 	netstack_handle_t nh;
19920 	netstack_t *ns;
19921 
19922 	netstack_next_init(&nh);
19923 	while ((ns = netstack_next(&nh)) != NULL) {
19924 		ip_trash_ire_reclaim_stack(ns->netstack_ip);
19925 		netstack_rele(ns);
19926 	}
19927 	netstack_next_fini(&nh);
19928 }
19929 
19930 static void
19931 ip_trash_ire_reclaim_stack(ip_stack_t *ipst)
19932 {
19933 	ire_cache_count_t icc;
19934 	ire_cache_reclaim_t icr;
19935 	ncc_cache_count_t ncc;
19936 	nce_cache_reclaim_t ncr;
19937 	uint_t delete_cnt;
19938 	/*
19939 	 * Memory reclaim call back.
19940 	 * Count unused, offlink, pmtu, and onlink IRE_CACHE entries.
19941 	 * Then, with a target of freeing 1/Nth of IRE_CACHE
19942 	 * entries, determine what fraction to free for
19943 	 * each category of IRE_CACHE entries giving absolute priority
19944 	 * in the order of onlink, pmtu, offlink, unused (e.g. no pmtu
19945 	 * entry will be freed unless all offlink entries are freed).
19946 	 */
19947 	icc.icc_total = 0;
19948 	icc.icc_unused = 0;
19949 	icc.icc_offlink = 0;
19950 	icc.icc_pmtu = 0;
19951 	icc.icc_onlink = 0;
19952 	ire_walk(ire_cache_count, (char *)&icc, ipst);
19953 
19954 	/*
19955 	 * Free NCEs for IPv6 like the onlink ires.
19956 	 */
19957 	ncc.ncc_total = 0;
19958 	ncc.ncc_host = 0;
19959 	ndp_walk(NULL, (pfi_t)ndp_cache_count, (uchar_t *)&ncc, ipst);
19960 
19961 	ASSERT(icc.icc_total == icc.icc_unused + icc.icc_offlink +
19962 	    icc.icc_pmtu + icc.icc_onlink);
19963 	delete_cnt = icc.icc_total/ipst->ips_ip_ire_reclaim_fraction;
19964 	IP_STAT(ipst, ip_trash_ire_reclaim_calls);
19965 	if (delete_cnt == 0)
19966 		return;
19967 	IP_STAT(ipst, ip_trash_ire_reclaim_success);
19968 	/* Always delete all unused offlink entries */
19969 	icr.icr_ipst = ipst;
19970 	icr.icr_unused = 1;
19971 	if (delete_cnt <= icc.icc_unused) {
19972 		/*
19973 		 * Only need to free unused entries.  In other words,
19974 		 * there are enough unused entries to free to meet our
19975 		 * target number of freed ire cache entries.
19976 		 */
19977 		icr.icr_offlink = icr.icr_pmtu = icr.icr_onlink = 0;
19978 		ncr.ncr_host = 0;
19979 	} else if (delete_cnt <= icc.icc_unused + icc.icc_offlink) {
19980 		/*
19981 		 * Only need to free unused entries, plus a fraction of offlink
19982 		 * entries.  It follows from the first if statement that
19983 		 * icc_offlink is non-zero, and that delete_cnt != icc_unused.
19984 		 */
19985 		delete_cnt -= icc.icc_unused;
19986 		/* Round up # deleted by truncating fraction */
19987 		icr.icr_offlink = icc.icc_offlink / delete_cnt;
19988 		icr.icr_pmtu = icr.icr_onlink = 0;
19989 		ncr.ncr_host = 0;
19990 	} else if (delete_cnt <=
19991 	    icc.icc_unused + icc.icc_offlink + icc.icc_pmtu) {
19992 		/*
19993 		 * Free all unused and offlink entries, plus a fraction of
19994 		 * pmtu entries.  It follows from the previous if statement
19995 		 * that icc_pmtu is non-zero, and that
19996 		 * delete_cnt != icc_unused + icc_offlink.
19997 		 */
19998 		icr.icr_offlink = 1;
19999 		delete_cnt -= icc.icc_unused + icc.icc_offlink;
20000 		/* Round up # deleted by truncating fraction */
20001 		icr.icr_pmtu = icc.icc_pmtu / delete_cnt;
20002 		icr.icr_onlink = 0;
20003 		ncr.ncr_host = 0;
20004 	} else {
20005 		/*
20006 		 * Free all unused, offlink, and pmtu entries, plus a fraction
20007 		 * of onlink entries.  If we're here, then we know that
20008 		 * icc_onlink is non-zero, and that
20009 		 * delete_cnt != icc_unused + icc_offlink + icc_pmtu.
20010 		 */
20011 		icr.icr_offlink = icr.icr_pmtu = 1;
20012 		delete_cnt -= icc.icc_unused + icc.icc_offlink +
20013 		    icc.icc_pmtu;
20014 		/* Round up # deleted by truncating fraction */
20015 		icr.icr_onlink = icc.icc_onlink / delete_cnt;
20016 		/* Using the same delete fraction as for onlink IREs */
20017 		ncr.ncr_host = ncc.ncc_host / delete_cnt;
20018 	}
20019 #ifdef DEBUG
20020 	ip1dbg(("IP reclaim: target %d out of %d current %d/%d/%d/%d "
20021 	    "fractions %d/%d/%d/%d\n",
20022 	    icc.icc_total/ipst->ips_ip_ire_reclaim_fraction, icc.icc_total,
20023 	    icc.icc_unused, icc.icc_offlink,
20024 	    icc.icc_pmtu, icc.icc_onlink,
20025 	    icr.icr_unused, icr.icr_offlink,
20026 	    icr.icr_pmtu, icr.icr_onlink));
20027 #endif
20028 	ire_walk(ire_cache_reclaim, (char *)&icr, ipst);
20029 	if (ncr.ncr_host != 0)
20030 		ndp_walk(NULL, (pfi_t)ndp_cache_reclaim,
20031 		    (uchar_t *)&ncr, ipst);
20032 #ifdef DEBUG
20033 	icc.icc_total = 0; icc.icc_unused = 0; icc.icc_offlink = 0;
20034 	icc.icc_pmtu = 0; icc.icc_onlink = 0;
20035 	ire_walk(ire_cache_count, (char *)&icc, ipst);
20036 	ip1dbg(("IP reclaim: result total %d %d/%d/%d/%d\n",
20037 	    icc.icc_total, icc.icc_unused, icc.icc_offlink,
20038 	    icc.icc_pmtu, icc.icc_onlink));
20039 #endif
20040 }
20041 
20042 /*
20043  * ip_unbind is called when a copy of an unbind request is received from the
20044  * upper level protocol.  We remove this conn from any fanout hash list it is
20045  * on, and zero out the bind information.  No reply is expected up above.
20046  */
20047 mblk_t *
20048 ip_unbind(queue_t *q, mblk_t *mp)
20049 {
20050 	conn_t	*connp = Q_TO_CONN(q);
20051 
20052 	ASSERT(!MUTEX_HELD(&connp->conn_lock));
20053 
20054 	if (is_system_labeled() && connp->conn_anon_port) {
20055 		(void) tsol_mlp_anon(crgetzone(connp->conn_cred),
20056 		    connp->conn_mlp_type, connp->conn_ulp,
20057 		    ntohs(connp->conn_lport), B_FALSE);
20058 		connp->conn_anon_port = 0;
20059 	}
20060 	connp->conn_mlp_type = mlptSingle;
20061 
20062 	ipcl_hash_remove(connp);
20063 
20064 	ASSERT(mp->b_cont == NULL);
20065 	/*
20066 	 * Convert mp into a T_OK_ACK
20067 	 */
20068 	mp = mi_tpi_ok_ack_alloc(mp);
20069 
20070 	/*
20071 	 * should not happen in practice... T_OK_ACK is smaller than the
20072 	 * original message.
20073 	 */
20074 	if (mp == NULL)
20075 		return (NULL);
20076 
20077 	return (mp);
20078 }
20079 
20080 /*
20081  * Write side put procedure.  Outbound data, IOCTLs, responses from
20082  * resolvers, etc, come down through here.
20083  *
20084  * arg2 is always a queue_t *.
20085  * When that queue is an ill_t (i.e. q_next != NULL), then arg must be
20086  * the zoneid.
20087  * When that queue is not an ill_t, then arg must be a conn_t pointer.
20088  */
20089 void
20090 ip_output(void *arg, mblk_t *mp, void *arg2, int caller)
20091 {
20092 	ip_output_options(arg, mp, arg2, caller, &zero_info);
20093 }
20094 
20095 void
20096 ip_output_options(void *arg, mblk_t *mp, void *arg2, int caller,
20097     ip_opt_info_t *infop)
20098 {
20099 	conn_t		*connp = NULL;
20100 	queue_t		*q = (queue_t *)arg2;
20101 	ipha_t		*ipha;
20102 #define	rptr	((uchar_t *)ipha)
20103 	ire_t		*ire = NULL;
20104 	ire_t		*sctp_ire = NULL;
20105 	uint32_t	v_hlen_tos_len;
20106 	ipaddr_t	dst;
20107 	mblk_t		*first_mp = NULL;
20108 	boolean_t	mctl_present;
20109 	ipsec_out_t	*io;
20110 	int		match_flags;
20111 	ill_t		*attach_ill = NULL;
20112 					/* Bind to IPIF_NOFAILOVER ill etc. */
20113 	ill_t		*xmit_ill = NULL;	/* IP_PKTINFO etc. */
20114 	ipif_t		*dst_ipif;
20115 	boolean_t	multirt_need_resolve = B_FALSE;
20116 	mblk_t		*copy_mp = NULL;
20117 	int		err;
20118 	zoneid_t	zoneid;
20119 	int	adjust;
20120 	uint16_t iplen;
20121 	boolean_t	need_decref = B_FALSE;
20122 	boolean_t	ignore_dontroute = B_FALSE;
20123 	boolean_t	ignore_nexthop = B_FALSE;
20124 	boolean_t	ip_nexthop = B_FALSE;
20125 	ipaddr_t	nexthop_addr;
20126 	ip_stack_t	*ipst;
20127 
20128 #ifdef	_BIG_ENDIAN
20129 #define	V_HLEN	(v_hlen_tos_len >> 24)
20130 #else
20131 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
20132 #endif
20133 
20134 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_START,
20135 	    "ip_wput_start: q %p", q);
20136 
20137 	/*
20138 	 * ip_wput fast path
20139 	 */
20140 
20141 	/* is packet from ARP ? */
20142 	if (q->q_next != NULL) {
20143 		zoneid = (zoneid_t)(uintptr_t)arg;
20144 		goto qnext;
20145 	}
20146 
20147 	connp = (conn_t *)arg;
20148 	ASSERT(connp != NULL);
20149 	zoneid = connp->conn_zoneid;
20150 	ipst = connp->conn_netstack->netstack_ip;
20151 
20152 	/* is queue flow controlled? */
20153 	if ((q->q_first != NULL || connp->conn_draining) &&
20154 	    (caller == IP_WPUT)) {
20155 		ASSERT(!need_decref);
20156 		(void) putq(q, mp);
20157 		return;
20158 	}
20159 
20160 	/* Multidata transmit? */
20161 	if (DB_TYPE(mp) == M_MULTIDATA) {
20162 		/*
20163 		 * We should never get here, since all Multidata messages
20164 		 * originating from tcp should have been directed over to
20165 		 * tcp_multisend() in the first place.
20166 		 */
20167 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20168 		freemsg(mp);
20169 		return;
20170 	} else if (DB_TYPE(mp) != M_DATA)
20171 		goto notdata;
20172 
20173 	if (mp->b_flag & MSGHASREF) {
20174 		ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20175 		mp->b_flag &= ~MSGHASREF;
20176 		SCTP_EXTRACT_IPINFO(mp, sctp_ire);
20177 		need_decref = B_TRUE;
20178 	}
20179 	ipha = (ipha_t *)mp->b_rptr;
20180 
20181 	/* is IP header non-aligned or mblk smaller than basic IP header */
20182 #ifndef SAFETY_BEFORE_SPEED
20183 	if (!OK_32PTR(rptr) ||
20184 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH)
20185 		goto hdrtoosmall;
20186 #endif
20187 
20188 	ASSERT(OK_32PTR(ipha));
20189 
20190 	/*
20191 	 * This function assumes that mp points to an IPv4 packet.  If it's the
20192 	 * wrong version, we'll catch it again in ip_output_v6.
20193 	 *
20194 	 * Note that this is *only* locally-generated output here, and never
20195 	 * forwarded data, and that we need to deal only with transports that
20196 	 * don't know how to label.  (TCP, UDP, and ICMP/raw-IP all know how to
20197 	 * label.)
20198 	 */
20199 	if (is_system_labeled() &&
20200 	    (ipha->ipha_version_and_hdr_length & 0xf0) == (IPV4_VERSION << 4) &&
20201 	    !connp->conn_ulp_labeled) {
20202 		err = tsol_check_label(BEST_CRED(mp, connp), &mp, &adjust,
20203 		    connp->conn_mac_exempt, ipst);
20204 		ipha = (ipha_t *)mp->b_rptr;
20205 		if (err != 0) {
20206 			first_mp = mp;
20207 			if (err == EINVAL)
20208 				goto icmp_parameter_problem;
20209 			ip2dbg(("ip_wput: label check failed (%d)\n", err));
20210 			goto discard_pkt;
20211 		}
20212 		iplen = ntohs(ipha->ipha_length) + adjust;
20213 		ipha->ipha_length = htons(iplen);
20214 	}
20215 
20216 	ASSERT(infop != NULL);
20217 
20218 	if (infop->ip_opt_flags & IP_VERIFY_SRC) {
20219 		/*
20220 		 * IP_PKTINFO ancillary option is present.
20221 		 * IPCL_ZONEID is used to honor IP_ALLZONES option which
20222 		 * allows using address of any zone as the source address.
20223 		 */
20224 		ire = ire_ctable_lookup(ipha->ipha_src, 0,
20225 		    (IRE_LOCAL|IRE_LOOPBACK), NULL, IPCL_ZONEID(connp),
20226 		    NULL, MATCH_IRE_TYPE | MATCH_IRE_ZONEONLY, ipst);
20227 		if (ire == NULL)
20228 			goto drop_pkt;
20229 		ire_refrele(ire);
20230 		ire = NULL;
20231 	}
20232 
20233 	/*
20234 	 * IP_DONTFAILOVER_IF and IP_BOUND_IF have precedence over ill index
20235 	 * passed in IP_PKTINFO.
20236 	 */
20237 	if (infop->ip_opt_ill_index != 0 &&
20238 	    connp->conn_outgoing_ill == NULL &&
20239 	    connp->conn_nofailover_ill == NULL) {
20240 
20241 		xmit_ill = ill_lookup_on_ifindex(
20242 		    infop->ip_opt_ill_index, B_FALSE, NULL, NULL, NULL, NULL,
20243 		    ipst);
20244 
20245 		if (xmit_ill == NULL || IS_VNI(xmit_ill))
20246 			goto drop_pkt;
20247 		/*
20248 		 * check that there is an ipif belonging
20249 		 * to our zone. IPCL_ZONEID is not used because
20250 		 * IP_ALLZONES option is valid only when the ill is
20251 		 * accessible from all zones i.e has a valid ipif in
20252 		 * all zones.
20253 		 */
20254 		if (!ipif_lookup_zoneid_group(xmit_ill, zoneid, 0, NULL)) {
20255 			goto drop_pkt;
20256 		}
20257 	}
20258 
20259 	/*
20260 	 * If there is a policy, try to attach an ipsec_out in
20261 	 * the front. At the end, first_mp either points to a
20262 	 * M_DATA message or IPSEC_OUT message linked to a
20263 	 * M_DATA message. We have to do it now as we might
20264 	 * lose the "conn" if we go through ip_newroute.
20265 	 */
20266 	if (connp->conn_out_enforce_policy || (connp->conn_latch != NULL)) {
20267 		if (((mp = ipsec_attach_ipsec_out(&mp, connp, NULL,
20268 		    ipha->ipha_protocol, ipst->ips_netstack)) == NULL)) {
20269 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20270 			if (need_decref)
20271 				CONN_DEC_REF(connp);
20272 			return;
20273 		} else {
20274 			ASSERT(mp->b_datap->db_type == M_CTL);
20275 			first_mp = mp;
20276 			mp = mp->b_cont;
20277 			mctl_present = B_TRUE;
20278 		}
20279 	} else {
20280 		first_mp = mp;
20281 		mctl_present = B_FALSE;
20282 	}
20283 
20284 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20285 
20286 	/* is wrong version or IP options present */
20287 	if (V_HLEN != IP_SIMPLE_HDR_VERSION)
20288 		goto version_hdrlen_check;
20289 	dst = ipha->ipha_dst;
20290 
20291 	if (connp->conn_nofailover_ill != NULL) {
20292 		attach_ill = conn_get_held_ill(connp,
20293 		    &connp->conn_nofailover_ill, &err);
20294 		if (err == ILL_LOOKUP_FAILED) {
20295 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20296 			if (need_decref)
20297 				CONN_DEC_REF(connp);
20298 			freemsg(first_mp);
20299 			return;
20300 		}
20301 	}
20302 
20303 	/* If IP_BOUND_IF has been set, use that ill. */
20304 	if (connp->conn_outgoing_ill != NULL) {
20305 		xmit_ill = conn_get_held_ill(connp,
20306 		    &connp->conn_outgoing_ill, &err);
20307 		if (err == ILL_LOOKUP_FAILED)
20308 			goto drop_pkt;
20309 
20310 		goto send_from_ill;
20311 	}
20312 
20313 	/* is packet multicast? */
20314 	if (CLASSD(dst))
20315 		goto multicast;
20316 
20317 	/*
20318 	 * If xmit_ill is set above due to index passed in ip_pkt_info. It
20319 	 * takes precedence over conn_dontroute and conn_nexthop_set
20320 	 */
20321 	if (xmit_ill != NULL)
20322 		goto send_from_ill;
20323 
20324 	if (connp->conn_dontroute || connp->conn_nexthop_set) {
20325 		/*
20326 		 * If the destination is a broadcast, local, or loopback
20327 		 * address, SO_DONTROUTE and IP_NEXTHOP go through the
20328 		 * standard path.
20329 		 */
20330 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20331 		if ((ire == NULL) || (ire->ire_type &
20332 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK)) == 0) {
20333 			if (ire != NULL) {
20334 				ire_refrele(ire);
20335 				/* No more access to ire */
20336 				ire = NULL;
20337 			}
20338 			/*
20339 			 * bypass routing checks and go directly to interface.
20340 			 */
20341 			if (connp->conn_dontroute)
20342 				goto dontroute;
20343 
20344 			ASSERT(connp->conn_nexthop_set);
20345 			ip_nexthop = B_TRUE;
20346 			nexthop_addr = connp->conn_nexthop_v4;
20347 			goto send_from_ill;
20348 		}
20349 
20350 		/* Must be a broadcast, a loopback or a local ire */
20351 		ire_refrele(ire);
20352 		/* No more access to ire */
20353 		ire = NULL;
20354 	}
20355 
20356 	if (attach_ill != NULL)
20357 		goto send_from_ill;
20358 
20359 	/*
20360 	 * We cache IRE_CACHEs to avoid lookups. We don't do
20361 	 * this for the tcp global queue and listen end point
20362 	 * as it does not really have a real destination to
20363 	 * talk to.  This is also true for SCTP.
20364 	 */
20365 	if (IP_FLOW_CONTROLLED_ULP(connp->conn_ulp) &&
20366 	    !connp->conn_fully_bound) {
20367 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20368 		if (ire == NULL)
20369 			goto noirefound;
20370 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20371 		    "ip_wput_end: q %p (%S)", q, "end");
20372 
20373 		/*
20374 		 * Check if the ire has the RTF_MULTIRT flag, inherited
20375 		 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20376 		 */
20377 		if (ire->ire_flags & RTF_MULTIRT) {
20378 
20379 			/*
20380 			 * Force the TTL of multirouted packets if required.
20381 			 * The TTL of such packets is bounded by the
20382 			 * ip_multirt_ttl ndd variable.
20383 			 */
20384 			if ((ipst->ips_ip_multirt_ttl > 0) &&
20385 			    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20386 				ip2dbg(("ip_wput: forcing multirt TTL to %d "
20387 				    "(was %d), dst 0x%08x\n",
20388 				    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20389 				    ntohl(ire->ire_addr)));
20390 				ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20391 			}
20392 			/*
20393 			 * We look at this point if there are pending
20394 			 * unresolved routes. ire_multirt_resolvable()
20395 			 * checks in O(n) that all IRE_OFFSUBNET ire
20396 			 * entries for the packet's destination and
20397 			 * flagged RTF_MULTIRT are currently resolved.
20398 			 * If some remain unresolved, we make a copy
20399 			 * of the current message. It will be used
20400 			 * to initiate additional route resolutions.
20401 			 */
20402 			multirt_need_resolve =
20403 			    ire_multirt_need_resolve(ire->ire_addr,
20404 			    MBLK_GETLABEL(first_mp), ipst);
20405 			ip2dbg(("ip_wput[TCP]: ire %p, "
20406 			    "multirt_need_resolve %d, first_mp %p\n",
20407 			    (void *)ire, multirt_need_resolve,
20408 			    (void *)first_mp));
20409 			if (multirt_need_resolve) {
20410 				copy_mp = copymsg(first_mp);
20411 				if (copy_mp != NULL) {
20412 					MULTIRT_DEBUG_TAG(copy_mp);
20413 				}
20414 			}
20415 		}
20416 
20417 		ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20418 
20419 		/*
20420 		 * Try to resolve another multiroute if
20421 		 * ire_multirt_need_resolve() deemed it necessary.
20422 		 */
20423 		if (copy_mp != NULL)
20424 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20425 		if (need_decref)
20426 			CONN_DEC_REF(connp);
20427 		return;
20428 	}
20429 
20430 	/*
20431 	 * Access to conn_ire_cache. (protected by conn_lock)
20432 	 *
20433 	 * IRE_MARK_CONDEMNED is marked in ire_delete. We don't grab
20434 	 * the ire bucket lock here to check for CONDEMNED as it is okay to
20435 	 * send a packet or two with the IRE_CACHE that is going away.
20436 	 * Access to the ire requires an ire refhold on the ire prior to
20437 	 * its use since an interface unplumb thread may delete the cached
20438 	 * ire and release the refhold at any time.
20439 	 *
20440 	 * Caching an ire in the conn_ire_cache
20441 	 *
20442 	 * o Caching an ire pointer in the conn requires a strict check for
20443 	 * IRE_MARK_CONDEMNED. An interface unplumb thread deletes all relevant
20444 	 * ires  before cleaning up the conns. So the caching of an ire pointer
20445 	 * in the conn is done after making sure under the bucket lock that the
20446 	 * ire has not yet been marked CONDEMNED. Otherwise we will end up
20447 	 * caching an ire after the unplumb thread has cleaned up the conn.
20448 	 * If the conn does not send a packet subsequently the unplumb thread
20449 	 * will be hanging waiting for the ire count to drop to zero.
20450 	 *
20451 	 * o We also need to atomically test for a null conn_ire_cache and
20452 	 * set the conn_ire_cache under the the protection of the conn_lock
20453 	 * to avoid races among concurrent threads trying to simultaneously
20454 	 * cache an ire in the conn_ire_cache.
20455 	 */
20456 	mutex_enter(&connp->conn_lock);
20457 	ire = sctp_ire != NULL ? sctp_ire : connp->conn_ire_cache;
20458 
20459 	if (ire != NULL && ire->ire_addr == dst &&
20460 	    !(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20461 
20462 		IRE_REFHOLD(ire);
20463 		mutex_exit(&connp->conn_lock);
20464 
20465 	} else {
20466 		boolean_t cached = B_FALSE;
20467 		connp->conn_ire_cache = NULL;
20468 		mutex_exit(&connp->conn_lock);
20469 		/* Release the old ire */
20470 		if (ire != NULL && sctp_ire == NULL)
20471 			IRE_REFRELE_NOTR(ire);
20472 
20473 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
20474 		if (ire == NULL)
20475 			goto noirefound;
20476 		IRE_REFHOLD_NOTR(ire);
20477 
20478 		mutex_enter(&connp->conn_lock);
20479 		if (CONN_CACHE_IRE(connp) && connp->conn_ire_cache == NULL) {
20480 			rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
20481 			if (!(ire->ire_marks & IRE_MARK_CONDEMNED)) {
20482 				if (connp->conn_ulp == IPPROTO_TCP)
20483 					TCP_CHECK_IREINFO(connp->conn_tcp, ire);
20484 				connp->conn_ire_cache = ire;
20485 				cached = B_TRUE;
20486 			}
20487 			rw_exit(&ire->ire_bucket->irb_lock);
20488 		}
20489 		mutex_exit(&connp->conn_lock);
20490 
20491 		/*
20492 		 * We can continue to use the ire but since it was
20493 		 * not cached, we should drop the extra reference.
20494 		 */
20495 		if (!cached)
20496 			IRE_REFRELE_NOTR(ire);
20497 	}
20498 
20499 
20500 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20501 	    "ip_wput_end: q %p (%S)", q, "end");
20502 
20503 	/*
20504 	 * Check if the ire has the RTF_MULTIRT flag, inherited
20505 	 * from an IRE_OFFSUBNET ire entry in ip_newroute().
20506 	 */
20507 	if (ire->ire_flags & RTF_MULTIRT) {
20508 
20509 		/*
20510 		 * Force the TTL of multirouted packets if required.
20511 		 * The TTL of such packets is bounded by the
20512 		 * ip_multirt_ttl ndd variable.
20513 		 */
20514 		if ((ipst->ips_ip_multirt_ttl > 0) &&
20515 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
20516 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
20517 			    "(was %d), dst 0x%08x\n",
20518 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
20519 			    ntohl(ire->ire_addr)));
20520 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
20521 		}
20522 
20523 		/*
20524 		 * At this point, we check to see if there are any pending
20525 		 * unresolved routes. ire_multirt_resolvable()
20526 		 * checks in O(n) that all IRE_OFFSUBNET ire
20527 		 * entries for the packet's destination and
20528 		 * flagged RTF_MULTIRT are currently resolved.
20529 		 * If some remain unresolved, we make a copy
20530 		 * of the current message. It will be used
20531 		 * to initiate additional route resolutions.
20532 		 */
20533 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
20534 		    MBLK_GETLABEL(first_mp), ipst);
20535 		ip2dbg(("ip_wput[not TCP]: ire %p, "
20536 		    "multirt_need_resolve %d, first_mp %p\n",
20537 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
20538 		if (multirt_need_resolve) {
20539 			copy_mp = copymsg(first_mp);
20540 			if (copy_mp != NULL) {
20541 				MULTIRT_DEBUG_TAG(copy_mp);
20542 			}
20543 		}
20544 	}
20545 
20546 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
20547 
20548 	/*
20549 	 * Try to resolve another multiroute if
20550 	 * ire_multirt_resolvable() deemed it necessary
20551 	 */
20552 	if (copy_mp != NULL)
20553 		ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
20554 	if (need_decref)
20555 		CONN_DEC_REF(connp);
20556 	return;
20557 
20558 qnext:
20559 	/*
20560 	 * Upper Level Protocols pass down complete IP datagrams
20561 	 * as M_DATA messages.	Everything else is a sideshow.
20562 	 *
20563 	 * 1) We could be re-entering ip_wput because of ip_neworute
20564 	 *    in which case we could have a IPSEC_OUT message. We
20565 	 *    need to pass through ip_wput like other datagrams and
20566 	 *    hence cannot branch to ip_wput_nondata.
20567 	 *
20568 	 * 2) ARP, AH, ESP, and other clients who are on the module
20569 	 *    instance of IP stream, give us something to deal with.
20570 	 *    We will handle AH and ESP here and rest in ip_wput_nondata.
20571 	 *
20572 	 * 3) ICMP replies also could come here.
20573 	 */
20574 	ipst = ILLQ_TO_IPST(q);
20575 
20576 	if (DB_TYPE(mp) != M_DATA) {
20577 notdata:
20578 		if (DB_TYPE(mp) == M_CTL) {
20579 			/*
20580 			 * M_CTL messages are used by ARP, AH and ESP to
20581 			 * communicate with IP. We deal with IPSEC_IN and
20582 			 * IPSEC_OUT here. ip_wput_nondata handles other
20583 			 * cases.
20584 			 */
20585 			ipsec_info_t *ii = (ipsec_info_t *)mp->b_rptr;
20586 			if (mp->b_cont && (mp->b_cont->b_flag & MSGHASREF)) {
20587 				first_mp = mp->b_cont;
20588 				first_mp->b_flag &= ~MSGHASREF;
20589 				ASSERT(connp->conn_ulp == IPPROTO_SCTP);
20590 				SCTP_EXTRACT_IPINFO(first_mp, sctp_ire);
20591 				CONN_DEC_REF(connp);
20592 				connp = NULL;
20593 			}
20594 			if (ii->ipsec_info_type == IPSEC_IN) {
20595 				/*
20596 				 * Either this message goes back to
20597 				 * IPsec for further processing or to
20598 				 * ULP after policy checks.
20599 				 */
20600 				ip_fanout_proto_again(mp, NULL, NULL, NULL);
20601 				return;
20602 			} else if (ii->ipsec_info_type == IPSEC_OUT) {
20603 				io = (ipsec_out_t *)ii;
20604 				if (io->ipsec_out_proc_begin) {
20605 					/*
20606 					 * IPsec processing has already started.
20607 					 * Complete it.
20608 					 * IPQoS notes: We don't care what is
20609 					 * in ipsec_out_ill_index since this
20610 					 * won't be processed for IPQoS policies
20611 					 * in ipsec_out_process.
20612 					 */
20613 					ipsec_out_process(q, mp, NULL,
20614 					    io->ipsec_out_ill_index);
20615 					return;
20616 				} else {
20617 					connp = (q->q_next != NULL) ?
20618 					    NULL : Q_TO_CONN(q);
20619 					first_mp = mp;
20620 					mp = mp->b_cont;
20621 					mctl_present = B_TRUE;
20622 				}
20623 				zoneid = io->ipsec_out_zoneid;
20624 				ASSERT(zoneid != ALL_ZONES);
20625 			} else if (ii->ipsec_info_type == IPSEC_CTL) {
20626 				/*
20627 				 * It's an IPsec control message requesting
20628 				 * an SADB update to be sent to the IPsec
20629 				 * hardware acceleration capable ills.
20630 				 */
20631 				ipsec_ctl_t *ipsec_ctl =
20632 				    (ipsec_ctl_t *)mp->b_rptr;
20633 				ipsa_t *sa = (ipsa_t *)ipsec_ctl->ipsec_ctl_sa;
20634 				uint_t satype = ipsec_ctl->ipsec_ctl_sa_type;
20635 				mblk_t *cmp = mp->b_cont;
20636 
20637 				ASSERT(MBLKL(mp) >= sizeof (ipsec_ctl_t));
20638 				ASSERT(cmp != NULL);
20639 
20640 				freeb(mp);
20641 				ill_ipsec_capab_send_all(satype, cmp, sa,
20642 				    ipst->ips_netstack);
20643 				return;
20644 			} else {
20645 				/*
20646 				 * This must be ARP or special TSOL signaling.
20647 				 */
20648 				ip_wput_nondata(NULL, q, mp, NULL);
20649 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20650 				    "ip_wput_end: q %p (%S)", q, "nondata");
20651 				return;
20652 			}
20653 		} else {
20654 			/*
20655 			 * This must be non-(ARP/AH/ESP) messages.
20656 			 */
20657 			ASSERT(!need_decref);
20658 			ip_wput_nondata(NULL, q, mp, NULL);
20659 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20660 			    "ip_wput_end: q %p (%S)", q, "nondata");
20661 			return;
20662 		}
20663 	} else {
20664 		first_mp = mp;
20665 		mctl_present = B_FALSE;
20666 	}
20667 
20668 	ASSERT(first_mp != NULL);
20669 	/*
20670 	 * ICMP echo replies attach an ipsec_out and set ipsec_out_attach_if
20671 	 * to make sure that this packet goes out on the same interface it
20672 	 * came in. We handle that here.
20673 	 */
20674 	if (mctl_present) {
20675 		uint_t ifindex;
20676 
20677 		io = (ipsec_out_t *)first_mp->b_rptr;
20678 		if (io->ipsec_out_attach_if || io->ipsec_out_ip_nexthop) {
20679 			/*
20680 			 * We may have lost the conn context if we are
20681 			 * coming here from ip_newroute(). Copy the
20682 			 * nexthop information.
20683 			 */
20684 			if (io->ipsec_out_ip_nexthop) {
20685 				ip_nexthop = B_TRUE;
20686 				nexthop_addr = io->ipsec_out_nexthop_addr;
20687 
20688 				ipha = (ipha_t *)mp->b_rptr;
20689 				dst = ipha->ipha_dst;
20690 				goto send_from_ill;
20691 			} else {
20692 				ASSERT(io->ipsec_out_ill_index != 0);
20693 				ifindex = io->ipsec_out_ill_index;
20694 				attach_ill = ill_lookup_on_ifindex(ifindex,
20695 				    B_FALSE, NULL, NULL, NULL, NULL, ipst);
20696 				if (attach_ill == NULL) {
20697 					ASSERT(xmit_ill == NULL);
20698 					ip1dbg(("ip_output: bad ifindex for "
20699 					    "(BIND TO IPIF_NOFAILOVER) %d\n",
20700 					    ifindex));
20701 					freemsg(first_mp);
20702 					BUMP_MIB(&ipst->ips_ip_mib,
20703 					    ipIfStatsOutDiscards);
20704 					ASSERT(!need_decref);
20705 					return;
20706 				}
20707 			}
20708 		}
20709 	}
20710 
20711 	ASSERT(xmit_ill == NULL);
20712 
20713 	/* We have a complete IP datagram heading outbound. */
20714 	ipha = (ipha_t *)mp->b_rptr;
20715 
20716 #ifndef SPEED_BEFORE_SAFETY
20717 	/*
20718 	 * Make sure we have a full-word aligned message and that at least
20719 	 * a simple IP header is accessible in the first message.  If not,
20720 	 * try a pullup.  For labeled systems we need to always take this
20721 	 * path as M_CTLs are "notdata" but have trailing data to process.
20722 	 */
20723 	if (!OK_32PTR(rptr) ||
20724 	    (mp->b_wptr - rptr) < IP_SIMPLE_HDR_LENGTH || is_system_labeled()) {
20725 hdrtoosmall:
20726 		if (!pullupmsg(mp, IP_SIMPLE_HDR_LENGTH)) {
20727 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20728 			    "ip_wput_end: q %p (%S)", q, "pullupfailed");
20729 			if (first_mp == NULL)
20730 				first_mp = mp;
20731 			goto discard_pkt;
20732 		}
20733 
20734 		/* This function assumes that mp points to an IPv4 packet. */
20735 		if (is_system_labeled() && q->q_next == NULL &&
20736 		    (*mp->b_rptr & 0xf0) == (IPV4_VERSION << 4) &&
20737 		    !connp->conn_ulp_labeled) {
20738 			err = tsol_check_label(BEST_CRED(mp, connp), &mp,
20739 			    &adjust, connp->conn_mac_exempt, ipst);
20740 			ipha = (ipha_t *)mp->b_rptr;
20741 			if (first_mp != NULL)
20742 				first_mp->b_cont = mp;
20743 			if (err != 0) {
20744 				if (first_mp == NULL)
20745 					first_mp = mp;
20746 				if (err == EINVAL)
20747 					goto icmp_parameter_problem;
20748 				ip2dbg(("ip_wput: label check failed (%d)\n",
20749 				    err));
20750 				goto discard_pkt;
20751 			}
20752 			iplen = ntohs(ipha->ipha_length) + adjust;
20753 			ipha->ipha_length = htons(iplen);
20754 		}
20755 
20756 		ipha = (ipha_t *)mp->b_rptr;
20757 		if (first_mp == NULL) {
20758 			ASSERT(attach_ill == NULL && xmit_ill == NULL);
20759 			/*
20760 			 * If we got here because of "goto hdrtoosmall"
20761 			 * We need to attach a IPSEC_OUT.
20762 			 */
20763 			if (connp->conn_out_enforce_policy) {
20764 				if (((mp = ipsec_attach_ipsec_out(&mp, connp,
20765 				    NULL, ipha->ipha_protocol,
20766 				    ipst->ips_netstack)) == NULL)) {
20767 					BUMP_MIB(&ipst->ips_ip_mib,
20768 					    ipIfStatsOutDiscards);
20769 					if (need_decref)
20770 						CONN_DEC_REF(connp);
20771 					return;
20772 				} else {
20773 					ASSERT(mp->b_datap->db_type == M_CTL);
20774 					first_mp = mp;
20775 					mp = mp->b_cont;
20776 					mctl_present = B_TRUE;
20777 				}
20778 			} else {
20779 				first_mp = mp;
20780 				mctl_present = B_FALSE;
20781 			}
20782 		}
20783 	}
20784 #endif
20785 
20786 	/* Most of the code below is written for speed, not readability */
20787 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
20788 
20789 	/*
20790 	 * If ip_newroute() fails, we're going to need a full
20791 	 * header for the icmp wraparound.
20792 	 */
20793 	if (V_HLEN != IP_SIMPLE_HDR_VERSION) {
20794 		uint_t	v_hlen;
20795 version_hdrlen_check:
20796 		ASSERT(first_mp != NULL);
20797 		v_hlen = V_HLEN;
20798 		/*
20799 		 * siphon off IPv6 packets coming down from transport
20800 		 * layer modules here.
20801 		 * Note: high-order bit carries NUD reachability confirmation
20802 		 */
20803 		if (((v_hlen >> 4) & 0x7) == IPV6_VERSION) {
20804 			/*
20805 			 * FIXME: assume that callers of ip_output* call
20806 			 * the right version?
20807 			 */
20808 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutWrongIPVersion);
20809 			ASSERT(xmit_ill == NULL);
20810 			if (attach_ill != NULL)
20811 				ill_refrele(attach_ill);
20812 			if (need_decref)
20813 				mp->b_flag |= MSGHASREF;
20814 			(void) ip_output_v6(arg, first_mp, arg2, caller);
20815 			return;
20816 		}
20817 
20818 		if ((v_hlen >> 4) != IP_VERSION) {
20819 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20820 			    "ip_wput_end: q %p (%S)", q, "badvers");
20821 			goto discard_pkt;
20822 		}
20823 		/*
20824 		 * Is the header length at least 20 bytes?
20825 		 *
20826 		 * Are there enough bytes accessible in the header?  If
20827 		 * not, try a pullup.
20828 		 */
20829 		v_hlen &= 0xF;
20830 		v_hlen <<= 2;
20831 		if (v_hlen < IP_SIMPLE_HDR_LENGTH) {
20832 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20833 			    "ip_wput_end: q %p (%S)", q, "badlen");
20834 			goto discard_pkt;
20835 		}
20836 		if (v_hlen > (mp->b_wptr - rptr)) {
20837 			if (!pullupmsg(mp, v_hlen)) {
20838 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20839 				    "ip_wput_end: q %p (%S)", q, "badpullup2");
20840 				goto discard_pkt;
20841 			}
20842 			ipha = (ipha_t *)mp->b_rptr;
20843 		}
20844 		/*
20845 		 * Move first entry from any source route into ipha_dst and
20846 		 * verify the options
20847 		 */
20848 		if (ip_wput_options(q, first_mp, ipha, mctl_present,
20849 		    zoneid, ipst)) {
20850 			ASSERT(xmit_ill == NULL);
20851 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
20852 			if (attach_ill != NULL)
20853 				ill_refrele(attach_ill);
20854 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
20855 			    "ip_wput_end: q %p (%S)", q, "badopts");
20856 			if (need_decref)
20857 				CONN_DEC_REF(connp);
20858 			return;
20859 		}
20860 	}
20861 	dst = ipha->ipha_dst;
20862 
20863 	/*
20864 	 * Try to get an IRE_CACHE for the destination address.	 If we can't,
20865 	 * we have to run the packet through ip_newroute which will take
20866 	 * the appropriate action to arrange for an IRE_CACHE, such as querying
20867 	 * a resolver, or assigning a default gateway, etc.
20868 	 */
20869 	if (CLASSD(dst)) {
20870 		ipif_t	*ipif;
20871 		uint32_t setsrc = 0;
20872 
20873 multicast:
20874 		ASSERT(first_mp != NULL);
20875 		ip2dbg(("ip_wput: CLASSD\n"));
20876 		if (connp == NULL) {
20877 			/*
20878 			 * Use the first good ipif on the ill.
20879 			 * XXX Should this ever happen? (Appears
20880 			 * to show up with just ppp and no ethernet due
20881 			 * to in.rdisc.)
20882 			 * However, ire_send should be able to
20883 			 * call ip_wput_ire directly.
20884 			 *
20885 			 * XXX Also, this can happen for ICMP and other packets
20886 			 * with multicast source addresses.  Perhaps we should
20887 			 * fix things so that we drop the packet in question,
20888 			 * but for now, just run with it.
20889 			 */
20890 			ill_t *ill = (ill_t *)q->q_ptr;
20891 
20892 			/*
20893 			 * Don't honor attach_if for this case. If ill
20894 			 * is part of the group, ipif could belong to
20895 			 * any ill and we cannot maintain attach_ill
20896 			 * and ipif_ill same anymore and the assert
20897 			 * below would fail.
20898 			 */
20899 			if (mctl_present && io->ipsec_out_attach_if) {
20900 				io->ipsec_out_ill_index = 0;
20901 				io->ipsec_out_attach_if = B_FALSE;
20902 				ASSERT(attach_ill != NULL);
20903 				ill_refrele(attach_ill);
20904 				attach_ill = NULL;
20905 			}
20906 
20907 			ASSERT(attach_ill == NULL);
20908 			ipif = ipif_select_source(ill, dst, GLOBAL_ZONEID);
20909 			if (ipif == NULL) {
20910 				if (need_decref)
20911 					CONN_DEC_REF(connp);
20912 				freemsg(first_mp);
20913 				return;
20914 			}
20915 			ip1dbg(("ip_wput: CLASSD no CONN: dst 0x%x on %s\n",
20916 			    ntohl(dst), ill->ill_name));
20917 		} else {
20918 			/*
20919 			 * The order of precedence is IP_BOUND_IF, IP_PKTINFO
20920 			 * and IP_MULTICAST_IF.  The block comment above this
20921 			 * function explains the locking mechanism used here.
20922 			 */
20923 			if (xmit_ill == NULL) {
20924 				xmit_ill = conn_get_held_ill(connp,
20925 				    &connp->conn_outgoing_ill, &err);
20926 				if (err == ILL_LOOKUP_FAILED) {
20927 					ip1dbg(("ip_wput: No ill for "
20928 					    "IP_BOUND_IF\n"));
20929 					BUMP_MIB(&ipst->ips_ip_mib,
20930 					    ipIfStatsOutNoRoutes);
20931 					goto drop_pkt;
20932 				}
20933 			}
20934 
20935 			if (xmit_ill == NULL) {
20936 				ipif = conn_get_held_ipif(connp,
20937 				    &connp->conn_multicast_ipif, &err);
20938 				if (err == IPIF_LOOKUP_FAILED) {
20939 					ip1dbg(("ip_wput: No ipif for "
20940 					    "multicast\n"));
20941 					BUMP_MIB(&ipst->ips_ip_mib,
20942 					    ipIfStatsOutNoRoutes);
20943 					goto drop_pkt;
20944 				}
20945 			}
20946 			if (xmit_ill != NULL) {
20947 				ipif = ipif_get_next_ipif(NULL, xmit_ill);
20948 				if (ipif == NULL) {
20949 					ip1dbg(("ip_wput: No ipif for "
20950 					    "xmit_ill\n"));
20951 					BUMP_MIB(&ipst->ips_ip_mib,
20952 					    ipIfStatsOutNoRoutes);
20953 					goto drop_pkt;
20954 				}
20955 			} else if (ipif == NULL || ipif->ipif_isv6) {
20956 				/*
20957 				 * We must do this ipif determination here
20958 				 * else we could pass through ip_newroute
20959 				 * and come back here without the conn context.
20960 				 *
20961 				 * Note: we do late binding i.e. we bind to
20962 				 * the interface when the first packet is sent.
20963 				 * For performance reasons we do not rebind on
20964 				 * each packet but keep the binding until the
20965 				 * next IP_MULTICAST_IF option.
20966 				 *
20967 				 * conn_multicast_{ipif,ill} are shared between
20968 				 * IPv4 and IPv6 and AF_INET6 sockets can
20969 				 * send both IPv4 and IPv6 packets. Hence
20970 				 * we have to check that "isv6" matches above.
20971 				 */
20972 				if (ipif != NULL)
20973 					ipif_refrele(ipif);
20974 				ipif = ipif_lookup_group(dst, zoneid, ipst);
20975 				if (ipif == NULL) {
20976 					ip1dbg(("ip_wput: No ipif for "
20977 					    "multicast\n"));
20978 					BUMP_MIB(&ipst->ips_ip_mib,
20979 					    ipIfStatsOutNoRoutes);
20980 					goto drop_pkt;
20981 				}
20982 				err = conn_set_held_ipif(connp,
20983 				    &connp->conn_multicast_ipif, ipif);
20984 				if (err == IPIF_LOOKUP_FAILED) {
20985 					ipif_refrele(ipif);
20986 					ip1dbg(("ip_wput: No ipif for "
20987 					    "multicast\n"));
20988 					BUMP_MIB(&ipst->ips_ip_mib,
20989 					    ipIfStatsOutNoRoutes);
20990 					goto drop_pkt;
20991 				}
20992 			}
20993 		}
20994 		ASSERT(!ipif->ipif_isv6);
20995 		/*
20996 		 * As we may lose the conn by the time we reach ip_wput_ire,
20997 		 * we copy conn_multicast_loop and conn_dontroute on to an
20998 		 * ipsec_out. In case if this datagram goes out secure,
20999 		 * we need the ill_index also. Copy that also into the
21000 		 * ipsec_out.
21001 		 */
21002 		if (mctl_present) {
21003 			io = (ipsec_out_t *)first_mp->b_rptr;
21004 			ASSERT(first_mp->b_datap->db_type == M_CTL);
21005 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
21006 		} else {
21007 			ASSERT(mp == first_mp);
21008 			if ((first_mp = allocb(sizeof (ipsec_info_t),
21009 			    BPRI_HI)) == NULL) {
21010 				ipif_refrele(ipif);
21011 				first_mp = mp;
21012 				goto discard_pkt;
21013 			}
21014 			first_mp->b_datap->db_type = M_CTL;
21015 			first_mp->b_wptr += sizeof (ipsec_info_t);
21016 			/* ipsec_out_secure is B_FALSE now */
21017 			bzero(first_mp->b_rptr, sizeof (ipsec_info_t));
21018 			io = (ipsec_out_t *)first_mp->b_rptr;
21019 			io->ipsec_out_type = IPSEC_OUT;
21020 			io->ipsec_out_len = sizeof (ipsec_out_t);
21021 			io->ipsec_out_use_global_policy = B_TRUE;
21022 			io->ipsec_out_ns = ipst->ips_netstack;
21023 			first_mp->b_cont = mp;
21024 			mctl_present = B_TRUE;
21025 		}
21026 		if (attach_ill != NULL) {
21027 			ASSERT(attach_ill == ipif->ipif_ill);
21028 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21029 
21030 			/*
21031 			 * Check if we need an ire that will not be
21032 			 * looked up by anybody else i.e. HIDDEN.
21033 			 */
21034 			if (ill_is_probeonly(attach_ill)) {
21035 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21036 			}
21037 			io->ipsec_out_ill_index =
21038 			    attach_ill->ill_phyint->phyint_ifindex;
21039 			io->ipsec_out_attach_if = B_TRUE;
21040 		} else {
21041 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21042 			io->ipsec_out_ill_index =
21043 			    ipif->ipif_ill->ill_phyint->phyint_ifindex;
21044 		}
21045 		if (connp != NULL) {
21046 			io->ipsec_out_multicast_loop =
21047 			    connp->conn_multicast_loop;
21048 			io->ipsec_out_dontroute = connp->conn_dontroute;
21049 			io->ipsec_out_zoneid = connp->conn_zoneid;
21050 		}
21051 		/*
21052 		 * If the application uses IP_MULTICAST_IF with
21053 		 * different logical addresses of the same ILL, we
21054 		 * need to make sure that the soruce address of
21055 		 * the packet matches the logical IP address used
21056 		 * in the option. We do it by initializing ipha_src
21057 		 * here. This should keep IPsec also happy as
21058 		 * when we return from IPsec processing, we don't
21059 		 * have to worry about getting the right address on
21060 		 * the packet. Thus it is sufficient to look for
21061 		 * IRE_CACHE using MATCH_IRE_ILL rathen than
21062 		 * MATCH_IRE_IPIF.
21063 		 *
21064 		 * NOTE : We need to do it for non-secure case also as
21065 		 * this might go out secure if there is a global policy
21066 		 * match in ip_wput_ire. For bind to IPIF_NOFAILOVER
21067 		 * address, the source should be initialized already and
21068 		 * hence we won't be initializing here.
21069 		 *
21070 		 * As we do not have the ire yet, it is possible that
21071 		 * we set the source address here and then later discover
21072 		 * that the ire implies the source address to be assigned
21073 		 * through the RTF_SETSRC flag.
21074 		 * In that case, the setsrc variable will remind us
21075 		 * that overwritting the source address by the one
21076 		 * of the RTF_SETSRC-flagged ire is allowed.
21077 		 */
21078 		if (ipha->ipha_src == INADDR_ANY &&
21079 		    (connp == NULL || !connp->conn_unspec_src)) {
21080 			ipha->ipha_src = ipif->ipif_src_addr;
21081 			setsrc = RTF_SETSRC;
21082 		}
21083 		/*
21084 		 * Find an IRE which matches the destination and the outgoing
21085 		 * queue (i.e. the outgoing interface.)
21086 		 * For loopback use a unicast IP address for
21087 		 * the ire lookup.
21088 		 */
21089 		if (IS_LOOPBACK(ipif->ipif_ill))
21090 			dst = ipif->ipif_lcl_addr;
21091 
21092 		/*
21093 		 * If xmit_ill is set, we branch out to ip_newroute_ipif.
21094 		 * We don't need to lookup ire in ctable as the packet
21095 		 * needs to be sent to the destination through the specified
21096 		 * ill irrespective of ires in the cache table.
21097 		 */
21098 		ire = NULL;
21099 		if (xmit_ill == NULL) {
21100 			ire = ire_ctable_lookup(dst, 0, 0, ipif,
21101 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21102 		}
21103 
21104 		/*
21105 		 * refrele attach_ill as its not needed anymore.
21106 		 */
21107 		if (attach_ill != NULL) {
21108 			ill_refrele(attach_ill);
21109 			attach_ill = NULL;
21110 		}
21111 
21112 		if (ire == NULL) {
21113 			/*
21114 			 * Multicast loopback and multicast forwarding is
21115 			 * done in ip_wput_ire.
21116 			 *
21117 			 * Mark this packet to make it be delivered to
21118 			 * ip_wput_ire after the new ire has been
21119 			 * created.
21120 			 *
21121 			 * The call to ip_newroute_ipif takes into account
21122 			 * the setsrc reminder. In any case, we take care
21123 			 * of the RTF_MULTIRT flag.
21124 			 */
21125 			mp->b_prev = mp->b_next = NULL;
21126 			if (xmit_ill == NULL ||
21127 			    xmit_ill->ill_ipif_up_count > 0) {
21128 				ip_newroute_ipif(q, first_mp, ipif, dst, connp,
21129 				    setsrc | RTF_MULTIRT, zoneid, infop);
21130 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21131 				    "ip_wput_end: q %p (%S)", q, "noire");
21132 			} else {
21133 				freemsg(first_mp);
21134 			}
21135 			ipif_refrele(ipif);
21136 			if (xmit_ill != NULL)
21137 				ill_refrele(xmit_ill);
21138 			if (need_decref)
21139 				CONN_DEC_REF(connp);
21140 			return;
21141 		}
21142 
21143 		ipif_refrele(ipif);
21144 		ipif = NULL;
21145 		ASSERT(xmit_ill == NULL);
21146 
21147 		/*
21148 		 * Honor the RTF_SETSRC flag for multicast packets,
21149 		 * if allowed by the setsrc reminder.
21150 		 */
21151 		if ((ire->ire_flags & RTF_SETSRC) && setsrc) {
21152 			ipha->ipha_src = ire->ire_src_addr;
21153 		}
21154 
21155 		/*
21156 		 * Unconditionally force the TTL to 1 for
21157 		 * multirouted multicast packets:
21158 		 * multirouted multicast should not cross
21159 		 * multicast routers.
21160 		 */
21161 		if (ire->ire_flags & RTF_MULTIRT) {
21162 			if (ipha->ipha_ttl > 1) {
21163 				ip2dbg(("ip_wput: forcing multicast "
21164 				    "multirt TTL to 1 (was %d), dst 0x%08x\n",
21165 				    ipha->ipha_ttl, ntohl(ire->ire_addr)));
21166 				ipha->ipha_ttl = 1;
21167 			}
21168 		}
21169 	} else {
21170 		ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp), ipst);
21171 		if ((ire != NULL) && (ire->ire_type &
21172 		    (IRE_BROADCAST | IRE_LOCAL | IRE_LOOPBACK))) {
21173 			ignore_dontroute = B_TRUE;
21174 			ignore_nexthop = B_TRUE;
21175 		}
21176 		if (ire != NULL) {
21177 			ire_refrele(ire);
21178 			ire = NULL;
21179 		}
21180 		/*
21181 		 * Guard against coming in from arp in which case conn is NULL.
21182 		 * Also guard against non M_DATA with dontroute set but
21183 		 * destined to local, loopback or broadcast addresses.
21184 		 */
21185 		if (connp != NULL && connp->conn_dontroute &&
21186 		    !ignore_dontroute) {
21187 dontroute:
21188 			/*
21189 			 * Set TTL to 1 if SO_DONTROUTE is set to prevent
21190 			 * routing protocols from seeing false direct
21191 			 * connectivity.
21192 			 */
21193 			ipha->ipha_ttl = 1;
21194 
21195 			/* If suitable ipif not found, drop packet */
21196 			dst_ipif = ipif_lookup_onlink_addr(dst, zoneid, ipst);
21197 			if (dst_ipif == NULL) {
21198 noroute:
21199 				ip1dbg(("ip_wput: no route for dst using"
21200 				    " SO_DONTROUTE\n"));
21201 				BUMP_MIB(&ipst->ips_ip_mib,
21202 				    ipIfStatsOutNoRoutes);
21203 				mp->b_prev = mp->b_next = NULL;
21204 				if (first_mp == NULL)
21205 					first_mp = mp;
21206 				goto drop_pkt;
21207 			} else {
21208 				/*
21209 				 * If suitable ipif has been found, set
21210 				 * xmit_ill to the corresponding
21211 				 * ipif_ill because we'll be using the
21212 				 * send_from_ill logic below.
21213 				 */
21214 				ASSERT(xmit_ill == NULL);
21215 				xmit_ill = dst_ipif->ipif_ill;
21216 				mutex_enter(&xmit_ill->ill_lock);
21217 				if (!ILL_CAN_LOOKUP(xmit_ill)) {
21218 					mutex_exit(&xmit_ill->ill_lock);
21219 					xmit_ill = NULL;
21220 					ipif_refrele(dst_ipif);
21221 					goto noroute;
21222 				}
21223 				ill_refhold_locked(xmit_ill);
21224 				mutex_exit(&xmit_ill->ill_lock);
21225 				ipif_refrele(dst_ipif);
21226 			}
21227 		}
21228 		/*
21229 		 * If we are bound to IPIF_NOFAILOVER address, look for
21230 		 * an IRE_CACHE matching the ill.
21231 		 */
21232 send_from_ill:
21233 		if (attach_ill != NULL) {
21234 			ipif_t	*attach_ipif;
21235 
21236 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
21237 
21238 			/*
21239 			 * Check if we need an ire that will not be
21240 			 * looked up by anybody else i.e. HIDDEN.
21241 			 */
21242 			if (ill_is_probeonly(attach_ill)) {
21243 				match_flags |= MATCH_IRE_MARK_HIDDEN;
21244 			}
21245 
21246 			attach_ipif = ipif_get_next_ipif(NULL, attach_ill);
21247 			if (attach_ipif == NULL) {
21248 				ip1dbg(("ip_wput: No ipif for attach_ill\n"));
21249 				goto discard_pkt;
21250 			}
21251 			ire = ire_ctable_lookup(dst, 0, 0, attach_ipif,
21252 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21253 			ipif_refrele(attach_ipif);
21254 		} else if (xmit_ill != NULL) {
21255 			ipif_t *ipif;
21256 
21257 			/*
21258 			 * Mark this packet as originated locally
21259 			 */
21260 			mp->b_prev = mp->b_next = NULL;
21261 
21262 			/*
21263 			 * Could be SO_DONTROUTE case also.
21264 			 * Verify that at least one ipif is up on the ill.
21265 			 */
21266 			if (xmit_ill->ill_ipif_up_count == 0) {
21267 				ip1dbg(("ip_output: xmit_ill %s is down\n",
21268 				    xmit_ill->ill_name));
21269 				goto drop_pkt;
21270 			}
21271 
21272 			ipif = ipif_get_next_ipif(NULL, xmit_ill);
21273 			if (ipif == NULL) {
21274 				ip1dbg(("ip_output: xmit_ill %s NULL ipif\n",
21275 				    xmit_ill->ill_name));
21276 				goto drop_pkt;
21277 			}
21278 
21279 			/*
21280 			 * Look for a ire that is part of the group,
21281 			 * if found use it else call ip_newroute_ipif.
21282 			 * IPCL_ZONEID is not used for matching because
21283 			 * IP_ALLZONES option is valid only when the
21284 			 * ill is accessible from all zones i.e has a
21285 			 * valid ipif in all zones.
21286 			 */
21287 			match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
21288 			ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
21289 			    MBLK_GETLABEL(mp), match_flags, ipst);
21290 			/*
21291 			 * If an ire exists use it or else create
21292 			 * an ire but don't add it to the cache.
21293 			 * Adding an ire may cause issues with
21294 			 * asymmetric routing.
21295 			 * In case of multiroute always act as if
21296 			 * ire does not exist.
21297 			 */
21298 			if (ire == NULL || ire->ire_flags & RTF_MULTIRT) {
21299 				if (ire != NULL)
21300 					ire_refrele(ire);
21301 				ip_newroute_ipif(q, first_mp, ipif,
21302 				    dst, connp, 0, zoneid, infop);
21303 				ipif_refrele(ipif);
21304 				ip1dbg(("ip_output: xmit_ill via %s\n",
21305 				    xmit_ill->ill_name));
21306 				ill_refrele(xmit_ill);
21307 				if (need_decref)
21308 					CONN_DEC_REF(connp);
21309 				return;
21310 			}
21311 			ipif_refrele(ipif);
21312 		} else if (ip_nexthop || (connp != NULL &&
21313 		    (connp->conn_nexthop_set)) && !ignore_nexthop) {
21314 			if (!ip_nexthop) {
21315 				ip_nexthop = B_TRUE;
21316 				nexthop_addr = connp->conn_nexthop_v4;
21317 			}
21318 			match_flags = MATCH_IRE_MARK_PRIVATE_ADDR |
21319 			    MATCH_IRE_GW;
21320 			ire = ire_ctable_lookup(dst, nexthop_addr, 0,
21321 			    NULL, zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
21322 		} else {
21323 			ire = ire_cache_lookup(dst, zoneid, MBLK_GETLABEL(mp),
21324 			    ipst);
21325 		}
21326 		if (!ire) {
21327 			/*
21328 			 * Make sure we don't load spread if this
21329 			 * is IPIF_NOFAILOVER case.
21330 			 */
21331 			if ((attach_ill != NULL) ||
21332 			    (ip_nexthop && !ignore_nexthop)) {
21333 				if (mctl_present) {
21334 					io = (ipsec_out_t *)first_mp->b_rptr;
21335 					ASSERT(first_mp->b_datap->db_type ==
21336 					    M_CTL);
21337 					ASSERT(io->ipsec_out_type == IPSEC_OUT);
21338 				} else {
21339 					ASSERT(mp == first_mp);
21340 					first_mp = allocb(
21341 					    sizeof (ipsec_info_t), BPRI_HI);
21342 					if (first_mp == NULL) {
21343 						first_mp = mp;
21344 						goto discard_pkt;
21345 					}
21346 					first_mp->b_datap->db_type = M_CTL;
21347 					first_mp->b_wptr +=
21348 					    sizeof (ipsec_info_t);
21349 					/* ipsec_out_secure is B_FALSE now */
21350 					bzero(first_mp->b_rptr,
21351 					    sizeof (ipsec_info_t));
21352 					io = (ipsec_out_t *)first_mp->b_rptr;
21353 					io->ipsec_out_type = IPSEC_OUT;
21354 					io->ipsec_out_len =
21355 					    sizeof (ipsec_out_t);
21356 					io->ipsec_out_use_global_policy =
21357 					    B_TRUE;
21358 					io->ipsec_out_ns = ipst->ips_netstack;
21359 					first_mp->b_cont = mp;
21360 					mctl_present = B_TRUE;
21361 				}
21362 				if (attach_ill != NULL) {
21363 					io->ipsec_out_ill_index = attach_ill->
21364 					    ill_phyint->phyint_ifindex;
21365 					io->ipsec_out_attach_if = B_TRUE;
21366 				} else {
21367 					io->ipsec_out_ip_nexthop = ip_nexthop;
21368 					io->ipsec_out_nexthop_addr =
21369 					    nexthop_addr;
21370 				}
21371 			}
21372 noirefound:
21373 			/*
21374 			 * Mark this packet as having originated on
21375 			 * this machine.  This will be noted in
21376 			 * ire_add_then_send, which needs to know
21377 			 * whether to run it back through ip_wput or
21378 			 * ip_rput following successful resolution.
21379 			 */
21380 			mp->b_prev = NULL;
21381 			mp->b_next = NULL;
21382 			ip_newroute(q, first_mp, dst, connp, zoneid, ipst);
21383 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21384 			    "ip_wput_end: q %p (%S)", q, "newroute");
21385 			if (attach_ill != NULL)
21386 				ill_refrele(attach_ill);
21387 			if (xmit_ill != NULL)
21388 				ill_refrele(xmit_ill);
21389 			if (need_decref)
21390 				CONN_DEC_REF(connp);
21391 			return;
21392 		}
21393 	}
21394 
21395 	/* We now know where we are going with it. */
21396 
21397 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21398 	    "ip_wput_end: q %p (%S)", q, "end");
21399 
21400 	/*
21401 	 * Check if the ire has the RTF_MULTIRT flag, inherited
21402 	 * from an IRE_OFFSUBNET ire entry in ip_newroute.
21403 	 */
21404 	if (ire->ire_flags & RTF_MULTIRT) {
21405 		/*
21406 		 * Force the TTL of multirouted packets if required.
21407 		 * The TTL of such packets is bounded by the
21408 		 * ip_multirt_ttl ndd variable.
21409 		 */
21410 		if ((ipst->ips_ip_multirt_ttl > 0) &&
21411 		    (ipha->ipha_ttl > ipst->ips_ip_multirt_ttl)) {
21412 			ip2dbg(("ip_wput: forcing multirt TTL to %d "
21413 			    "(was %d), dst 0x%08x\n",
21414 			    ipst->ips_ip_multirt_ttl, ipha->ipha_ttl,
21415 			    ntohl(ire->ire_addr)));
21416 			ipha->ipha_ttl = ipst->ips_ip_multirt_ttl;
21417 		}
21418 		/*
21419 		 * At this point, we check to see if there are any pending
21420 		 * unresolved routes. ire_multirt_resolvable()
21421 		 * checks in O(n) that all IRE_OFFSUBNET ire
21422 		 * entries for the packet's destination and
21423 		 * flagged RTF_MULTIRT are currently resolved.
21424 		 * If some remain unresolved, we make a copy
21425 		 * of the current message. It will be used
21426 		 * to initiate additional route resolutions.
21427 		 */
21428 		multirt_need_resolve = ire_multirt_need_resolve(ire->ire_addr,
21429 		    MBLK_GETLABEL(first_mp), ipst);
21430 		ip2dbg(("ip_wput[noirefound]: ire %p, "
21431 		    "multirt_need_resolve %d, first_mp %p\n",
21432 		    (void *)ire, multirt_need_resolve, (void *)first_mp));
21433 		if (multirt_need_resolve) {
21434 			copy_mp = copymsg(first_mp);
21435 			if (copy_mp != NULL) {
21436 				MULTIRT_DEBUG_TAG(copy_mp);
21437 			}
21438 		}
21439 	}
21440 
21441 	ip_wput_ire(q, first_mp, ire, connp, caller, zoneid);
21442 	/*
21443 	 * Try to resolve another multiroute if
21444 	 * ire_multirt_resolvable() deemed it necessary.
21445 	 * At this point, we need to distinguish
21446 	 * multicasts from other packets. For multicasts,
21447 	 * we call ip_newroute_ipif() and request that both
21448 	 * multirouting and setsrc flags are checked.
21449 	 */
21450 	if (copy_mp != NULL) {
21451 		if (CLASSD(dst)) {
21452 			ipif_t *ipif = ipif_lookup_group(dst, zoneid, ipst);
21453 			if (ipif) {
21454 				ASSERT(infop->ip_opt_ill_index == 0);
21455 				ip_newroute_ipif(q, copy_mp, ipif, dst, connp,
21456 				    RTF_SETSRC | RTF_MULTIRT, zoneid, infop);
21457 				ipif_refrele(ipif);
21458 			} else {
21459 				MULTIRT_DEBUG_UNTAG(copy_mp);
21460 				freemsg(copy_mp);
21461 				copy_mp = NULL;
21462 			}
21463 		} else {
21464 			ip_newroute(q, copy_mp, dst, connp, zoneid, ipst);
21465 		}
21466 	}
21467 	if (attach_ill != NULL)
21468 		ill_refrele(attach_ill);
21469 	if (xmit_ill != NULL)
21470 		ill_refrele(xmit_ill);
21471 	if (need_decref)
21472 		CONN_DEC_REF(connp);
21473 	return;
21474 
21475 icmp_parameter_problem:
21476 	/* could not have originated externally */
21477 	ASSERT(mp->b_prev == NULL);
21478 	if (ip_hdr_complete(ipha, zoneid, ipst) == 0) {
21479 		BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
21480 		/* it's the IP header length that's in trouble */
21481 		icmp_param_problem(q, first_mp, 0, zoneid, ipst);
21482 		first_mp = NULL;
21483 	}
21484 
21485 discard_pkt:
21486 	BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
21487 drop_pkt:
21488 	ip1dbg(("ip_wput: dropped packet\n"));
21489 	if (ire != NULL)
21490 		ire_refrele(ire);
21491 	if (need_decref)
21492 		CONN_DEC_REF(connp);
21493 	freemsg(first_mp);
21494 	if (attach_ill != NULL)
21495 		ill_refrele(attach_ill);
21496 	if (xmit_ill != NULL)
21497 		ill_refrele(xmit_ill);
21498 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_END,
21499 	    "ip_wput_end: q %p (%S)", q, "droppkt");
21500 }
21501 
21502 /*
21503  * If this is a conn_t queue, then we pass in the conn. This includes the
21504  * zoneid.
21505  * Otherwise, this is a message coming back from ARP or for an ill_t queue,
21506  * in which case we use the global zoneid since those are all part of
21507  * the global zone.
21508  */
21509 void
21510 ip_wput(queue_t *q, mblk_t *mp)
21511 {
21512 	if (CONN_Q(q))
21513 		ip_output(Q_TO_CONN(q), mp, q, IP_WPUT);
21514 	else
21515 		ip_output(GLOBAL_ZONEID, mp, q, IP_WPUT);
21516 }
21517 
21518 /*
21519  *
21520  * The following rules must be observed when accessing any ipif or ill
21521  * that has been cached in the conn. Typically conn_nofailover_ill,
21522  * conn_outgoing_ill, conn_multicast_ipif and conn_multicast_ill.
21523  *
21524  * Access: The ipif or ill pointed to from the conn can be accessed under
21525  * the protection of the conn_lock or after it has been refheld under the
21526  * protection of the conn lock. In addition the IPIF_CAN_LOOKUP or
21527  * ILL_CAN_LOOKUP macros must be used before actually doing the refhold.
21528  * The reason for this is that a concurrent unplumb could actually be
21529  * cleaning up these cached pointers by walking the conns and might have
21530  * finished cleaning up the conn in question. The macros check that an
21531  * unplumb has not yet started on the ipif or ill.
21532  *
21533  * Caching: An ipif or ill pointer may be cached in the conn only after
21534  * making sure that an unplumb has not started. So the caching is done
21535  * while holding both the conn_lock and the ill_lock and after using the
21536  * ILL_CAN_LOOKUP/IPIF_CAN_LOOKUP macro. An unplumb will set the ILL_CONDEMNED
21537  * flag before starting the cleanup of conns.
21538  *
21539  * The list of ipifs hanging off the ill is protected by ill_g_lock and ill_lock
21540  * On the other hand to access ipif->ipif_ill, we need one of either ill_g_lock
21541  * or a reference to the ipif or a reference to an ire that references the
21542  * ipif. An ipif does not change its ill except for failover/failback. Since
21543  * failover/failback happens only after bringing down the ipif and making sure
21544  * the ipif refcnt has gone to zero and holding the ill_g_lock and ill_lock
21545  * the above holds.
21546  */
21547 ipif_t *
21548 conn_get_held_ipif(conn_t *connp, ipif_t **ipifp, int *err)
21549 {
21550 	ipif_t	*ipif;
21551 	ill_t	*ill;
21552 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
21553 
21554 	*err = 0;
21555 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
21556 	mutex_enter(&connp->conn_lock);
21557 	ipif = *ipifp;
21558 	if (ipif != NULL) {
21559 		ill = ipif->ipif_ill;
21560 		mutex_enter(&ill->ill_lock);
21561 		if (IPIF_CAN_LOOKUP(ipif)) {
21562 			ipif_refhold_locked(ipif);
21563 			mutex_exit(&ill->ill_lock);
21564 			mutex_exit(&connp->conn_lock);
21565 			rw_exit(&ipst->ips_ill_g_lock);
21566 			return (ipif);
21567 		} else {
21568 			*err = IPIF_LOOKUP_FAILED;
21569 		}
21570 		mutex_exit(&ill->ill_lock);
21571 	}
21572 	mutex_exit(&connp->conn_lock);
21573 	rw_exit(&ipst->ips_ill_g_lock);
21574 	return (NULL);
21575 }
21576 
21577 ill_t *
21578 conn_get_held_ill(conn_t *connp, ill_t **illp, int *err)
21579 {
21580 	ill_t	*ill;
21581 
21582 	*err = 0;
21583 	mutex_enter(&connp->conn_lock);
21584 	ill = *illp;
21585 	if (ill != NULL) {
21586 		mutex_enter(&ill->ill_lock);
21587 		if (ILL_CAN_LOOKUP(ill)) {
21588 			ill_refhold_locked(ill);
21589 			mutex_exit(&ill->ill_lock);
21590 			mutex_exit(&connp->conn_lock);
21591 			return (ill);
21592 		} else {
21593 			*err = ILL_LOOKUP_FAILED;
21594 		}
21595 		mutex_exit(&ill->ill_lock);
21596 	}
21597 	mutex_exit(&connp->conn_lock);
21598 	return (NULL);
21599 }
21600 
21601 static int
21602 conn_set_held_ipif(conn_t *connp, ipif_t **ipifp, ipif_t *ipif)
21603 {
21604 	ill_t	*ill;
21605 
21606 	ill = ipif->ipif_ill;
21607 	mutex_enter(&connp->conn_lock);
21608 	mutex_enter(&ill->ill_lock);
21609 	if (IPIF_CAN_LOOKUP(ipif)) {
21610 		*ipifp = ipif;
21611 		mutex_exit(&ill->ill_lock);
21612 		mutex_exit(&connp->conn_lock);
21613 		return (0);
21614 	}
21615 	mutex_exit(&ill->ill_lock);
21616 	mutex_exit(&connp->conn_lock);
21617 	return (IPIF_LOOKUP_FAILED);
21618 }
21619 
21620 /*
21621  * This is called if the outbound datagram needs fragmentation.
21622  *
21623  * NOTE : This function does not ire_refrele the ire argument passed in.
21624  */
21625 static void
21626 ip_wput_ire_fragmentit(mblk_t *ipsec_mp, ire_t *ire, zoneid_t zoneid,
21627     ip_stack_t *ipst)
21628 {
21629 	ipha_t		*ipha;
21630 	mblk_t		*mp;
21631 	uint32_t	v_hlen_tos_len;
21632 	uint32_t	max_frag;
21633 	uint32_t	frag_flag;
21634 	boolean_t	dont_use;
21635 
21636 	if (ipsec_mp->b_datap->db_type == M_CTL) {
21637 		mp = ipsec_mp->b_cont;
21638 	} else {
21639 		mp = ipsec_mp;
21640 	}
21641 
21642 	ipha = (ipha_t *)mp->b_rptr;
21643 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
21644 
21645 #ifdef	_BIG_ENDIAN
21646 #define	V_HLEN	(v_hlen_tos_len >> 24)
21647 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
21648 #else
21649 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
21650 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
21651 #endif
21652 
21653 #ifndef SPEED_BEFORE_SAFETY
21654 	/*
21655 	 * Check that ipha_length is consistent with
21656 	 * the mblk length
21657 	 */
21658 	if (LENGTH != (mp->b_cont ? msgdsize(mp) : mp->b_wptr - rptr)) {
21659 		ip0dbg(("Packet length mismatch: %d, %ld\n",
21660 		    LENGTH, msgdsize(mp)));
21661 		freemsg(ipsec_mp);
21662 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
21663 		    "ip_wput_ire_fragmentit: mp %p (%S)", mp,
21664 		    "packet length mismatch");
21665 		return;
21666 	}
21667 #endif
21668 	/*
21669 	 * Don't use frag_flag if pre-built packet or source
21670 	 * routed or if multicast (since multicast packets do not solicit
21671 	 * ICMP "packet too big" messages). Get the values of
21672 	 * max_frag and frag_flag atomically by acquiring the
21673 	 * ire_lock.
21674 	 */
21675 	mutex_enter(&ire->ire_lock);
21676 	max_frag = ire->ire_max_frag;
21677 	frag_flag = ire->ire_frag_flag;
21678 	mutex_exit(&ire->ire_lock);
21679 
21680 	dont_use = ((ipha->ipha_ident == IP_HDR_INCLUDED) ||
21681 	    (V_HLEN != IP_SIMPLE_HDR_VERSION &&
21682 	    ip_source_route_included(ipha)) || CLASSD(ipha->ipha_dst));
21683 
21684 	ip_wput_frag(ire, ipsec_mp, OB_PKT, max_frag,
21685 	    (dont_use ? 0 : frag_flag), zoneid, ipst);
21686 }
21687 
21688 /*
21689  * Used for deciding the MSS size for the upper layer. Thus
21690  * we need to check the outbound policy values in the conn.
21691  */
21692 int
21693 conn_ipsec_length(conn_t *connp)
21694 {
21695 	ipsec_latch_t *ipl;
21696 
21697 	ipl = connp->conn_latch;
21698 	if (ipl == NULL)
21699 		return (0);
21700 
21701 	if (ipl->ipl_out_policy == NULL)
21702 		return (0);
21703 
21704 	return (ipl->ipl_out_policy->ipsp_act->ipa_ovhd);
21705 }
21706 
21707 /*
21708  * Returns an estimate of the IPsec headers size. This is used if
21709  * we don't want to call into IPsec to get the exact size.
21710  */
21711 int
21712 ipsec_out_extra_length(mblk_t *ipsec_mp)
21713 {
21714 	ipsec_out_t *io = (ipsec_out_t *)ipsec_mp->b_rptr;
21715 	ipsec_action_t *a;
21716 
21717 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
21718 	if (!io->ipsec_out_secure)
21719 		return (0);
21720 
21721 	a = io->ipsec_out_act;
21722 
21723 	if (a == NULL) {
21724 		ASSERT(io->ipsec_out_policy != NULL);
21725 		a = io->ipsec_out_policy->ipsp_act;
21726 	}
21727 	ASSERT(a != NULL);
21728 
21729 	return (a->ipa_ovhd);
21730 }
21731 
21732 /*
21733  * Returns an estimate of the IPsec headers size. This is used if
21734  * we don't want to call into IPsec to get the exact size.
21735  */
21736 int
21737 ipsec_in_extra_length(mblk_t *ipsec_mp)
21738 {
21739 	ipsec_in_t *ii = (ipsec_in_t *)ipsec_mp->b_rptr;
21740 	ipsec_action_t *a;
21741 
21742 	ASSERT(ii->ipsec_in_type == IPSEC_IN);
21743 
21744 	a = ii->ipsec_in_action;
21745 	return (a == NULL ? 0 : a->ipa_ovhd);
21746 }
21747 
21748 /*
21749  * If there are any source route options, return the true final
21750  * destination. Otherwise, return the destination.
21751  */
21752 ipaddr_t
21753 ip_get_dst(ipha_t *ipha)
21754 {
21755 	ipoptp_t	opts;
21756 	uchar_t		*opt;
21757 	uint8_t		optval;
21758 	uint8_t		optlen;
21759 	ipaddr_t	dst;
21760 	uint32_t off;
21761 
21762 	dst = ipha->ipha_dst;
21763 
21764 	if (IS_SIMPLE_IPH(ipha))
21765 		return (dst);
21766 
21767 	for (optval = ipoptp_first(&opts, ipha);
21768 	    optval != IPOPT_EOL;
21769 	    optval = ipoptp_next(&opts)) {
21770 		opt = opts.ipoptp_cur;
21771 		optlen = opts.ipoptp_len;
21772 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
21773 		switch (optval) {
21774 		case IPOPT_SSRR:
21775 		case IPOPT_LSRR:
21776 			off = opt[IPOPT_OFFSET];
21777 			/*
21778 			 * If one of the conditions is true, it means
21779 			 * end of options and dst already has the right
21780 			 * value.
21781 			 */
21782 			if (!(optlen < IP_ADDR_LEN || off > optlen - 3)) {
21783 				off = optlen - IP_ADDR_LEN;
21784 				bcopy(&opt[off], &dst, IP_ADDR_LEN);
21785 			}
21786 			return (dst);
21787 		default:
21788 			break;
21789 		}
21790 	}
21791 
21792 	return (dst);
21793 }
21794 
21795 mblk_t *
21796 ip_wput_ire_parse_ipsec_out(mblk_t *mp, ipha_t *ipha, ip6_t *ip6h, ire_t *ire,
21797     conn_t *connp, boolean_t unspec_src, zoneid_t zoneid)
21798 {
21799 	ipsec_out_t	*io;
21800 	mblk_t		*first_mp;
21801 	boolean_t policy_present;
21802 	ip_stack_t	*ipst;
21803 	ipsec_stack_t	*ipss;
21804 
21805 	ASSERT(ire != NULL);
21806 	ipst = ire->ire_ipst;
21807 	ipss = ipst->ips_netstack->netstack_ipsec;
21808 
21809 	first_mp = mp;
21810 	if (mp->b_datap->db_type == M_CTL) {
21811 		io = (ipsec_out_t *)first_mp->b_rptr;
21812 		/*
21813 		 * ip_wput[_v6] attaches an IPSEC_OUT in two cases.
21814 		 *
21815 		 * 1) There is per-socket policy (including cached global
21816 		 *    policy) or a policy on the IP-in-IP tunnel.
21817 		 * 2) There is no per-socket policy, but it is
21818 		 *    a multicast packet that needs to go out
21819 		 *    on a specific interface. This is the case
21820 		 *    where (ip_wput and ip_wput_multicast) attaches
21821 		 *    an IPSEC_OUT and sets ipsec_out_secure B_FALSE.
21822 		 *
21823 		 * In case (2) we check with global policy to
21824 		 * see if there is a match and set the ill_index
21825 		 * appropriately so that we can lookup the ire
21826 		 * properly in ip_wput_ipsec_out.
21827 		 */
21828 
21829 		/*
21830 		 * ipsec_out_use_global_policy is set to B_FALSE
21831 		 * in ipsec_in_to_out(). Refer to that function for
21832 		 * details.
21833 		 */
21834 		if ((io->ipsec_out_latch == NULL) &&
21835 		    (io->ipsec_out_use_global_policy)) {
21836 			return (ip_wput_attach_policy(first_mp, ipha, ip6h,
21837 			    ire, connp, unspec_src, zoneid));
21838 		}
21839 		if (!io->ipsec_out_secure) {
21840 			/*
21841 			 * If this is not a secure packet, drop
21842 			 * the IPSEC_OUT mp and treat it as a clear
21843 			 * packet. This happens when we are sending
21844 			 * a ICMP reply back to a clear packet. See
21845 			 * ipsec_in_to_out() for details.
21846 			 */
21847 			mp = first_mp->b_cont;
21848 			freeb(first_mp);
21849 		}
21850 		return (mp);
21851 	}
21852 	/*
21853 	 * See whether we need to attach a global policy here. We
21854 	 * don't depend on the conn (as it could be null) for deciding
21855 	 * what policy this datagram should go through because it
21856 	 * should have happened in ip_wput if there was some
21857 	 * policy. This normally happens for connections which are not
21858 	 * fully bound preventing us from caching policies in
21859 	 * ip_bind. Packets coming from the TCP listener/global queue
21860 	 * - which are non-hard_bound - could also be affected by
21861 	 * applying policy here.
21862 	 *
21863 	 * If this packet is coming from tcp global queue or listener,
21864 	 * we will be applying policy here.  This may not be *right*
21865 	 * if these packets are coming from the detached connection as
21866 	 * it could have gone in clear before. This happens only if a
21867 	 * TCP connection started when there is no policy and somebody
21868 	 * added policy before it became detached. Thus packets of the
21869 	 * detached connection could go out secure and the other end
21870 	 * would drop it because it will be expecting in clear. The
21871 	 * converse is not true i.e if somebody starts a TCP
21872 	 * connection and deletes the policy, all the packets will
21873 	 * still go out with the policy that existed before deleting
21874 	 * because ip_unbind sends up policy information which is used
21875 	 * by TCP on subsequent ip_wputs. The right solution is to fix
21876 	 * TCP to attach a dummy IPSEC_OUT and set
21877 	 * ipsec_out_use_global_policy to B_FALSE. As this might
21878 	 * affect performance for normal cases, we are not doing it.
21879 	 * Thus, set policy before starting any TCP connections.
21880 	 *
21881 	 * NOTE - We might apply policy even for a hard bound connection
21882 	 * - for which we cached policy in ip_bind - if somebody added
21883 	 * global policy after we inherited the policy in ip_bind.
21884 	 * This means that the packets that were going out in clear
21885 	 * previously would start going secure and hence get dropped
21886 	 * on the other side. To fix this, TCP attaches a dummy
21887 	 * ipsec_out and make sure that we don't apply global policy.
21888 	 */
21889 	if (ipha != NULL)
21890 		policy_present = ipss->ipsec_outbound_v4_policy_present;
21891 	else
21892 		policy_present = ipss->ipsec_outbound_v6_policy_present;
21893 	if (!policy_present)
21894 		return (mp);
21895 
21896 	return (ip_wput_attach_policy(mp, ipha, ip6h, ire, connp, unspec_src,
21897 	    zoneid));
21898 }
21899 
21900 ire_t *
21901 conn_set_outgoing_ill(conn_t *connp, ire_t *ire, ill_t **conn_outgoing_ill)
21902 {
21903 	ipaddr_t addr;
21904 	ire_t *save_ire;
21905 	irb_t *irb;
21906 	ill_group_t *illgrp;
21907 	int	err;
21908 
21909 	save_ire = ire;
21910 	addr = ire->ire_addr;
21911 
21912 	ASSERT(ire->ire_type == IRE_BROADCAST);
21913 
21914 	illgrp = connp->conn_outgoing_ill->ill_group;
21915 	if (illgrp == NULL) {
21916 		*conn_outgoing_ill = conn_get_held_ill(connp,
21917 		    &connp->conn_outgoing_ill, &err);
21918 		if (err == ILL_LOOKUP_FAILED) {
21919 			ire_refrele(save_ire);
21920 			return (NULL);
21921 		}
21922 		return (save_ire);
21923 	}
21924 	/*
21925 	 * If IP_BOUND_IF has been done, conn_outgoing_ill will be set.
21926 	 * If it is part of the group, we need to send on the ire
21927 	 * that has been cleared of IRE_MARK_NORECV and that belongs
21928 	 * to this group. This is okay as IP_BOUND_IF really means
21929 	 * any ill in the group. We depend on the fact that the
21930 	 * first ire in the group is always cleared of IRE_MARK_NORECV
21931 	 * if such an ire exists. This is possible only if you have
21932 	 * at least one ill in the group that has not failed.
21933 	 *
21934 	 * First get to the ire that matches the address and group.
21935 	 *
21936 	 * We don't look for an ire with a matching zoneid because a given zone
21937 	 * won't always have broadcast ires on all ills in the group.
21938 	 */
21939 	irb = ire->ire_bucket;
21940 	rw_enter(&irb->irb_lock, RW_READER);
21941 	if (ire->ire_marks & IRE_MARK_NORECV) {
21942 		/*
21943 		 * If the current zone only has an ire broadcast for this
21944 		 * address marked NORECV, the ire we want is ahead in the
21945 		 * bucket, so we look it up deliberately ignoring the zoneid.
21946 		 */
21947 		for (ire = irb->irb_ire; ire != NULL; ire = ire->ire_next) {
21948 			if (ire->ire_addr != addr)
21949 				continue;
21950 			/* skip over deleted ires */
21951 			if (ire->ire_marks & IRE_MARK_CONDEMNED)
21952 				continue;
21953 		}
21954 	}
21955 	while (ire != NULL) {
21956 		/*
21957 		 * If a new interface is coming up, we could end up
21958 		 * seeing the loopback ire and the non-loopback ire
21959 		 * may not have been added yet. So check for ire_stq
21960 		 */
21961 		if (ire->ire_stq != NULL && (ire->ire_addr != addr ||
21962 		    ire->ire_ipif->ipif_ill->ill_group == illgrp)) {
21963 			break;
21964 		}
21965 		ire = ire->ire_next;
21966 	}
21967 	if (ire != NULL && ire->ire_addr == addr &&
21968 	    ire->ire_ipif->ipif_ill->ill_group == illgrp) {
21969 		IRE_REFHOLD(ire);
21970 		rw_exit(&irb->irb_lock);
21971 		ire_refrele(save_ire);
21972 		*conn_outgoing_ill = ire_to_ill(ire);
21973 		/*
21974 		 * Refhold the ill to make the conn_outgoing_ill
21975 		 * independent of the ire. ip_wput_ire goes in a loop
21976 		 * and may refrele the ire. Since we have an ire at this
21977 		 * point we don't need to use ILL_CAN_LOOKUP on the ill.
21978 		 */
21979 		ill_refhold(*conn_outgoing_ill);
21980 		return (ire);
21981 	}
21982 	rw_exit(&irb->irb_lock);
21983 	ip1dbg(("conn_set_outgoing_ill: No matching ire\n"));
21984 	/*
21985 	 * If we can't find a suitable ire, return the original ire.
21986 	 */
21987 	return (save_ire);
21988 }
21989 
21990 /*
21991  * This function does the ire_refrele of the ire passed in as the
21992  * argument. As this function looks up more ires i.e broadcast ires,
21993  * it needs to REFRELE them. Currently, for simplicity we don't
21994  * differentiate the one passed in and looked up here. We always
21995  * REFRELE.
21996  * IPQoS Notes:
21997  * IP policy is invoked if IPP_LOCAL_OUT is enabled. Processing for
21998  * IPsec packets are done in ipsec_out_process.
21999  *
22000  */
22001 void
22002 ip_wput_ire(queue_t *q, mblk_t *mp, ire_t *ire, conn_t *connp, int caller,
22003     zoneid_t zoneid)
22004 {
22005 	ipha_t		*ipha;
22006 #define	rptr	((uchar_t *)ipha)
22007 	queue_t		*stq;
22008 #define	Q_TO_INDEX(stq)	(((ill_t *)stq->q_ptr)->ill_phyint->phyint_ifindex)
22009 	uint32_t	v_hlen_tos_len;
22010 	uint32_t	ttl_protocol;
22011 	ipaddr_t	src;
22012 	ipaddr_t	dst;
22013 	uint32_t	cksum;
22014 	ipaddr_t	orig_src;
22015 	ire_t		*ire1;
22016 	mblk_t		*next_mp;
22017 	uint_t		hlen;
22018 	uint16_t	*up;
22019 	uint32_t	max_frag = ire->ire_max_frag;
22020 	ill_t		*ill = ire_to_ill(ire);
22021 	int		clusterwide;
22022 	uint16_t	ip_hdr_included; /* IP header included by ULP? */
22023 	int		ipsec_len;
22024 	mblk_t		*first_mp;
22025 	ipsec_out_t	*io;
22026 	boolean_t	conn_dontroute;		/* conn value for multicast */
22027 	boolean_t	conn_multicast_loop;	/* conn value for multicast */
22028 	boolean_t	multicast_forward;	/* Should we forward ? */
22029 	boolean_t	unspec_src;
22030 	ill_t		*conn_outgoing_ill = NULL;
22031 	ill_t		*ire_ill;
22032 	ill_t		*ire1_ill;
22033 	ill_t		*out_ill;
22034 	uint32_t 	ill_index = 0;
22035 	boolean_t	multirt_send = B_FALSE;
22036 	int		err;
22037 	ipxmit_state_t	pktxmit_state;
22038 	ip_stack_t	*ipst = ire->ire_ipst;
22039 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
22040 
22041 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_IRE_START,
22042 	    "ip_wput_ire_start: q %p", q);
22043 
22044 	multicast_forward = B_FALSE;
22045 	unspec_src = (connp != NULL && connp->conn_unspec_src);
22046 
22047 	if (ire->ire_flags & RTF_MULTIRT) {
22048 		/*
22049 		 * Multirouting case. The bucket where ire is stored
22050 		 * probably holds other RTF_MULTIRT flagged ire
22051 		 * to the destination. In this call to ip_wput_ire,
22052 		 * we attempt to send the packet through all
22053 		 * those ires. Thus, we first ensure that ire is the
22054 		 * first RTF_MULTIRT ire in the bucket,
22055 		 * before walking the ire list.
22056 		 */
22057 		ire_t *first_ire;
22058 		irb_t *irb = ire->ire_bucket;
22059 		ASSERT(irb != NULL);
22060 
22061 		/* Make sure we do not omit any multiroute ire. */
22062 		IRB_REFHOLD(irb);
22063 		for (first_ire = irb->irb_ire;
22064 		    first_ire != NULL;
22065 		    first_ire = first_ire->ire_next) {
22066 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
22067 			    (first_ire->ire_addr == ire->ire_addr) &&
22068 			    !(first_ire->ire_marks &
22069 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
22070 				break;
22071 			}
22072 		}
22073 
22074 		if ((first_ire != NULL) && (first_ire != ire)) {
22075 			IRE_REFHOLD(first_ire);
22076 			ire_refrele(ire);
22077 			ire = first_ire;
22078 			ill = ire_to_ill(ire);
22079 		}
22080 		IRB_REFRELE(irb);
22081 	}
22082 
22083 	/*
22084 	 * conn_outgoing_ill variable is used only in the broadcast loop.
22085 	 * for performance we don't grab the mutexs in the fastpath
22086 	 */
22087 	if ((connp != NULL) &&
22088 	    (ire->ire_type == IRE_BROADCAST) &&
22089 	    ((connp->conn_nofailover_ill != NULL) ||
22090 	    (connp->conn_outgoing_ill != NULL))) {
22091 		/*
22092 		 * Bind to IPIF_NOFAILOVER address overrides IP_BOUND_IF
22093 		 * option. So, see if this endpoint is bound to a
22094 		 * IPIF_NOFAILOVER address. If so, honor it. This implies
22095 		 * that if the interface is failed, we will still send
22096 		 * the packet on the same ill which is what we want.
22097 		 */
22098 		conn_outgoing_ill = conn_get_held_ill(connp,
22099 		    &connp->conn_nofailover_ill, &err);
22100 		if (err == ILL_LOOKUP_FAILED) {
22101 			ire_refrele(ire);
22102 			freemsg(mp);
22103 			return;
22104 		}
22105 		if (conn_outgoing_ill == NULL) {
22106 			/*
22107 			 * Choose a good ill in the group to send the
22108 			 * packets on.
22109 			 */
22110 			ire = conn_set_outgoing_ill(connp, ire,
22111 			    &conn_outgoing_ill);
22112 			if (ire == NULL) {
22113 				freemsg(mp);
22114 				return;
22115 			}
22116 		}
22117 	}
22118 
22119 	if (mp->b_datap->db_type != M_CTL) {
22120 		ipha = (ipha_t *)mp->b_rptr;
22121 	} else {
22122 		io = (ipsec_out_t *)mp->b_rptr;
22123 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22124 		ASSERT(zoneid == io->ipsec_out_zoneid);
22125 		ASSERT(zoneid != ALL_ZONES);
22126 		ipha = (ipha_t *)mp->b_cont->b_rptr;
22127 		dst = ipha->ipha_dst;
22128 		/*
22129 		 * For the multicast case, ipsec_out carries conn_dontroute and
22130 		 * conn_multicast_loop as conn may not be available here. We
22131 		 * need this for multicast loopback and forwarding which is done
22132 		 * later in the code.
22133 		 */
22134 		if (CLASSD(dst)) {
22135 			conn_dontroute = io->ipsec_out_dontroute;
22136 			conn_multicast_loop = io->ipsec_out_multicast_loop;
22137 			/*
22138 			 * If conn_dontroute is not set or conn_multicast_loop
22139 			 * is set, we need to do forwarding/loopback. For
22140 			 * datagrams from ip_wput_multicast, conn_dontroute is
22141 			 * set to B_TRUE and conn_multicast_loop is set to
22142 			 * B_FALSE so that we neither do forwarding nor
22143 			 * loopback.
22144 			 */
22145 			if (!conn_dontroute || conn_multicast_loop)
22146 				multicast_forward = B_TRUE;
22147 		}
22148 	}
22149 
22150 	if (ire->ire_type == IRE_LOCAL && ire->ire_zoneid != zoneid &&
22151 	    ire->ire_zoneid != ALL_ZONES) {
22152 		/*
22153 		 * When a zone sends a packet to another zone, we try to deliver
22154 		 * the packet under the same conditions as if the destination
22155 		 * was a real node on the network. To do so, we look for a
22156 		 * matching route in the forwarding table.
22157 		 * RTF_REJECT and RTF_BLACKHOLE are handled just like
22158 		 * ip_newroute() does.
22159 		 * Note that IRE_LOCAL are special, since they are used
22160 		 * when the zoneid doesn't match in some cases. This means that
22161 		 * we need to handle ipha_src differently since ire_src_addr
22162 		 * belongs to the receiving zone instead of the sending zone.
22163 		 * When ip_restrict_interzone_loopback is set, then
22164 		 * ire_cache_lookup() ensures that IRE_LOCAL are only used
22165 		 * for loopback between zones when the logical "Ethernet" would
22166 		 * have looped them back.
22167 		 */
22168 		ire_t *src_ire;
22169 
22170 		src_ire = ire_ftable_lookup(ipha->ipha_dst, 0, 0, 0,
22171 		    NULL, NULL, zoneid, 0, NULL, (MATCH_IRE_RECURSIVE |
22172 		    MATCH_IRE_DEFAULT | MATCH_IRE_RJ_BHOLE), ipst);
22173 		if (src_ire != NULL &&
22174 		    !(src_ire->ire_flags & (RTF_REJECT | RTF_BLACKHOLE)) &&
22175 		    (!ipst->ips_ip_restrict_interzone_loopback ||
22176 		    ire_local_same_ill_group(ire, src_ire))) {
22177 			if (ipha->ipha_src == INADDR_ANY && !unspec_src)
22178 				ipha->ipha_src = src_ire->ire_src_addr;
22179 			ire_refrele(src_ire);
22180 		} else {
22181 			ire_refrele(ire);
22182 			if (conn_outgoing_ill != NULL)
22183 				ill_refrele(conn_outgoing_ill);
22184 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
22185 			if (src_ire != NULL) {
22186 				if (src_ire->ire_flags & RTF_BLACKHOLE) {
22187 					ire_refrele(src_ire);
22188 					freemsg(mp);
22189 					return;
22190 				}
22191 				ire_refrele(src_ire);
22192 			}
22193 			if (ip_hdr_complete(ipha, zoneid, ipst)) {
22194 				/* Failed */
22195 				freemsg(mp);
22196 				return;
22197 			}
22198 			icmp_unreachable(q, mp, ICMP_HOST_UNREACHABLE, zoneid,
22199 			    ipst);
22200 			return;
22201 		}
22202 	}
22203 
22204 	if (mp->b_datap->db_type == M_CTL ||
22205 	    ipss->ipsec_outbound_v4_policy_present) {
22206 		mp = ip_wput_ire_parse_ipsec_out(mp, ipha, NULL, ire, connp,
22207 		    unspec_src, zoneid);
22208 		if (mp == NULL) {
22209 			ire_refrele(ire);
22210 			if (conn_outgoing_ill != NULL)
22211 				ill_refrele(conn_outgoing_ill);
22212 			return;
22213 		}
22214 		/*
22215 		 * Trusted Extensions supports all-zones interfaces, so
22216 		 * zoneid == ALL_ZONES is valid, but IPsec maps ALL_ZONES to
22217 		 * the global zone.
22218 		 */
22219 		if (zoneid == ALL_ZONES && mp->b_datap->db_type == M_CTL) {
22220 			io = (ipsec_out_t *)mp->b_rptr;
22221 			ASSERT(io->ipsec_out_type == IPSEC_OUT);
22222 			zoneid = io->ipsec_out_zoneid;
22223 		}
22224 	}
22225 
22226 	first_mp = mp;
22227 	ipsec_len = 0;
22228 
22229 	if (first_mp->b_datap->db_type == M_CTL) {
22230 		io = (ipsec_out_t *)first_mp->b_rptr;
22231 		ASSERT(io->ipsec_out_type == IPSEC_OUT);
22232 		mp = first_mp->b_cont;
22233 		ipsec_len = ipsec_out_extra_length(first_mp);
22234 		ASSERT(ipsec_len >= 0);
22235 		/* We already picked up the zoneid from the M_CTL above */
22236 		ASSERT(zoneid == io->ipsec_out_zoneid);
22237 		ASSERT(zoneid != ALL_ZONES);
22238 
22239 		/*
22240 		 * Drop M_CTL here if IPsec processing is not needed.
22241 		 * (Non-IPsec use of M_CTL extracted any information it
22242 		 * needed above).
22243 		 */
22244 		if (ipsec_len == 0) {
22245 			freeb(first_mp);
22246 			first_mp = mp;
22247 		}
22248 	}
22249 
22250 	/*
22251 	 * Fast path for ip_wput_ire
22252 	 */
22253 
22254 	ipha = (ipha_t *)mp->b_rptr;
22255 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
22256 	dst = ipha->ipha_dst;
22257 
22258 	/*
22259 	 * ICMP(RAWIP) module should set the ipha_ident to IP_HDR_INCLUDED
22260 	 * if the socket is a SOCK_RAW type. The transport checksum should
22261 	 * be provided in the pre-built packet, so we don't need to compute it.
22262 	 * Also, other application set flags, like DF, should not be altered.
22263 	 * Other transport MUST pass down zero.
22264 	 */
22265 	ip_hdr_included = ipha->ipha_ident;
22266 	ASSERT(ipha->ipha_ident == 0 || ipha->ipha_ident == IP_HDR_INCLUDED);
22267 
22268 	if (CLASSD(dst)) {
22269 		ip1dbg(("ip_wput_ire: to 0x%x ire %s addr 0x%x\n",
22270 		    ntohl(dst),
22271 		    ip_nv_lookup(ire_nv_tbl, ire->ire_type),
22272 		    ntohl(ire->ire_addr)));
22273 	}
22274 
22275 /* Macros to extract header fields from data already in registers */
22276 #ifdef	_BIG_ENDIAN
22277 #define	V_HLEN	(v_hlen_tos_len >> 24)
22278 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
22279 #define	PROTO	(ttl_protocol & 0xFF)
22280 #else
22281 #define	V_HLEN	(v_hlen_tos_len & 0xFF)
22282 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
22283 #define	PROTO	(ttl_protocol >> 8)
22284 #endif
22285 
22286 
22287 	orig_src = src = ipha->ipha_src;
22288 	/* (The loop back to "another" is explained down below.) */
22289 another:;
22290 	/*
22291 	 * Assign an ident value for this packet.  We assign idents on
22292 	 * a per destination basis out of the IRE.  There could be
22293 	 * other threads targeting the same destination, so we have to
22294 	 * arrange for a atomic increment.  Note that we use a 32-bit
22295 	 * atomic add because it has better performance than its
22296 	 * 16-bit sibling.
22297 	 *
22298 	 * If running in cluster mode and if the source address
22299 	 * belongs to a replicated service then vector through
22300 	 * cl_inet_ipident vector to allocate ip identifier
22301 	 * NOTE: This is a contract private interface with the
22302 	 * clustering group.
22303 	 */
22304 	clusterwide = 0;
22305 	if (cl_inet_ipident) {
22306 		ASSERT(cl_inet_isclusterwide);
22307 		if ((*cl_inet_isclusterwide)(IPPROTO_IP,
22308 		    AF_INET, (uint8_t *)(uintptr_t)src)) {
22309 			ipha->ipha_ident = (*cl_inet_ipident)(IPPROTO_IP,
22310 			    AF_INET, (uint8_t *)(uintptr_t)src,
22311 			    (uint8_t *)(uintptr_t)dst);
22312 			clusterwide = 1;
22313 		}
22314 	}
22315 	if (!clusterwide) {
22316 		ipha->ipha_ident =
22317 		    (uint16_t)atomic_add_32_nv(&ire->ire_ident, 1);
22318 	}
22319 
22320 #ifndef _BIG_ENDIAN
22321 	ipha->ipha_ident = (ipha->ipha_ident << 8) | (ipha->ipha_ident >> 8);
22322 #endif
22323 
22324 	/*
22325 	 * Set source address unless sent on an ill or conn_unspec_src is set.
22326 	 * This is needed to obey conn_unspec_src when packets go through
22327 	 * ip_newroute + arp.
22328 	 * Assumes ip_newroute{,_multi} sets the source address as well.
22329 	 */
22330 	if (src == INADDR_ANY && !unspec_src) {
22331 		/*
22332 		 * Assign the appropriate source address from the IRE if none
22333 		 * was specified.
22334 		 */
22335 		ASSERT(ire->ire_ipversion == IPV4_VERSION);
22336 
22337 		/*
22338 		 * With IP multipathing, broadcast packets are sent on the ire
22339 		 * that has been cleared of IRE_MARK_NORECV and that belongs to
22340 		 * the group. However, this ire might not be in the same zone so
22341 		 * we can't always use its source address. We look for a
22342 		 * broadcast ire in the same group and in the right zone.
22343 		 */
22344 		if (ire->ire_type == IRE_BROADCAST &&
22345 		    ire->ire_zoneid != zoneid) {
22346 			ire_t *src_ire = ire_ctable_lookup(dst, 0,
22347 			    IRE_BROADCAST, ire->ire_ipif, zoneid, NULL,
22348 			    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
22349 			if (src_ire != NULL) {
22350 				src = src_ire->ire_src_addr;
22351 				ire_refrele(src_ire);
22352 			} else {
22353 				ire_refrele(ire);
22354 				if (conn_outgoing_ill != NULL)
22355 					ill_refrele(conn_outgoing_ill);
22356 				freemsg(first_mp);
22357 				if (ill != NULL) {
22358 					BUMP_MIB(ill->ill_ip_mib,
22359 					    ipIfStatsOutDiscards);
22360 				} else {
22361 					BUMP_MIB(&ipst->ips_ip_mib,
22362 					    ipIfStatsOutDiscards);
22363 				}
22364 				return;
22365 			}
22366 		} else {
22367 			src = ire->ire_src_addr;
22368 		}
22369 
22370 		if (connp == NULL) {
22371 			ip1dbg(("ip_wput_ire: no connp and no src "
22372 			    "address for dst 0x%x, using src 0x%x\n",
22373 			    ntohl(dst),
22374 			    ntohl(src)));
22375 		}
22376 		ipha->ipha_src = src;
22377 	}
22378 	stq = ire->ire_stq;
22379 
22380 	/*
22381 	 * We only allow ire chains for broadcasts since there will
22382 	 * be multiple IRE_CACHE entries for the same multicast
22383 	 * address (one per ipif).
22384 	 */
22385 	next_mp = NULL;
22386 
22387 	/* broadcast packet */
22388 	if (ire->ire_type == IRE_BROADCAST)
22389 		goto broadcast;
22390 
22391 	/* loopback ? */
22392 	if (stq == NULL)
22393 		goto nullstq;
22394 
22395 	/* The ill_index for outbound ILL */
22396 	ill_index = Q_TO_INDEX(stq);
22397 
22398 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutRequests);
22399 	ttl_protocol = ((uint16_t *)ipha)[4];
22400 
22401 	/* pseudo checksum (do it in parts for IP header checksum) */
22402 	cksum = (dst >> 16) + (dst & 0xFFFF) + (src >> 16) + (src & 0xFFFF);
22403 
22404 	if (!IP_FLOW_CONTROLLED_ULP(PROTO)) {
22405 		queue_t *dev_q = stq->q_next;
22406 
22407 		/* flow controlled */
22408 		if ((dev_q->q_next || dev_q->q_first) &&
22409 		    !canput(dev_q))
22410 			goto blocked;
22411 		if ((PROTO == IPPROTO_UDP) &&
22412 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22413 			hlen = (V_HLEN & 0xF) << 2;
22414 			up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22415 			if (*up != 0) {
22416 				IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO,
22417 				    hlen, LENGTH, max_frag, ipsec_len, cksum);
22418 				/* Software checksum? */
22419 				if (DB_CKSUMFLAGS(mp) == 0) {
22420 					IP_STAT(ipst, ip_out_sw_cksum);
22421 					IP_STAT_UPDATE(ipst,
22422 					    ip_udp_out_sw_cksum_bytes,
22423 					    LENGTH - hlen);
22424 				}
22425 			}
22426 		}
22427 	} else if (ip_hdr_included != IP_HDR_INCLUDED) {
22428 		hlen = (V_HLEN & 0xF) << 2;
22429 		if (PROTO == IPPROTO_TCP) {
22430 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22431 			/*
22432 			 * The packet header is processed once and for all, even
22433 			 * in the multirouting case. We disable hardware
22434 			 * checksum if the packet is multirouted, as it will be
22435 			 * replicated via several interfaces, and not all of
22436 			 * them may have this capability.
22437 			 */
22438 			IP_CKSUM_XMIT(ill, ire, mp, ipha, up, PROTO, hlen,
22439 			    LENGTH, max_frag, ipsec_len, cksum);
22440 			/* Software checksum? */
22441 			if (DB_CKSUMFLAGS(mp) == 0) {
22442 				IP_STAT(ipst, ip_out_sw_cksum);
22443 				IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22444 				    LENGTH - hlen);
22445 			}
22446 		} else {
22447 			sctp_hdr_t	*sctph;
22448 
22449 			ASSERT(PROTO == IPPROTO_SCTP);
22450 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22451 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22452 			/*
22453 			 * Zero out the checksum field to ensure proper
22454 			 * checksum calculation.
22455 			 */
22456 			sctph->sh_chksum = 0;
22457 #ifdef	DEBUG
22458 			if (!skip_sctp_cksum)
22459 #endif
22460 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22461 		}
22462 	}
22463 
22464 	/*
22465 	 * If this is a multicast packet and originated from ip_wput
22466 	 * we need to do loopback and forwarding checks. If it comes
22467 	 * from ip_wput_multicast, we SHOULD not do this.
22468 	 */
22469 	if (CLASSD(ipha->ipha_dst) && multicast_forward) goto multi_loopback;
22470 
22471 	/* checksum */
22472 	cksum += ttl_protocol;
22473 
22474 	/* fragment the packet */
22475 	if (max_frag < (uint_t)(LENGTH + ipsec_len))
22476 		goto fragmentit;
22477 	/*
22478 	 * Don't use frag_flag if packet is pre-built or source
22479 	 * routed or if multicast (since multicast packets do
22480 	 * not solicit ICMP "packet too big" messages).
22481 	 */
22482 	if ((ip_hdr_included != IP_HDR_INCLUDED) &&
22483 	    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
22484 	    !ip_source_route_included(ipha)) &&
22485 	    !CLASSD(ipha->ipha_dst))
22486 		ipha->ipha_fragment_offset_and_flags |=
22487 		    htons(ire->ire_frag_flag);
22488 
22489 	if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
22490 		/* calculate IP header checksum */
22491 		cksum += ipha->ipha_ident;
22492 		cksum += (v_hlen_tos_len >> 16)+(v_hlen_tos_len & 0xFFFF);
22493 		cksum += ipha->ipha_fragment_offset_and_flags;
22494 
22495 		/* IP options present */
22496 		hlen = (V_HLEN & 0xF) - IP_SIMPLE_HDR_LENGTH_IN_WORDS;
22497 		if (hlen)
22498 			goto checksumoptions;
22499 
22500 		/* calculate hdr checksum */
22501 		cksum = ((cksum & 0xFFFF) + (cksum >> 16));
22502 		cksum = ~(cksum + (cksum >> 16));
22503 		ipha->ipha_hdr_checksum = (uint16_t)cksum;
22504 	}
22505 	if (ipsec_len != 0) {
22506 		/*
22507 		 * We will do the rest of the processing after
22508 		 * we come back from IPsec in ip_wput_ipsec_out().
22509 		 */
22510 		ASSERT(MBLKL(first_mp) >= sizeof (ipsec_out_t));
22511 
22512 		io = (ipsec_out_t *)first_mp->b_rptr;
22513 		io->ipsec_out_ill_index = ((ill_t *)stq->q_ptr)->
22514 		    ill_phyint->phyint_ifindex;
22515 
22516 		ipsec_out_process(q, first_mp, ire, ill_index);
22517 		ire_refrele(ire);
22518 		if (conn_outgoing_ill != NULL)
22519 			ill_refrele(conn_outgoing_ill);
22520 		return;
22521 	}
22522 
22523 	/*
22524 	 * In most cases, the emission loop below is entered only
22525 	 * once. Only in the case where the ire holds the
22526 	 * RTF_MULTIRT flag, do we loop to process all RTF_MULTIRT
22527 	 * flagged ires in the bucket, and send the packet
22528 	 * through all crossed RTF_MULTIRT routes.
22529 	 */
22530 	if (ire->ire_flags & RTF_MULTIRT) {
22531 		multirt_send = B_TRUE;
22532 	}
22533 	do {
22534 		if (multirt_send) {
22535 			irb_t *irb;
22536 			/*
22537 			 * We are in a multiple send case, need to get
22538 			 * the next ire and make a duplicate of the packet.
22539 			 * ire1 holds here the next ire to process in the
22540 			 * bucket. If multirouting is expected,
22541 			 * any non-RTF_MULTIRT ire that has the
22542 			 * right destination address is ignored.
22543 			 */
22544 			irb = ire->ire_bucket;
22545 			ASSERT(irb != NULL);
22546 
22547 			IRB_REFHOLD(irb);
22548 			for (ire1 = ire->ire_next;
22549 			    ire1 != NULL;
22550 			    ire1 = ire1->ire_next) {
22551 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
22552 					continue;
22553 				if (ire1->ire_addr != ire->ire_addr)
22554 					continue;
22555 				if (ire1->ire_marks &
22556 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
22557 					continue;
22558 
22559 				/* Got one */
22560 				IRE_REFHOLD(ire1);
22561 				break;
22562 			}
22563 			IRB_REFRELE(irb);
22564 
22565 			if (ire1 != NULL) {
22566 				next_mp = copyb(mp);
22567 				if ((next_mp == NULL) ||
22568 				    ((mp->b_cont != NULL) &&
22569 				    ((next_mp->b_cont =
22570 				    dupmsg(mp->b_cont)) == NULL))) {
22571 					freemsg(next_mp);
22572 					next_mp = NULL;
22573 					ire_refrele(ire1);
22574 					ire1 = NULL;
22575 				}
22576 			}
22577 
22578 			/* Last multiroute ire; don't loop anymore. */
22579 			if (ire1 == NULL) {
22580 				multirt_send = B_FALSE;
22581 			}
22582 		}
22583 
22584 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
22585 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha,
22586 		    mblk_t *, mp);
22587 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
22588 		    ipst->ips_ipv4firewall_physical_out,
22589 		    NULL, ire->ire_ipif->ipif_ill, ipha, mp, mp, 0, ipst);
22590 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, mp);
22591 		if (mp == NULL)
22592 			goto release_ire_and_ill;
22593 
22594 		mp->b_prev = SET_BPREV_FLAG(IPP_LOCAL_OUT);
22595 		DTRACE_PROBE2(ip__xmit__1, mblk_t *, mp, ire_t *, ire);
22596 		pktxmit_state = ip_xmit_v4(mp, ire, NULL, B_TRUE);
22597 		if ((pktxmit_state == SEND_FAILED) ||
22598 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
22599 			ip2dbg(("ip_wput_ire: ip_xmit_v4 failed"
22600 			    "- packet dropped\n"));
22601 release_ire_and_ill:
22602 			ire_refrele(ire);
22603 			if (next_mp != NULL) {
22604 				freemsg(next_mp);
22605 				ire_refrele(ire1);
22606 			}
22607 			if (conn_outgoing_ill != NULL)
22608 				ill_refrele(conn_outgoing_ill);
22609 			return;
22610 		}
22611 
22612 		if (CLASSD(dst)) {
22613 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastPkts);
22614 			UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutMcastOctets,
22615 			    LENGTH);
22616 		}
22617 
22618 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22619 		    "ip_wput_ire_end: q %p (%S)",
22620 		    q, "last copy out");
22621 		IRE_REFRELE(ire);
22622 
22623 		if (multirt_send) {
22624 			ASSERT(ire1);
22625 			/*
22626 			 * Proceed with the next RTF_MULTIRT ire,
22627 			 * Also set up the send-to queue accordingly.
22628 			 */
22629 			ire = ire1;
22630 			ire1 = NULL;
22631 			stq = ire->ire_stq;
22632 			mp = next_mp;
22633 			next_mp = NULL;
22634 			ipha = (ipha_t *)mp->b_rptr;
22635 			ill_index = Q_TO_INDEX(stq);
22636 			ill = (ill_t *)stq->q_ptr;
22637 		}
22638 	} while (multirt_send);
22639 	if (conn_outgoing_ill != NULL)
22640 		ill_refrele(conn_outgoing_ill);
22641 	return;
22642 
22643 	/*
22644 	 * ire->ire_type == IRE_BROADCAST (minimize diffs)
22645 	 */
22646 broadcast:
22647 	{
22648 		/*
22649 		 * To avoid broadcast storms, we usually set the TTL to 1 for
22650 		 * broadcasts.  However, if SO_DONTROUTE isn't set, this value
22651 		 * can be overridden stack-wide through the ip_broadcast_ttl
22652 		 * ndd tunable, or on a per-connection basis through the
22653 		 * IP_BROADCAST_TTL socket option.
22654 		 *
22655 		 * In the event that we are replying to incoming ICMP packets,
22656 		 * connp could be NULL.
22657 		 */
22658 		ipha->ipha_ttl = ipst->ips_ip_broadcast_ttl;
22659 		if (connp != NULL) {
22660 			if (connp->conn_dontroute)
22661 				ipha->ipha_ttl = 1;
22662 			else if (connp->conn_broadcast_ttl != 0)
22663 				ipha->ipha_ttl = connp->conn_broadcast_ttl;
22664 		}
22665 
22666 		/*
22667 		 * Note that we are not doing a IRB_REFHOLD here.
22668 		 * Actually we don't care if the list changes i.e
22669 		 * if somebody deletes an IRE from the list while
22670 		 * we drop the lock, the next time we come around
22671 		 * ire_next will be NULL and hence we won't send
22672 		 * out multiple copies which is fine.
22673 		 */
22674 		rw_enter(&ire->ire_bucket->irb_lock, RW_READER);
22675 		ire1 = ire->ire_next;
22676 		if (conn_outgoing_ill != NULL) {
22677 			while (ire->ire_ipif->ipif_ill != conn_outgoing_ill) {
22678 				ASSERT(ire1 == ire->ire_next);
22679 				if (ire1 != NULL && ire1->ire_addr == dst) {
22680 					ire_refrele(ire);
22681 					ire = ire1;
22682 					IRE_REFHOLD(ire);
22683 					ire1 = ire->ire_next;
22684 					continue;
22685 				}
22686 				rw_exit(&ire->ire_bucket->irb_lock);
22687 				/* Did not find a matching ill */
22688 				ip1dbg(("ip_wput_ire: broadcast with no "
22689 				    "matching IP_BOUND_IF ill %s dst %x\n",
22690 				    conn_outgoing_ill->ill_name, dst));
22691 				freemsg(first_mp);
22692 				if (ire != NULL)
22693 					ire_refrele(ire);
22694 				ill_refrele(conn_outgoing_ill);
22695 				return;
22696 			}
22697 		} else if (ire1 != NULL && ire1->ire_addr == dst) {
22698 			/*
22699 			 * If the next IRE has the same address and is not one
22700 			 * of the two copies that we need to send, try to see
22701 			 * whether this copy should be sent at all. This
22702 			 * assumes that we insert loopbacks first and then
22703 			 * non-loopbacks. This is acheived by inserting the
22704 			 * loopback always before non-loopback.
22705 			 * This is used to send a single copy of a broadcast
22706 			 * packet out all physical interfaces that have an
22707 			 * matching IRE_BROADCAST while also looping
22708 			 * back one copy (to ip_wput_local) for each
22709 			 * matching physical interface. However, we avoid
22710 			 * sending packets out different logical that match by
22711 			 * having ipif_up/ipif_down supress duplicate
22712 			 * IRE_BROADCASTS.
22713 			 *
22714 			 * This feature is currently used to get broadcasts
22715 			 * sent to multiple interfaces, when the broadcast
22716 			 * address being used applies to multiple interfaces.
22717 			 * For example, a whole net broadcast will be
22718 			 * replicated on every connected subnet of
22719 			 * the target net.
22720 			 *
22721 			 * Each zone has its own set of IRE_BROADCASTs, so that
22722 			 * we're able to distribute inbound packets to multiple
22723 			 * zones who share a broadcast address. We avoid looping
22724 			 * back outbound packets in different zones but on the
22725 			 * same ill, as the application would see duplicates.
22726 			 *
22727 			 * If the interfaces are part of the same group,
22728 			 * we would want to send only one copy out for
22729 			 * whole group.
22730 			 *
22731 			 * This logic assumes that ire_add_v4() groups the
22732 			 * IRE_BROADCAST entries so that those with the same
22733 			 * ire_addr and ill_group are kept together.
22734 			 */
22735 			ire_ill = ire->ire_ipif->ipif_ill;
22736 			if (ire->ire_stq == NULL && ire1->ire_stq != NULL) {
22737 				if (ire_ill->ill_group != NULL &&
22738 				    (ire->ire_marks & IRE_MARK_NORECV)) {
22739 					/*
22740 					 * If the current zone only has an ire
22741 					 * broadcast for this address marked
22742 					 * NORECV, the ire we want is ahead in
22743 					 * the bucket, so we look it up
22744 					 * deliberately ignoring the zoneid.
22745 					 */
22746 					for (ire1 = ire->ire_bucket->irb_ire;
22747 					    ire1 != NULL;
22748 					    ire1 = ire1->ire_next) {
22749 						ire1_ill =
22750 						    ire1->ire_ipif->ipif_ill;
22751 						if (ire1->ire_addr != dst)
22752 							continue;
22753 						/* skip over the current ire */
22754 						if (ire1 == ire)
22755 							continue;
22756 						/* skip over deleted ires */
22757 						if (ire1->ire_marks &
22758 						    IRE_MARK_CONDEMNED)
22759 							continue;
22760 						/*
22761 						 * non-loopback ire in our
22762 						 * group: use it for the next
22763 						 * pass in the loop
22764 						 */
22765 						if (ire1->ire_stq != NULL &&
22766 						    ire1_ill->ill_group ==
22767 						    ire_ill->ill_group)
22768 							break;
22769 					}
22770 				}
22771 			} else {
22772 				while (ire1 != NULL && ire1->ire_addr == dst) {
22773 					ire1_ill = ire1->ire_ipif->ipif_ill;
22774 					/*
22775 					 * We can have two broadcast ires on the
22776 					 * same ill in different zones; here
22777 					 * we'll send a copy of the packet on
22778 					 * each ill and the fanout code will
22779 					 * call conn_wantpacket() to check that
22780 					 * the zone has the broadcast address
22781 					 * configured on the ill. If the two
22782 					 * ires are in the same group we only
22783 					 * send one copy up.
22784 					 */
22785 					if (ire1_ill != ire_ill &&
22786 					    (ire1_ill->ill_group == NULL ||
22787 					    ire_ill->ill_group == NULL ||
22788 					    ire1_ill->ill_group !=
22789 					    ire_ill->ill_group)) {
22790 						break;
22791 					}
22792 					ire1 = ire1->ire_next;
22793 				}
22794 			}
22795 		}
22796 		ASSERT(multirt_send == B_FALSE);
22797 		if (ire1 != NULL && ire1->ire_addr == dst) {
22798 			if ((ire->ire_flags & RTF_MULTIRT) &&
22799 			    (ire1->ire_flags & RTF_MULTIRT)) {
22800 				/*
22801 				 * We are in the multirouting case.
22802 				 * The message must be sent at least
22803 				 * on both ires. These ires have been
22804 				 * inserted AFTER the standard ones
22805 				 * in ip_rt_add(). There are thus no
22806 				 * other ire entries for the destination
22807 				 * address in the rest of the bucket
22808 				 * that do not have the RTF_MULTIRT
22809 				 * flag. We don't process a copy
22810 				 * of the message here. This will be
22811 				 * done in the final sending loop.
22812 				 */
22813 				multirt_send = B_TRUE;
22814 			} else {
22815 				next_mp = ip_copymsg(first_mp);
22816 				if (next_mp != NULL)
22817 					IRE_REFHOLD(ire1);
22818 			}
22819 		}
22820 		rw_exit(&ire->ire_bucket->irb_lock);
22821 	}
22822 
22823 	if (stq) {
22824 		/*
22825 		 * A non-NULL send-to queue means this packet is going
22826 		 * out of this machine.
22827 		 */
22828 		out_ill = (ill_t *)stq->q_ptr;
22829 
22830 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutRequests);
22831 		ttl_protocol = ((uint16_t *)ipha)[4];
22832 		/*
22833 		 * We accumulate the pseudo header checksum in cksum.
22834 		 * This is pretty hairy code, so watch close.  One
22835 		 * thing to keep in mind is that UDP and TCP have
22836 		 * stored their respective datagram lengths in their
22837 		 * checksum fields.  This lines things up real nice.
22838 		 */
22839 		cksum = (dst >> 16) + (dst & 0xFFFF) +
22840 		    (src >> 16) + (src & 0xFFFF);
22841 		/*
22842 		 * We assume the udp checksum field contains the
22843 		 * length, so to compute the pseudo header checksum,
22844 		 * all we need is the protocol number and src/dst.
22845 		 */
22846 		/* Provide the checksums for UDP and TCP. */
22847 		if ((PROTO == IPPROTO_TCP) &&
22848 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22849 			/* hlen gets the number of uchar_ts in the IP header */
22850 			hlen = (V_HLEN & 0xF) << 2;
22851 			up = IPH_TCPH_CHECKSUMP(ipha, hlen);
22852 			IP_STAT(ipst, ip_out_sw_cksum);
22853 			IP_STAT_UPDATE(ipst, ip_tcp_out_sw_cksum_bytes,
22854 			    LENGTH - hlen);
22855 			*up = IP_CSUM(mp, hlen, cksum + IP_TCP_CSUM_COMP);
22856 		} else if (PROTO == IPPROTO_SCTP &&
22857 		    (ip_hdr_included != IP_HDR_INCLUDED)) {
22858 			sctp_hdr_t	*sctph;
22859 
22860 			hlen = (V_HLEN & 0xF) << 2;
22861 			ASSERT(MBLKL(mp) >= (hlen + sizeof (*sctph)));
22862 			sctph = (sctp_hdr_t *)(mp->b_rptr + hlen);
22863 			sctph->sh_chksum = 0;
22864 #ifdef	DEBUG
22865 			if (!skip_sctp_cksum)
22866 #endif
22867 				sctph->sh_chksum = sctp_cksum(mp, hlen);
22868 		} else {
22869 			queue_t *dev_q = stq->q_next;
22870 
22871 			if ((dev_q->q_next || dev_q->q_first) &&
22872 			    !canput(dev_q)) {
22873 blocked:
22874 				ipha->ipha_ident = ip_hdr_included;
22875 				/*
22876 				 * If we don't have a conn to apply
22877 				 * backpressure, free the message.
22878 				 * In the ire_send path, we don't know
22879 				 * the position to requeue the packet. Rather
22880 				 * than reorder packets, we just drop this
22881 				 * packet.
22882 				 */
22883 				if (ipst->ips_ip_output_queue &&
22884 				    connp != NULL &&
22885 				    caller != IRE_SEND) {
22886 					if (caller == IP_WSRV) {
22887 						connp->conn_did_putbq = 1;
22888 						(void) putbq(connp->conn_wq,
22889 						    first_mp);
22890 						conn_drain_insert(connp);
22891 						/*
22892 						 * This is the service thread,
22893 						 * and the queue is already
22894 						 * noenabled. The check for
22895 						 * canput and the putbq is not
22896 						 * atomic. So we need to check
22897 						 * again.
22898 						 */
22899 						if (canput(stq->q_next))
22900 							connp->conn_did_putbq
22901 							    = 0;
22902 						IP_STAT(ipst, ip_conn_flputbq);
22903 					} else {
22904 						/*
22905 						 * We are not the service proc.
22906 						 * ip_wsrv will be scheduled or
22907 						 * is already running.
22908 						 */
22909 						(void) putq(connp->conn_wq,
22910 						    first_mp);
22911 					}
22912 				} else {
22913 					out_ill = (ill_t *)stq->q_ptr;
22914 					BUMP_MIB(out_ill->ill_ip_mib,
22915 					    ipIfStatsOutDiscards);
22916 					freemsg(first_mp);
22917 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
22918 					    "ip_wput_ire_end: q %p (%S)",
22919 					    q, "discard");
22920 				}
22921 				ire_refrele(ire);
22922 				if (next_mp) {
22923 					ire_refrele(ire1);
22924 					freemsg(next_mp);
22925 				}
22926 				if (conn_outgoing_ill != NULL)
22927 					ill_refrele(conn_outgoing_ill);
22928 				return;
22929 			}
22930 			if ((PROTO == IPPROTO_UDP) &&
22931 			    (ip_hdr_included != IP_HDR_INCLUDED)) {
22932 				/*
22933 				 * hlen gets the number of uchar_ts in the
22934 				 * IP header
22935 				 */
22936 				hlen = (V_HLEN & 0xF) << 2;
22937 				up = IPH_UDPH_CHECKSUMP(ipha, hlen);
22938 				max_frag = ire->ire_max_frag;
22939 				if (*up != 0) {
22940 					IP_CKSUM_XMIT(out_ill, ire, mp, ipha,
22941 					    up, PROTO, hlen, LENGTH, max_frag,
22942 					    ipsec_len, cksum);
22943 					/* Software checksum? */
22944 					if (DB_CKSUMFLAGS(mp) == 0) {
22945 						IP_STAT(ipst, ip_out_sw_cksum);
22946 						IP_STAT_UPDATE(ipst,
22947 						    ip_udp_out_sw_cksum_bytes,
22948 						    LENGTH - hlen);
22949 					}
22950 				}
22951 			}
22952 		}
22953 		/*
22954 		 * Need to do this even when fragmenting. The local
22955 		 * loopback can be done without computing checksums
22956 		 * but forwarding out other interface must be done
22957 		 * after the IP checksum (and ULP checksums) have been
22958 		 * computed.
22959 		 *
22960 		 * NOTE : multicast_forward is set only if this packet
22961 		 * originated from ip_wput. For packets originating from
22962 		 * ip_wput_multicast, it is not set.
22963 		 */
22964 		if (CLASSD(ipha->ipha_dst) && multicast_forward) {
22965 multi_loopback:
22966 			ip2dbg(("ip_wput: multicast, loop %d\n",
22967 			    conn_multicast_loop));
22968 
22969 			/*  Forget header checksum offload */
22970 			DB_CKSUMFLAGS(mp) &= ~HCK_IPV4_HDRCKSUM;
22971 
22972 			/*
22973 			 * Local loopback of multicasts?  Check the
22974 			 * ill.
22975 			 *
22976 			 * Note that the loopback function will not come
22977 			 * in through ip_rput - it will only do the
22978 			 * client fanout thus we need to do an mforward
22979 			 * as well.  The is different from the BSD
22980 			 * logic.
22981 			 */
22982 			if (ill != NULL) {
22983 				ilm_t	*ilm;
22984 
22985 				ILM_WALKER_HOLD(ill);
22986 				ilm = ilm_lookup_ill(ill, ipha->ipha_dst,
22987 				    ALL_ZONES);
22988 				ILM_WALKER_RELE(ill);
22989 				if (ilm != NULL) {
22990 					/*
22991 					 * Pass along the virtual output q.
22992 					 * ip_wput_local() will distribute the
22993 					 * packet to all the matching zones,
22994 					 * except the sending zone when
22995 					 * IP_MULTICAST_LOOP is false.
22996 					 */
22997 					ip_multicast_loopback(q, ill, first_mp,
22998 					    conn_multicast_loop ? 0 :
22999 					    IP_FF_NO_MCAST_LOOP, zoneid);
23000 				}
23001 			}
23002 			if (ipha->ipha_ttl == 0) {
23003 				/*
23004 				 * 0 => only to this host i.e. we are
23005 				 * done. We are also done if this was the
23006 				 * loopback interface since it is sufficient
23007 				 * to loopback one copy of a multicast packet.
23008 				 */
23009 				freemsg(first_mp);
23010 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23011 				    "ip_wput_ire_end: q %p (%S)",
23012 				    q, "loopback");
23013 				ire_refrele(ire);
23014 				if (conn_outgoing_ill != NULL)
23015 					ill_refrele(conn_outgoing_ill);
23016 				return;
23017 			}
23018 			/*
23019 			 * ILLF_MULTICAST is checked in ip_newroute
23020 			 * i.e. we don't need to check it here since
23021 			 * all IRE_CACHEs come from ip_newroute.
23022 			 * For multicast traffic, SO_DONTROUTE is interpreted
23023 			 * to mean only send the packet out the interface
23024 			 * (optionally specified with IP_MULTICAST_IF)
23025 			 * and do not forward it out additional interfaces.
23026 			 * RSVP and the rsvp daemon is an example of a
23027 			 * protocol and user level process that
23028 			 * handles it's own routing. Hence, it uses the
23029 			 * SO_DONTROUTE option to accomplish this.
23030 			 */
23031 
23032 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
23033 			    ill != NULL) {
23034 				/* Unconditionally redo the checksum */
23035 				ipha->ipha_hdr_checksum = 0;
23036 				ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23037 
23038 				/*
23039 				 * If this needs to go out secure, we need
23040 				 * to wait till we finish the IPsec
23041 				 * processing.
23042 				 */
23043 				if (ipsec_len == 0 &&
23044 				    ip_mforward(ill, ipha, mp)) {
23045 					freemsg(first_mp);
23046 					ip1dbg(("ip_wput: mforward failed\n"));
23047 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23048 					    "ip_wput_ire_end: q %p (%S)",
23049 					    q, "mforward failed");
23050 					ire_refrele(ire);
23051 					if (conn_outgoing_ill != NULL)
23052 						ill_refrele(conn_outgoing_ill);
23053 					return;
23054 				}
23055 			}
23056 		}
23057 		max_frag = ire->ire_max_frag;
23058 		cksum += ttl_protocol;
23059 		if (max_frag >= (uint_t)(LENGTH + ipsec_len)) {
23060 			/* No fragmentation required for this one. */
23061 			/*
23062 			 * Don't use frag_flag if packet is pre-built or source
23063 			 * routed or if multicast (since multicast packets do
23064 			 * not solicit ICMP "packet too big" messages).
23065 			 */
23066 			if ((ip_hdr_included != IP_HDR_INCLUDED) &&
23067 			    (V_HLEN == IP_SIMPLE_HDR_VERSION ||
23068 			    !ip_source_route_included(ipha)) &&
23069 			    !CLASSD(ipha->ipha_dst))
23070 				ipha->ipha_fragment_offset_and_flags |=
23071 				    htons(ire->ire_frag_flag);
23072 
23073 			if (!(DB_CKSUMFLAGS(mp) & HCK_IPV4_HDRCKSUM)) {
23074 				/* Complete the IP header checksum. */
23075 				cksum += ipha->ipha_ident;
23076 				cksum += (v_hlen_tos_len >> 16)+
23077 				    (v_hlen_tos_len & 0xFFFF);
23078 				cksum += ipha->ipha_fragment_offset_and_flags;
23079 				hlen = (V_HLEN & 0xF) -
23080 				    IP_SIMPLE_HDR_LENGTH_IN_WORDS;
23081 				if (hlen) {
23082 checksumoptions:
23083 					/*
23084 					 * Account for the IP Options in the IP
23085 					 * header checksum.
23086 					 */
23087 					up = (uint16_t *)(rptr+
23088 					    IP_SIMPLE_HDR_LENGTH);
23089 					do {
23090 						cksum += up[0];
23091 						cksum += up[1];
23092 						up += 2;
23093 					} while (--hlen);
23094 				}
23095 				cksum = ((cksum & 0xFFFF) + (cksum >> 16));
23096 				cksum = ~(cksum + (cksum >> 16));
23097 				ipha->ipha_hdr_checksum = (uint16_t)cksum;
23098 			}
23099 			if (ipsec_len != 0) {
23100 				ipsec_out_process(q, first_mp, ire, ill_index);
23101 				if (!next_mp) {
23102 					ire_refrele(ire);
23103 					if (conn_outgoing_ill != NULL)
23104 						ill_refrele(conn_outgoing_ill);
23105 					return;
23106 				}
23107 				goto next;
23108 			}
23109 
23110 			/*
23111 			 * multirt_send has already been handled
23112 			 * for broadcast, but not yet for multicast
23113 			 * or IP options.
23114 			 */
23115 			if (next_mp == NULL) {
23116 				if (ire->ire_flags & RTF_MULTIRT) {
23117 					multirt_send = B_TRUE;
23118 				}
23119 			}
23120 
23121 			/*
23122 			 * In most cases, the emission loop below is
23123 			 * entered only once. Only in the case where
23124 			 * the ire holds the RTF_MULTIRT flag, do we loop
23125 			 * to process all RTF_MULTIRT ires in the bucket,
23126 			 * and send the packet through all crossed
23127 			 * RTF_MULTIRT routes.
23128 			 */
23129 			do {
23130 				if (multirt_send) {
23131 					irb_t *irb;
23132 
23133 					irb = ire->ire_bucket;
23134 					ASSERT(irb != NULL);
23135 					/*
23136 					 * We are in a multiple send case,
23137 					 * need to get the next IRE and make
23138 					 * a duplicate of the packet.
23139 					 */
23140 					IRB_REFHOLD(irb);
23141 					for (ire1 = ire->ire_next;
23142 					    ire1 != NULL;
23143 					    ire1 = ire1->ire_next) {
23144 						if (!(ire1->ire_flags &
23145 						    RTF_MULTIRT)) {
23146 							continue;
23147 						}
23148 						if (ire1->ire_addr !=
23149 						    ire->ire_addr) {
23150 							continue;
23151 						}
23152 						if (ire1->ire_marks &
23153 						    (IRE_MARK_CONDEMNED|
23154 						    IRE_MARK_HIDDEN)) {
23155 							continue;
23156 						}
23157 
23158 						/* Got one */
23159 						IRE_REFHOLD(ire1);
23160 						break;
23161 					}
23162 					IRB_REFRELE(irb);
23163 
23164 					if (ire1 != NULL) {
23165 						next_mp = copyb(mp);
23166 						if ((next_mp == NULL) ||
23167 						    ((mp->b_cont != NULL) &&
23168 						    ((next_mp->b_cont =
23169 						    dupmsg(mp->b_cont))
23170 						    == NULL))) {
23171 							freemsg(next_mp);
23172 							next_mp = NULL;
23173 							ire_refrele(ire1);
23174 							ire1 = NULL;
23175 						}
23176 					}
23177 
23178 					/*
23179 					 * Last multiroute ire; don't loop
23180 					 * anymore. The emission is over
23181 					 * and next_mp is NULL.
23182 					 */
23183 					if (ire1 == NULL) {
23184 						multirt_send = B_FALSE;
23185 					}
23186 				}
23187 
23188 				out_ill = ire_to_ill(ire);
23189 				DTRACE_PROBE4(ip4__physical__out__start,
23190 				    ill_t *, NULL,
23191 				    ill_t *, out_ill,
23192 				    ipha_t *, ipha, mblk_t *, mp);
23193 				FW_HOOKS(ipst->ips_ip4_physical_out_event,
23194 				    ipst->ips_ipv4firewall_physical_out,
23195 				    NULL, out_ill, ipha, mp, mp, 0, ipst);
23196 				DTRACE_PROBE1(ip4__physical__out__end,
23197 				    mblk_t *, mp);
23198 				if (mp == NULL)
23199 					goto release_ire_and_ill_2;
23200 
23201 				ASSERT(ipsec_len == 0);
23202 				mp->b_prev =
23203 				    SET_BPREV_FLAG(IPP_LOCAL_OUT);
23204 				DTRACE_PROBE2(ip__xmit__2,
23205 				    mblk_t *, mp, ire_t *, ire);
23206 				pktxmit_state = ip_xmit_v4(mp, ire,
23207 				    NULL, B_TRUE);
23208 				if ((pktxmit_state == SEND_FAILED) ||
23209 				    (pktxmit_state == LLHDR_RESLV_FAILED)) {
23210 release_ire_and_ill_2:
23211 					if (next_mp) {
23212 						freemsg(next_mp);
23213 						ire_refrele(ire1);
23214 					}
23215 					ire_refrele(ire);
23216 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23217 					    "ip_wput_ire_end: q %p (%S)",
23218 					    q, "discard MDATA");
23219 					if (conn_outgoing_ill != NULL)
23220 						ill_refrele(conn_outgoing_ill);
23221 					return;
23222 				}
23223 
23224 				if (CLASSD(dst)) {
23225 					BUMP_MIB(out_ill->ill_ip_mib,
23226 					    ipIfStatsHCOutMcastPkts);
23227 					UPDATE_MIB(out_ill->ill_ip_mib,
23228 					    ipIfStatsHCOutMcastOctets,
23229 					    LENGTH);
23230 				} else if (ire->ire_type == IRE_BROADCAST) {
23231 					BUMP_MIB(out_ill->ill_ip_mib,
23232 					    ipIfStatsHCOutBcastPkts);
23233 				}
23234 
23235 				if (multirt_send) {
23236 					/*
23237 					 * We are in a multiple send case,
23238 					 * need to re-enter the sending loop
23239 					 * using the next ire.
23240 					 */
23241 					ire_refrele(ire);
23242 					ire = ire1;
23243 					stq = ire->ire_stq;
23244 					mp = next_mp;
23245 					next_mp = NULL;
23246 					ipha = (ipha_t *)mp->b_rptr;
23247 					ill_index = Q_TO_INDEX(stq);
23248 				}
23249 			} while (multirt_send);
23250 
23251 			if (!next_mp) {
23252 				/*
23253 				 * Last copy going out (the ultra-common
23254 				 * case).  Note that we intentionally replicate
23255 				 * the putnext rather than calling it before
23256 				 * the next_mp check in hopes of a little
23257 				 * tail-call action out of the compiler.
23258 				 */
23259 				TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23260 				    "ip_wput_ire_end: q %p (%S)",
23261 				    q, "last copy out(1)");
23262 				ire_refrele(ire);
23263 				if (conn_outgoing_ill != NULL)
23264 					ill_refrele(conn_outgoing_ill);
23265 				return;
23266 			}
23267 			/* More copies going out below. */
23268 		} else {
23269 			int offset;
23270 fragmentit:
23271 			offset = ntohs(ipha->ipha_fragment_offset_and_flags);
23272 			/*
23273 			 * If this would generate a icmp_frag_needed message,
23274 			 * we need to handle it before we do the IPsec
23275 			 * processing. Otherwise, we need to strip the IPsec
23276 			 * headers before we send up the message to the ULPs
23277 			 * which becomes messy and difficult.
23278 			 */
23279 			if (ipsec_len != 0) {
23280 				if ((max_frag < (unsigned int)(LENGTH +
23281 				    ipsec_len)) && (offset & IPH_DF)) {
23282 					out_ill = (ill_t *)stq->q_ptr;
23283 					BUMP_MIB(out_ill->ill_ip_mib,
23284 					    ipIfStatsOutFragFails);
23285 					BUMP_MIB(out_ill->ill_ip_mib,
23286 					    ipIfStatsOutFragReqds);
23287 					ipha->ipha_hdr_checksum = 0;
23288 					ipha->ipha_hdr_checksum =
23289 					    (uint16_t)ip_csum_hdr(ipha);
23290 					icmp_frag_needed(ire->ire_stq, first_mp,
23291 					    max_frag, zoneid, ipst);
23292 					if (!next_mp) {
23293 						ire_refrele(ire);
23294 						if (conn_outgoing_ill != NULL) {
23295 							ill_refrele(
23296 							    conn_outgoing_ill);
23297 						}
23298 						return;
23299 					}
23300 				} else {
23301 					/*
23302 					 * This won't cause a icmp_frag_needed
23303 					 * message. to be generated. Send it on
23304 					 * the wire. Note that this could still
23305 					 * cause fragmentation and all we
23306 					 * do is the generation of the message
23307 					 * to the ULP if needed before IPsec.
23308 					 */
23309 					if (!next_mp) {
23310 						ipsec_out_process(q, first_mp,
23311 						    ire, ill_index);
23312 						TRACE_2(TR_FAC_IP,
23313 						    TR_IP_WPUT_IRE_END,
23314 						    "ip_wput_ire_end: q %p "
23315 						    "(%S)", q,
23316 						    "last ipsec_out_process");
23317 						ire_refrele(ire);
23318 						if (conn_outgoing_ill != NULL) {
23319 							ill_refrele(
23320 							    conn_outgoing_ill);
23321 						}
23322 						return;
23323 					}
23324 					ipsec_out_process(q, first_mp,
23325 					    ire, ill_index);
23326 				}
23327 			} else {
23328 				/*
23329 				 * Initiate IPPF processing. For
23330 				 * fragmentable packets we finish
23331 				 * all QOS packet processing before
23332 				 * calling:
23333 				 * ip_wput_ire_fragmentit->ip_wput_frag
23334 				 */
23335 
23336 				if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23337 					ip_process(IPP_LOCAL_OUT, &mp,
23338 					    ill_index);
23339 					if (mp == NULL) {
23340 						out_ill = (ill_t *)stq->q_ptr;
23341 						BUMP_MIB(out_ill->ill_ip_mib,
23342 						    ipIfStatsOutDiscards);
23343 						if (next_mp != NULL) {
23344 							freemsg(next_mp);
23345 							ire_refrele(ire1);
23346 						}
23347 						ire_refrele(ire);
23348 						TRACE_2(TR_FAC_IP,
23349 						    TR_IP_WPUT_IRE_END,
23350 						    "ip_wput_ire: q %p (%S)",
23351 						    q, "discard MDATA");
23352 						if (conn_outgoing_ill != NULL) {
23353 							ill_refrele(
23354 							    conn_outgoing_ill);
23355 						}
23356 						return;
23357 					}
23358 				}
23359 				if (!next_mp) {
23360 					TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23361 					    "ip_wput_ire_end: q %p (%S)",
23362 					    q, "last fragmentation");
23363 					ip_wput_ire_fragmentit(mp, ire,
23364 					    zoneid, ipst);
23365 					ire_refrele(ire);
23366 					if (conn_outgoing_ill != NULL)
23367 						ill_refrele(conn_outgoing_ill);
23368 					return;
23369 				}
23370 				ip_wput_ire_fragmentit(mp, ire, zoneid, ipst);
23371 			}
23372 		}
23373 	} else {
23374 nullstq:
23375 		/* A NULL stq means the destination address is local. */
23376 		UPDATE_OB_PKT_COUNT(ire);
23377 		ire->ire_last_used_time = lbolt;
23378 		ASSERT(ire->ire_ipif != NULL);
23379 		if (!next_mp) {
23380 			/*
23381 			 * Is there an "in" and "out" for traffic local
23382 			 * to a host (loopback)?  The code in Solaris doesn't
23383 			 * explicitly draw a line in its code for in vs out,
23384 			 * so we've had to draw a line in the sand: ip_wput_ire
23385 			 * is considered to be the "output" side and
23386 			 * ip_wput_local to be the "input" side.
23387 			 */
23388 			out_ill = ire_to_ill(ire);
23389 
23390 			DTRACE_PROBE4(ip4__loopback__out__start,
23391 			    ill_t *, NULL, ill_t *, out_ill,
23392 			    ipha_t *, ipha, mblk_t *, first_mp);
23393 
23394 			FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23395 			    ipst->ips_ipv4firewall_loopback_out,
23396 			    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23397 
23398 			DTRACE_PROBE1(ip4__loopback__out_end,
23399 			    mblk_t *, first_mp);
23400 
23401 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_IRE_END,
23402 			    "ip_wput_ire_end: q %p (%S)",
23403 			    q, "local address");
23404 
23405 			if (first_mp != NULL)
23406 				ip_wput_local(q, out_ill, ipha,
23407 				    first_mp, ire, 0, ire->ire_zoneid);
23408 			ire_refrele(ire);
23409 			if (conn_outgoing_ill != NULL)
23410 				ill_refrele(conn_outgoing_ill);
23411 			return;
23412 		}
23413 
23414 		out_ill = ire_to_ill(ire);
23415 
23416 		DTRACE_PROBE4(ip4__loopback__out__start,
23417 		    ill_t *, NULL, ill_t *, out_ill,
23418 		    ipha_t *, ipha, mblk_t *, first_mp);
23419 
23420 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
23421 		    ipst->ips_ipv4firewall_loopback_out,
23422 		    NULL, out_ill, ipha, first_mp, mp, 0, ipst);
23423 
23424 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, first_mp);
23425 
23426 		if (first_mp != NULL)
23427 			ip_wput_local(q, out_ill, ipha,
23428 			    first_mp, ire, 0, ire->ire_zoneid);
23429 	}
23430 next:
23431 	/*
23432 	 * More copies going out to additional interfaces.
23433 	 * ire1 has already been held. We don't need the
23434 	 * "ire" anymore.
23435 	 */
23436 	ire_refrele(ire);
23437 	ire = ire1;
23438 	ASSERT(ire != NULL && ire->ire_refcnt >= 1 && next_mp != NULL);
23439 	mp = next_mp;
23440 	ASSERT(ire->ire_ipversion == IPV4_VERSION);
23441 	ill = ire_to_ill(ire);
23442 	first_mp = mp;
23443 	if (ipsec_len != 0) {
23444 		ASSERT(first_mp->b_datap->db_type == M_CTL);
23445 		mp = mp->b_cont;
23446 	}
23447 	dst = ire->ire_addr;
23448 	ipha = (ipha_t *)mp->b_rptr;
23449 	/*
23450 	 * Restore src so that we will pick up ire->ire_src_addr if src was 0.
23451 	 * Restore ipha_ident "no checksum" flag.
23452 	 */
23453 	src = orig_src;
23454 	ipha->ipha_ident = ip_hdr_included;
23455 	goto another;
23456 
23457 #undef	rptr
23458 #undef	Q_TO_INDEX
23459 }
23460 
23461 /*
23462  * Routine to allocate a message that is used to notify the ULP about MDT.
23463  * The caller may provide a pointer to the link-layer MDT capabilities,
23464  * or NULL if MDT is to be disabled on the stream.
23465  */
23466 mblk_t *
23467 ip_mdinfo_alloc(ill_mdt_capab_t *isrc)
23468 {
23469 	mblk_t *mp;
23470 	ip_mdt_info_t *mdti;
23471 	ill_mdt_capab_t *idst;
23472 
23473 	if ((mp = allocb(sizeof (*mdti), BPRI_HI)) != NULL) {
23474 		DB_TYPE(mp) = M_CTL;
23475 		mp->b_wptr = mp->b_rptr + sizeof (*mdti);
23476 		mdti = (ip_mdt_info_t *)mp->b_rptr;
23477 		mdti->mdt_info_id = MDT_IOC_INFO_UPDATE;
23478 		idst = &(mdti->mdt_capab);
23479 
23480 		/*
23481 		 * If the caller provides us with the capability, copy
23482 		 * it over into our notification message; otherwise
23483 		 * we zero out the capability portion.
23484 		 */
23485 		if (isrc != NULL)
23486 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23487 		else
23488 			bzero((caddr_t)idst, sizeof (*idst));
23489 	}
23490 	return (mp);
23491 }
23492 
23493 /*
23494  * Routine which determines whether MDT can be enabled on the destination
23495  * IRE and IPC combination, and if so, allocates and returns the MDT
23496  * notification mblk that may be used by ULP.  We also check if we need to
23497  * turn MDT back to 'on' when certain restrictions prohibiting us to allow
23498  * MDT usage in the past have been lifted.  This gets called during IP
23499  * and ULP binding.
23500  */
23501 mblk_t *
23502 ip_mdinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23503     ill_mdt_capab_t *mdt_cap)
23504 {
23505 	mblk_t *mp;
23506 	boolean_t rc = B_FALSE;
23507 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
23508 
23509 	ASSERT(dst_ire != NULL);
23510 	ASSERT(connp != NULL);
23511 	ASSERT(mdt_cap != NULL);
23512 
23513 	/*
23514 	 * Currently, we only support simple TCP/{IPv4,IPv6} with
23515 	 * Multidata, which is handled in tcp_multisend().  This
23516 	 * is the reason why we do all these checks here, to ensure
23517 	 * that we don't enable Multidata for the cases which we
23518 	 * can't handle at the moment.
23519 	 */
23520 	do {
23521 		/* Only do TCP at the moment */
23522 		if (connp->conn_ulp != IPPROTO_TCP)
23523 			break;
23524 
23525 		/*
23526 		 * IPsec outbound policy present?  Note that we get here
23527 		 * after calling ipsec_conn_cache_policy() where the global
23528 		 * policy checking is performed.  conn_latch will be
23529 		 * non-NULL as long as there's a policy defined,
23530 		 * i.e. conn_out_enforce_policy may be NULL in such case
23531 		 * when the connection is non-secure, and hence we check
23532 		 * further if the latch refers to an outbound policy.
23533 		 */
23534 		if (CONN_IPSEC_OUT_ENCAPSULATED(connp))
23535 			break;
23536 
23537 		/* CGTP (multiroute) is enabled? */
23538 		if (dst_ire->ire_flags & RTF_MULTIRT)
23539 			break;
23540 
23541 		/* Outbound IPQoS enabled? */
23542 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23543 			/*
23544 			 * In this case, we disable MDT for this and all
23545 			 * future connections going over the interface.
23546 			 */
23547 			mdt_cap->ill_mdt_on = 0;
23548 			break;
23549 		}
23550 
23551 		/* socket option(s) present? */
23552 		if (!CONN_IS_LSO_MD_FASTPATH(connp))
23553 			break;
23554 
23555 		rc = B_TRUE;
23556 	/* CONSTCOND */
23557 	} while (0);
23558 
23559 	/* Remember the result */
23560 	connp->conn_mdt_ok = rc;
23561 
23562 	if (!rc)
23563 		return (NULL);
23564 	else if (!mdt_cap->ill_mdt_on) {
23565 		/*
23566 		 * If MDT has been previously turned off in the past, and we
23567 		 * currently can do MDT (due to IPQoS policy removal, etc.)
23568 		 * then enable it for this interface.
23569 		 */
23570 		mdt_cap->ill_mdt_on = 1;
23571 		ip1dbg(("ip_mdinfo_return: reenabling MDT for "
23572 		    "interface %s\n", ill_name));
23573 	}
23574 
23575 	/* Allocate the MDT info mblk */
23576 	if ((mp = ip_mdinfo_alloc(mdt_cap)) == NULL) {
23577 		ip0dbg(("ip_mdinfo_return: can't enable Multidata for "
23578 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23579 		return (NULL);
23580 	}
23581 	return (mp);
23582 }
23583 
23584 /*
23585  * Routine to allocate a message that is used to notify the ULP about LSO.
23586  * The caller may provide a pointer to the link-layer LSO capabilities,
23587  * or NULL if LSO is to be disabled on the stream.
23588  */
23589 mblk_t *
23590 ip_lsoinfo_alloc(ill_lso_capab_t *isrc)
23591 {
23592 	mblk_t *mp;
23593 	ip_lso_info_t *lsoi;
23594 	ill_lso_capab_t *idst;
23595 
23596 	if ((mp = allocb(sizeof (*lsoi), BPRI_HI)) != NULL) {
23597 		DB_TYPE(mp) = M_CTL;
23598 		mp->b_wptr = mp->b_rptr + sizeof (*lsoi);
23599 		lsoi = (ip_lso_info_t *)mp->b_rptr;
23600 		lsoi->lso_info_id = LSO_IOC_INFO_UPDATE;
23601 		idst = &(lsoi->lso_capab);
23602 
23603 		/*
23604 		 * If the caller provides us with the capability, copy
23605 		 * it over into our notification message; otherwise
23606 		 * we zero out the capability portion.
23607 		 */
23608 		if (isrc != NULL)
23609 			bcopy((caddr_t)isrc, (caddr_t)idst, sizeof (*idst));
23610 		else
23611 			bzero((caddr_t)idst, sizeof (*idst));
23612 	}
23613 	return (mp);
23614 }
23615 
23616 /*
23617  * Routine which determines whether LSO can be enabled on the destination
23618  * IRE and IPC combination, and if so, allocates and returns the LSO
23619  * notification mblk that may be used by ULP.  We also check if we need to
23620  * turn LSO back to 'on' when certain restrictions prohibiting us to allow
23621  * LSO usage in the past have been lifted.  This gets called during IP
23622  * and ULP binding.
23623  */
23624 mblk_t *
23625 ip_lsoinfo_return(ire_t *dst_ire, conn_t *connp, char *ill_name,
23626     ill_lso_capab_t *lso_cap)
23627 {
23628 	mblk_t *mp;
23629 	ip_stack_t *ipst = connp->conn_netstack->netstack_ip;
23630 
23631 	ASSERT(dst_ire != NULL);
23632 	ASSERT(connp != NULL);
23633 	ASSERT(lso_cap != NULL);
23634 
23635 	connp->conn_lso_ok = B_TRUE;
23636 
23637 	if ((connp->conn_ulp != IPPROTO_TCP) ||
23638 	    CONN_IPSEC_OUT_ENCAPSULATED(connp) ||
23639 	    (dst_ire->ire_flags & RTF_MULTIRT) ||
23640 	    !CONN_IS_LSO_MD_FASTPATH(connp) ||
23641 	    (IPP_ENABLED(IPP_LOCAL_OUT, ipst))) {
23642 		connp->conn_lso_ok = B_FALSE;
23643 		if (IPP_ENABLED(IPP_LOCAL_OUT, ipst)) {
23644 			/*
23645 			 * Disable LSO for this and all future connections going
23646 			 * over the interface.
23647 			 */
23648 			lso_cap->ill_lso_on = 0;
23649 		}
23650 	}
23651 
23652 	if (!connp->conn_lso_ok)
23653 		return (NULL);
23654 	else if (!lso_cap->ill_lso_on) {
23655 		/*
23656 		 * If LSO has been previously turned off in the past, and we
23657 		 * currently can do LSO (due to IPQoS policy removal, etc.)
23658 		 * then enable it for this interface.
23659 		 */
23660 		lso_cap->ill_lso_on = 1;
23661 		ip1dbg(("ip_mdinfo_return: reenabling LSO for interface %s\n",
23662 		    ill_name));
23663 	}
23664 
23665 	/* Allocate the LSO info mblk */
23666 	if ((mp = ip_lsoinfo_alloc(lso_cap)) == NULL)
23667 		ip0dbg(("ip_lsoinfo_return: can't enable LSO for "
23668 		    "conn %p on %s (ENOMEM)\n", (void *)connp, ill_name));
23669 
23670 	return (mp);
23671 }
23672 
23673 /*
23674  * Create destination address attribute, and fill it with the physical
23675  * destination address and SAP taken from the template DL_UNITDATA_REQ
23676  * message block.
23677  */
23678 boolean_t
23679 ip_md_addr_attr(multidata_t *mmd, pdesc_t *pd, const mblk_t *dlmp)
23680 {
23681 	dl_unitdata_req_t *dlurp;
23682 	pattr_t *pa;
23683 	pattrinfo_t pa_info;
23684 	pattr_addr_t **das = (pattr_addr_t **)&pa_info.buf;
23685 	uint_t das_len, das_off;
23686 
23687 	ASSERT(dlmp != NULL);
23688 
23689 	dlurp = (dl_unitdata_req_t *)dlmp->b_rptr;
23690 	das_len = dlurp->dl_dest_addr_length;
23691 	das_off = dlurp->dl_dest_addr_offset;
23692 
23693 	pa_info.type = PATTR_DSTADDRSAP;
23694 	pa_info.len = sizeof (**das) + das_len - 1;
23695 
23696 	/* create and associate the attribute */
23697 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23698 	if (pa != NULL) {
23699 		ASSERT(*das != NULL);
23700 		(*das)->addr_is_group = 0;
23701 		(*das)->addr_len = (uint8_t)das_len;
23702 		bcopy((caddr_t)dlurp + das_off, (*das)->addr, das_len);
23703 	}
23704 
23705 	return (pa != NULL);
23706 }
23707 
23708 /*
23709  * Create hardware checksum attribute and fill it with the values passed.
23710  */
23711 boolean_t
23712 ip_md_hcksum_attr(multidata_t *mmd, pdesc_t *pd, uint32_t start_offset,
23713     uint32_t stuff_offset, uint32_t end_offset, uint32_t flags)
23714 {
23715 	pattr_t *pa;
23716 	pattrinfo_t pa_info;
23717 
23718 	ASSERT(mmd != NULL);
23719 
23720 	pa_info.type = PATTR_HCKSUM;
23721 	pa_info.len = sizeof (pattr_hcksum_t);
23722 
23723 	/* create and associate the attribute */
23724 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23725 	if (pa != NULL) {
23726 		pattr_hcksum_t *hck = (pattr_hcksum_t *)pa_info.buf;
23727 
23728 		hck->hcksum_start_offset = start_offset;
23729 		hck->hcksum_stuff_offset = stuff_offset;
23730 		hck->hcksum_end_offset = end_offset;
23731 		hck->hcksum_flags = flags;
23732 	}
23733 	return (pa != NULL);
23734 }
23735 
23736 /*
23737  * Create zerocopy attribute and fill it with the specified flags
23738  */
23739 boolean_t
23740 ip_md_zcopy_attr(multidata_t *mmd, pdesc_t *pd, uint_t flags)
23741 {
23742 	pattr_t *pa;
23743 	pattrinfo_t pa_info;
23744 
23745 	ASSERT(mmd != NULL);
23746 	pa_info.type = PATTR_ZCOPY;
23747 	pa_info.len = sizeof (pattr_zcopy_t);
23748 
23749 	/* create and associate the attribute */
23750 	pa = mmd_addpattr(mmd, pd, &pa_info, B_TRUE, KM_NOSLEEP);
23751 	if (pa != NULL) {
23752 		pattr_zcopy_t *zcopy = (pattr_zcopy_t *)pa_info.buf;
23753 
23754 		zcopy->zcopy_flags = flags;
23755 	}
23756 	return (pa != NULL);
23757 }
23758 
23759 /*
23760  * Check if ip_wput_frag_mdt() and ip_wput_frag_mdt_v6() can handle a message
23761  * block chain. We could rewrite to handle arbitrary message block chains but
23762  * that would make the code complicated and slow. Right now there three
23763  * restrictions:
23764  *
23765  *   1. The first message block must contain the complete IP header and
23766  *	at least 1 byte of payload data.
23767  *   2. At most MULTIDATA_MAX_PBUFS non-empty message blocks are allowed
23768  *	so that we can use a single Multidata message.
23769  *   3. No frag must be distributed over two or more message blocks so
23770  *	that we don't need more than two packet descriptors per frag.
23771  *
23772  * The above restrictions allow us to support userland applications (which
23773  * will send down a single message block) and NFS over UDP (which will
23774  * send down a chain of at most three message blocks).
23775  *
23776  * We also don't use MDT for payloads with less than or equal to
23777  * ip_wput_frag_mdt_min bytes because it would cause too much overhead.
23778  */
23779 boolean_t
23780 ip_can_frag_mdt(mblk_t *mp, ssize_t hdr_len, ssize_t len)
23781 {
23782 	int	blocks;
23783 	ssize_t	total, missing, size;
23784 
23785 	ASSERT(mp != NULL);
23786 	ASSERT(hdr_len > 0);
23787 
23788 	size = MBLKL(mp) - hdr_len;
23789 	if (size <= 0)
23790 		return (B_FALSE);
23791 
23792 	/* The first mblk contains the header and some payload. */
23793 	blocks = 1;
23794 	total = size;
23795 	size %= len;
23796 	missing = (size == 0) ? 0 : (len - size);
23797 	mp = mp->b_cont;
23798 
23799 	while (mp != NULL) {
23800 		/*
23801 		 * Give up if we encounter a zero length message block.
23802 		 * In practice, this should rarely happen and therefore
23803 		 * not worth the trouble of freeing and re-linking the
23804 		 * mblk from the chain to handle such case.
23805 		 */
23806 		if ((size = MBLKL(mp)) == 0)
23807 			return (B_FALSE);
23808 
23809 		/* Too many payload buffers for a single Multidata message? */
23810 		if (++blocks > MULTIDATA_MAX_PBUFS)
23811 			return (B_FALSE);
23812 
23813 		total += size;
23814 		/* Is a frag distributed over two or more message blocks? */
23815 		if (missing > size)
23816 			return (B_FALSE);
23817 		size -= missing;
23818 
23819 		size %= len;
23820 		missing = (size == 0) ? 0 : (len - size);
23821 
23822 		mp = mp->b_cont;
23823 	}
23824 
23825 	return (total > ip_wput_frag_mdt_min);
23826 }
23827 
23828 /*
23829  * Outbound IPv4 fragmentation routine using MDT.
23830  */
23831 static void
23832 ip_wput_frag_mdt(ire_t *ire, mblk_t *mp, ip_pkt_t pkt_type, int len,
23833     uint32_t frag_flag, int offset)
23834 {
23835 	ipha_t		*ipha_orig;
23836 	int		i1, ip_data_end;
23837 	uint_t		pkts, wroff, hdr_chunk_len, pbuf_idx;
23838 	mblk_t		*hdr_mp, *md_mp = NULL;
23839 	unsigned char	*hdr_ptr, *pld_ptr;
23840 	multidata_t	*mmd;
23841 	ip_pdescinfo_t	pdi;
23842 	ill_t		*ill;
23843 	ip_stack_t	*ipst = ire->ire_ipst;
23844 
23845 	ASSERT(DB_TYPE(mp) == M_DATA);
23846 	ASSERT(MBLKL(mp) > sizeof (ipha_t));
23847 
23848 	ill = ire_to_ill(ire);
23849 	ASSERT(ill != NULL);
23850 
23851 	ipha_orig = (ipha_t *)mp->b_rptr;
23852 	mp->b_rptr += sizeof (ipha_t);
23853 
23854 	/* Calculate how many packets we will send out */
23855 	i1 = (mp->b_cont == NULL) ? MBLKL(mp) : msgsize(mp);
23856 	pkts = (i1 + len - 1) / len;
23857 	ASSERT(pkts > 1);
23858 
23859 	/* Allocate a message block which will hold all the IP Headers. */
23860 	wroff = ipst->ips_ip_wroff_extra;
23861 	hdr_chunk_len = wroff + IP_SIMPLE_HDR_LENGTH;
23862 
23863 	i1 = pkts * hdr_chunk_len;
23864 	/*
23865 	 * Create the header buffer, Multidata and destination address
23866 	 * and SAP attribute that should be associated with it.
23867 	 */
23868 	if ((hdr_mp = allocb(i1, BPRI_HI)) == NULL ||
23869 	    ((hdr_mp->b_wptr += i1),
23870 	    (mmd = mmd_alloc(hdr_mp, &md_mp, KM_NOSLEEP)) == NULL) ||
23871 	    !ip_md_addr_attr(mmd, NULL, ire->ire_nce->nce_res_mp)) {
23872 		freemsg(mp);
23873 		if (md_mp == NULL) {
23874 			freemsg(hdr_mp);
23875 		} else {
23876 free_mmd:		IP_STAT(ipst, ip_frag_mdt_discarded);
23877 			freemsg(md_mp);
23878 		}
23879 		IP_STAT(ipst, ip_frag_mdt_allocfail);
23880 		BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragFails);
23881 		return;
23882 	}
23883 	IP_STAT(ipst, ip_frag_mdt_allocd);
23884 
23885 	/*
23886 	 * Add a payload buffer to the Multidata; this operation must not
23887 	 * fail, or otherwise our logic in this routine is broken.  There
23888 	 * is no memory allocation done by the routine, so any returned
23889 	 * failure simply tells us that we've done something wrong.
23890 	 *
23891 	 * A failure tells us that either we're adding the same payload
23892 	 * buffer more than once, or we're trying to add more buffers than
23893 	 * allowed.  None of the above cases should happen, and we panic
23894 	 * because either there's horrible heap corruption, and/or
23895 	 * programming mistake.
23896 	 */
23897 	if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23898 		goto pbuf_panic;
23899 
23900 	hdr_ptr = hdr_mp->b_rptr;
23901 	pld_ptr = mp->b_rptr;
23902 
23903 	/* Establish the ending byte offset, based on the starting offset. */
23904 	offset <<= 3;
23905 	ip_data_end = offset + ntohs(ipha_orig->ipha_length) -
23906 	    IP_SIMPLE_HDR_LENGTH;
23907 
23908 	pdi.flags = PDESC_HBUF_REF | PDESC_PBUF_REF;
23909 
23910 	while (pld_ptr < mp->b_wptr) {
23911 		ipha_t		*ipha;
23912 		uint16_t	offset_and_flags;
23913 		uint16_t	ip_len;
23914 		int		error;
23915 
23916 		ASSERT((hdr_ptr + hdr_chunk_len) <= hdr_mp->b_wptr);
23917 		ipha = (ipha_t *)(hdr_ptr + wroff);
23918 		ASSERT(OK_32PTR(ipha));
23919 		*ipha = *ipha_orig;
23920 
23921 		if (ip_data_end - offset > len) {
23922 			offset_and_flags = IPH_MF;
23923 		} else {
23924 			/*
23925 			 * Last frag. Set len to the length of this last piece.
23926 			 */
23927 			len = ip_data_end - offset;
23928 			/* A frag of a frag might have IPH_MF non-zero */
23929 			offset_and_flags =
23930 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
23931 			    IPH_MF;
23932 		}
23933 		offset_and_flags |= (uint16_t)(offset >> 3);
23934 		offset_and_flags |= (uint16_t)frag_flag;
23935 		/* Store the offset and flags in the IP header. */
23936 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
23937 
23938 		/* Store the length in the IP header. */
23939 		ip_len = (uint16_t)(len + IP_SIMPLE_HDR_LENGTH);
23940 		ipha->ipha_length = htons(ip_len);
23941 
23942 		/*
23943 		 * Set the IP header checksum.  Note that mp is just
23944 		 * the header, so this is easy to pass to ip_csum.
23945 		 */
23946 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
23947 
23948 		/*
23949 		 * Record offset and size of header and data of the next packet
23950 		 * in the multidata message.
23951 		 */
23952 		PDESC_HDR_ADD(&pdi, hdr_ptr, wroff, IP_SIMPLE_HDR_LENGTH, 0);
23953 		PDESC_PLD_INIT(&pdi);
23954 		i1 = MIN(mp->b_wptr - pld_ptr, len);
23955 		ASSERT(i1 > 0);
23956 		PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, pld_ptr, i1);
23957 		if (i1 == len) {
23958 			pld_ptr += len;
23959 		} else {
23960 			i1 = len - i1;
23961 			mp = mp->b_cont;
23962 			ASSERT(mp != NULL);
23963 			ASSERT(MBLKL(mp) >= i1);
23964 			/*
23965 			 * Attach the next payload message block to the
23966 			 * multidata message.
23967 			 */
23968 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
23969 				goto pbuf_panic;
23970 			PDESC_PLD_SPAN_ADD(&pdi, pbuf_idx, mp->b_rptr, i1);
23971 			pld_ptr = mp->b_rptr + i1;
23972 		}
23973 
23974 		if ((mmd_addpdesc(mmd, (pdescinfo_t *)&pdi, &error,
23975 		    KM_NOSLEEP)) == NULL) {
23976 			/*
23977 			 * Any failure other than ENOMEM indicates that we
23978 			 * have passed in invalid pdesc info or parameters
23979 			 * to mmd_addpdesc, which must not happen.
23980 			 *
23981 			 * EINVAL is a result of failure on boundary checks
23982 			 * against the pdesc info contents.  It should not
23983 			 * happen, and we panic because either there's
23984 			 * horrible heap corruption, and/or programming
23985 			 * mistake.
23986 			 */
23987 			if (error != ENOMEM) {
23988 				cmn_err(CE_PANIC, "ip_wput_frag_mdt: "
23989 				    "pdesc logic error detected for "
23990 				    "mmd %p pinfo %p (%d)\n",
23991 				    (void *)mmd, (void *)&pdi, error);
23992 				/* NOTREACHED */
23993 			}
23994 			IP_STAT(ipst, ip_frag_mdt_addpdescfail);
23995 			/* Free unattached payload message blocks as well */
23996 			md_mp->b_cont = mp->b_cont;
23997 			goto free_mmd;
23998 		}
23999 
24000 		/* Advance fragment offset. */
24001 		offset += len;
24002 
24003 		/* Advance to location for next header in the buffer. */
24004 		hdr_ptr += hdr_chunk_len;
24005 
24006 		/* Did we reach the next payload message block? */
24007 		if (pld_ptr == mp->b_wptr && mp->b_cont != NULL) {
24008 			mp = mp->b_cont;
24009 			/*
24010 			 * Attach the next message block with payload
24011 			 * data to the multidata message.
24012 			 */
24013 			if ((pbuf_idx = mmd_addpldbuf(mmd, mp)) < 0)
24014 				goto pbuf_panic;
24015 			pld_ptr = mp->b_rptr;
24016 		}
24017 	}
24018 
24019 	ASSERT(hdr_mp->b_wptr == hdr_ptr);
24020 	ASSERT(mp->b_wptr == pld_ptr);
24021 
24022 	/* Update IP statistics */
24023 	IP_STAT_UPDATE(ipst, ip_frag_mdt_pkt_out, pkts);
24024 
24025 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsOutFragCreates, pkts);
24026 	BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutFragOKs);
24027 
24028 	len = ntohs(ipha_orig->ipha_length) + (pkts - 1) * IP_SIMPLE_HDR_LENGTH;
24029 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutTransmits, pkts);
24030 	UPDATE_MIB(ill->ill_ip_mib, ipIfStatsHCOutOctets, len);
24031 
24032 	if (pkt_type == OB_PKT) {
24033 		ire->ire_ob_pkt_count += pkts;
24034 		if (ire->ire_ipif != NULL)
24035 			atomic_add_32(&ire->ire_ipif->ipif_ob_pkt_count, pkts);
24036 	} else {
24037 		/* The type is IB_PKT in the forwarding path. */
24038 		ire->ire_ib_pkt_count += pkts;
24039 		ASSERT(!IRE_IS_LOCAL(ire));
24040 		if (ire->ire_type & IRE_BROADCAST) {
24041 			atomic_add_32(&ire->ire_ipif->ipif_ib_pkt_count, pkts);
24042 		} else {
24043 			UPDATE_MIB(ill->ill_ip_mib,
24044 			    ipIfStatsHCOutForwDatagrams, pkts);
24045 			atomic_add_32(&ire->ire_ipif->ipif_fo_pkt_count, pkts);
24046 		}
24047 	}
24048 	ire->ire_last_used_time = lbolt;
24049 	/* Send it down */
24050 	putnext(ire->ire_stq, md_mp);
24051 	return;
24052 
24053 pbuf_panic:
24054 	cmn_err(CE_PANIC, "ip_wput_frag_mdt: payload buffer logic "
24055 	    "error for mmd %p pbuf %p (%d)", (void *)mmd, (void *)mp,
24056 	    pbuf_idx);
24057 	/* NOTREACHED */
24058 }
24059 
24060 /*
24061  * Outbound IP fragmentation routine.
24062  *
24063  * NOTE : This routine does not ire_refrele the ire that is passed in
24064  * as the argument.
24065  */
24066 static void
24067 ip_wput_frag(ire_t *ire, mblk_t *mp_orig, ip_pkt_t pkt_type, uint32_t max_frag,
24068     uint32_t frag_flag, zoneid_t zoneid, ip_stack_t *ipst)
24069 {
24070 	int		i1;
24071 	mblk_t		*ll_hdr_mp;
24072 	int 		ll_hdr_len;
24073 	int		hdr_len;
24074 	mblk_t		*hdr_mp;
24075 	ipha_t		*ipha;
24076 	int		ip_data_end;
24077 	int		len;
24078 	mblk_t		*mp = mp_orig, *mp1;
24079 	int		offset;
24080 	queue_t		*q;
24081 	uint32_t	v_hlen_tos_len;
24082 	mblk_t		*first_mp;
24083 	boolean_t	mctl_present;
24084 	ill_t		*ill;
24085 	ill_t		*out_ill;
24086 	mblk_t		*xmit_mp;
24087 	mblk_t		*carve_mp;
24088 	ire_t		*ire1 = NULL;
24089 	ire_t		*save_ire = NULL;
24090 	mblk_t  	*next_mp = NULL;
24091 	boolean_t	last_frag = B_FALSE;
24092 	boolean_t	multirt_send = B_FALSE;
24093 	ire_t		*first_ire = NULL;
24094 	irb_t		*irb = NULL;
24095 	mib2_ipIfStatsEntry_t *mibptr = NULL;
24096 
24097 	ill = ire_to_ill(ire);
24098 	mibptr = (ill != NULL) ? ill->ill_ip_mib : &ipst->ips_ip_mib;
24099 
24100 	BUMP_MIB(mibptr, ipIfStatsOutFragReqds);
24101 
24102 	if (max_frag == 0) {
24103 		ip1dbg(("ip_wput_frag: ire frag size is 0"
24104 		    " -  dropping packet\n"));
24105 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24106 		freemsg(mp);
24107 		return;
24108 	}
24109 
24110 	/*
24111 	 * IPsec does not allow hw accelerated packets to be fragmented
24112 	 * This check is made in ip_wput_ipsec_out prior to coming here
24113 	 * via ip_wput_ire_fragmentit.
24114 	 *
24115 	 * If at this point we have an ire whose ARP request has not
24116 	 * been sent out, we call ip_xmit_v4->ire_arpresolve to trigger
24117 	 * sending of ARP query and change ire's state to ND_INCOMPLETE.
24118 	 * This packet and all fragmentable packets for this ire will
24119 	 * continue to get dropped while ire_nce->nce_state remains in
24120 	 * ND_INCOMPLETE. Post-ARP resolution, after ire's nce_state changes to
24121 	 * ND_REACHABLE, all subsquent large packets for this ire will
24122 	 * get fragemented and sent out by this function.
24123 	 */
24124 	if (ire->ire_nce && ire->ire_nce->nce_state != ND_REACHABLE) {
24125 		/* If nce_state is ND_INITIAL, trigger ARP query */
24126 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
24127 		ip1dbg(("ip_wput_frag: mac address for ire is unresolved"
24128 		    " -  dropping packet\n"));
24129 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24130 		freemsg(mp);
24131 		return;
24132 	}
24133 
24134 	TRACE_0(TR_FAC_IP, TR_IP_WPUT_FRAG_START,
24135 	    "ip_wput_frag_start:");
24136 
24137 	if (mp->b_datap->db_type == M_CTL) {
24138 		first_mp = mp;
24139 		mp_orig = mp = mp->b_cont;
24140 		mctl_present = B_TRUE;
24141 	} else {
24142 		first_mp = mp;
24143 		mctl_present = B_FALSE;
24144 	}
24145 
24146 	ASSERT(MBLKL(mp) >= sizeof (ipha_t));
24147 	ipha = (ipha_t *)mp->b_rptr;
24148 
24149 	/*
24150 	 * If the Don't Fragment flag is on, generate an ICMP destination
24151 	 * unreachable, fragmentation needed.
24152 	 */
24153 	offset = ntohs(ipha->ipha_fragment_offset_and_flags);
24154 	if (offset & IPH_DF) {
24155 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24156 		if (is_system_labeled()) {
24157 			max_frag = tsol_pmtu_adjust(mp, ire->ire_max_frag,
24158 			    ire->ire_max_frag - max_frag, AF_INET);
24159 		}
24160 		/*
24161 		 * Need to compute hdr checksum if called from ip_wput_ire.
24162 		 * Note that ip_rput_forward verifies the checksum before
24163 		 * calling this routine so in that case this is a noop.
24164 		 */
24165 		ipha->ipha_hdr_checksum = 0;
24166 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24167 		icmp_frag_needed(ire->ire_stq, first_mp, max_frag, zoneid,
24168 		    ipst);
24169 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24170 		    "ip_wput_frag_end:(%S)",
24171 		    "don't fragment");
24172 		return;
24173 	}
24174 	/*
24175 	 * Labeled systems adjust max_frag if they add a label
24176 	 * to send the correct path mtu.  We need the real mtu since we
24177 	 * are fragmenting the packet after label adjustment.
24178 	 */
24179 	if (is_system_labeled())
24180 		max_frag = ire->ire_max_frag;
24181 	if (mctl_present)
24182 		freeb(first_mp);
24183 	/*
24184 	 * Establish the starting offset.  May not be zero if we are fragging
24185 	 * a fragment that is being forwarded.
24186 	 */
24187 	offset = offset & IPH_OFFSET;
24188 
24189 	/* TODO why is this test needed? */
24190 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
24191 	if (((max_frag - LENGTH) & ~7) < 8) {
24192 		/* TODO: notify ulp somehow */
24193 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24194 		freemsg(mp);
24195 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24196 		    "ip_wput_frag_end:(%S)",
24197 		    "len < 8");
24198 		return;
24199 	}
24200 
24201 	hdr_len = (V_HLEN & 0xF) << 2;
24202 
24203 	ipha->ipha_hdr_checksum = 0;
24204 
24205 	/*
24206 	 * Establish the number of bytes maximum per frag, after putting
24207 	 * in the header.
24208 	 */
24209 	len = (max_frag - hdr_len) & ~7;
24210 
24211 	/* Check if we can use MDT to send out the frags. */
24212 	ASSERT(!IRE_IS_LOCAL(ire));
24213 	if (hdr_len == IP_SIMPLE_HDR_LENGTH &&
24214 	    ipst->ips_ip_multidata_outbound &&
24215 	    !(ire->ire_flags & RTF_MULTIRT) &&
24216 	    !IPP_ENABLED(IPP_LOCAL_OUT, ipst) &&
24217 	    ill != NULL && ILL_MDT_CAPABLE(ill) &&
24218 	    IP_CAN_FRAG_MDT(mp, IP_SIMPLE_HDR_LENGTH, len)) {
24219 		ASSERT(ill->ill_mdt_capab != NULL);
24220 		if (!ill->ill_mdt_capab->ill_mdt_on) {
24221 			/*
24222 			 * If MDT has been previously turned off in the past,
24223 			 * and we currently can do MDT (due to IPQoS policy
24224 			 * removal, etc.) then enable it for this interface.
24225 			 */
24226 			ill->ill_mdt_capab->ill_mdt_on = 1;
24227 			ip1dbg(("ip_wput_frag: enabled MDT for interface %s\n",
24228 			    ill->ill_name));
24229 		}
24230 		ip_wput_frag_mdt(ire, mp, pkt_type, len, frag_flag,
24231 		    offset);
24232 		return;
24233 	}
24234 
24235 	/* Get a copy of the header for the trailing frags */
24236 	hdr_mp = ip_wput_frag_copyhdr((uchar_t *)ipha, hdr_len, offset, ipst);
24237 	if (!hdr_mp) {
24238 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24239 		freemsg(mp);
24240 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24241 		    "ip_wput_frag_end:(%S)",
24242 		    "couldn't copy hdr");
24243 		return;
24244 	}
24245 	if (DB_CRED(mp) != NULL)
24246 		mblk_setcred(hdr_mp, DB_CRED(mp));
24247 
24248 	/* Store the starting offset, with the MoreFrags flag. */
24249 	i1 = offset | IPH_MF | frag_flag;
24250 	ipha->ipha_fragment_offset_and_flags = htons((uint16_t)i1);
24251 
24252 	/* Establish the ending byte offset, based on the starting offset. */
24253 	offset <<= 3;
24254 	ip_data_end = offset + ntohs(ipha->ipha_length) - hdr_len;
24255 
24256 	/* Store the length of the first fragment in the IP header. */
24257 	i1 = len + hdr_len;
24258 	ASSERT(i1 <= IP_MAXPACKET);
24259 	ipha->ipha_length = htons((uint16_t)i1);
24260 
24261 	/*
24262 	 * Compute the IP header checksum for the first frag.  We have to
24263 	 * watch out that we stop at the end of the header.
24264 	 */
24265 	ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24266 
24267 	/*
24268 	 * Now carve off the first frag.  Note that this will include the
24269 	 * original IP header.
24270 	 */
24271 	if (!(mp = ip_carve_mp(&mp_orig, i1))) {
24272 		BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24273 		freeb(hdr_mp);
24274 		freemsg(mp_orig);
24275 		TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24276 		    "ip_wput_frag_end:(%S)",
24277 		    "couldn't carve first");
24278 		return;
24279 	}
24280 
24281 	/*
24282 	 * Multirouting case. Each fragment is replicated
24283 	 * via all non-condemned RTF_MULTIRT routes
24284 	 * currently resolved.
24285 	 * We ensure that first_ire is the first RTF_MULTIRT
24286 	 * ire in the bucket.
24287 	 */
24288 	if (ire->ire_flags & RTF_MULTIRT) {
24289 		irb = ire->ire_bucket;
24290 		ASSERT(irb != NULL);
24291 
24292 		multirt_send = B_TRUE;
24293 
24294 		/* Make sure we do not omit any multiroute ire. */
24295 		IRB_REFHOLD(irb);
24296 		for (first_ire = irb->irb_ire;
24297 		    first_ire != NULL;
24298 		    first_ire = first_ire->ire_next) {
24299 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
24300 			    (first_ire->ire_addr == ire->ire_addr) &&
24301 			    !(first_ire->ire_marks &
24302 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
24303 				break;
24304 			}
24305 		}
24306 
24307 		if (first_ire != NULL) {
24308 			if (first_ire != ire) {
24309 				IRE_REFHOLD(first_ire);
24310 				/*
24311 				 * Do not release the ire passed in
24312 				 * as the argument.
24313 				 */
24314 				ire = first_ire;
24315 			} else {
24316 				first_ire = NULL;
24317 			}
24318 		}
24319 		IRB_REFRELE(irb);
24320 
24321 		/*
24322 		 * Save the first ire; we will need to restore it
24323 		 * for the trailing frags.
24324 		 * We REFHOLD save_ire, as each iterated ire will be
24325 		 * REFRELEd.
24326 		 */
24327 		save_ire = ire;
24328 		IRE_REFHOLD(save_ire);
24329 	}
24330 
24331 	/*
24332 	 * First fragment emission loop.
24333 	 * In most cases, the emission loop below is entered only
24334 	 * once. Only in the case where the ire holds the RTF_MULTIRT
24335 	 * flag, do we loop to process all RTF_MULTIRT ires in the
24336 	 * bucket, and send the fragment through all crossed
24337 	 * RTF_MULTIRT routes.
24338 	 */
24339 	do {
24340 		if (ire->ire_flags & RTF_MULTIRT) {
24341 			/*
24342 			 * We are in a multiple send case, need to get
24343 			 * the next ire and make a copy of the packet.
24344 			 * ire1 holds here the next ire to process in the
24345 			 * bucket. If multirouting is expected,
24346 			 * any non-RTF_MULTIRT ire that has the
24347 			 * right destination address is ignored.
24348 			 *
24349 			 * We have to take into account the MTU of
24350 			 * each walked ire. max_frag is set by the
24351 			 * the caller and generally refers to
24352 			 * the primary ire entry. Here we ensure that
24353 			 * no route with a lower MTU will be used, as
24354 			 * fragments are carved once for all ires,
24355 			 * then replicated.
24356 			 */
24357 			ASSERT(irb != NULL);
24358 			IRB_REFHOLD(irb);
24359 			for (ire1 = ire->ire_next;
24360 			    ire1 != NULL;
24361 			    ire1 = ire1->ire_next) {
24362 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
24363 					continue;
24364 				if (ire1->ire_addr != ire->ire_addr)
24365 					continue;
24366 				if (ire1->ire_marks &
24367 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
24368 					continue;
24369 				/*
24370 				 * Ensure we do not exceed the MTU
24371 				 * of the next route.
24372 				 */
24373 				if (ire1->ire_max_frag < max_frag) {
24374 					ip_multirt_bad_mtu(ire1, max_frag);
24375 					continue;
24376 				}
24377 
24378 				/* Got one. */
24379 				IRE_REFHOLD(ire1);
24380 				break;
24381 			}
24382 			IRB_REFRELE(irb);
24383 
24384 			if (ire1 != NULL) {
24385 				next_mp = copyb(mp);
24386 				if ((next_mp == NULL) ||
24387 				    ((mp->b_cont != NULL) &&
24388 				    ((next_mp->b_cont =
24389 				    dupmsg(mp->b_cont)) == NULL))) {
24390 					freemsg(next_mp);
24391 					next_mp = NULL;
24392 					ire_refrele(ire1);
24393 					ire1 = NULL;
24394 				}
24395 			}
24396 
24397 			/* Last multiroute ire; don't loop anymore. */
24398 			if (ire1 == NULL) {
24399 				multirt_send = B_FALSE;
24400 			}
24401 		}
24402 
24403 		ll_hdr_len = 0;
24404 		LOCK_IRE_FP_MP(ire);
24405 		ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24406 		if (ll_hdr_mp != NULL) {
24407 			ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24408 			ll_hdr_len = ll_hdr_mp->b_wptr - ll_hdr_mp->b_rptr;
24409 		} else {
24410 			ll_hdr_mp = ire->ire_nce->nce_res_mp;
24411 		}
24412 
24413 		/* If there is a transmit header, get a copy for this frag. */
24414 		/*
24415 		 * TODO: should check db_ref before calling ip_carve_mp since
24416 		 * it might give us a dup.
24417 		 */
24418 		if (!ll_hdr_mp) {
24419 			/* No xmit header. */
24420 			xmit_mp = mp;
24421 
24422 		/* We have a link-layer header that can fit in our mblk. */
24423 		} else if (mp->b_datap->db_ref == 1 &&
24424 		    ll_hdr_len != 0 &&
24425 		    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24426 			/* M_DATA fastpath */
24427 			mp->b_rptr -= ll_hdr_len;
24428 			bcopy(ll_hdr_mp->b_rptr, mp->b_rptr, ll_hdr_len);
24429 			xmit_mp = mp;
24430 
24431 		/* Corner case if copyb has failed */
24432 		} else if (!(xmit_mp = copyb(ll_hdr_mp))) {
24433 			UNLOCK_IRE_FP_MP(ire);
24434 			BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24435 			freeb(hdr_mp);
24436 			freemsg(mp);
24437 			freemsg(mp_orig);
24438 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24439 			    "ip_wput_frag_end:(%S)",
24440 			    "discard");
24441 
24442 			if (multirt_send) {
24443 				ASSERT(ire1);
24444 				ASSERT(next_mp);
24445 
24446 				freemsg(next_mp);
24447 				ire_refrele(ire1);
24448 			}
24449 			if (save_ire != NULL)
24450 				IRE_REFRELE(save_ire);
24451 
24452 			if (first_ire != NULL)
24453 				ire_refrele(first_ire);
24454 			return;
24455 
24456 		/*
24457 		 * Case of res_mp OR the fastpath mp can't fit
24458 		 * in the mblk
24459 		 */
24460 		} else {
24461 			xmit_mp->b_cont = mp;
24462 			if (DB_CRED(mp) != NULL)
24463 				mblk_setcred(xmit_mp, DB_CRED(mp));
24464 			/*
24465 			 * Get priority marking, if any.
24466 			 * We propagate the CoS marking from the
24467 			 * original packet that went to QoS processing
24468 			 * in ip_wput_ire to the newly carved mp.
24469 			 */
24470 			if (DB_TYPE(xmit_mp) == M_DATA)
24471 				xmit_mp->b_band = mp->b_band;
24472 		}
24473 		UNLOCK_IRE_FP_MP(ire);
24474 
24475 		q = ire->ire_stq;
24476 		out_ill = (ill_t *)q->q_ptr;
24477 
24478 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24479 
24480 		DTRACE_PROBE4(ip4__physical__out__start,
24481 		    ill_t *, NULL, ill_t *, out_ill,
24482 		    ipha_t *, ipha, mblk_t *, xmit_mp);
24483 
24484 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
24485 		    ipst->ips_ipv4firewall_physical_out,
24486 		    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24487 
24488 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, xmit_mp);
24489 
24490 		if (xmit_mp != NULL) {
24491 			putnext(q, xmit_mp);
24492 
24493 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutTransmits);
24494 			UPDATE_MIB(out_ill->ill_ip_mib,
24495 			    ipIfStatsHCOutOctets, i1);
24496 
24497 			if (pkt_type != OB_PKT) {
24498 				/*
24499 				 * Update the packet count and MIB stats
24500 				 * of trailing RTF_MULTIRT ires.
24501 				 */
24502 				UPDATE_OB_PKT_COUNT(ire);
24503 				BUMP_MIB(out_ill->ill_ip_mib,
24504 				    ipIfStatsOutFragReqds);
24505 			}
24506 		}
24507 
24508 		if (multirt_send) {
24509 			/*
24510 			 * We are in a multiple send case; look for
24511 			 * the next ire and re-enter the loop.
24512 			 */
24513 			ASSERT(ire1);
24514 			ASSERT(next_mp);
24515 			/* REFRELE the current ire before looping */
24516 			ire_refrele(ire);
24517 			ire = ire1;
24518 			ire1 = NULL;
24519 			mp = next_mp;
24520 			next_mp = NULL;
24521 		}
24522 	} while (multirt_send);
24523 
24524 	ASSERT(ire1 == NULL);
24525 
24526 	/* Restore the original ire; we need it for the trailing frags */
24527 	if (save_ire != NULL) {
24528 		/* REFRELE the last iterated ire */
24529 		ire_refrele(ire);
24530 		/* save_ire has been REFHOLDed */
24531 		ire = save_ire;
24532 		save_ire = NULL;
24533 		q = ire->ire_stq;
24534 	}
24535 
24536 	if (pkt_type == OB_PKT) {
24537 		UPDATE_OB_PKT_COUNT(ire);
24538 	} else {
24539 		out_ill = (ill_t *)q->q_ptr;
24540 		BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsHCOutForwDatagrams);
24541 		UPDATE_IB_PKT_COUNT(ire);
24542 	}
24543 
24544 	/* Advance the offset to the second frag starting point. */
24545 	offset += len;
24546 	/*
24547 	 * Update hdr_len from the copied header - there might be less options
24548 	 * in the later fragments.
24549 	 */
24550 	hdr_len = IPH_HDR_LENGTH(hdr_mp->b_rptr);
24551 	/* Loop until done. */
24552 	for (;;) {
24553 		uint16_t	offset_and_flags;
24554 		uint16_t	ip_len;
24555 
24556 		if (ip_data_end - offset > len) {
24557 			/*
24558 			 * Carve off the appropriate amount from the original
24559 			 * datagram.
24560 			 */
24561 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24562 				mp = NULL;
24563 				break;
24564 			}
24565 			/*
24566 			 * More frags after this one.  Get another copy
24567 			 * of the header.
24568 			 */
24569 			if (carve_mp->b_datap->db_ref == 1 &&
24570 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24571 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24572 				/* Inline IP header */
24573 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24574 				    hdr_mp->b_rptr;
24575 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24576 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24577 				mp = carve_mp;
24578 			} else {
24579 				if (!(mp = copyb(hdr_mp))) {
24580 					freemsg(carve_mp);
24581 					break;
24582 				}
24583 				/* Get priority marking, if any. */
24584 				mp->b_band = carve_mp->b_band;
24585 				mp->b_cont = carve_mp;
24586 			}
24587 			ipha = (ipha_t *)mp->b_rptr;
24588 			offset_and_flags = IPH_MF;
24589 		} else {
24590 			/*
24591 			 * Last frag.  Consume the header. Set len to
24592 			 * the length of this last piece.
24593 			 */
24594 			len = ip_data_end - offset;
24595 
24596 			/*
24597 			 * Carve off the appropriate amount from the original
24598 			 * datagram.
24599 			 */
24600 			if (!(carve_mp = ip_carve_mp(&mp_orig, len))) {
24601 				mp = NULL;
24602 				break;
24603 			}
24604 			if (carve_mp->b_datap->db_ref == 1 &&
24605 			    hdr_mp->b_wptr - hdr_mp->b_rptr <
24606 			    carve_mp->b_rptr - carve_mp->b_datap->db_base) {
24607 				/* Inline IP header */
24608 				carve_mp->b_rptr -= hdr_mp->b_wptr -
24609 				    hdr_mp->b_rptr;
24610 				bcopy(hdr_mp->b_rptr, carve_mp->b_rptr,
24611 				    hdr_mp->b_wptr - hdr_mp->b_rptr);
24612 				mp = carve_mp;
24613 				freeb(hdr_mp);
24614 				hdr_mp = mp;
24615 			} else {
24616 				mp = hdr_mp;
24617 				/* Get priority marking, if any. */
24618 				mp->b_band = carve_mp->b_band;
24619 				mp->b_cont = carve_mp;
24620 			}
24621 			ipha = (ipha_t *)mp->b_rptr;
24622 			/* A frag of a frag might have IPH_MF non-zero */
24623 			offset_and_flags =
24624 			    ntohs(ipha->ipha_fragment_offset_and_flags) &
24625 			    IPH_MF;
24626 		}
24627 		offset_and_flags |= (uint16_t)(offset >> 3);
24628 		offset_and_flags |= (uint16_t)frag_flag;
24629 		/* Store the offset and flags in the IP header. */
24630 		ipha->ipha_fragment_offset_and_flags = htons(offset_and_flags);
24631 
24632 		/* Store the length in the IP header. */
24633 		ip_len = (uint16_t)(len + hdr_len);
24634 		ipha->ipha_length = htons(ip_len);
24635 
24636 		/*
24637 		 * Set the IP header checksum.	Note that mp is just
24638 		 * the header, so this is easy to pass to ip_csum.
24639 		 */
24640 		ipha->ipha_hdr_checksum = ip_csum_hdr(ipha);
24641 
24642 		/* Attach a transmit header, if any, and ship it. */
24643 		if (pkt_type == OB_PKT) {
24644 			UPDATE_OB_PKT_COUNT(ire);
24645 		} else {
24646 			out_ill = (ill_t *)q->q_ptr;
24647 			BUMP_MIB(out_ill->ill_ip_mib,
24648 			    ipIfStatsHCOutForwDatagrams);
24649 			UPDATE_IB_PKT_COUNT(ire);
24650 		}
24651 
24652 		if (ire->ire_flags & RTF_MULTIRT) {
24653 			irb = ire->ire_bucket;
24654 			ASSERT(irb != NULL);
24655 
24656 			multirt_send = B_TRUE;
24657 
24658 			/*
24659 			 * Save the original ire; we will need to restore it
24660 			 * for the tailing frags.
24661 			 */
24662 			save_ire = ire;
24663 			IRE_REFHOLD(save_ire);
24664 		}
24665 		/*
24666 		 * Emission loop for this fragment, similar
24667 		 * to what is done for the first fragment.
24668 		 */
24669 		do {
24670 			if (multirt_send) {
24671 				/*
24672 				 * We are in a multiple send case, need to get
24673 				 * the next ire and make a copy of the packet.
24674 				 */
24675 				ASSERT(irb != NULL);
24676 				IRB_REFHOLD(irb);
24677 				for (ire1 = ire->ire_next;
24678 				    ire1 != NULL;
24679 				    ire1 = ire1->ire_next) {
24680 					if (!(ire1->ire_flags & RTF_MULTIRT))
24681 						continue;
24682 					if (ire1->ire_addr != ire->ire_addr)
24683 						continue;
24684 					if (ire1->ire_marks &
24685 					    (IRE_MARK_CONDEMNED|
24686 					    IRE_MARK_HIDDEN)) {
24687 						continue;
24688 					}
24689 					/*
24690 					 * Ensure we do not exceed the MTU
24691 					 * of the next route.
24692 					 */
24693 					if (ire1->ire_max_frag < max_frag) {
24694 						ip_multirt_bad_mtu(ire1,
24695 						    max_frag);
24696 						continue;
24697 					}
24698 
24699 					/* Got one. */
24700 					IRE_REFHOLD(ire1);
24701 					break;
24702 				}
24703 				IRB_REFRELE(irb);
24704 
24705 				if (ire1 != NULL) {
24706 					next_mp = copyb(mp);
24707 					if ((next_mp == NULL) ||
24708 					    ((mp->b_cont != NULL) &&
24709 					    ((next_mp->b_cont =
24710 					    dupmsg(mp->b_cont)) == NULL))) {
24711 						freemsg(next_mp);
24712 						next_mp = NULL;
24713 						ire_refrele(ire1);
24714 						ire1 = NULL;
24715 					}
24716 				}
24717 
24718 				/* Last multiroute ire; don't loop anymore. */
24719 				if (ire1 == NULL) {
24720 					multirt_send = B_FALSE;
24721 				}
24722 			}
24723 
24724 			/* Update transmit header */
24725 			ll_hdr_len = 0;
24726 			LOCK_IRE_FP_MP(ire);
24727 			ll_hdr_mp = ire->ire_nce->nce_fp_mp;
24728 			if (ll_hdr_mp != NULL) {
24729 				ASSERT(ll_hdr_mp->b_datap->db_type == M_DATA);
24730 				ll_hdr_len = MBLKL(ll_hdr_mp);
24731 			} else {
24732 				ll_hdr_mp = ire->ire_nce->nce_res_mp;
24733 			}
24734 
24735 			if (!ll_hdr_mp) {
24736 				xmit_mp = mp;
24737 
24738 			/*
24739 			 * We have link-layer header that can fit in
24740 			 * our mblk.
24741 			 */
24742 			} else if (mp->b_datap->db_ref == 1 &&
24743 			    ll_hdr_len != 0 &&
24744 			    ll_hdr_len <= mp->b_rptr - mp->b_datap->db_base) {
24745 				/* M_DATA fastpath */
24746 				mp->b_rptr -= ll_hdr_len;
24747 				bcopy(ll_hdr_mp->b_rptr, mp->b_rptr,
24748 				    ll_hdr_len);
24749 				xmit_mp = mp;
24750 
24751 			/*
24752 			 * Case of res_mp OR the fastpath mp can't fit
24753 			 * in the mblk
24754 			 */
24755 			} else if ((xmit_mp = copyb(ll_hdr_mp)) != NULL) {
24756 				xmit_mp->b_cont = mp;
24757 				if (DB_CRED(mp) != NULL)
24758 					mblk_setcred(xmit_mp, DB_CRED(mp));
24759 				/* Get priority marking, if any. */
24760 				if (DB_TYPE(xmit_mp) == M_DATA)
24761 					xmit_mp->b_band = mp->b_band;
24762 
24763 			/* Corner case if copyb failed */
24764 			} else {
24765 				/*
24766 				 * Exit both the replication and
24767 				 * fragmentation loops.
24768 				 */
24769 				UNLOCK_IRE_FP_MP(ire);
24770 				goto drop_pkt;
24771 			}
24772 			UNLOCK_IRE_FP_MP(ire);
24773 
24774 			mp1 = mp;
24775 			out_ill = (ill_t *)q->q_ptr;
24776 
24777 			BUMP_MIB(out_ill->ill_ip_mib, ipIfStatsOutFragCreates);
24778 
24779 			DTRACE_PROBE4(ip4__physical__out__start,
24780 			    ill_t *, NULL, ill_t *, out_ill,
24781 			    ipha_t *, ipha, mblk_t *, xmit_mp);
24782 
24783 			FW_HOOKS(ipst->ips_ip4_physical_out_event,
24784 			    ipst->ips_ipv4firewall_physical_out,
24785 			    NULL, out_ill, ipha, xmit_mp, mp, 0, ipst);
24786 
24787 			DTRACE_PROBE1(ip4__physical__out__end,
24788 			    mblk_t *, xmit_mp);
24789 
24790 			if (mp != mp1 && hdr_mp == mp1)
24791 				hdr_mp = mp;
24792 			if (mp != mp1 && mp_orig == mp1)
24793 				mp_orig = mp;
24794 
24795 			if (xmit_mp != NULL) {
24796 				putnext(q, xmit_mp);
24797 
24798 				BUMP_MIB(out_ill->ill_ip_mib,
24799 				    ipIfStatsHCOutTransmits);
24800 				UPDATE_MIB(out_ill->ill_ip_mib,
24801 				    ipIfStatsHCOutOctets, ip_len);
24802 
24803 				if (pkt_type != OB_PKT) {
24804 					/*
24805 					 * Update the packet count of trailing
24806 					 * RTF_MULTIRT ires.
24807 					 */
24808 					UPDATE_OB_PKT_COUNT(ire);
24809 				}
24810 			}
24811 
24812 			/* All done if we just consumed the hdr_mp. */
24813 			if (mp == hdr_mp) {
24814 				last_frag = B_TRUE;
24815 				BUMP_MIB(out_ill->ill_ip_mib,
24816 				    ipIfStatsOutFragOKs);
24817 			}
24818 
24819 			if (multirt_send) {
24820 				/*
24821 				 * We are in a multiple send case; look for
24822 				 * the next ire and re-enter the loop.
24823 				 */
24824 				ASSERT(ire1);
24825 				ASSERT(next_mp);
24826 				/* REFRELE the current ire before looping */
24827 				ire_refrele(ire);
24828 				ire = ire1;
24829 				ire1 = NULL;
24830 				q = ire->ire_stq;
24831 				mp = next_mp;
24832 				next_mp = NULL;
24833 			}
24834 		} while (multirt_send);
24835 		/*
24836 		 * Restore the original ire; we need it for the
24837 		 * trailing frags
24838 		 */
24839 		if (save_ire != NULL) {
24840 			ASSERT(ire1 == NULL);
24841 			/* REFRELE the last iterated ire */
24842 			ire_refrele(ire);
24843 			/* save_ire has been REFHOLDed */
24844 			ire = save_ire;
24845 			q = ire->ire_stq;
24846 			save_ire = NULL;
24847 		}
24848 
24849 		if (last_frag) {
24850 			TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24851 			    "ip_wput_frag_end:(%S)",
24852 			    "consumed hdr_mp");
24853 
24854 			if (first_ire != NULL)
24855 				ire_refrele(first_ire);
24856 			return;
24857 		}
24858 		/* Otherwise, advance and loop. */
24859 		offset += len;
24860 	}
24861 
24862 drop_pkt:
24863 	/* Clean up following allocation failure. */
24864 	BUMP_MIB(mibptr, ipIfStatsOutFragFails);
24865 	freemsg(mp);
24866 	if (mp != hdr_mp)
24867 		freeb(hdr_mp);
24868 	if (mp != mp_orig)
24869 		freemsg(mp_orig);
24870 
24871 	if (save_ire != NULL)
24872 		IRE_REFRELE(save_ire);
24873 	if (first_ire != NULL)
24874 		ire_refrele(first_ire);
24875 
24876 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_FRAG_END,
24877 	    "ip_wput_frag_end:(%S)",
24878 	    "end--alloc failure");
24879 }
24880 
24881 /*
24882  * Copy the header plus those options which have the copy bit set
24883  */
24884 static mblk_t *
24885 ip_wput_frag_copyhdr(uchar_t *rptr, int hdr_len, int offset, ip_stack_t *ipst)
24886 {
24887 	mblk_t	*mp;
24888 	uchar_t	*up;
24889 
24890 	/*
24891 	 * Quick check if we need to look for options without the copy bit
24892 	 * set
24893 	 */
24894 	mp = allocb(ipst->ips_ip_wroff_extra + hdr_len, BPRI_HI);
24895 	if (!mp)
24896 		return (mp);
24897 	mp->b_rptr += ipst->ips_ip_wroff_extra;
24898 	if (hdr_len == IP_SIMPLE_HDR_LENGTH || offset != 0) {
24899 		bcopy(rptr, mp->b_rptr, hdr_len);
24900 		mp->b_wptr += hdr_len + ipst->ips_ip_wroff_extra;
24901 		return (mp);
24902 	}
24903 	up  = mp->b_rptr;
24904 	bcopy(rptr, up, IP_SIMPLE_HDR_LENGTH);
24905 	up += IP_SIMPLE_HDR_LENGTH;
24906 	rptr += IP_SIMPLE_HDR_LENGTH;
24907 	hdr_len -= IP_SIMPLE_HDR_LENGTH;
24908 	while (hdr_len > 0) {
24909 		uint32_t optval;
24910 		uint32_t optlen;
24911 
24912 		optval = *rptr;
24913 		if (optval == IPOPT_EOL)
24914 			break;
24915 		if (optval == IPOPT_NOP)
24916 			optlen = 1;
24917 		else
24918 			optlen = rptr[1];
24919 		if (optval & IPOPT_COPY) {
24920 			bcopy(rptr, up, optlen);
24921 			up += optlen;
24922 		}
24923 		rptr += optlen;
24924 		hdr_len -= optlen;
24925 	}
24926 	/*
24927 	 * Make sure that we drop an even number of words by filling
24928 	 * with EOL to the next word boundary.
24929 	 */
24930 	for (hdr_len = up - (mp->b_rptr + IP_SIMPLE_HDR_LENGTH);
24931 	    hdr_len & 0x3; hdr_len++)
24932 		*up++ = IPOPT_EOL;
24933 	mp->b_wptr = up;
24934 	/* Update header length */
24935 	mp->b_rptr[0] = (uint8_t)((IP_VERSION << 4) | ((up - mp->b_rptr) >> 2));
24936 	return (mp);
24937 }
24938 
24939 /*
24940  * Delivery to local recipients including fanout to multiple recipients.
24941  * Does not do checksumming of UDP/TCP.
24942  * Note: q should be the read side queue for either the ill or conn.
24943  * Note: rq should be the read side q for the lower (ill) stream.
24944  * We don't send packets to IPPF processing, thus the last argument
24945  * to all the fanout calls are B_FALSE.
24946  */
24947 void
24948 ip_wput_local(queue_t *q, ill_t *ill, ipha_t *ipha, mblk_t *mp, ire_t *ire,
24949     int fanout_flags, zoneid_t zoneid)
24950 {
24951 	uint32_t	protocol;
24952 	mblk_t		*first_mp;
24953 	boolean_t	mctl_present;
24954 	int		ire_type;
24955 #define	rptr	((uchar_t *)ipha)
24956 	ip_stack_t	*ipst = ill->ill_ipst;
24957 
24958 	TRACE_1(TR_FAC_IP, TR_IP_WPUT_LOCAL_START,
24959 	    "ip_wput_local_start: q %p", q);
24960 
24961 	if (ire != NULL) {
24962 		ire_type = ire->ire_type;
24963 	} else {
24964 		/*
24965 		 * Only ip_multicast_loopback() calls us with a NULL ire. If the
24966 		 * packet is not multicast, we can't tell the ire type.
24967 		 */
24968 		ASSERT(CLASSD(ipha->ipha_dst));
24969 		ire_type = IRE_BROADCAST;
24970 	}
24971 
24972 	first_mp = mp;
24973 	if (first_mp->b_datap->db_type == M_CTL) {
24974 		ipsec_out_t *io = (ipsec_out_t *)first_mp->b_rptr;
24975 		if (!io->ipsec_out_secure) {
24976 			/*
24977 			 * This ipsec_out_t was allocated in ip_wput
24978 			 * for multicast packets to store the ill_index.
24979 			 * As this is being delivered locally, we don't
24980 			 * need this anymore.
24981 			 */
24982 			mp = first_mp->b_cont;
24983 			freeb(first_mp);
24984 			first_mp = mp;
24985 			mctl_present = B_FALSE;
24986 		} else {
24987 			/*
24988 			 * Convert IPSEC_OUT to IPSEC_IN, preserving all
24989 			 * security properties for the looped-back packet.
24990 			 */
24991 			mctl_present = B_TRUE;
24992 			mp = first_mp->b_cont;
24993 			ASSERT(mp != NULL);
24994 			ipsec_out_to_in(first_mp);
24995 		}
24996 	} else {
24997 		mctl_present = B_FALSE;
24998 	}
24999 
25000 	DTRACE_PROBE4(ip4__loopback__in__start,
25001 	    ill_t *, ill, ill_t *, NULL,
25002 	    ipha_t *, ipha, mblk_t *, first_mp);
25003 
25004 	FW_HOOKS(ipst->ips_ip4_loopback_in_event,
25005 	    ipst->ips_ipv4firewall_loopback_in,
25006 	    ill, NULL, ipha, first_mp, mp, 0, ipst);
25007 
25008 	DTRACE_PROBE1(ip4__loopback__in__end, mblk_t *, first_mp);
25009 
25010 	if (first_mp == NULL)
25011 		return;
25012 
25013 	ipst->ips_loopback_packets++;
25014 
25015 	ip2dbg(("ip_wput_local: from 0x%x to 0x%x in zone %d\n",
25016 	    ntohl(ipha->ipha_src), ntohl(ipha->ipha_dst), zoneid));
25017 	if (!IS_SIMPLE_IPH(ipha)) {
25018 		ip_wput_local_options(ipha, ipst);
25019 	}
25020 
25021 	protocol = ipha->ipha_protocol;
25022 	switch (protocol) {
25023 	case IPPROTO_ICMP: {
25024 		ire_t		*ire_zone;
25025 		ilm_t		*ilm;
25026 		mblk_t		*mp1;
25027 		zoneid_t	last_zoneid;
25028 
25029 		if (CLASSD(ipha->ipha_dst) && !IS_LOOPBACK(ill)) {
25030 			ASSERT(ire_type == IRE_BROADCAST);
25031 			/*
25032 			 * In the multicast case, applications may have joined
25033 			 * the group from different zones, so we need to deliver
25034 			 * the packet to each of them. Loop through the
25035 			 * multicast memberships structures (ilm) on the receive
25036 			 * ill and send a copy of the packet up each matching
25037 			 * one. However, we don't do this for multicasts sent on
25038 			 * the loopback interface (PHYI_LOOPBACK flag set) as
25039 			 * they must stay in the sender's zone.
25040 			 *
25041 			 * ilm_add_v6() ensures that ilms in the same zone are
25042 			 * contiguous in the ill_ilm list. We use this property
25043 			 * to avoid sending duplicates needed when two
25044 			 * applications in the same zone join the same group on
25045 			 * different logical interfaces: we ignore the ilm if
25046 			 * it's zoneid is the same as the last matching one.
25047 			 * In addition, the sending of the packet for
25048 			 * ire_zoneid is delayed until all of the other ilms
25049 			 * have been exhausted.
25050 			 */
25051 			last_zoneid = -1;
25052 			ILM_WALKER_HOLD(ill);
25053 			for (ilm = ill->ill_ilm; ilm != NULL;
25054 			    ilm = ilm->ilm_next) {
25055 				if ((ilm->ilm_flags & ILM_DELETED) ||
25056 				    ipha->ipha_dst != ilm->ilm_addr ||
25057 				    ilm->ilm_zoneid == last_zoneid ||
25058 				    ilm->ilm_zoneid == zoneid ||
25059 				    !(ilm->ilm_ipif->ipif_flags & IPIF_UP))
25060 					continue;
25061 				mp1 = ip_copymsg(first_mp);
25062 				if (mp1 == NULL)
25063 					continue;
25064 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25065 				    mctl_present, B_FALSE, ill,
25066 				    ilm->ilm_zoneid);
25067 				last_zoneid = ilm->ilm_zoneid;
25068 			}
25069 			ILM_WALKER_RELE(ill);
25070 			/*
25071 			 * Loopback case: the sending endpoint has
25072 			 * IP_MULTICAST_LOOP disabled, therefore we don't
25073 			 * dispatch the multicast packet to the sending zone.
25074 			 */
25075 			if (fanout_flags & IP_FF_NO_MCAST_LOOP) {
25076 				freemsg(first_mp);
25077 				return;
25078 			}
25079 		} else if (ire_type == IRE_BROADCAST) {
25080 			/*
25081 			 * In the broadcast case, there may be many zones
25082 			 * which need a copy of the packet delivered to them.
25083 			 * There is one IRE_BROADCAST per broadcast address
25084 			 * and per zone; we walk those using a helper function.
25085 			 * In addition, the sending of the packet for zoneid is
25086 			 * delayed until all of the other ires have been
25087 			 * processed.
25088 			 */
25089 			IRB_REFHOLD(ire->ire_bucket);
25090 			ire_zone = NULL;
25091 			while ((ire_zone = ire_get_next_bcast_ire(ire_zone,
25092 			    ire)) != NULL) {
25093 				mp1 = ip_copymsg(first_mp);
25094 				if (mp1 == NULL)
25095 					continue;
25096 
25097 				UPDATE_IB_PKT_COUNT(ire_zone);
25098 				ire_zone->ire_last_used_time = lbolt;
25099 				icmp_inbound(q, mp1, B_TRUE, ill, 0, 0,
25100 				    mctl_present, B_FALSE, ill,
25101 				    ire_zone->ire_zoneid);
25102 			}
25103 			IRB_REFRELE(ire->ire_bucket);
25104 		}
25105 		icmp_inbound(q, first_mp, (ire_type == IRE_BROADCAST), ill, 0,
25106 		    0, mctl_present, B_FALSE, ill, zoneid);
25107 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25108 		    "ip_wput_local_end: q %p (%S)",
25109 		    q, "icmp");
25110 		return;
25111 	}
25112 	case IPPROTO_IGMP:
25113 		if ((mp = igmp_input(q, mp, ill)) == NULL) {
25114 			/* Bad packet - discarded by igmp_input */
25115 			TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25116 			    "ip_wput_local_end: q %p (%S)",
25117 			    q, "igmp_input--bad packet");
25118 			if (mctl_present)
25119 				freeb(first_mp);
25120 			return;
25121 		}
25122 		/*
25123 		 * igmp_input() may have returned the pulled up message.
25124 		 * So first_mp and ipha need to be reinitialized.
25125 		 */
25126 		ipha = (ipha_t *)mp->b_rptr;
25127 		if (mctl_present)
25128 			first_mp->b_cont = mp;
25129 		else
25130 			first_mp = mp;
25131 		/* deliver to local raw users */
25132 		break;
25133 	case IPPROTO_ENCAP:
25134 		/*
25135 		 * This case is covered by either ip_fanout_proto, or by
25136 		 * the above security processing for self-tunneled packets.
25137 		 */
25138 		break;
25139 	case IPPROTO_UDP: {
25140 		uint16_t	*up;
25141 		uint32_t	ports;
25142 
25143 		up = (uint16_t *)(rptr + IPH_HDR_LENGTH(ipha) +
25144 		    UDP_PORTS_OFFSET);
25145 		/* Force a 'valid' checksum. */
25146 		up[3] = 0;
25147 
25148 		ports = *(uint32_t *)up;
25149 		ip_fanout_udp(q, first_mp, ill, ipha, ports,
25150 		    (ire_type == IRE_BROADCAST),
25151 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25152 		    IP_FF_SEND_SLLA | IP_FF_IPINFO, mctl_present, B_FALSE,
25153 		    ill, zoneid);
25154 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25155 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_udp");
25156 		return;
25157 	}
25158 	case IPPROTO_TCP: {
25159 
25160 		/*
25161 		 * For TCP, discard broadcast packets.
25162 		 */
25163 		if ((ushort_t)ire_type == IRE_BROADCAST) {
25164 			freemsg(first_mp);
25165 			BUMP_MIB(ill->ill_ip_mib, ipIfStatsInDiscards);
25166 			ip2dbg(("ip_wput_local: discard broadcast\n"));
25167 			return;
25168 		}
25169 
25170 		if (mp->b_datap->db_type == M_DATA) {
25171 			/*
25172 			 * M_DATA mblk, so init mblk (chain) for no struio().
25173 			 */
25174 			mblk_t	*mp1 = mp;
25175 
25176 			do {
25177 				mp1->b_datap->db_struioflag = 0;
25178 			} while ((mp1 = mp1->b_cont) != NULL);
25179 		}
25180 		ASSERT((rptr + IPH_HDR_LENGTH(ipha) + TCP_PORTS_OFFSET + 4)
25181 		    <= mp->b_wptr);
25182 		ip_fanout_tcp(q, first_mp, ill, ipha,
25183 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25184 		    IP_FF_SYN_ADDIRE | IP_FF_IPINFO,
25185 		    mctl_present, B_FALSE, zoneid);
25186 		TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25187 		    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_tcp");
25188 		return;
25189 	}
25190 	case IPPROTO_SCTP:
25191 	{
25192 		uint32_t	ports;
25193 
25194 		bcopy(rptr + IPH_HDR_LENGTH(ipha), &ports, sizeof (ports));
25195 		ip_fanout_sctp(first_mp, ill, ipha, ports,
25196 		    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE |
25197 		    IP_FF_IPINFO, mctl_present, B_FALSE, zoneid);
25198 		return;
25199 	}
25200 
25201 	default:
25202 		break;
25203 	}
25204 	/*
25205 	 * Find a client for some other protocol.  We give
25206 	 * copies to multiple clients, if more than one is
25207 	 * bound.
25208 	 */
25209 	ip_fanout_proto(q, first_mp, ill, ipha,
25210 	    fanout_flags | IP_FF_SEND_ICMP | IP_FF_HDR_COMPLETE | IP_FF_RAWIP,
25211 	    mctl_present, B_FALSE, ill, zoneid);
25212 	TRACE_2(TR_FAC_IP, TR_IP_WPUT_LOCAL_END,
25213 	    "ip_wput_local_end: q %p (%S)", q, "ip_fanout_proto");
25214 #undef	rptr
25215 }
25216 
25217 /*
25218  * Update any source route, record route, or timestamp options.
25219  * Check that we are at end of strict source route.
25220  * The options have been sanity checked by ip_wput_options().
25221  */
25222 static void
25223 ip_wput_local_options(ipha_t *ipha, ip_stack_t *ipst)
25224 {
25225 	ipoptp_t	opts;
25226 	uchar_t		*opt;
25227 	uint8_t		optval;
25228 	uint8_t		optlen;
25229 	ipaddr_t	dst;
25230 	uint32_t	ts;
25231 	ire_t		*ire;
25232 	timestruc_t	now;
25233 
25234 	ip2dbg(("ip_wput_local_options\n"));
25235 	for (optval = ipoptp_first(&opts, ipha);
25236 	    optval != IPOPT_EOL;
25237 	    optval = ipoptp_next(&opts)) {
25238 		opt = opts.ipoptp_cur;
25239 		optlen = opts.ipoptp_len;
25240 		ASSERT((opts.ipoptp_flags & IPOPTP_ERROR) == 0);
25241 		switch (optval) {
25242 			uint32_t off;
25243 		case IPOPT_SSRR:
25244 		case IPOPT_LSRR:
25245 			off = opt[IPOPT_OFFSET];
25246 			off--;
25247 			if (optlen < IP_ADDR_LEN ||
25248 			    off > optlen - IP_ADDR_LEN) {
25249 				/* End of source route */
25250 				break;
25251 			}
25252 			/*
25253 			 * This will only happen if two consecutive entries
25254 			 * in the source route contains our address or if
25255 			 * it is a packet with a loose source route which
25256 			 * reaches us before consuming the whole source route
25257 			 */
25258 			ip1dbg(("ip_wput_local_options: not end of SR\n"));
25259 			if (optval == IPOPT_SSRR) {
25260 				return;
25261 			}
25262 			/*
25263 			 * Hack: instead of dropping the packet truncate the
25264 			 * source route to what has been used by filling the
25265 			 * rest with IPOPT_NOP.
25266 			 */
25267 			opt[IPOPT_OLEN] = (uint8_t)off;
25268 			while (off < optlen) {
25269 				opt[off++] = IPOPT_NOP;
25270 			}
25271 			break;
25272 		case IPOPT_RR:
25273 			off = opt[IPOPT_OFFSET];
25274 			off--;
25275 			if (optlen < IP_ADDR_LEN ||
25276 			    off > optlen - IP_ADDR_LEN) {
25277 				/* No more room - ignore */
25278 				ip1dbg((
25279 				    "ip_wput_forward_options: end of RR\n"));
25280 				break;
25281 			}
25282 			dst = htonl(INADDR_LOOPBACK);
25283 			bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25284 			opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25285 			break;
25286 		case IPOPT_TS:
25287 			/* Insert timestamp if there is romm */
25288 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25289 			case IPOPT_TS_TSONLY:
25290 				off = IPOPT_TS_TIMELEN;
25291 				break;
25292 			case IPOPT_TS_PRESPEC:
25293 			case IPOPT_TS_PRESPEC_RFC791:
25294 				/* Verify that the address matched */
25295 				off = opt[IPOPT_OFFSET] - 1;
25296 				bcopy((char *)opt + off, &dst, IP_ADDR_LEN);
25297 				ire = ire_ctable_lookup(dst, 0, IRE_LOCAL,
25298 				    NULL, ALL_ZONES, NULL, MATCH_IRE_TYPE,
25299 				    ipst);
25300 				if (ire == NULL) {
25301 					/* Not for us */
25302 					break;
25303 				}
25304 				ire_refrele(ire);
25305 				/* FALLTHRU */
25306 			case IPOPT_TS_TSANDADDR:
25307 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
25308 				break;
25309 			default:
25310 				/*
25311 				 * ip_*put_options should have already
25312 				 * dropped this packet.
25313 				 */
25314 				cmn_err(CE_PANIC, "ip_wput_local_options: "
25315 				    "unknown IT - bug in ip_wput_options?\n");
25316 				return;	/* Keep "lint" happy */
25317 			}
25318 			if (opt[IPOPT_OFFSET] - 1 + off > optlen) {
25319 				/* Increase overflow counter */
25320 				off = (opt[IPOPT_POS_OV_FLG] >> 4) + 1;
25321 				opt[IPOPT_POS_OV_FLG] = (uint8_t)
25322 				    (opt[IPOPT_POS_OV_FLG] & 0x0F) |
25323 				    (off << 4);
25324 				break;
25325 			}
25326 			off = opt[IPOPT_OFFSET] - 1;
25327 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
25328 			case IPOPT_TS_PRESPEC:
25329 			case IPOPT_TS_PRESPEC_RFC791:
25330 			case IPOPT_TS_TSANDADDR:
25331 				dst = htonl(INADDR_LOOPBACK);
25332 				bcopy(&dst, (char *)opt + off, IP_ADDR_LEN);
25333 				opt[IPOPT_OFFSET] += IP_ADDR_LEN;
25334 				/* FALLTHRU */
25335 			case IPOPT_TS_TSONLY:
25336 				off = opt[IPOPT_OFFSET] - 1;
25337 				/* Compute # of milliseconds since midnight */
25338 				gethrestime(&now);
25339 				ts = (now.tv_sec % (24 * 60 * 60)) * 1000 +
25340 				    now.tv_nsec / (NANOSEC / MILLISEC);
25341 				bcopy(&ts, (char *)opt + off, IPOPT_TS_TIMELEN);
25342 				opt[IPOPT_OFFSET] += IPOPT_TS_TIMELEN;
25343 				break;
25344 			}
25345 			break;
25346 		}
25347 	}
25348 }
25349 
25350 /*
25351  * Send out a multicast packet on interface ipif.
25352  * The sender does not have an conn.
25353  * Caller verifies that this isn't a PHYI_LOOPBACK.
25354  */
25355 void
25356 ip_wput_multicast(queue_t *q, mblk_t *mp, ipif_t *ipif, zoneid_t zoneid)
25357 {
25358 	ipha_t	*ipha;
25359 	ire_t	*ire;
25360 	ipaddr_t	dst;
25361 	mblk_t		*first_mp;
25362 	ip_stack_t	*ipst = ipif->ipif_ill->ill_ipst;
25363 
25364 	/* igmp_sendpkt always allocates a ipsec_out_t */
25365 	ASSERT(mp->b_datap->db_type == M_CTL);
25366 	ASSERT(!ipif->ipif_isv6);
25367 	ASSERT(!IS_LOOPBACK(ipif->ipif_ill));
25368 
25369 	first_mp = mp;
25370 	mp = first_mp->b_cont;
25371 	ASSERT(mp->b_datap->db_type == M_DATA);
25372 	ipha = (ipha_t *)mp->b_rptr;
25373 
25374 	/*
25375 	 * Find an IRE which matches the destination and the outgoing
25376 	 * queue (i.e. the outgoing interface.)
25377 	 */
25378 	if (ipif->ipif_flags & IPIF_POINTOPOINT)
25379 		dst = ipif->ipif_pp_dst_addr;
25380 	else
25381 		dst = ipha->ipha_dst;
25382 	/*
25383 	 * The source address has already been initialized by the
25384 	 * caller and hence matching on ILL (MATCH_IRE_ILL) would
25385 	 * be sufficient rather than MATCH_IRE_IPIF.
25386 	 *
25387 	 * This function is used for sending IGMP packets. We need
25388 	 * to make sure that we send the packet out of the interface
25389 	 * (ipif->ipif_ill) where we joined the group. This is to
25390 	 * prevent from switches doing IGMP snooping to send us multicast
25391 	 * packets for a given group on the interface we have joined.
25392 	 * If we can't find an ire, igmp_sendpkt has already initialized
25393 	 * ipsec_out_attach_if so that this will not be load spread in
25394 	 * ip_newroute_ipif.
25395 	 */
25396 	ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid, NULL,
25397 	    MATCH_IRE_ILL, ipst);
25398 	if (!ire) {
25399 		/*
25400 		 * Mark this packet to make it be delivered to
25401 		 * ip_wput_ire after the new ire has been
25402 		 * created.
25403 		 */
25404 		mp->b_prev = NULL;
25405 		mp->b_next = NULL;
25406 		ip_newroute_ipif(q, first_mp, ipif, dst, NULL, RTF_SETSRC,
25407 		    zoneid, &zero_info);
25408 		return;
25409 	}
25410 
25411 	/*
25412 	 * Honor the RTF_SETSRC flag; this is the only case
25413 	 * where we force this addr whatever the current src addr is,
25414 	 * because this address is set by igmp_sendpkt(), and
25415 	 * cannot be specified by any user.
25416 	 */
25417 	if (ire->ire_flags & RTF_SETSRC) {
25418 		ipha->ipha_src = ire->ire_src_addr;
25419 	}
25420 
25421 	ip_wput_ire(q, first_mp, ire, NULL, B_FALSE, zoneid);
25422 }
25423 
25424 /*
25425  * NOTE : This function does not ire_refrele the ire argument passed in.
25426  *
25427  * Copy the link layer header and do IPQoS if needed. Frees the mblk on
25428  * failure. The nce_fp_mp can vanish any time in the case of
25429  * IRE_BROADCAST due to DL_NOTE_FASTPATH_FLUSH. Hence we have to hold
25430  * the ire_lock to access the nce_fp_mp in this case.
25431  * IPQoS assumes that the first M_DATA contains the IP header. So, if we are
25432  * prepending a fastpath message IPQoS processing must precede it, we also set
25433  * the b_band of the fastpath message to that of the  mblk returned by IPQoS
25434  * (IPQoS might have set the b_band for CoS marking).
25435  * However, if we are prepending DL_UNITDATA_REQ message, IPQoS processing
25436  * must follow it so that IPQoS can mark the dl_priority field for CoS
25437  * marking, if needed.
25438  */
25439 static mblk_t *
25440 ip_wput_attach_llhdr(mblk_t *mp, ire_t *ire, ip_proc_t proc, uint32_t ill_index)
25441 {
25442 	uint_t	hlen;
25443 	ipha_t *ipha;
25444 	mblk_t *mp1;
25445 	boolean_t qos_done = B_FALSE;
25446 	uchar_t	*ll_hdr;
25447 	ip_stack_t	*ipst = ire->ire_ipst;
25448 
25449 #define	rptr	((uchar_t *)ipha)
25450 
25451 	ipha = (ipha_t *)mp->b_rptr;
25452 	hlen = 0;
25453 	LOCK_IRE_FP_MP(ire);
25454 	if ((mp1 = ire->ire_nce->nce_fp_mp) != NULL) {
25455 		ASSERT(DB_TYPE(mp1) == M_DATA);
25456 		/* Initiate IPPF processing */
25457 		if ((proc != 0) && IPP_ENABLED(proc, ipst)) {
25458 			UNLOCK_IRE_FP_MP(ire);
25459 			ip_process(proc, &mp, ill_index);
25460 			if (mp == NULL)
25461 				return (NULL);
25462 
25463 			ipha = (ipha_t *)mp->b_rptr;
25464 			LOCK_IRE_FP_MP(ire);
25465 			if ((mp1 = ire->ire_nce->nce_fp_mp) == NULL) {
25466 				qos_done = B_TRUE;
25467 				goto no_fp_mp;
25468 			}
25469 			ASSERT(DB_TYPE(mp1) == M_DATA);
25470 		}
25471 		hlen = MBLKL(mp1);
25472 		/*
25473 		 * Check if we have enough room to prepend fastpath
25474 		 * header
25475 		 */
25476 		if (hlen != 0 && (rptr - mp->b_datap->db_base) >= hlen) {
25477 			ll_hdr = rptr - hlen;
25478 			bcopy(mp1->b_rptr, ll_hdr, hlen);
25479 			/*
25480 			 * Set the b_rptr to the start of the link layer
25481 			 * header
25482 			 */
25483 			mp->b_rptr = ll_hdr;
25484 			mp1 = mp;
25485 		} else {
25486 			mp1 = copyb(mp1);
25487 			if (mp1 == NULL)
25488 				goto unlock_err;
25489 			mp1->b_band = mp->b_band;
25490 			mp1->b_cont = mp;
25491 			/*
25492 			 * certain system generated traffic may not
25493 			 * have cred/label in ip header block. This
25494 			 * is true even for a labeled system. But for
25495 			 * labeled traffic, inherit the label in the
25496 			 * new header.
25497 			 */
25498 			if (DB_CRED(mp) != NULL)
25499 				mblk_setcred(mp1, DB_CRED(mp));
25500 			/*
25501 			 * XXX disable ICK_VALID and compute checksum
25502 			 * here; can happen if nce_fp_mp changes and
25503 			 * it can't be copied now due to insufficient
25504 			 * space. (unlikely, fp mp can change, but it
25505 			 * does not increase in length)
25506 			 */
25507 		}
25508 		UNLOCK_IRE_FP_MP(ire);
25509 	} else {
25510 no_fp_mp:
25511 		mp1 = copyb(ire->ire_nce->nce_res_mp);
25512 		if (mp1 == NULL) {
25513 unlock_err:
25514 			UNLOCK_IRE_FP_MP(ire);
25515 			freemsg(mp);
25516 			return (NULL);
25517 		}
25518 		UNLOCK_IRE_FP_MP(ire);
25519 		mp1->b_cont = mp;
25520 		/*
25521 		 * certain system generated traffic may not
25522 		 * have cred/label in ip header block. This
25523 		 * is true even for a labeled system. But for
25524 		 * labeled traffic, inherit the label in the
25525 		 * new header.
25526 		 */
25527 		if (DB_CRED(mp) != NULL)
25528 			mblk_setcred(mp1, DB_CRED(mp));
25529 		if (!qos_done && (proc != 0) && IPP_ENABLED(proc, ipst)) {
25530 			ip_process(proc, &mp1, ill_index);
25531 			if (mp1 == NULL)
25532 				return (NULL);
25533 		}
25534 	}
25535 	return (mp1);
25536 #undef rptr
25537 }
25538 
25539 /*
25540  * Finish the outbound IPsec processing for an IPv6 packet. This function
25541  * is called from ipsec_out_process() if the IPsec packet was processed
25542  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25543  * asynchronously.
25544  */
25545 void
25546 ip_wput_ipsec_out_v6(queue_t *q, mblk_t *ipsec_mp, ip6_t *ip6h, ill_t *ill,
25547     ire_t *ire_arg)
25548 {
25549 	in6_addr_t *v6dstp;
25550 	ire_t *ire;
25551 	mblk_t *mp;
25552 	ip6_t *ip6h1;
25553 	uint_t	ill_index;
25554 	ipsec_out_t *io;
25555 	boolean_t attach_if, hwaccel;
25556 	uint32_t flags = IP6_NO_IPPOLICY;
25557 	int match_flags;
25558 	zoneid_t zoneid;
25559 	boolean_t ill_need_rele = B_FALSE;
25560 	boolean_t ire_need_rele = B_FALSE;
25561 	ip_stack_t	*ipst;
25562 
25563 	mp = ipsec_mp->b_cont;
25564 	ip6h1 = (ip6_t *)mp->b_rptr;
25565 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25566 	ASSERT(io->ipsec_out_ns != NULL);
25567 	ipst = io->ipsec_out_ns->netstack_ip;
25568 	ill_index = io->ipsec_out_ill_index;
25569 	if (io->ipsec_out_reachable) {
25570 		flags |= IPV6_REACHABILITY_CONFIRMATION;
25571 	}
25572 	attach_if = io->ipsec_out_attach_if;
25573 	hwaccel = io->ipsec_out_accelerated;
25574 	zoneid = io->ipsec_out_zoneid;
25575 	ASSERT(zoneid != ALL_ZONES);
25576 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25577 	/* Multicast addresses should have non-zero ill_index. */
25578 	v6dstp = &ip6h->ip6_dst;
25579 	ASSERT(ip6h->ip6_nxt != IPPROTO_RAW);
25580 	ASSERT(!IN6_IS_ADDR_MULTICAST(v6dstp) || ill_index != 0);
25581 	ASSERT(!attach_if || ill_index != 0);
25582 	if (ill_index != 0) {
25583 		if (ill == NULL) {
25584 			ill = ip_grab_attach_ill(NULL, ipsec_mp, ill_index,
25585 			    B_TRUE, ipst);
25586 
25587 			/* Failure case frees things for us. */
25588 			if (ill == NULL)
25589 				return;
25590 
25591 			ill_need_rele = B_TRUE;
25592 		}
25593 		/*
25594 		 * If this packet needs to go out on a particular interface
25595 		 * honor it.
25596 		 */
25597 		if (attach_if) {
25598 			match_flags = MATCH_IRE_ILL;
25599 
25600 			/*
25601 			 * Check if we need an ire that will not be
25602 			 * looked up by anybody else i.e. HIDDEN.
25603 			 */
25604 			if (ill_is_probeonly(ill)) {
25605 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25606 			}
25607 		}
25608 	}
25609 	ASSERT(mp != NULL);
25610 
25611 	if (IN6_IS_ADDR_MULTICAST(v6dstp)) {
25612 		boolean_t unspec_src;
25613 		ipif_t	*ipif;
25614 
25615 		/*
25616 		 * Use the ill_index to get the right ill.
25617 		 */
25618 		unspec_src = io->ipsec_out_unspec_src;
25619 		(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25620 		if (ipif == NULL) {
25621 			if (ill_need_rele)
25622 				ill_refrele(ill);
25623 			freemsg(ipsec_mp);
25624 			return;
25625 		}
25626 
25627 		if (ire_arg != NULL) {
25628 			ire = ire_arg;
25629 		} else {
25630 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25631 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25632 			ire_need_rele = B_TRUE;
25633 		}
25634 		if (ire != NULL) {
25635 			ipif_refrele(ipif);
25636 			/*
25637 			 * XXX Do the multicast forwarding now, as the IPsec
25638 			 * processing has been done.
25639 			 */
25640 			goto send;
25641 		}
25642 
25643 		ip0dbg(("ip_wput_ipsec_out_v6: multicast: IRE disappeared\n"));
25644 		mp->b_prev = NULL;
25645 		mp->b_next = NULL;
25646 
25647 		/*
25648 		 * If the IPsec packet was processed asynchronously,
25649 		 * drop it now.
25650 		 */
25651 		if (q == NULL) {
25652 			if (ill_need_rele)
25653 				ill_refrele(ill);
25654 			freemsg(ipsec_mp);
25655 			return;
25656 		}
25657 
25658 		ip_newroute_ipif_v6(q, ipsec_mp, ipif, *v6dstp,
25659 		    unspec_src, zoneid);
25660 		ipif_refrele(ipif);
25661 	} else {
25662 		if (attach_if) {
25663 			ipif_t	*ipif;
25664 
25665 			ipif = ipif_get_next_ipif(NULL, ill);
25666 			if (ipif == NULL) {
25667 				if (ill_need_rele)
25668 					ill_refrele(ill);
25669 				freemsg(ipsec_mp);
25670 				return;
25671 			}
25672 			ire = ire_ctable_lookup_v6(v6dstp, 0, 0, ipif,
25673 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25674 			ire_need_rele = B_TRUE;
25675 			ipif_refrele(ipif);
25676 		} else {
25677 			if (ire_arg != NULL) {
25678 				ire = ire_arg;
25679 			} else {
25680 				ire = ire_cache_lookup_v6(v6dstp, zoneid, NULL,
25681 				    ipst);
25682 				ire_need_rele = B_TRUE;
25683 			}
25684 		}
25685 		if (ire != NULL)
25686 			goto send;
25687 		/*
25688 		 * ire disappeared underneath.
25689 		 *
25690 		 * What we need to do here is the ip_newroute
25691 		 * logic to get the ire without doing the IPsec
25692 		 * processing. Follow the same old path. But this
25693 		 * time, ip_wput or ire_add_then_send will call us
25694 		 * directly as all the IPsec operations are done.
25695 		 */
25696 		ip1dbg(("ip_wput_ipsec_out_v6: IRE disappeared\n"));
25697 		mp->b_prev = NULL;
25698 		mp->b_next = NULL;
25699 
25700 		/*
25701 		 * If the IPsec packet was processed asynchronously,
25702 		 * drop it now.
25703 		 */
25704 		if (q == NULL) {
25705 			if (ill_need_rele)
25706 				ill_refrele(ill);
25707 			freemsg(ipsec_mp);
25708 			return;
25709 		}
25710 
25711 		ip_newroute_v6(q, ipsec_mp, v6dstp, &ip6h->ip6_src, ill,
25712 		    zoneid, ipst);
25713 	}
25714 	if (ill != NULL && ill_need_rele)
25715 		ill_refrele(ill);
25716 	return;
25717 send:
25718 	if (ill != NULL && ill_need_rele)
25719 		ill_refrele(ill);
25720 
25721 	/* Local delivery */
25722 	if (ire->ire_stq == NULL) {
25723 		ill_t	*out_ill;
25724 		ASSERT(q != NULL);
25725 
25726 		/* PFHooks: LOOPBACK_OUT */
25727 		out_ill = ire_to_ill(ire);
25728 
25729 		DTRACE_PROBE4(ip6__loopback__out__start,
25730 		    ill_t *, NULL, ill_t *, out_ill,
25731 		    ip6_t *, ip6h1, mblk_t *, ipsec_mp);
25732 
25733 		FW_HOOKS6(ipst->ips_ip6_loopback_out_event,
25734 		    ipst->ips_ipv6firewall_loopback_out,
25735 		    NULL, out_ill, ip6h1, ipsec_mp, mp, 0, ipst);
25736 
25737 		DTRACE_PROBE1(ip6__loopback__out__end, mblk_t *, ipsec_mp);
25738 
25739 		if (ipsec_mp != NULL)
25740 			ip_wput_local_v6(RD(q), out_ill,
25741 			    ip6h, ipsec_mp, ire, 0);
25742 		if (ire_need_rele)
25743 			ire_refrele(ire);
25744 		return;
25745 	}
25746 	/*
25747 	 * Everything is done. Send it out on the wire.
25748 	 * We force the insertion of a fragment header using the
25749 	 * IPH_FRAG_HDR flag in two cases:
25750 	 * - after reception of an ICMPv6 "packet too big" message
25751 	 *   with a MTU < 1280 (cf. RFC 2460 section 5)
25752 	 * - for multirouted IPv6 packets, so that the receiver can
25753 	 *   discard duplicates according to their fragment identifier
25754 	 */
25755 	/* XXX fix flow control problems. */
25756 	if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN > ire->ire_max_frag ||
25757 	    (ire->ire_frag_flag & IPH_FRAG_HDR)) {
25758 		if (hwaccel) {
25759 			/*
25760 			 * hardware acceleration does not handle these
25761 			 * "slow path" cases.
25762 			 */
25763 			/* IPsec KSTATS: should bump bean counter here. */
25764 			if (ire_need_rele)
25765 				ire_refrele(ire);
25766 			freemsg(ipsec_mp);
25767 			return;
25768 		}
25769 		if (ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN !=
25770 		    (mp->b_cont ? msgdsize(mp) :
25771 		    mp->b_wptr - (uchar_t *)ip6h)) {
25772 			/* IPsec KSTATS: should bump bean counter here. */
25773 			ip0dbg(("Packet length mismatch: %d, %ld\n",
25774 			    ntohs(ip6h->ip6_plen) + IPV6_HDR_LEN,
25775 			    msgdsize(mp)));
25776 			if (ire_need_rele)
25777 				ire_refrele(ire);
25778 			freemsg(ipsec_mp);
25779 			return;
25780 		}
25781 		ASSERT(mp->b_prev == NULL);
25782 		ip2dbg(("Fragmenting Size = %d, mtu = %d\n",
25783 		    ntohs(ip6h->ip6_plen) +
25784 		    IPV6_HDR_LEN, ire->ire_max_frag));
25785 		ip_wput_frag_v6(mp, ire, flags, NULL, B_FALSE,
25786 		    ire->ire_max_frag);
25787 	} else {
25788 		UPDATE_OB_PKT_COUNT(ire);
25789 		ire->ire_last_used_time = lbolt;
25790 		ip_xmit_v6(mp, ire, flags, NULL, B_FALSE, hwaccel ? io : NULL);
25791 	}
25792 	if (ire_need_rele)
25793 		ire_refrele(ire);
25794 	freeb(ipsec_mp);
25795 }
25796 
25797 void
25798 ipsec_hw_putnext(queue_t *q, mblk_t *mp)
25799 {
25800 	mblk_t *hada_mp;	/* attributes M_CTL mblk */
25801 	da_ipsec_t *hada;	/* data attributes */
25802 	ill_t *ill = (ill_t *)q->q_ptr;
25803 
25804 	IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_hw_putnext: accelerated packet\n"));
25805 
25806 	if ((ill->ill_capabilities & (ILL_CAPAB_AH | ILL_CAPAB_ESP)) == 0) {
25807 		/* IPsec KSTATS: Bump lose counter here! */
25808 		freemsg(mp);
25809 		return;
25810 	}
25811 
25812 	/*
25813 	 * It's an IPsec packet that must be
25814 	 * accelerated by the Provider, and the
25815 	 * outbound ill is IPsec acceleration capable.
25816 	 * Prepends the mblk with an IPHADA_M_CTL, and ship it
25817 	 * to the ill.
25818 	 * IPsec KSTATS: should bump packet counter here.
25819 	 */
25820 
25821 	hada_mp = allocb(sizeof (da_ipsec_t), BPRI_HI);
25822 	if (hada_mp == NULL) {
25823 		/* IPsec KSTATS: should bump packet counter here. */
25824 		freemsg(mp);
25825 		return;
25826 	}
25827 
25828 	hada_mp->b_datap->db_type = M_CTL;
25829 	hada_mp->b_wptr = hada_mp->b_rptr + sizeof (*hada);
25830 	hada_mp->b_cont = mp;
25831 
25832 	hada = (da_ipsec_t *)hada_mp->b_rptr;
25833 	bzero(hada, sizeof (da_ipsec_t));
25834 	hada->da_type = IPHADA_M_CTL;
25835 
25836 	putnext(q, hada_mp);
25837 }
25838 
25839 /*
25840  * Finish the outbound IPsec processing. This function is called from
25841  * ipsec_out_process() if the IPsec packet was processed
25842  * synchronously, or from {ah,esp}_kcf_callback() if it was processed
25843  * asynchronously.
25844  */
25845 void
25846 ip_wput_ipsec_out(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha, ill_t *ill,
25847     ire_t *ire_arg)
25848 {
25849 	uint32_t v_hlen_tos_len;
25850 	ipaddr_t	dst;
25851 	ipif_t	*ipif = NULL;
25852 	ire_t *ire;
25853 	ire_t *ire1 = NULL;
25854 	mblk_t *next_mp = NULL;
25855 	uint32_t max_frag;
25856 	boolean_t multirt_send = B_FALSE;
25857 	mblk_t *mp;
25858 	ipha_t *ipha1;
25859 	uint_t	ill_index;
25860 	ipsec_out_t *io;
25861 	boolean_t attach_if;
25862 	int match_flags;
25863 	irb_t *irb = NULL;
25864 	boolean_t ill_need_rele = B_FALSE, ire_need_rele = B_TRUE;
25865 	zoneid_t zoneid;
25866 	ipxmit_state_t	pktxmit_state;
25867 	ip_stack_t	*ipst;
25868 
25869 #ifdef	_BIG_ENDIAN
25870 #define	LENGTH	(v_hlen_tos_len & 0xFFFF)
25871 #else
25872 #define	LENGTH	((v_hlen_tos_len >> 24) | ((v_hlen_tos_len >> 8) & 0xFF00))
25873 #endif
25874 
25875 	mp = ipsec_mp->b_cont;
25876 	ipha1 = (ipha_t *)mp->b_rptr;
25877 	ASSERT(mp != NULL);
25878 	v_hlen_tos_len = ((uint32_t *)ipha)[0];
25879 	dst = ipha->ipha_dst;
25880 
25881 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
25882 	ill_index = io->ipsec_out_ill_index;
25883 	attach_if = io->ipsec_out_attach_if;
25884 	zoneid = io->ipsec_out_zoneid;
25885 	ASSERT(zoneid != ALL_ZONES);
25886 	ipst = io->ipsec_out_ns->netstack_ip;
25887 	ASSERT(io->ipsec_out_ns != NULL);
25888 
25889 	match_flags = MATCH_IRE_ILL_GROUP | MATCH_IRE_SECATTR;
25890 	if (ill_index != 0) {
25891 		if (ill == NULL) {
25892 			ill = ip_grab_attach_ill(NULL, ipsec_mp,
25893 			    ill_index, B_FALSE, ipst);
25894 
25895 			/* Failure case frees things for us. */
25896 			if (ill == NULL)
25897 				return;
25898 
25899 			ill_need_rele = B_TRUE;
25900 		}
25901 		/*
25902 		 * If this packet needs to go out on a particular interface
25903 		 * honor it.
25904 		 */
25905 		if (attach_if) {
25906 			match_flags = MATCH_IRE_ILL | MATCH_IRE_SECATTR;
25907 
25908 			/*
25909 			 * Check if we need an ire that will not be
25910 			 * looked up by anybody else i.e. HIDDEN.
25911 			 */
25912 			if (ill_is_probeonly(ill)) {
25913 				match_flags |= MATCH_IRE_MARK_HIDDEN;
25914 			}
25915 		}
25916 	}
25917 
25918 	if (CLASSD(dst)) {
25919 		boolean_t conn_dontroute;
25920 		/*
25921 		 * Use the ill_index to get the right ipif.
25922 		 */
25923 		conn_dontroute = io->ipsec_out_dontroute;
25924 		if (ill_index == 0)
25925 			ipif = ipif_lookup_group(dst, zoneid, ipst);
25926 		else
25927 			(void) ipif_lookup_zoneid(ill, zoneid, 0, &ipif);
25928 		if (ipif == NULL) {
25929 			ip1dbg(("ip_wput_ipsec_out: No ipif for"
25930 			    " multicast\n"));
25931 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutNoRoutes);
25932 			freemsg(ipsec_mp);
25933 			goto done;
25934 		}
25935 		/*
25936 		 * ipha_src has already been intialized with the
25937 		 * value of the ipif in ip_wput. All we need now is
25938 		 * an ire to send this downstream.
25939 		 */
25940 		ire = ire_ctable_lookup(dst, 0, 0, ipif, zoneid,
25941 		    MBLK_GETLABEL(mp), match_flags, ipst);
25942 		if (ire != NULL) {
25943 			ill_t *ill1;
25944 			/*
25945 			 * Do the multicast forwarding now, as the IPsec
25946 			 * processing has been done.
25947 			 */
25948 			if (ipst->ips_ip_g_mrouter && !conn_dontroute &&
25949 			    (ill1 = ire_to_ill(ire))) {
25950 				if (ip_mforward(ill1, ipha, mp)) {
25951 					freemsg(ipsec_mp);
25952 					ip1dbg(("ip_wput_ipsec_out: mforward "
25953 					    "failed\n"));
25954 					ire_refrele(ire);
25955 					goto done;
25956 				}
25957 			}
25958 			goto send;
25959 		}
25960 
25961 		ip0dbg(("ip_wput_ipsec_out: multicast: IRE disappeared\n"));
25962 		mp->b_prev = NULL;
25963 		mp->b_next = NULL;
25964 
25965 		/*
25966 		 * If the IPsec packet was processed asynchronously,
25967 		 * drop it now.
25968 		 */
25969 		if (q == NULL) {
25970 			freemsg(ipsec_mp);
25971 			goto done;
25972 		}
25973 
25974 		/*
25975 		 * We may be using a wrong ipif to create the ire.
25976 		 * But it is okay as the source address is assigned
25977 		 * for the packet already. Next outbound packet would
25978 		 * create the IRE with the right IPIF in ip_wput.
25979 		 *
25980 		 * Also handle RTF_MULTIRT routes.
25981 		 */
25982 		ip_newroute_ipif(q, ipsec_mp, ipif, dst, NULL, RTF_MULTIRT,
25983 		    zoneid, &zero_info);
25984 	} else {
25985 		if (attach_if) {
25986 			ire = ire_ctable_lookup(dst, 0, 0, ill->ill_ipif,
25987 			    zoneid, MBLK_GETLABEL(mp), match_flags, ipst);
25988 		} else {
25989 			if (ire_arg != NULL) {
25990 				ire = ire_arg;
25991 				ire_need_rele = B_FALSE;
25992 			} else {
25993 				ire = ire_cache_lookup(dst, zoneid,
25994 				    MBLK_GETLABEL(mp), ipst);
25995 			}
25996 		}
25997 		if (ire != NULL) {
25998 			goto send;
25999 		}
26000 
26001 		/*
26002 		 * ire disappeared underneath.
26003 		 *
26004 		 * What we need to do here is the ip_newroute
26005 		 * logic to get the ire without doing the IPsec
26006 		 * processing. Follow the same old path. But this
26007 		 * time, ip_wput or ire_add_then_put will call us
26008 		 * directly as all the IPsec operations are done.
26009 		 */
26010 		ip1dbg(("ip_wput_ipsec_out: IRE disappeared\n"));
26011 		mp->b_prev = NULL;
26012 		mp->b_next = NULL;
26013 
26014 		/*
26015 		 * If the IPsec packet was processed asynchronously,
26016 		 * drop it now.
26017 		 */
26018 		if (q == NULL) {
26019 			freemsg(ipsec_mp);
26020 			goto done;
26021 		}
26022 
26023 		/*
26024 		 * Since we're going through ip_newroute() again, we
26025 		 * need to make sure we don't:
26026 		 *
26027 		 *	1.) Trigger the ASSERT() with the ipha_ident
26028 		 *	    overloading.
26029 		 *	2.) Redo transport-layer checksumming, since we've
26030 		 *	    already done all that to get this far.
26031 		 *
26032 		 * The easiest way not do either of the above is to set
26033 		 * the ipha_ident field to IP_HDR_INCLUDED.
26034 		 */
26035 		ipha->ipha_ident = IP_HDR_INCLUDED;
26036 		ip_newroute(q, ipsec_mp, dst, (CONN_Q(q) ? Q_TO_CONN(q) : NULL),
26037 		    zoneid, ipst);
26038 	}
26039 	goto done;
26040 send:
26041 	if (ire->ire_stq == NULL) {
26042 		ill_t	*out_ill;
26043 		/*
26044 		 * Loopbacks go through ip_wput_local except for one case.
26045 		 * We come here if we generate a icmp_frag_needed message
26046 		 * after IPsec processing is over. When this function calls
26047 		 * ip_wput_ire_fragmentit, ip_wput_frag might end up calling
26048 		 * icmp_frag_needed. The message generated comes back here
26049 		 * through icmp_frag_needed -> icmp_pkt -> ip_wput ->
26050 		 * ipsec_out_process -> ip_wput_ipsec_out. We need to set the
26051 		 * source address as it is usually set in ip_wput_ire. As
26052 		 * ipsec_out_proc_begin is set, ip_wput calls ipsec_out_process
26053 		 * and we end up here. We can't enter ip_wput_ire once the
26054 		 * IPsec processing is over and hence we need to do it here.
26055 		 */
26056 		ASSERT(q != NULL);
26057 		UPDATE_OB_PKT_COUNT(ire);
26058 		ire->ire_last_used_time = lbolt;
26059 		if (ipha->ipha_src == 0)
26060 			ipha->ipha_src = ire->ire_src_addr;
26061 
26062 		/* PFHooks: LOOPBACK_OUT */
26063 		out_ill = ire_to_ill(ire);
26064 
26065 		DTRACE_PROBE4(ip4__loopback__out__start,
26066 		    ill_t *, NULL, ill_t *, out_ill,
26067 		    ipha_t *, ipha1, mblk_t *, ipsec_mp);
26068 
26069 		FW_HOOKS(ipst->ips_ip4_loopback_out_event,
26070 		    ipst->ips_ipv4firewall_loopback_out,
26071 		    NULL, out_ill, ipha1, ipsec_mp, mp, 0, ipst);
26072 
26073 		DTRACE_PROBE1(ip4__loopback__out__end, mblk_t *, ipsec_mp);
26074 
26075 		if (ipsec_mp != NULL)
26076 			ip_wput_local(RD(q), out_ill,
26077 			    ipha, ipsec_mp, ire, 0, zoneid);
26078 		if (ire_need_rele)
26079 			ire_refrele(ire);
26080 		goto done;
26081 	}
26082 
26083 	if (ire->ire_max_frag < (unsigned int)LENGTH) {
26084 		/*
26085 		 * We are through with IPsec processing.
26086 		 * Fragment this and send it on the wire.
26087 		 */
26088 		if (io->ipsec_out_accelerated) {
26089 			/*
26090 			 * The packet has been accelerated but must
26091 			 * be fragmented. This should not happen
26092 			 * since AH and ESP must not accelerate
26093 			 * packets that need fragmentation, however
26094 			 * the configuration could have changed
26095 			 * since the AH or ESP processing.
26096 			 * Drop packet.
26097 			 * IPsec KSTATS: bump bean counter here.
26098 			 */
26099 			IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_wput_ipsec_out: "
26100 			    "fragmented accelerated packet!\n"));
26101 			freemsg(ipsec_mp);
26102 		} else {
26103 			ip_wput_ire_fragmentit(ipsec_mp, ire, zoneid, ipst);
26104 		}
26105 		if (ire_need_rele)
26106 			ire_refrele(ire);
26107 		goto done;
26108 	}
26109 
26110 	ip2dbg(("ip_wput_ipsec_out: ipsec_mp %p, ire %p, ire_ipif %p, "
26111 	    "ipif %p\n", (void *)ipsec_mp, (void *)ire,
26112 	    (void *)ire->ire_ipif, (void *)ipif));
26113 
26114 	/*
26115 	 * Multiroute the secured packet, unless IPsec really
26116 	 * requires the packet to go out only through a particular
26117 	 * interface.
26118 	 */
26119 	if ((ire->ire_flags & RTF_MULTIRT) && !attach_if) {
26120 		ire_t *first_ire;
26121 		irb = ire->ire_bucket;
26122 		ASSERT(irb != NULL);
26123 		/*
26124 		 * This ire has been looked up as the one that
26125 		 * goes through the given ipif;
26126 		 * make sure we do not omit any other multiroute ire
26127 		 * that may be present in the bucket before this one.
26128 		 */
26129 		IRB_REFHOLD(irb);
26130 		for (first_ire = irb->irb_ire;
26131 		    first_ire != NULL;
26132 		    first_ire = first_ire->ire_next) {
26133 			if ((first_ire->ire_flags & RTF_MULTIRT) &&
26134 			    (first_ire->ire_addr == ire->ire_addr) &&
26135 			    !(first_ire->ire_marks &
26136 			    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))) {
26137 				break;
26138 			}
26139 		}
26140 
26141 		if ((first_ire != NULL) && (first_ire != ire)) {
26142 			/*
26143 			 * Don't change the ire if the packet must
26144 			 * be fragmented if sent via this new one.
26145 			 */
26146 			if (first_ire->ire_max_frag >= (unsigned int)LENGTH) {
26147 				IRE_REFHOLD(first_ire);
26148 				if (ire_need_rele)
26149 					ire_refrele(ire);
26150 				else
26151 					ire_need_rele = B_TRUE;
26152 				ire = first_ire;
26153 			}
26154 		}
26155 		IRB_REFRELE(irb);
26156 
26157 		multirt_send = B_TRUE;
26158 		max_frag = ire->ire_max_frag;
26159 	} else {
26160 		if ((ire->ire_flags & RTF_MULTIRT) && attach_if) {
26161 			ip1dbg(("ip_wput_ipsec_out: ignoring multirouting "
26162 			    "flag, attach_if %d\n", attach_if));
26163 		}
26164 	}
26165 
26166 	/*
26167 	 * In most cases, the emission loop below is entered only once.
26168 	 * Only in the case where the ire holds the RTF_MULTIRT
26169 	 * flag, we loop to process all RTF_MULTIRT ires in the
26170 	 * bucket, and send the packet through all crossed
26171 	 * RTF_MULTIRT routes.
26172 	 */
26173 	do {
26174 		if (multirt_send) {
26175 			/*
26176 			 * ire1 holds here the next ire to process in the
26177 			 * bucket. If multirouting is expected,
26178 			 * any non-RTF_MULTIRT ire that has the
26179 			 * right destination address is ignored.
26180 			 */
26181 			ASSERT(irb != NULL);
26182 			IRB_REFHOLD(irb);
26183 			for (ire1 = ire->ire_next;
26184 			    ire1 != NULL;
26185 			    ire1 = ire1->ire_next) {
26186 				if ((ire1->ire_flags & RTF_MULTIRT) == 0)
26187 					continue;
26188 				if (ire1->ire_addr != ire->ire_addr)
26189 					continue;
26190 				if (ire1->ire_marks &
26191 				    (IRE_MARK_CONDEMNED | IRE_MARK_HIDDEN))
26192 					continue;
26193 				/* No loopback here */
26194 				if (ire1->ire_stq == NULL)
26195 					continue;
26196 				/*
26197 				 * Ensure we do not exceed the MTU
26198 				 * of the next route.
26199 				 */
26200 				if (ire1->ire_max_frag < (unsigned int)LENGTH) {
26201 					ip_multirt_bad_mtu(ire1, max_frag);
26202 					continue;
26203 				}
26204 
26205 				IRE_REFHOLD(ire1);
26206 				break;
26207 			}
26208 			IRB_REFRELE(irb);
26209 			if (ire1 != NULL) {
26210 				/*
26211 				 * We are in a multiple send case, need to
26212 				 * make a copy of the packet.
26213 				 */
26214 				next_mp = copymsg(ipsec_mp);
26215 				if (next_mp == NULL) {
26216 					ire_refrele(ire1);
26217 					ire1 = NULL;
26218 				}
26219 			}
26220 		}
26221 		/*
26222 		 * Everything is done. Send it out on the wire
26223 		 *
26224 		 * ip_xmit_v4 will call ip_wput_attach_llhdr and then
26225 		 * either send it on the wire or, in the case of
26226 		 * HW acceleration, call ipsec_hw_putnext.
26227 		 */
26228 		if (ire->ire_nce &&
26229 		    ire->ire_nce->nce_state != ND_REACHABLE) {
26230 			DTRACE_PROBE2(ip__wput__ipsec__bail,
26231 			    (ire_t *), ire,  (mblk_t *), ipsec_mp);
26232 			/*
26233 			 * If ire's link-layer is unresolved (this
26234 			 * would only happen if the incomplete ire
26235 			 * was added to cachetable via forwarding path)
26236 			 * don't bother going to ip_xmit_v4. Just drop the
26237 			 * packet.
26238 			 * There is a slight risk here, in that, if we
26239 			 * have the forwarding path create an incomplete
26240 			 * IRE, then until the IRE is completed, any
26241 			 * transmitted IPsec packets will be dropped
26242 			 * instead of being queued waiting for resolution.
26243 			 *
26244 			 * But the likelihood of a forwarding packet and a wput
26245 			 * packet sending to the same dst at the same time
26246 			 * and there not yet be an ARP entry for it is small.
26247 			 * Furthermore, if this actually happens, it might
26248 			 * be likely that wput would generate multiple
26249 			 * packets (and forwarding would also have a train
26250 			 * of packets) for that destination. If this is
26251 			 * the case, some of them would have been dropped
26252 			 * anyway, since ARP only queues a few packets while
26253 			 * waiting for resolution
26254 			 *
26255 			 * NOTE: We should really call ip_xmit_v4,
26256 			 * and let it queue the packet and send the
26257 			 * ARP query and have ARP come back thus:
26258 			 * <ARP> ip_wput->ip_output->ip-wput_nondata->
26259 			 * ip_xmit_v4->ip_wput_attach_llhdr + ipsec
26260 			 * hw accel work. But it's too complex to get
26261 			 * the IPsec hw  acceleration approach to fit
26262 			 * well with ip_xmit_v4 doing ARP without
26263 			 * doing IPsec simplification. For now, we just
26264 			 * poke ip_xmit_v4 to trigger the arp resolve, so
26265 			 * that we can continue with the send on the next
26266 			 * attempt.
26267 			 *
26268 			 * XXX THis should be revisited, when
26269 			 * the IPsec/IP interaction is cleaned up
26270 			 */
26271 			ip1dbg(("ip_wput_ipsec_out: ire is incomplete"
26272 			    " - dropping packet\n"));
26273 			freemsg(ipsec_mp);
26274 			/*
26275 			 * Call ip_xmit_v4() to trigger ARP query
26276 			 * in case the nce_state is ND_INITIAL
26277 			 */
26278 			(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
26279 			goto drop_pkt;
26280 		}
26281 
26282 		DTRACE_PROBE4(ip4__physical__out__start, ill_t *, NULL,
26283 		    ill_t *, ire->ire_ipif->ipif_ill, ipha_t *, ipha1,
26284 		    mblk_t *, ipsec_mp);
26285 		FW_HOOKS(ipst->ips_ip4_physical_out_event,
26286 		    ipst->ips_ipv4firewall_physical_out, NULL,
26287 		    ire->ire_ipif->ipif_ill, ipha1, ipsec_mp, mp, 0, ipst);
26288 		DTRACE_PROBE1(ip4__physical__out__end, mblk_t *, ipsec_mp);
26289 		if (ipsec_mp == NULL)
26290 			goto drop_pkt;
26291 
26292 		ip1dbg(("ip_wput_ipsec_out: calling ip_xmit_v4\n"));
26293 		pktxmit_state = ip_xmit_v4(mp, ire,
26294 		    (io->ipsec_out_accelerated ? io : NULL), B_FALSE);
26295 
26296 		if ((pktxmit_state ==  SEND_FAILED) ||
26297 		    (pktxmit_state == LLHDR_RESLV_FAILED)) {
26298 
26299 			freeb(ipsec_mp); /* ip_xmit_v4 frees the mp */
26300 drop_pkt:
26301 			BUMP_MIB(((ill_t *)ire->ire_stq->q_ptr)->ill_ip_mib,
26302 			    ipIfStatsOutDiscards);
26303 			if (ire_need_rele)
26304 				ire_refrele(ire);
26305 			if (ire1 != NULL) {
26306 				ire_refrele(ire1);
26307 				freemsg(next_mp);
26308 			}
26309 			goto done;
26310 		}
26311 
26312 		freeb(ipsec_mp);
26313 		if (ire_need_rele)
26314 			ire_refrele(ire);
26315 
26316 		if (ire1 != NULL) {
26317 			ire = ire1;
26318 			ire_need_rele = B_TRUE;
26319 			ASSERT(next_mp);
26320 			ipsec_mp = next_mp;
26321 			mp = ipsec_mp->b_cont;
26322 			ire1 = NULL;
26323 			next_mp = NULL;
26324 			io = (ipsec_out_t *)ipsec_mp->b_rptr;
26325 		} else {
26326 			multirt_send = B_FALSE;
26327 		}
26328 	} while (multirt_send);
26329 done:
26330 	if (ill != NULL && ill_need_rele)
26331 		ill_refrele(ill);
26332 	if (ipif != NULL)
26333 		ipif_refrele(ipif);
26334 }
26335 
26336 /*
26337  * Get the ill corresponding to the specified ire, and compare its
26338  * capabilities with the protocol and algorithms specified by the
26339  * the SA obtained from ipsec_out. If they match, annotate the
26340  * ipsec_out structure to indicate that the packet needs acceleration.
26341  *
26342  *
26343  * A packet is eligible for outbound hardware acceleration if the
26344  * following conditions are satisfied:
26345  *
26346  * 1. the packet will not be fragmented
26347  * 2. the provider supports the algorithm
26348  * 3. there is no pending control message being exchanged
26349  * 4. snoop is not attached
26350  * 5. the destination address is not a broadcast or multicast address.
26351  *
26352  * Rationale:
26353  *	- Hardware drivers do not support fragmentation with
26354  *	  the current interface.
26355  *	- snoop, multicast, and broadcast may result in exposure of
26356  *	  a cleartext datagram.
26357  * We check all five of these conditions here.
26358  *
26359  * XXX would like to nuke "ire_t *" parameter here; problem is that
26360  * IRE is only way to figure out if a v4 address is a broadcast and
26361  * thus ineligible for acceleration...
26362  */
26363 static void
26364 ipsec_out_is_accelerated(mblk_t *ipsec_mp, ipsa_t *sa, ill_t *ill, ire_t *ire)
26365 {
26366 	ipsec_out_t *io;
26367 	mblk_t *data_mp;
26368 	uint_t plen, overhead;
26369 	ip_stack_t	*ipst;
26370 
26371 	if ((sa->ipsa_flags & IPSA_F_HW) == 0)
26372 		return;
26373 
26374 	if (ill == NULL)
26375 		return;
26376 	ipst = ill->ill_ipst;
26377 	/*
26378 	 * Destination address is a broadcast or multicast.  Punt.
26379 	 */
26380 	if ((ire != NULL) && (ire->ire_type & (IRE_BROADCAST|IRE_LOOPBACK|
26381 	    IRE_LOCAL)))
26382 		return;
26383 
26384 	data_mp = ipsec_mp->b_cont;
26385 
26386 	if (ill->ill_isv6) {
26387 		ip6_t *ip6h = (ip6_t *)data_mp->b_rptr;
26388 
26389 		if (IN6_IS_ADDR_MULTICAST(&ip6h->ip6_dst))
26390 			return;
26391 
26392 		plen = ip6h->ip6_plen;
26393 	} else {
26394 		ipha_t *ipha = (ipha_t *)data_mp->b_rptr;
26395 
26396 		if (CLASSD(ipha->ipha_dst))
26397 			return;
26398 
26399 		plen = ipha->ipha_length;
26400 	}
26401 	/*
26402 	 * Is there a pending DLPI control message being exchanged
26403 	 * between IP/IPsec and the DLS Provider? If there is, it
26404 	 * could be a SADB update, and the state of the DLS Provider
26405 	 * SADB might not be in sync with the SADB maintained by
26406 	 * IPsec. To avoid dropping packets or using the wrong keying
26407 	 * material, we do not accelerate this packet.
26408 	 */
26409 	if (ill->ill_dlpi_pending != DL_PRIM_INVAL) {
26410 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26411 		    "ill_dlpi_pending! don't accelerate packet\n"));
26412 		return;
26413 	}
26414 
26415 	/*
26416 	 * Is the Provider in promiscous mode? If it does, we don't
26417 	 * accelerate the packet since it will bounce back up to the
26418 	 * listeners in the clear.
26419 	 */
26420 	if (ill->ill_promisc_on_phys) {
26421 		IPSECHW_DEBUG(IPSECHW_PKT, ("ipsec_out_check_is_accelerated: "
26422 		    "ill in promiscous mode, don't accelerate packet\n"));
26423 		return;
26424 	}
26425 
26426 	/*
26427 	 * Will the packet require fragmentation?
26428 	 */
26429 
26430 	/*
26431 	 * IPsec ESP note: this is a pessimistic estimate, but the same
26432 	 * as is used elsewhere.
26433 	 * SPI + sequence + MAC + IV(blocksize) + padding(blocksize-1)
26434 	 *	+ 2-byte trailer
26435 	 */
26436 	overhead = (sa->ipsa_type == SADB_SATYPE_AH) ? IPSEC_MAX_AH_HDR_SIZE :
26437 	    IPSEC_BASE_ESP_HDR_SIZE(sa);
26438 
26439 	if ((plen + overhead) > ill->ill_max_mtu)
26440 		return;
26441 
26442 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26443 
26444 	/*
26445 	 * Can the ill accelerate this IPsec protocol and algorithm
26446 	 * specified by the SA?
26447 	 */
26448 	if (!ipsec_capab_match(ill, io->ipsec_out_capab_ill_index,
26449 	    ill->ill_isv6, sa, ipst->ips_netstack)) {
26450 		return;
26451 	}
26452 
26453 	/*
26454 	 * Tell AH or ESP that the outbound ill is capable of
26455 	 * accelerating this packet.
26456 	 */
26457 	io->ipsec_out_is_capab_ill = B_TRUE;
26458 }
26459 
26460 /*
26461  * Select which AH & ESP SA's to use (if any) for the outbound packet.
26462  *
26463  * If this function returns B_TRUE, the requested SA's have been filled
26464  * into the ipsec_out_*_sa pointers.
26465  *
26466  * If the function returns B_FALSE, the packet has been "consumed", most
26467  * likely by an ACQUIRE sent up via PF_KEY to a key management daemon.
26468  *
26469  * The SA references created by the protocol-specific "select"
26470  * function will be released when the ipsec_mp is freed, thanks to the
26471  * ipsec_out_free destructor -- see spd.c.
26472  */
26473 static boolean_t
26474 ipsec_out_select_sa(mblk_t *ipsec_mp)
26475 {
26476 	boolean_t need_ah_acquire = B_FALSE, need_esp_acquire = B_FALSE;
26477 	ipsec_out_t *io;
26478 	ipsec_policy_t *pp;
26479 	ipsec_action_t *ap;
26480 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26481 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26482 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26483 
26484 	if (!io->ipsec_out_secure) {
26485 		/*
26486 		 * We came here by mistake.
26487 		 * Don't bother with ipsec processing
26488 		 * We should "discourage" this path in the future.
26489 		 */
26490 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26491 		return (B_FALSE);
26492 	}
26493 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26494 	ASSERT((io->ipsec_out_policy != NULL) ||
26495 	    (io->ipsec_out_act != NULL));
26496 
26497 	ASSERT(io->ipsec_out_failed == B_FALSE);
26498 
26499 	/*
26500 	 * IPsec processing has started.
26501 	 */
26502 	io->ipsec_out_proc_begin = B_TRUE;
26503 	ap = io->ipsec_out_act;
26504 	if (ap == NULL) {
26505 		pp = io->ipsec_out_policy;
26506 		ASSERT(pp != NULL);
26507 		ap = pp->ipsp_act;
26508 		ASSERT(ap != NULL);
26509 	}
26510 
26511 	/*
26512 	 * We have an action.  now, let's select SA's.
26513 	 * (In the future, we can cache this in the conn_t..)
26514 	 */
26515 	if (ap->ipa_want_esp) {
26516 		if (io->ipsec_out_esp_sa == NULL) {
26517 			need_esp_acquire = !ipsec_outbound_sa(ipsec_mp,
26518 			    IPPROTO_ESP);
26519 		}
26520 		ASSERT(need_esp_acquire || io->ipsec_out_esp_sa != NULL);
26521 	}
26522 
26523 	if (ap->ipa_want_ah) {
26524 		if (io->ipsec_out_ah_sa == NULL) {
26525 			need_ah_acquire = !ipsec_outbound_sa(ipsec_mp,
26526 			    IPPROTO_AH);
26527 		}
26528 		ASSERT(need_ah_acquire || io->ipsec_out_ah_sa != NULL);
26529 		/*
26530 		 * The ESP and AH processing order needs to be preserved
26531 		 * when both protocols are required (ESP should be applied
26532 		 * before AH for an outbound packet). Force an ESP ACQUIRE
26533 		 * when both ESP and AH are required, and an AH ACQUIRE
26534 		 * is needed.
26535 		 */
26536 		if (ap->ipa_want_esp && need_ah_acquire)
26537 			need_esp_acquire = B_TRUE;
26538 	}
26539 
26540 	/*
26541 	 * Send an ACQUIRE (extended, regular, or both) if we need one.
26542 	 * Release SAs that got referenced, but will not be used until we
26543 	 * acquire _all_ of the SAs we need.
26544 	 */
26545 	if (need_ah_acquire || need_esp_acquire) {
26546 		if (io->ipsec_out_ah_sa != NULL) {
26547 			IPSA_REFRELE(io->ipsec_out_ah_sa);
26548 			io->ipsec_out_ah_sa = NULL;
26549 		}
26550 		if (io->ipsec_out_esp_sa != NULL) {
26551 			IPSA_REFRELE(io->ipsec_out_esp_sa);
26552 			io->ipsec_out_esp_sa = NULL;
26553 		}
26554 
26555 		sadb_acquire(ipsec_mp, io, need_ah_acquire, need_esp_acquire);
26556 		return (B_FALSE);
26557 	}
26558 
26559 	return (B_TRUE);
26560 }
26561 
26562 /*
26563  * Process an IPSEC_OUT message and see what you can
26564  * do with it.
26565  * IPQoS Notes:
26566  * We do IPPF processing if IPP_LOCAL_OUT is enabled before processing for
26567  * IPsec.
26568  * XXX would like to nuke ire_t.
26569  * XXX ill_index better be "real"
26570  */
26571 void
26572 ipsec_out_process(queue_t *q, mblk_t *ipsec_mp, ire_t *ire, uint_t ill_index)
26573 {
26574 	ipsec_out_t *io;
26575 	ipsec_policy_t *pp;
26576 	ipsec_action_t *ap;
26577 	ipha_t *ipha;
26578 	ip6_t *ip6h;
26579 	mblk_t *mp;
26580 	ill_t *ill;
26581 	zoneid_t zoneid;
26582 	ipsec_status_t ipsec_rc;
26583 	boolean_t ill_need_rele = B_FALSE;
26584 	ip_stack_t	*ipst;
26585 	ipsec_stack_t	*ipss;
26586 
26587 	io = (ipsec_out_t *)ipsec_mp->b_rptr;
26588 	ASSERT(io->ipsec_out_type == IPSEC_OUT);
26589 	ASSERT(io->ipsec_out_len == sizeof (ipsec_out_t));
26590 	ipst = io->ipsec_out_ns->netstack_ip;
26591 	mp = ipsec_mp->b_cont;
26592 
26593 	/*
26594 	 * Initiate IPPF processing. We do it here to account for packets
26595 	 * coming here that don't have any policy (i.e. !io->ipsec_out_secure).
26596 	 * We can check for ipsec_out_proc_begin even for such packets, as
26597 	 * they will always be false (asserted below).
26598 	 */
26599 	if (IPP_ENABLED(IPP_LOCAL_OUT, ipst) && !io->ipsec_out_proc_begin) {
26600 		ip_process(IPP_LOCAL_OUT, &mp, io->ipsec_out_ill_index != 0 ?
26601 		    io->ipsec_out_ill_index : ill_index);
26602 		if (mp == NULL) {
26603 			ip2dbg(("ipsec_out_process: packet dropped "\
26604 			    "during IPPF processing\n"));
26605 			freeb(ipsec_mp);
26606 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26607 			return;
26608 		}
26609 	}
26610 
26611 	if (!io->ipsec_out_secure) {
26612 		/*
26613 		 * We came here by mistake.
26614 		 * Don't bother with ipsec processing
26615 		 * Should "discourage" this path in the future.
26616 		 */
26617 		ASSERT(io->ipsec_out_proc_begin == B_FALSE);
26618 		goto done;
26619 	}
26620 	ASSERT(io->ipsec_out_need_policy == B_FALSE);
26621 	ASSERT((io->ipsec_out_policy != NULL) ||
26622 	    (io->ipsec_out_act != NULL));
26623 	ASSERT(io->ipsec_out_failed == B_FALSE);
26624 
26625 	ipss = ipst->ips_netstack->netstack_ipsec;
26626 	if (!ipsec_loaded(ipss)) {
26627 		ipha = (ipha_t *)ipsec_mp->b_cont->b_rptr;
26628 		if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26629 			BUMP_MIB(&ipst->ips_ip_mib, ipIfStatsOutDiscards);
26630 		} else {
26631 			BUMP_MIB(&ipst->ips_ip6_mib, ipIfStatsOutDiscards);
26632 		}
26633 		ip_drop_packet(ipsec_mp, B_FALSE, NULL, ire,
26634 		    DROPPER(ipss, ipds_ip_ipsec_not_loaded),
26635 		    &ipss->ipsec_dropper);
26636 		return;
26637 	}
26638 
26639 	/*
26640 	 * IPsec processing has started.
26641 	 */
26642 	io->ipsec_out_proc_begin = B_TRUE;
26643 	ap = io->ipsec_out_act;
26644 	if (ap == NULL) {
26645 		pp = io->ipsec_out_policy;
26646 		ASSERT(pp != NULL);
26647 		ap = pp->ipsp_act;
26648 		ASSERT(ap != NULL);
26649 	}
26650 
26651 	/*
26652 	 * Save the outbound ill index. When the packet comes back
26653 	 * from IPsec, we make sure the ill hasn't changed or disappeared
26654 	 * before sending it the accelerated packet.
26655 	 */
26656 	if ((ire != NULL) && (io->ipsec_out_capab_ill_index == 0)) {
26657 		int ifindex;
26658 		ill = ire_to_ill(ire);
26659 		ifindex = ill->ill_phyint->phyint_ifindex;
26660 		io->ipsec_out_capab_ill_index = ifindex;
26661 	}
26662 
26663 	/*
26664 	 * The order of processing is first insert a IP header if needed.
26665 	 * Then insert the ESP header and then the AH header.
26666 	 */
26667 	if ((io->ipsec_out_se_done == B_FALSE) &&
26668 	    (ap->ipa_want_se)) {
26669 		/*
26670 		 * First get the outer IP header before sending
26671 		 * it to ESP.
26672 		 */
26673 		ipha_t *oipha, *iipha;
26674 		mblk_t *outer_mp, *inner_mp;
26675 
26676 		if ((outer_mp = allocb(sizeof (ipha_t), BPRI_HI)) == NULL) {
26677 			(void) mi_strlog(q, 0, SL_ERROR|SL_TRACE|SL_CONSOLE,
26678 			    "ipsec_out_process: "
26679 			    "Self-Encapsulation failed: Out of memory\n");
26680 			freemsg(ipsec_mp);
26681 			if (ill != NULL) {
26682 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26683 			} else {
26684 				BUMP_MIB(&ipst->ips_ip_mib,
26685 				    ipIfStatsOutDiscards);
26686 			}
26687 			return;
26688 		}
26689 		inner_mp = ipsec_mp->b_cont;
26690 		ASSERT(inner_mp->b_datap->db_type == M_DATA);
26691 		oipha = (ipha_t *)outer_mp->b_rptr;
26692 		iipha = (ipha_t *)inner_mp->b_rptr;
26693 		*oipha = *iipha;
26694 		outer_mp->b_wptr += sizeof (ipha_t);
26695 		oipha->ipha_length = htons(ntohs(iipha->ipha_length) +
26696 		    sizeof (ipha_t));
26697 		oipha->ipha_protocol = IPPROTO_ENCAP;
26698 		oipha->ipha_version_and_hdr_length =
26699 		    IP_SIMPLE_HDR_VERSION;
26700 		oipha->ipha_hdr_checksum = 0;
26701 		oipha->ipha_hdr_checksum = ip_csum_hdr(oipha);
26702 		outer_mp->b_cont = inner_mp;
26703 		ipsec_mp->b_cont = outer_mp;
26704 
26705 		io->ipsec_out_se_done = B_TRUE;
26706 		io->ipsec_out_tunnel = B_TRUE;
26707 	}
26708 
26709 	if (((ap->ipa_want_ah && (io->ipsec_out_ah_sa == NULL)) ||
26710 	    (ap->ipa_want_esp && (io->ipsec_out_esp_sa == NULL))) &&
26711 	    !ipsec_out_select_sa(ipsec_mp))
26712 		return;
26713 
26714 	/*
26715 	 * By now, we know what SA's to use.  Toss over to ESP & AH
26716 	 * to do the heavy lifting.
26717 	 */
26718 	zoneid = io->ipsec_out_zoneid;
26719 	ASSERT(zoneid != ALL_ZONES);
26720 	if ((io->ipsec_out_esp_done == B_FALSE) && (ap->ipa_want_esp)) {
26721 		ASSERT(io->ipsec_out_esp_sa != NULL);
26722 		io->ipsec_out_esp_done = B_TRUE;
26723 		/*
26724 		 * Note that since hw accel can only apply one transform,
26725 		 * not two, we skip hw accel for ESP if we also have AH
26726 		 * This is an design limitation of the interface
26727 		 * which should be revisited.
26728 		 */
26729 		ASSERT(ire != NULL);
26730 		if (io->ipsec_out_ah_sa == NULL) {
26731 			ill = (ill_t *)ire->ire_stq->q_ptr;
26732 			ipsec_out_is_accelerated(ipsec_mp,
26733 			    io->ipsec_out_esp_sa, ill, ire);
26734 		}
26735 
26736 		ipsec_rc = io->ipsec_out_esp_sa->ipsa_output_func(ipsec_mp);
26737 		switch (ipsec_rc) {
26738 		case IPSEC_STATUS_SUCCESS:
26739 			break;
26740 		case IPSEC_STATUS_FAILED:
26741 			if (ill != NULL) {
26742 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26743 			} else {
26744 				BUMP_MIB(&ipst->ips_ip_mib,
26745 				    ipIfStatsOutDiscards);
26746 			}
26747 			/* FALLTHRU */
26748 		case IPSEC_STATUS_PENDING:
26749 			return;
26750 		}
26751 	}
26752 
26753 	if ((io->ipsec_out_ah_done == B_FALSE) && (ap->ipa_want_ah)) {
26754 		ASSERT(io->ipsec_out_ah_sa != NULL);
26755 		io->ipsec_out_ah_done = B_TRUE;
26756 		if (ire == NULL) {
26757 			int idx = io->ipsec_out_capab_ill_index;
26758 			ill = ill_lookup_on_ifindex(idx, B_FALSE,
26759 			    NULL, NULL, NULL, NULL, ipst);
26760 			ill_need_rele = B_TRUE;
26761 		} else {
26762 			ill = (ill_t *)ire->ire_stq->q_ptr;
26763 		}
26764 		ipsec_out_is_accelerated(ipsec_mp, io->ipsec_out_ah_sa, ill,
26765 		    ire);
26766 
26767 		ipsec_rc = io->ipsec_out_ah_sa->ipsa_output_func(ipsec_mp);
26768 		switch (ipsec_rc) {
26769 		case IPSEC_STATUS_SUCCESS:
26770 			break;
26771 		case IPSEC_STATUS_FAILED:
26772 			if (ill != NULL) {
26773 				BUMP_MIB(ill->ill_ip_mib, ipIfStatsOutDiscards);
26774 			} else {
26775 				BUMP_MIB(&ipst->ips_ip_mib,
26776 				    ipIfStatsOutDiscards);
26777 			}
26778 			/* FALLTHRU */
26779 		case IPSEC_STATUS_PENDING:
26780 			if (ill != NULL && ill_need_rele)
26781 				ill_refrele(ill);
26782 			return;
26783 		}
26784 	}
26785 	/*
26786 	 * We are done with IPsec processing. Send it over
26787 	 * the wire.
26788 	 */
26789 done:
26790 	mp = ipsec_mp->b_cont;
26791 	ipha = (ipha_t *)mp->b_rptr;
26792 	if (IPH_HDR_VERSION(ipha) == IP_VERSION) {
26793 		ip_wput_ipsec_out(q, ipsec_mp, ipha, ill, ire);
26794 	} else {
26795 		ip6h = (ip6_t *)ipha;
26796 		ip_wput_ipsec_out_v6(q, ipsec_mp, ip6h, ill, ire);
26797 	}
26798 	if (ill != NULL && ill_need_rele)
26799 		ill_refrele(ill);
26800 }
26801 
26802 /* ARGSUSED */
26803 void
26804 ip_restart_optmgmt(ipsq_t *dummy_sq, queue_t *q, mblk_t *first_mp, void *dummy)
26805 {
26806 	opt_restart_t	*or;
26807 	int	err;
26808 	conn_t	*connp;
26809 
26810 	ASSERT(CONN_Q(q));
26811 	connp = Q_TO_CONN(q);
26812 
26813 	ASSERT(first_mp->b_datap->db_type == M_CTL);
26814 	or = (opt_restart_t *)first_mp->b_rptr;
26815 	/*
26816 	 * We don't need to pass any credentials here since this is just
26817 	 * a restart. The credentials are passed in when svr4_optcom_req
26818 	 * is called the first time (from ip_wput_nondata).
26819 	 */
26820 	if (or->or_type == T_SVR4_OPTMGMT_REQ) {
26821 		err = svr4_optcom_req(q, first_mp, NULL,
26822 		    &ip_opt_obj, B_FALSE);
26823 	} else {
26824 		ASSERT(or->or_type == T_OPTMGMT_REQ);
26825 		err = tpi_optcom_req(q, first_mp, NULL,
26826 		    &ip_opt_obj, B_FALSE);
26827 	}
26828 	if (err != EINPROGRESS) {
26829 		/* operation is done */
26830 		CONN_OPER_PENDING_DONE(connp);
26831 	}
26832 }
26833 
26834 /*
26835  * ioctls that go through a down/up sequence may need to wait for the down
26836  * to complete. This involves waiting for the ire and ipif refcnts to go down
26837  * to zero. Subsequently the ioctl is restarted from ipif_ill_refrele_tail.
26838  */
26839 /* ARGSUSED */
26840 void
26841 ip_reprocess_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
26842 {
26843 	struct iocblk *iocp;
26844 	mblk_t *mp1;
26845 	ip_ioctl_cmd_t *ipip;
26846 	int err;
26847 	sin_t	*sin;
26848 	struct lifreq *lifr;
26849 	struct ifreq *ifr;
26850 
26851 	iocp = (struct iocblk *)mp->b_rptr;
26852 	ASSERT(ipsq != NULL);
26853 	/* Existence of mp1 verified in ip_wput_nondata */
26854 	mp1 = mp->b_cont->b_cont;
26855 	ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26856 	if (ipip->ipi_cmd == SIOCSLIFNAME || ipip->ipi_cmd == IF_UNITSEL) {
26857 		/*
26858 		 * Special case where ipsq_current_ipif is not set:
26859 		 * ill_phyint_reinit merged the v4 and v6 into a single ipsq.
26860 		 * ill could also have become part of a ipmp group in the
26861 		 * process, we are here as were not able to complete the
26862 		 * operation in ipif_set_values because we could not become
26863 		 * exclusive on the new ipsq, In such a case ipsq_current_ipif
26864 		 * will not be set so we need to set it.
26865 		 */
26866 		ill_t *ill = q->q_ptr;
26867 		ipsq_current_start(ipsq, ill->ill_ipif, ipip->ipi_cmd);
26868 	}
26869 	ASSERT(ipsq->ipsq_current_ipif != NULL);
26870 
26871 	if (ipip->ipi_cmd_type == IF_CMD) {
26872 		/* This a old style SIOC[GS]IF* command */
26873 		ifr = (struct ifreq *)mp1->b_rptr;
26874 		sin = (sin_t *)&ifr->ifr_addr;
26875 	} else if (ipip->ipi_cmd_type == LIF_CMD) {
26876 		/* This a new style SIOC[GS]LIF* command */
26877 		lifr = (struct lifreq *)mp1->b_rptr;
26878 		sin = (sin_t *)&lifr->lifr_addr;
26879 	} else {
26880 		sin = NULL;
26881 	}
26882 
26883 	err = (*ipip->ipi_func_restart)(ipsq->ipsq_current_ipif, sin, q, mp,
26884 	    ipip, mp1->b_rptr);
26885 
26886 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
26887 }
26888 
26889 /*
26890  * ioctl processing
26891  *
26892  * ioctl processing starts with ip_sioctl_copyin_setup(), which looks up
26893  * the ioctl command in the ioctl tables, determines the copyin data size
26894  * from the ipi_copyin_size field, and does an mi_copyin() of that size.
26895  *
26896  * ioctl processing then continues when the M_IOCDATA makes its way down to
26897  * ip_wput_nondata().  The ioctl is looked up again in the ioctl table, its
26898  * associated 'conn' is refheld till the end of the ioctl and the general
26899  * ioctl processing function ip_process_ioctl() is called to extract the
26900  * arguments and process the ioctl.  To simplify extraction, ioctl commands
26901  * are "typed" based on the arguments they take (e.g., LIF_CMD which takes a
26902  * `struct lifreq'), and a common extract function (e.g., ip_extract_lifreq())
26903  * is used to extract the ioctl's arguments.
26904  *
26905  * ip_process_ioctl determines if the ioctl needs to be serialized, and if
26906  * so goes thru the serialization primitive ipsq_try_enter. Then the
26907  * appropriate function to handle the ioctl is called based on the entry in
26908  * the ioctl table. ioctl completion is encapsulated in ip_ioctl_finish
26909  * which also refreleases the 'conn' that was refheld at the start of the
26910  * ioctl. Finally ipsq_exit is called if needed to exit the ipsq.
26911  *
26912  * Many exclusive ioctls go thru an internal down up sequence as part of
26913  * the operation. For example an attempt to change the IP address of an
26914  * ipif entails ipif_down, set address, ipif_up. Bringing down the interface
26915  * does all the cleanup such as deleting all ires that use this address.
26916  * Then we need to wait till all references to the interface go away.
26917  */
26918 void
26919 ip_process_ioctl(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *arg)
26920 {
26921 	struct iocblk *iocp = (struct iocblk *)mp->b_rptr;
26922 	ip_ioctl_cmd_t *ipip = arg;
26923 	ip_extract_func_t *extract_funcp;
26924 	cmd_info_t ci;
26925 	int err;
26926 	boolean_t entered_ipsq = B_FALSE;
26927 
26928 	ip3dbg(("ip_process_ioctl: ioctl %X\n", iocp->ioc_cmd));
26929 
26930 	if (ipip == NULL)
26931 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
26932 
26933 	/*
26934 	 * SIOCLIFADDIF needs to go thru a special path since the
26935 	 * ill may not exist yet. This happens in the case of lo0
26936 	 * which is created using this ioctl.
26937 	 */
26938 	if (ipip->ipi_cmd == SIOCLIFADDIF) {
26939 		err = ip_sioctl_addif(NULL, NULL, q, mp, NULL, NULL);
26940 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26941 		return;
26942 	}
26943 
26944 	ci.ci_ipif = NULL;
26945 	if (ipip->ipi_cmd_type == MISC_CMD) {
26946 		/*
26947 		 * All MISC_CMD ioctls come in here -- e.g. SIOCGLIFCONF.
26948 		 */
26949 		if (ipip->ipi_cmd == IF_UNITSEL) {
26950 			/* ioctl comes down the ill */
26951 			ci.ci_ipif = ((ill_t *)q->q_ptr)->ill_ipif;
26952 			ipif_refhold(ci.ci_ipif);
26953 		}
26954 		err = 0;
26955 		ci.ci_sin = NULL;
26956 		ci.ci_sin6 = NULL;
26957 		ci.ci_lifr = NULL;
26958 	} else {
26959 		switch (ipip->ipi_cmd_type) {
26960 		case IF_CMD:
26961 		case LIF_CMD:
26962 			extract_funcp = ip_extract_lifreq;
26963 			break;
26964 
26965 		case ARP_CMD:
26966 		case XARP_CMD:
26967 			extract_funcp = ip_extract_arpreq;
26968 			break;
26969 
26970 		case TUN_CMD:
26971 			extract_funcp = ip_extract_tunreq;
26972 			break;
26973 
26974 		case MSFILT_CMD:
26975 			extract_funcp = ip_extract_msfilter;
26976 			break;
26977 
26978 		default:
26979 			ASSERT(0);
26980 		}
26981 
26982 		err = (*extract_funcp)(q, mp, ipip, &ci, ip_process_ioctl);
26983 		if (err != 0) {
26984 			ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
26985 			return;
26986 		}
26987 
26988 		/*
26989 		 * All of the extraction functions return a refheld ipif.
26990 		 */
26991 		ASSERT(ci.ci_ipif != NULL);
26992 	}
26993 
26994 	/*
26995 	 * If ipsq is non-null, we are already being called exclusively
26996 	 */
26997 	ASSERT(ipsq == NULL || IAM_WRITER_IPSQ(ipsq));
26998 	if (!(ipip->ipi_flags & IPI_WR)) {
26999 		/*
27000 		 * A return value of EINPROGRESS means the ioctl is
27001 		 * either queued and waiting for some reason or has
27002 		 * already completed.
27003 		 */
27004 		err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip,
27005 		    ci.ci_lifr);
27006 		if (ci.ci_ipif != NULL)
27007 			ipif_refrele(ci.ci_ipif);
27008 		ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), NULL);
27009 		return;
27010 	}
27011 
27012 	ASSERT(ci.ci_ipif != NULL);
27013 
27014 	if (ipsq == NULL) {
27015 		ipsq = ipsq_try_enter(ci.ci_ipif, NULL, q, mp,
27016 		    ip_process_ioctl, NEW_OP, B_TRUE);
27017 		entered_ipsq = B_TRUE;
27018 	}
27019 	/*
27020 	 * Release the ipif so that ipif_down and friends that wait for
27021 	 * references to go away are not misled about the current ipif_refcnt
27022 	 * values. We are writer so we can access the ipif even after releasing
27023 	 * the ipif.
27024 	 */
27025 	ipif_refrele(ci.ci_ipif);
27026 	if (ipsq == NULL)
27027 		return;
27028 
27029 	ipsq_current_start(ipsq, ci.ci_ipif, ipip->ipi_cmd);
27030 
27031 	/*
27032 	 * For most set ioctls that come here, this serves as a single point
27033 	 * where we set the IPIF_CHANGING flag. This ensures that there won't
27034 	 * be any new references to the ipif. This helps functions that go
27035 	 * through this path and end up trying to wait for the refcnts
27036 	 * associated with the ipif to go down to zero. Some exceptions are
27037 	 * Failover, Failback, and Groupname commands that operate on more than
27038 	 * just the ci.ci_ipif. These commands internally determine the
27039 	 * set of ipif's they operate on and set and clear the IPIF_CHANGING
27040 	 * flags on that set. Another exception is the Removeif command that
27041 	 * sets the IPIF_CONDEMNED flag internally after identifying the right
27042 	 * ipif to operate on.
27043 	 */
27044 	mutex_enter(&(ci.ci_ipif)->ipif_ill->ill_lock);
27045 	if (ipip->ipi_cmd != SIOCLIFREMOVEIF &&
27046 	    ipip->ipi_cmd != SIOCLIFFAILOVER &&
27047 	    ipip->ipi_cmd != SIOCLIFFAILBACK &&
27048 	    ipip->ipi_cmd != SIOCSLIFGROUPNAME)
27049 		(ci.ci_ipif)->ipif_state_flags |= IPIF_CHANGING;
27050 	mutex_exit(&(ci.ci_ipif)->ipif_ill->ill_lock);
27051 
27052 	/*
27053 	 * A return value of EINPROGRESS means the ioctl is
27054 	 * either queued and waiting for some reason or has
27055 	 * already completed.
27056 	 */
27057 	err = (*ipip->ipi_func)(ci.ci_ipif, ci.ci_sin, q, mp, ipip, ci.ci_lifr);
27058 
27059 	ip_ioctl_finish(q, mp, err, IPI2MODE(ipip), ipsq);
27060 
27061 	if (entered_ipsq)
27062 		ipsq_exit(ipsq, B_TRUE, B_TRUE);
27063 }
27064 
27065 /*
27066  * Complete the ioctl. Typically ioctls use the mi package and need to
27067  * do mi_copyout/mi_copy_done.
27068  */
27069 void
27070 ip_ioctl_finish(queue_t *q, mblk_t *mp, int err, int mode, ipsq_t *ipsq)
27071 {
27072 	conn_t	*connp = NULL;
27073 
27074 	if (err == EINPROGRESS)
27075 		return;
27076 
27077 	if (CONN_Q(q)) {
27078 		connp = Q_TO_CONN(q);
27079 		ASSERT(connp->conn_ref >= 2);
27080 	}
27081 
27082 	switch (mode) {
27083 	case COPYOUT:
27084 		if (err == 0)
27085 			mi_copyout(q, mp);
27086 		else
27087 			mi_copy_done(q, mp, err);
27088 		break;
27089 
27090 	case NO_COPYOUT:
27091 		mi_copy_done(q, mp, err);
27092 		break;
27093 
27094 	default:
27095 		ASSERT(mode == CONN_CLOSE);	/* aborted through CONN_CLOSE */
27096 		break;
27097 	}
27098 
27099 	/*
27100 	 * The refhold placed at the start of the ioctl is released here.
27101 	 */
27102 	if (connp != NULL)
27103 		CONN_OPER_PENDING_DONE(connp);
27104 
27105 	if (ipsq != NULL)
27106 		ipsq_current_finish(ipsq);
27107 }
27108 
27109 /*
27110  * This is called from ip_wput_nondata to resume a deferred TCP bind.
27111  */
27112 /* ARGSUSED */
27113 void
27114 ip_resume_tcp_bind(void *arg, mblk_t *mp, void *arg2)
27115 {
27116 	conn_t *connp = arg;
27117 	tcp_t	*tcp;
27118 
27119 	ASSERT(connp != NULL && IPCL_IS_TCP(connp) && connp->conn_tcp != NULL);
27120 	tcp = connp->conn_tcp;
27121 
27122 	if (connp->conn_tcp->tcp_state == TCPS_CLOSED)
27123 		freemsg(mp);
27124 	else
27125 		tcp_rput_other(tcp, mp);
27126 	CONN_OPER_PENDING_DONE(connp);
27127 }
27128 
27129 /* Called from ip_wput for all non data messages */
27130 /* ARGSUSED */
27131 void
27132 ip_wput_nondata(ipsq_t *ipsq, queue_t *q, mblk_t *mp, void *dummy_arg)
27133 {
27134 	mblk_t		*mp1;
27135 	ire_t		*ire, *fake_ire;
27136 	ill_t		*ill;
27137 	struct iocblk	*iocp;
27138 	ip_ioctl_cmd_t	*ipip;
27139 	cred_t		*cr;
27140 	conn_t		*connp;
27141 	int		err;
27142 	nce_t		*nce;
27143 	ipif_t		*ipif;
27144 	ip_stack_t	*ipst;
27145 	char		*proto_str;
27146 
27147 	if (CONN_Q(q)) {
27148 		connp = Q_TO_CONN(q);
27149 		ipst = connp->conn_netstack->netstack_ip;
27150 	} else {
27151 		connp = NULL;
27152 		ipst = ILLQ_TO_IPST(q);
27153 	}
27154 
27155 	cr = DB_CREDDEF(mp, GET_QUEUE_CRED(q));
27156 
27157 	switch (DB_TYPE(mp)) {
27158 	case M_IOCTL:
27159 		/*
27160 		 * IOCTL processing begins in ip_sioctl_copyin_setup which
27161 		 * will arrange to copy in associated control structures.
27162 		 */
27163 		ip_sioctl_copyin_setup(q, mp);
27164 		return;
27165 	case M_IOCDATA:
27166 		/*
27167 		 * Ensure that this is associated with one of our trans-
27168 		 * parent ioctls.  If it's not ours, discard it if we're
27169 		 * running as a driver, or pass it on if we're a module.
27170 		 */
27171 		iocp = (struct iocblk *)mp->b_rptr;
27172 		ipip = ip_sioctl_lookup(iocp->ioc_cmd);
27173 		if (ipip == NULL) {
27174 			if (q->q_next == NULL) {
27175 				goto nak;
27176 			} else {
27177 				putnext(q, mp);
27178 			}
27179 			return;
27180 		}
27181 		if ((q->q_next != NULL) && !(ipip->ipi_flags & IPI_MODOK)) {
27182 			/*
27183 			 * the ioctl is one we recognise, but is not
27184 			 * consumed by IP as a module, pass M_IOCDATA
27185 			 * for processing downstream, but only for
27186 			 * common Streams ioctls.
27187 			 */
27188 			if (ipip->ipi_flags & IPI_PASS_DOWN) {
27189 				putnext(q, mp);
27190 				return;
27191 			} else {
27192 				goto nak;
27193 			}
27194 		}
27195 
27196 		/* IOCTL continuation following copyin or copyout. */
27197 		if (mi_copy_state(q, mp, NULL) == -1) {
27198 			/*
27199 			 * The copy operation failed.  mi_copy_state already
27200 			 * cleaned up, so we're out of here.
27201 			 */
27202 			return;
27203 		}
27204 		/*
27205 		 * If we just completed a copy in, we become writer and
27206 		 * continue processing in ip_sioctl_copyin_done.  If it
27207 		 * was a copy out, we call mi_copyout again.  If there is
27208 		 * nothing more to copy out, it will complete the IOCTL.
27209 		 */
27210 		if (MI_COPY_DIRECTION(mp) == MI_COPY_IN) {
27211 			if (!(mp1 = mp->b_cont) || !(mp1 = mp1->b_cont)) {
27212 				mi_copy_done(q, mp, EPROTO);
27213 				return;
27214 			}
27215 			/*
27216 			 * Check for cases that need more copying.  A return
27217 			 * value of 0 means a second copyin has been started,
27218 			 * so we return; a return value of 1 means no more
27219 			 * copying is needed, so we continue.
27220 			 */
27221 			if (ipip->ipi_cmd_type == MSFILT_CMD &&
27222 			    MI_COPY_COUNT(mp) == 1) {
27223 				if (ip_copyin_msfilter(q, mp) == 0)
27224 					return;
27225 			}
27226 			/*
27227 			 * Refhold the conn, till the ioctl completes. This is
27228 			 * needed in case the ioctl ends up in the pending mp
27229 			 * list. Every mp in the ill_pending_mp list and
27230 			 * the ipsq_pending_mp must have a refhold on the conn
27231 			 * to resume processing. The refhold is released when
27232 			 * the ioctl completes. (normally or abnormally)
27233 			 * In all cases ip_ioctl_finish is called to finish
27234 			 * the ioctl.
27235 			 */
27236 			if (connp != NULL) {
27237 				/* This is not a reentry */
27238 				ASSERT(ipsq == NULL);
27239 				CONN_INC_REF(connp);
27240 			} else {
27241 				if (!(ipip->ipi_flags & IPI_MODOK)) {
27242 					mi_copy_done(q, mp, EINVAL);
27243 					return;
27244 				}
27245 			}
27246 
27247 			ip_process_ioctl(ipsq, q, mp, ipip);
27248 
27249 		} else {
27250 			mi_copyout(q, mp);
27251 		}
27252 		return;
27253 nak:
27254 		iocp->ioc_error = EINVAL;
27255 		mp->b_datap->db_type = M_IOCNAK;
27256 		iocp->ioc_count = 0;
27257 		qreply(q, mp);
27258 		return;
27259 
27260 	case M_IOCNAK:
27261 		/*
27262 		 * The only way we could get here is if a resolver didn't like
27263 		 * an IOCTL we sent it.	 This shouldn't happen.
27264 		 */
27265 		(void) mi_strlog(q, 1, SL_ERROR|SL_TRACE,
27266 		    "ip_wput: unexpected M_IOCNAK, ioc_cmd 0x%x",
27267 		    ((struct iocblk *)mp->b_rptr)->ioc_cmd);
27268 		freemsg(mp);
27269 		return;
27270 	case M_IOCACK:
27271 		/* /dev/ip shouldn't see this */
27272 		if (CONN_Q(q))
27273 			goto nak;
27274 
27275 		/* Finish socket ioctls passed through to ARP. */
27276 		ip_sioctl_iocack(q, mp);
27277 		return;
27278 	case M_FLUSH:
27279 		if (*mp->b_rptr & FLUSHW)
27280 			flushq(q, FLUSHALL);
27281 		if (q->q_next) {
27282 			putnext(q, mp);
27283 			return;
27284 		}
27285 		if (*mp->b_rptr & FLUSHR) {
27286 			*mp->b_rptr &= ~FLUSHW;
27287 			qreply(q, mp);
27288 			return;
27289 		}
27290 		freemsg(mp);
27291 		return;
27292 	case IRE_DB_REQ_TYPE:
27293 		if (connp == NULL) {
27294 			proto_str = "IRE_DB_REQ_TYPE";
27295 			goto protonak;
27296 		}
27297 		/* An Upper Level Protocol wants a copy of an IRE. */
27298 		ip_ire_req(q, mp);
27299 		return;
27300 	case M_CTL:
27301 		if (mp->b_wptr - mp->b_rptr < sizeof (uint32_t))
27302 			break;
27303 
27304 		if (((ipsec_info_t *)mp->b_rptr)->ipsec_info_type ==
27305 		    TUN_HELLO) {
27306 			ASSERT(connp != NULL);
27307 			connp->conn_flags |= IPCL_IPTUN;
27308 			freeb(mp);
27309 			return;
27310 		}
27311 
27312 		/* M_CTL messages are used by ARP to tell us things. */
27313 		if ((mp->b_wptr - mp->b_rptr) < sizeof (arc_t))
27314 			break;
27315 		switch (((arc_t *)mp->b_rptr)->arc_cmd) {
27316 		case AR_ENTRY_SQUERY:
27317 			ip_wput_ctl(q, mp);
27318 			return;
27319 		case AR_CLIENT_NOTIFY:
27320 			ip_arp_news(q, mp);
27321 			return;
27322 		case AR_DLPIOP_DONE:
27323 			ASSERT(q->q_next != NULL);
27324 			ill = (ill_t *)q->q_ptr;
27325 			/* qwriter_ip releases the refhold */
27326 			/* refhold on ill stream is ok without ILL_CAN_LOOKUP */
27327 			ill_refhold(ill);
27328 			qwriter_ip(ill, q, mp, ip_arp_done, CUR_OP, B_FALSE);
27329 			return;
27330 		case AR_ARP_CLOSING:
27331 			/*
27332 			 * ARP (above us) is closing. If no ARP bringup is
27333 			 * currently pending, ack the message so that ARP
27334 			 * can complete its close. Also mark ill_arp_closing
27335 			 * so that new ARP bringups will fail. If any
27336 			 * ARP bringup is currently in progress, we will
27337 			 * ack this when the current ARP bringup completes.
27338 			 */
27339 			ASSERT(q->q_next != NULL);
27340 			ill = (ill_t *)q->q_ptr;
27341 			mutex_enter(&ill->ill_lock);
27342 			ill->ill_arp_closing = 1;
27343 			if (!ill->ill_arp_bringup_pending) {
27344 				mutex_exit(&ill->ill_lock);
27345 				qreply(q, mp);
27346 			} else {
27347 				mutex_exit(&ill->ill_lock);
27348 				freemsg(mp);
27349 			}
27350 			return;
27351 		case AR_ARP_EXTEND:
27352 			/*
27353 			 * The ARP module above us is capable of duplicate
27354 			 * address detection.  Old ATM drivers will not send
27355 			 * this message.
27356 			 */
27357 			ASSERT(q->q_next != NULL);
27358 			ill = (ill_t *)q->q_ptr;
27359 			ill->ill_arp_extend = B_TRUE;
27360 			freemsg(mp);
27361 			return;
27362 		default:
27363 			break;
27364 		}
27365 		break;
27366 	case M_PROTO:
27367 	case M_PCPROTO:
27368 		/*
27369 		 * The only PROTO messages we expect are ULP binds and
27370 		 * copies of option negotiation acknowledgements.
27371 		 */
27372 		switch (((union T_primitives *)mp->b_rptr)->type) {
27373 		case O_T_BIND_REQ:
27374 		case T_BIND_REQ: {
27375 			/* Request can get queued in bind */
27376 			if (connp == NULL) {
27377 				proto_str = "O_T_BIND_REQ/T_BIND_REQ";
27378 				goto protonak;
27379 			}
27380 			/*
27381 			 * The transports except SCTP call ip_bind_{v4,v6}()
27382 			 * directly instead of a a putnext. SCTP doesn't
27383 			 * generate any T_BIND_REQ since it has its own
27384 			 * fanout data structures. However, ESP and AH
27385 			 * come in for regular binds; all other cases are
27386 			 * bind retries.
27387 			 */
27388 			ASSERT(!IPCL_IS_SCTP(connp));
27389 
27390 			/* Don't increment refcnt if this is a re-entry */
27391 			if (ipsq == NULL)
27392 				CONN_INC_REF(connp);
27393 
27394 			mp = connp->conn_af_isv6 ? ip_bind_v6(q, mp,
27395 			    connp, NULL) : ip_bind_v4(q, mp, connp);
27396 			if (mp == NULL)
27397 				return;
27398 			if (IPCL_IS_TCP(connp)) {
27399 				/*
27400 				 * In the case of TCP endpoint we
27401 				 * come here only for bind retries
27402 				 */
27403 				ASSERT(ipsq != NULL);
27404 				CONN_INC_REF(connp);
27405 				squeue_fill(connp->conn_sqp, mp,
27406 				    ip_resume_tcp_bind, connp,
27407 				    SQTAG_BIND_RETRY);
27408 			} else if (IPCL_IS_UDP(connp)) {
27409 				/*
27410 				 * In the case of UDP endpoint we
27411 				 * come here only for bind retries
27412 				 */
27413 				ASSERT(ipsq != NULL);
27414 				udp_resume_bind(connp, mp);
27415 			} else if (IPCL_IS_RAWIP(connp)) {
27416 				/*
27417 				 * In the case of RAWIP endpoint we
27418 				 * come here only for bind retries
27419 				 */
27420 				ASSERT(ipsq != NULL);
27421 				rawip_resume_bind(connp, mp);
27422 			} else {
27423 				/* The case of AH and ESP */
27424 				qreply(q, mp);
27425 				CONN_OPER_PENDING_DONE(connp);
27426 			}
27427 			return;
27428 		}
27429 		case T_SVR4_OPTMGMT_REQ:
27430 			ip2dbg(("ip_wput: T_SVR4_OPTMGMT_REQ flags %x\n",
27431 			    ((struct T_optmgmt_req *)mp->b_rptr)->MGMT_flags));
27432 
27433 			if (connp == NULL) {
27434 				proto_str = "T_SVR4_OPTMGMT_REQ";
27435 				goto protonak;
27436 			}
27437 
27438 			if (!snmpcom_req(q, mp, ip_snmp_set,
27439 			    ip_snmp_get, cr)) {
27440 				/*
27441 				 * Call svr4_optcom_req so that it can
27442 				 * generate the ack. We don't come here
27443 				 * if this operation is being restarted.
27444 				 * ip_restart_optmgmt will drop the conn ref.
27445 				 * In the case of ipsec option after the ipsec
27446 				 * load is complete conn_restart_ipsec_waiter
27447 				 * drops the conn ref.
27448 				 */
27449 				ASSERT(ipsq == NULL);
27450 				CONN_INC_REF(connp);
27451 				if (ip_check_for_ipsec_opt(q, mp))
27452 					return;
27453 				err = svr4_optcom_req(q, mp, cr, &ip_opt_obj,
27454 				    B_FALSE);
27455 				if (err != EINPROGRESS) {
27456 					/* Operation is done */
27457 					CONN_OPER_PENDING_DONE(connp);
27458 				}
27459 			}
27460 			return;
27461 		case T_OPTMGMT_REQ:
27462 			ip2dbg(("ip_wput: T_OPTMGMT_REQ\n"));
27463 			/*
27464 			 * Note: No snmpcom_req support through new
27465 			 * T_OPTMGMT_REQ.
27466 			 * Call tpi_optcom_req so that it can
27467 			 * generate the ack.
27468 			 */
27469 			if (connp == NULL) {
27470 				proto_str = "T_OPTMGMT_REQ";
27471 				goto protonak;
27472 			}
27473 
27474 			ASSERT(ipsq == NULL);
27475 			/*
27476 			 * We don't come here for restart. ip_restart_optmgmt
27477 			 * will drop the conn ref. In the case of ipsec option
27478 			 * after the ipsec load is complete
27479 			 * conn_restart_ipsec_waiter drops the conn ref.
27480 			 */
27481 			CONN_INC_REF(connp);
27482 			if (ip_check_for_ipsec_opt(q, mp))
27483 				return;
27484 			err = tpi_optcom_req(q, mp, cr, &ip_opt_obj, B_FALSE);
27485 			if (err != EINPROGRESS) {
27486 				/* Operation is done */
27487 				CONN_OPER_PENDING_DONE(connp);
27488 			}
27489 			return;
27490 		case T_UNBIND_REQ:
27491 			if (connp == NULL) {
27492 				proto_str = "T_UNBIND_REQ";
27493 				goto protonak;
27494 			}
27495 			mp = ip_unbind(q, mp);
27496 			qreply(q, mp);
27497 			return;
27498 		default:
27499 			/*
27500 			 * Have to drop any DLPI messages coming down from
27501 			 * arp (such as an info_req which would cause ip
27502 			 * to receive an extra info_ack if it was passed
27503 			 * through.
27504 			 */
27505 			ip1dbg(("ip_wput_nondata: dropping M_PROTO %d\n",
27506 			    (int)*(uint_t *)mp->b_rptr));
27507 			freemsg(mp);
27508 			return;
27509 		}
27510 		/* NOTREACHED */
27511 	case IRE_DB_TYPE: {
27512 		nce_t		*nce;
27513 		ill_t		*ill;
27514 		in6_addr_t	gw_addr_v6;
27515 
27516 
27517 		/*
27518 		 * This is a response back from a resolver.  It
27519 		 * consists of a message chain containing:
27520 		 *	IRE_MBLK-->LL_HDR_MBLK->pkt
27521 		 * The IRE_MBLK is the one we allocated in ip_newroute.
27522 		 * The LL_HDR_MBLK is the DLPI header to use to get
27523 		 * the attached packet, and subsequent ones for the
27524 		 * same destination, transmitted.
27525 		 */
27526 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t))    /* ire */
27527 			break;
27528 		/*
27529 		 * First, check to make sure the resolution succeeded.
27530 		 * If it failed, the second mblk will be empty.
27531 		 * If it is, free the chain, dropping the packet.
27532 		 * (We must ire_delete the ire; that frees the ire mblk)
27533 		 * We're doing this now to support PVCs for ATM; it's
27534 		 * a partial xresolv implementation. When we fully implement
27535 		 * xresolv interfaces, instead of freeing everything here
27536 		 * we'll initiate neighbor discovery.
27537 		 *
27538 		 * For v4 (ARP and other external resolvers) the resolver
27539 		 * frees the message, so no check is needed. This check
27540 		 * is required, though, for a full xresolve implementation.
27541 		 * Including this code here now both shows how external
27542 		 * resolvers can NACK a resolution request using an
27543 		 * existing design that has no specific provisions for NACKs,
27544 		 * and also takes into account that the current non-ARP
27545 		 * external resolver has been coded to use this method of
27546 		 * NACKing for all IPv6 (xresolv) cases,
27547 		 * whether our xresolv implementation is complete or not.
27548 		 *
27549 		 */
27550 		ire = (ire_t *)mp->b_rptr;
27551 		ill = ire_to_ill(ire);
27552 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27553 		if (mp1->b_rptr == mp1->b_wptr) {
27554 			if (ire->ire_ipversion == IPV6_VERSION) {
27555 				/*
27556 				 * XRESOLV interface.
27557 				 */
27558 				ASSERT(ill->ill_flags & ILLF_XRESOLV);
27559 				mutex_enter(&ire->ire_lock);
27560 				gw_addr_v6 = ire->ire_gateway_addr_v6;
27561 				mutex_exit(&ire->ire_lock);
27562 				if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27563 					nce = ndp_lookup_v6(ill,
27564 					    &ire->ire_addr_v6, B_FALSE);
27565 				} else {
27566 					nce = ndp_lookup_v6(ill, &gw_addr_v6,
27567 					    B_FALSE);
27568 				}
27569 				if (nce != NULL) {
27570 					nce_resolv_failed(nce);
27571 					ndp_delete(nce);
27572 					NCE_REFRELE(nce);
27573 				}
27574 			}
27575 			mp->b_cont = NULL;
27576 			freemsg(mp1);		/* frees the pkt as well */
27577 			ASSERT(ire->ire_nce == NULL);
27578 			ire_delete((ire_t *)mp->b_rptr);
27579 			return;
27580 		}
27581 
27582 		/*
27583 		 * Split them into IRE_MBLK and pkt and feed it into
27584 		 * ire_add_then_send. Then in ire_add_then_send
27585 		 * the IRE will be added, and then the packet will be
27586 		 * run back through ip_wput. This time it will make
27587 		 * it to the wire.
27588 		 */
27589 		mp->b_cont = NULL;
27590 		mp = mp1->b_cont;		/* now, mp points to pkt */
27591 		mp1->b_cont = NULL;
27592 		ip1dbg(("ip_wput_nondata: reply from external resolver \n"));
27593 		if (ire->ire_ipversion == IPV6_VERSION) {
27594 			/*
27595 			 * XRESOLV interface. Find the nce and put a copy
27596 			 * of the dl_unitdata_req in nce_res_mp
27597 			 */
27598 			ASSERT(ill->ill_flags & ILLF_XRESOLV);
27599 			mutex_enter(&ire->ire_lock);
27600 			gw_addr_v6 = ire->ire_gateway_addr_v6;
27601 			mutex_exit(&ire->ire_lock);
27602 			if (IN6_IS_ADDR_UNSPECIFIED(&gw_addr_v6)) {
27603 				nce = ndp_lookup_v6(ill, &ire->ire_addr_v6,
27604 				    B_FALSE);
27605 			} else {
27606 				nce = ndp_lookup_v6(ill, &gw_addr_v6, B_FALSE);
27607 			}
27608 			if (nce != NULL) {
27609 				/*
27610 				 * We have to protect nce_res_mp here
27611 				 * from being accessed by other threads
27612 				 * while we change the mblk pointer.
27613 				 * Other functions will also lock the nce when
27614 				 * accessing nce_res_mp.
27615 				 *
27616 				 * The reason we change the mblk pointer
27617 				 * here rather than copying the resolved address
27618 				 * into the template is that, unlike with
27619 				 * ethernet, we have no guarantee that the
27620 				 * resolved address length will be
27621 				 * smaller than or equal to the lla length
27622 				 * with which the template was allocated,
27623 				 * (for ethernet, they're equal)
27624 				 * so we have to use the actual resolved
27625 				 * address mblk - which holds the real
27626 				 * dl_unitdata_req with the resolved address.
27627 				 *
27628 				 * Doing this is the same behavior as was
27629 				 * previously used in the v4 ARP case.
27630 				 */
27631 				mutex_enter(&nce->nce_lock);
27632 				if (nce->nce_res_mp != NULL)
27633 					freemsg(nce->nce_res_mp);
27634 				nce->nce_res_mp = mp1;
27635 				mutex_exit(&nce->nce_lock);
27636 				/*
27637 				 * We do a fastpath probe here because
27638 				 * we have resolved the address without
27639 				 * using Neighbor Discovery.
27640 				 * In the non-XRESOLV v6 case, the fastpath
27641 				 * probe is done right after neighbor
27642 				 * discovery completes.
27643 				 */
27644 				if (nce->nce_res_mp != NULL) {
27645 					int res;
27646 					nce_fastpath_list_add(nce);
27647 					res = ill_fastpath_probe(ill,
27648 					    nce->nce_res_mp);
27649 					if (res != 0 && res != EAGAIN)
27650 						nce_fastpath_list_delete(nce);
27651 				}
27652 
27653 				ire_add_then_send(q, ire, mp);
27654 				/*
27655 				 * Now we have to clean out any packets
27656 				 * that may have been queued on the nce
27657 				 * while it was waiting for address resolution
27658 				 * to complete.
27659 				 */
27660 				mutex_enter(&nce->nce_lock);
27661 				mp1 = nce->nce_qd_mp;
27662 				nce->nce_qd_mp = NULL;
27663 				mutex_exit(&nce->nce_lock);
27664 				while (mp1 != NULL) {
27665 					mblk_t *nxt_mp;
27666 					queue_t *fwdq = NULL;
27667 					ill_t   *inbound_ill;
27668 					uint_t ifindex;
27669 
27670 					nxt_mp = mp1->b_next;
27671 					mp1->b_next = NULL;
27672 					/*
27673 					 * Retrieve ifindex stored in
27674 					 * ip_rput_data_v6()
27675 					 */
27676 					ifindex =
27677 					    (uint_t)(uintptr_t)mp1->b_prev;
27678 					inbound_ill =
27679 					    ill_lookup_on_ifindex(ifindex,
27680 					    B_TRUE, NULL, NULL, NULL,
27681 					    NULL, ipst);
27682 					mp1->b_prev = NULL;
27683 					if (inbound_ill != NULL)
27684 						fwdq = inbound_ill->ill_rq;
27685 
27686 					if (fwdq != NULL) {
27687 						put(fwdq, mp1);
27688 						ill_refrele(inbound_ill);
27689 					} else
27690 						put(WR(ill->ill_rq), mp1);
27691 					mp1 = nxt_mp;
27692 				}
27693 				NCE_REFRELE(nce);
27694 			} else {	/* nce is NULL; clean up */
27695 				ire_delete(ire);
27696 				freemsg(mp);
27697 				freemsg(mp1);
27698 				return;
27699 			}
27700 		} else {
27701 			nce_t *arpce;
27702 			/*
27703 			 * Link layer resolution succeeded. Recompute the
27704 			 * ire_nce.
27705 			 */
27706 			ASSERT(ire->ire_type & (IRE_CACHE|IRE_BROADCAST));
27707 			if ((arpce = ndp_lookup_v4(ill,
27708 			    (ire->ire_gateway_addr != INADDR_ANY ?
27709 			    &ire->ire_gateway_addr : &ire->ire_addr),
27710 			    B_FALSE)) == NULL) {
27711 				freeb(ire->ire_mp);
27712 				freeb(mp1);
27713 				freemsg(mp);
27714 				return;
27715 			}
27716 			mutex_enter(&arpce->nce_lock);
27717 			arpce->nce_last = TICK_TO_MSEC(lbolt64);
27718 			if (arpce->nce_state == ND_REACHABLE) {
27719 				/*
27720 				 * Someone resolved this before us;
27721 				 * cleanup the res_mp. Since ire has
27722 				 * not been added yet, the call to ire_add_v4
27723 				 * from ire_add_then_send (when a dup is
27724 				 * detected) will clean up the ire.
27725 				 */
27726 				freeb(mp1);
27727 			} else {
27728 				ASSERT(arpce->nce_res_mp == NULL);
27729 				arpce->nce_res_mp = mp1;
27730 				arpce->nce_state = ND_REACHABLE;
27731 			}
27732 			mutex_exit(&arpce->nce_lock);
27733 			if (ire->ire_marks & IRE_MARK_NOADD) {
27734 				/*
27735 				 * this ire will not be added to the ire
27736 				 * cache table, so we can set the ire_nce
27737 				 * here, as there are no atomicity constraints.
27738 				 */
27739 				ire->ire_nce = arpce;
27740 				/*
27741 				 * We are associating this nce with the ire
27742 				 * so change the nce ref taken in
27743 				 * ndp_lookup_v4() from
27744 				 * NCE_REFHOLD to NCE_REFHOLD_NOTR
27745 				 */
27746 				NCE_REFHOLD_TO_REFHOLD_NOTR(ire->ire_nce);
27747 			} else {
27748 				NCE_REFRELE(arpce);
27749 			}
27750 			ire_add_then_send(q, ire, mp);
27751 		}
27752 		return;	/* All is well, the packet has been sent. */
27753 	}
27754 	case IRE_ARPRESOLVE_TYPE: {
27755 
27756 		if ((mp->b_wptr - mp->b_rptr) != sizeof (ire_t)) /* fake_ire */
27757 			break;
27758 		mp1 = mp->b_cont;		/* dl_unitdata_req */
27759 		mp->b_cont = NULL;
27760 		/*
27761 		 * First, check to make sure the resolution succeeded.
27762 		 * If it failed, the second mblk will be empty.
27763 		 */
27764 		if (mp1->b_rptr == mp1->b_wptr) {
27765 			/* cleanup  the incomplete ire, free queued packets */
27766 			freemsg(mp); /* fake ire */
27767 			freeb(mp1);  /* dl_unitdata response */
27768 			return;
27769 		}
27770 
27771 		/*
27772 		 * update any incomplete nce_t found. we lookup the ctable
27773 		 * and find the nce from the ire->ire_nce because we need
27774 		 * to pass the ire to ip_xmit_v4 later, and can find both
27775 		 * ire and nce in one lookup from the ctable.
27776 		 */
27777 		fake_ire = (ire_t *)mp->b_rptr;
27778 		/*
27779 		 * By the time we come back here from ARP
27780 		 * the logical outgoing interface  of the incomplete ire
27781 		 * we added in ire_forward could have disappeared,
27782 		 * causing the incomplete ire to also have
27783 		 * dissapeared. So we need to retreive the
27784 		 * proper ipif for the ire  before looking
27785 		 * in ctable;  do the ctablelookup based on ire_ipif_seqid
27786 		 */
27787 		ill = q->q_ptr;
27788 
27789 		/* Get the outgoing ipif */
27790 		mutex_enter(&ill->ill_lock);
27791 		if (ill->ill_state_flags & ILL_CONDEMNED) {
27792 			mutex_exit(&ill->ill_lock);
27793 			freemsg(mp); /* fake ire */
27794 			freeb(mp1);  /* dl_unitdata response */
27795 			return;
27796 		}
27797 		ipif = ipif_lookup_seqid(ill, fake_ire->ire_ipif_seqid);
27798 
27799 		if (ipif == NULL) {
27800 			mutex_exit(&ill->ill_lock);
27801 			ip1dbg(("logical intrf to incomplete ire vanished\n"));
27802 			freemsg(mp);
27803 			freeb(mp1);
27804 			return;
27805 		}
27806 		ipif_refhold_locked(ipif);
27807 		mutex_exit(&ill->ill_lock);
27808 		ire = ire_ctable_lookup(fake_ire->ire_addr,
27809 		    fake_ire->ire_gateway_addr, IRE_CACHE,
27810 		    ipif, fake_ire->ire_zoneid, NULL,
27811 		    (MATCH_IRE_GW|MATCH_IRE_IPIF|MATCH_IRE_ZONEONLY|
27812 		    MATCH_IRE_TYPE), ipst);
27813 		ipif_refrele(ipif);
27814 		if (ire == NULL) {
27815 			/*
27816 			 * no ire was found; check if there is an nce
27817 			 * for this lookup; if it has no ire's pointing at it
27818 			 * cleanup.
27819 			 */
27820 			if ((nce = ndp_lookup_v4(ill,
27821 			    (fake_ire->ire_gateway_addr != INADDR_ANY ?
27822 			    &fake_ire->ire_gateway_addr : &fake_ire->ire_addr),
27823 			    B_FALSE)) != NULL) {
27824 				/*
27825 				 * cleanup:
27826 				 * We check for refcnt 2 (one for the nce
27827 				 * hash list + 1 for the ref taken by
27828 				 * ndp_lookup_v4) to check that there are
27829 				 * no ire's pointing at the nce.
27830 				 */
27831 				if (nce->nce_refcnt == 2)
27832 					ndp_delete(nce);
27833 				NCE_REFRELE(nce);
27834 			}
27835 			freeb(mp1);  /* dl_unitdata response */
27836 			freemsg(mp); /* fake ire */
27837 			return;
27838 		}
27839 		nce = ire->ire_nce;
27840 		DTRACE_PROBE2(ire__arpresolve__type,
27841 		    ire_t *, ire, nce_t *, nce);
27842 		ASSERT(nce->nce_state != ND_INITIAL);
27843 		mutex_enter(&nce->nce_lock);
27844 		nce->nce_last = TICK_TO_MSEC(lbolt64);
27845 		if (nce->nce_state == ND_REACHABLE) {
27846 			/*
27847 			 * Someone resolved this before us;
27848 			 * our response is not needed any more.
27849 			 */
27850 			mutex_exit(&nce->nce_lock);
27851 			freeb(mp1);  /* dl_unitdata response */
27852 		} else {
27853 			ASSERT(nce->nce_res_mp == NULL);
27854 			nce->nce_res_mp = mp1;
27855 			nce->nce_state = ND_REACHABLE;
27856 			mutex_exit(&nce->nce_lock);
27857 			nce_fastpath(nce);
27858 		}
27859 		/*
27860 		 * The cached nce_t has been updated to be reachable;
27861 		 * Clear the IRE_MARK_UNCACHED flag and free the fake_ire.
27862 		 */
27863 		fake_ire->ire_marks &= ~IRE_MARK_UNCACHED;
27864 		freemsg(mp);
27865 		/*
27866 		 * send out queued packets.
27867 		 */
27868 		(void) ip_xmit_v4(NULL, ire, NULL, B_FALSE);
27869 
27870 		IRE_REFRELE(ire);
27871 		return;
27872 	}
27873 	default:
27874 		break;
27875 	}
27876 	if (q->q_next) {
27877 		putnext(q, mp);
27878 	} else
27879 		freemsg(mp);
27880 	return;
27881 
27882 protonak:
27883 	cmn_err(CE_NOTE, "IP doesn't process %s as a module", proto_str);
27884 	if ((mp = mi_tpi_err_ack_alloc(mp, TPROTO, EINVAL)) != NULL)
27885 		qreply(q, mp);
27886 }
27887 
27888 /*
27889  * Process IP options in an outbound packet.  Modify the destination if there
27890  * is a source route option.
27891  * Returns non-zero if something fails in which case an ICMP error has been
27892  * sent and mp freed.
27893  */
27894 static int
27895 ip_wput_options(queue_t *q, mblk_t *ipsec_mp, ipha_t *ipha,
27896     boolean_t mctl_present, zoneid_t zoneid, ip_stack_t *ipst)
27897 {
27898 	ipoptp_t	opts;
27899 	uchar_t		*opt;
27900 	uint8_t		optval;
27901 	uint8_t		optlen;
27902 	ipaddr_t	dst;
27903 	intptr_t	code = 0;
27904 	mblk_t		*mp;
27905 	ire_t		*ire = NULL;
27906 
27907 	ip2dbg(("ip_wput_options\n"));
27908 	mp = ipsec_mp;
27909 	if (mctl_present) {
27910 		mp = ipsec_mp->b_cont;
27911 	}
27912 
27913 	dst = ipha->ipha_dst;
27914 	for (optval = ipoptp_first(&opts, ipha);
27915 	    optval != IPOPT_EOL;
27916 	    optval = ipoptp_next(&opts)) {
27917 		opt = opts.ipoptp_cur;
27918 		optlen = opts.ipoptp_len;
27919 		ip2dbg(("ip_wput_options: opt %d, len %d\n",
27920 		    optval, optlen));
27921 		switch (optval) {
27922 			uint32_t off;
27923 		case IPOPT_SSRR:
27924 		case IPOPT_LSRR:
27925 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27926 				ip1dbg((
27927 				    "ip_wput_options: bad option offset\n"));
27928 				code = (char *)&opt[IPOPT_OLEN] -
27929 				    (char *)ipha;
27930 				goto param_prob;
27931 			}
27932 			off = opt[IPOPT_OFFSET];
27933 			ip1dbg(("ip_wput_options: next hop 0x%x\n",
27934 			    ntohl(dst)));
27935 			/*
27936 			 * For strict: verify that dst is directly
27937 			 * reachable.
27938 			 */
27939 			if (optval == IPOPT_SSRR) {
27940 				ire = ire_ftable_lookup(dst, 0, 0,
27941 				    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0,
27942 				    MBLK_GETLABEL(mp),
27943 				    MATCH_IRE_TYPE | MATCH_IRE_SECATTR, ipst);
27944 				if (ire == NULL) {
27945 					ip1dbg(("ip_wput_options: SSRR not"
27946 					    " directly reachable: 0x%x\n",
27947 					    ntohl(dst)));
27948 					goto bad_src_route;
27949 				}
27950 				ire_refrele(ire);
27951 			}
27952 			break;
27953 		case IPOPT_RR:
27954 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27955 				ip1dbg((
27956 				    "ip_wput_options: bad option offset\n"));
27957 				code = (char *)&opt[IPOPT_OLEN] -
27958 				    (char *)ipha;
27959 				goto param_prob;
27960 			}
27961 			break;
27962 		case IPOPT_TS:
27963 			/*
27964 			 * Verify that length >=5 and that there is either
27965 			 * room for another timestamp or that the overflow
27966 			 * counter is not maxed out.
27967 			 */
27968 			code = (char *)&opt[IPOPT_OLEN] - (char *)ipha;
27969 			if (optlen < IPOPT_MINLEN_IT) {
27970 				goto param_prob;
27971 			}
27972 			if ((opts.ipoptp_flags & IPOPTP_ERROR) != 0) {
27973 				ip1dbg((
27974 				    "ip_wput_options: bad option offset\n"));
27975 				code = (char *)&opt[IPOPT_OFFSET] -
27976 				    (char *)ipha;
27977 				goto param_prob;
27978 			}
27979 			switch (opt[IPOPT_POS_OV_FLG] & 0x0F) {
27980 			case IPOPT_TS_TSONLY:
27981 				off = IPOPT_TS_TIMELEN;
27982 				break;
27983 			case IPOPT_TS_TSANDADDR:
27984 			case IPOPT_TS_PRESPEC:
27985 			case IPOPT_TS_PRESPEC_RFC791:
27986 				off = IP_ADDR_LEN + IPOPT_TS_TIMELEN;
27987 				break;
27988 			default:
27989 				code = (char *)&opt[IPOPT_POS_OV_FLG] -
27990 				    (char *)ipha;
27991 				goto param_prob;
27992 			}
27993 			if (opt[IPOPT_OFFSET] - 1 + off > optlen &&
27994 			    (opt[IPOPT_POS_OV_FLG] & 0xF0) == 0xF0) {
27995 				/*
27996 				 * No room and the overflow counter is 15
27997 				 * already.
27998 				 */
27999 				goto param_prob;
28000 			}
28001 			break;
28002 		}
28003 	}
28004 
28005 	if ((opts.ipoptp_flags & IPOPTP_ERROR) == 0)
28006 		return (0);
28007 
28008 	ip1dbg(("ip_wput_options: error processing IP options."));
28009 	code = (char *)&opt[IPOPT_OFFSET] - (char *)ipha;
28010 
28011 param_prob:
28012 	/*
28013 	 * Since ip_wput() isn't close to finished, we fill
28014 	 * in enough of the header for credible error reporting.
28015 	 */
28016 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28017 		/* Failed */
28018 		freemsg(ipsec_mp);
28019 		return (-1);
28020 	}
28021 	icmp_param_problem(q, ipsec_mp, (uint8_t)code, zoneid, ipst);
28022 	return (-1);
28023 
28024 bad_src_route:
28025 	/*
28026 	 * Since ip_wput() isn't close to finished, we fill
28027 	 * in enough of the header for credible error reporting.
28028 	 */
28029 	if (ip_hdr_complete((ipha_t *)mp->b_rptr, zoneid, ipst)) {
28030 		/* Failed */
28031 		freemsg(ipsec_mp);
28032 		return (-1);
28033 	}
28034 	icmp_unreachable(q, ipsec_mp, ICMP_SOURCE_ROUTE_FAILED, zoneid, ipst);
28035 	return (-1);
28036 }
28037 
28038 /*
28039  * The maximum value of conn_drain_list_cnt is CONN_MAXDRAINCNT.
28040  * conn_drain_list_cnt can be changed by setting conn_drain_nthreads
28041  * thru /etc/system.
28042  */
28043 #define	CONN_MAXDRAINCNT	64
28044 
28045 static void
28046 conn_drain_init(ip_stack_t *ipst)
28047 {
28048 	int i;
28049 
28050 	ipst->ips_conn_drain_list_cnt = conn_drain_nthreads;
28051 
28052 	if ((ipst->ips_conn_drain_list_cnt == 0) ||
28053 	    (ipst->ips_conn_drain_list_cnt > CONN_MAXDRAINCNT)) {
28054 		/*
28055 		 * Default value of the number of drainers is the
28056 		 * number of cpus, subject to maximum of 8 drainers.
28057 		 */
28058 		if (boot_max_ncpus != -1)
28059 			ipst->ips_conn_drain_list_cnt = MIN(boot_max_ncpus, 8);
28060 		else
28061 			ipst->ips_conn_drain_list_cnt = MIN(max_ncpus, 8);
28062 	}
28063 
28064 	ipst->ips_conn_drain_list = kmem_zalloc(ipst->ips_conn_drain_list_cnt *
28065 	    sizeof (idl_t), KM_SLEEP);
28066 
28067 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28068 		mutex_init(&ipst->ips_conn_drain_list[i].idl_lock, NULL,
28069 		    MUTEX_DEFAULT, NULL);
28070 	}
28071 }
28072 
28073 static void
28074 conn_drain_fini(ip_stack_t *ipst)
28075 {
28076 	int i;
28077 
28078 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++)
28079 		mutex_destroy(&ipst->ips_conn_drain_list[i].idl_lock);
28080 	kmem_free(ipst->ips_conn_drain_list,
28081 	    ipst->ips_conn_drain_list_cnt * sizeof (idl_t));
28082 	ipst->ips_conn_drain_list = NULL;
28083 }
28084 
28085 /*
28086  * Note: For an overview of how flowcontrol is handled in IP please see the
28087  * IP Flowcontrol notes at the top of this file.
28088  *
28089  * Flow control has blocked us from proceeding. Insert the given conn in one
28090  * of the conn drain lists. These conn wq's will be qenabled later on when
28091  * STREAMS flow control does a backenable. conn_walk_drain will enable
28092  * the first conn in each of these drain lists. Each of these qenabled conns
28093  * in turn enables the next in the list, after it runs, or when it closes,
28094  * thus sustaining the drain process.
28095  *
28096  * The only possible calling sequence is ip_wsrv (on conn) -> ip_wput ->
28097  * conn_drain_insert. Thus there can be only 1 instance of conn_drain_insert
28098  * running at any time, on a given conn, since there can be only 1 service proc
28099  * running on a queue at any time.
28100  */
28101 void
28102 conn_drain_insert(conn_t *connp)
28103 {
28104 	idl_t	*idl;
28105 	uint_t	index;
28106 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28107 
28108 	mutex_enter(&connp->conn_lock);
28109 	if (connp->conn_state_flags & CONN_CLOSING) {
28110 		/*
28111 		 * The conn is closing as a result of which CONN_CLOSING
28112 		 * is set. Return.
28113 		 */
28114 		mutex_exit(&connp->conn_lock);
28115 		return;
28116 	} else if (connp->conn_idl == NULL) {
28117 		/*
28118 		 * Assign the next drain list round robin. We dont' use
28119 		 * a lock, and thus it may not be strictly round robin.
28120 		 * Atomicity of load/stores is enough to make sure that
28121 		 * conn_drain_list_index is always within bounds.
28122 		 */
28123 		index = ipst->ips_conn_drain_list_index;
28124 		ASSERT(index < ipst->ips_conn_drain_list_cnt);
28125 		connp->conn_idl = &ipst->ips_conn_drain_list[index];
28126 		index++;
28127 		if (index == ipst->ips_conn_drain_list_cnt)
28128 			index = 0;
28129 		ipst->ips_conn_drain_list_index = index;
28130 	}
28131 	mutex_exit(&connp->conn_lock);
28132 
28133 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28134 	if ((connp->conn_drain_prev != NULL) ||
28135 	    (connp->conn_state_flags & CONN_CLOSING)) {
28136 		/*
28137 		 * The conn is already in the drain list, OR
28138 		 * the conn is closing. We need to check again for
28139 		 * the closing case again since close can happen
28140 		 * after we drop the conn_lock, and before we
28141 		 * acquire the CONN_DRAIN_LIST_LOCK.
28142 		 */
28143 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28144 		return;
28145 	} else {
28146 		idl = connp->conn_idl;
28147 	}
28148 
28149 	/*
28150 	 * The conn is not in the drain list. Insert it at the
28151 	 * tail of the drain list. The drain list is circular
28152 	 * and doubly linked. idl_conn points to the 1st element
28153 	 * in the list.
28154 	 */
28155 	if (idl->idl_conn == NULL) {
28156 		idl->idl_conn = connp;
28157 		connp->conn_drain_next = connp;
28158 		connp->conn_drain_prev = connp;
28159 	} else {
28160 		conn_t *head = idl->idl_conn;
28161 
28162 		connp->conn_drain_next = head;
28163 		connp->conn_drain_prev = head->conn_drain_prev;
28164 		head->conn_drain_prev->conn_drain_next = connp;
28165 		head->conn_drain_prev = connp;
28166 	}
28167 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28168 }
28169 
28170 /*
28171  * This conn is closing, and we are called from ip_close. OR
28172  * This conn has been serviced by ip_wsrv, and we need to do the tail
28173  * processing.
28174  * If this conn is part of the drain list, we may need to sustain the drain
28175  * process by qenabling the next conn in the drain list. We may also need to
28176  * remove this conn from the list, if it is done.
28177  */
28178 static void
28179 conn_drain_tail(conn_t *connp, boolean_t closing)
28180 {
28181 	idl_t *idl;
28182 
28183 	/*
28184 	 * connp->conn_idl is stable at this point, and no lock is needed
28185 	 * to check it. If we are called from ip_close, close has already
28186 	 * set CONN_CLOSING, thus freezing the value of conn_idl, and
28187 	 * called us only because conn_idl is non-null. If we are called thru
28188 	 * service, conn_idl could be null, but it cannot change because
28189 	 * service is single-threaded per queue, and there cannot be another
28190 	 * instance of service trying to call conn_drain_insert on this conn
28191 	 * now.
28192 	 */
28193 	ASSERT(!closing || (connp->conn_idl != NULL));
28194 
28195 	/*
28196 	 * If connp->conn_idl is null, the conn has not been inserted into any
28197 	 * drain list even once since creation of the conn. Just return.
28198 	 */
28199 	if (connp->conn_idl == NULL)
28200 		return;
28201 
28202 	mutex_enter(CONN_DRAIN_LIST_LOCK(connp));
28203 
28204 	if (connp->conn_drain_prev == NULL) {
28205 		/* This conn is currently not in the drain list.  */
28206 		mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28207 		return;
28208 	}
28209 	idl = connp->conn_idl;
28210 	if (idl->idl_conn_draining == connp) {
28211 		/*
28212 		 * This conn is the current drainer. If this is the last conn
28213 		 * in the drain list, we need to do more checks, in the 'if'
28214 		 * below. Otherwwise we need to just qenable the next conn,
28215 		 * to sustain the draining, and is handled in the 'else'
28216 		 * below.
28217 		 */
28218 		if (connp->conn_drain_next == idl->idl_conn) {
28219 			/*
28220 			 * This conn is the last in this list. This round
28221 			 * of draining is complete. If idl_repeat is set,
28222 			 * it means another flow enabling has happened from
28223 			 * the driver/streams and we need to another round
28224 			 * of draining.
28225 			 * If there are more than 2 conns in the drain list,
28226 			 * do a left rotate by 1, so that all conns except the
28227 			 * conn at the head move towards the head by 1, and the
28228 			 * the conn at the head goes to the tail. This attempts
28229 			 * a more even share for all queues that are being
28230 			 * drained.
28231 			 */
28232 			if ((connp->conn_drain_next != connp) &&
28233 			    (idl->idl_conn->conn_drain_next != connp)) {
28234 				idl->idl_conn = idl->idl_conn->conn_drain_next;
28235 			}
28236 			if (idl->idl_repeat) {
28237 				qenable(idl->idl_conn->conn_wq);
28238 				idl->idl_conn_draining = idl->idl_conn;
28239 				idl->idl_repeat = 0;
28240 			} else {
28241 				idl->idl_conn_draining = NULL;
28242 			}
28243 		} else {
28244 			/*
28245 			 * If the next queue that we are now qenable'ing,
28246 			 * is closing, it will remove itself from this list
28247 			 * and qenable the subsequent queue in ip_close().
28248 			 * Serialization is acheived thru idl_lock.
28249 			 */
28250 			qenable(connp->conn_drain_next->conn_wq);
28251 			idl->idl_conn_draining = connp->conn_drain_next;
28252 		}
28253 	}
28254 	if (!connp->conn_did_putbq || closing) {
28255 		/*
28256 		 * Remove ourself from the drain list, if we did not do
28257 		 * a putbq, or if the conn is closing.
28258 		 * Note: It is possible that q->q_first is non-null. It means
28259 		 * that these messages landed after we did a enableok() in
28260 		 * ip_wsrv. Thus STREAMS will call ip_wsrv once again to
28261 		 * service them.
28262 		 */
28263 		if (connp->conn_drain_next == connp) {
28264 			/* Singleton in the list */
28265 			ASSERT(connp->conn_drain_prev == connp);
28266 			idl->idl_conn = NULL;
28267 			idl->idl_conn_draining = NULL;
28268 		} else {
28269 			connp->conn_drain_prev->conn_drain_next =
28270 			    connp->conn_drain_next;
28271 			connp->conn_drain_next->conn_drain_prev =
28272 			    connp->conn_drain_prev;
28273 			if (idl->idl_conn == connp)
28274 				idl->idl_conn = connp->conn_drain_next;
28275 			ASSERT(idl->idl_conn_draining != connp);
28276 
28277 		}
28278 		connp->conn_drain_next = NULL;
28279 		connp->conn_drain_prev = NULL;
28280 	}
28281 	mutex_exit(CONN_DRAIN_LIST_LOCK(connp));
28282 }
28283 
28284 /*
28285  * Write service routine. Shared perimeter entry point.
28286  * ip_wsrv can be called in any of the following ways.
28287  * 1. The device queue's messages has fallen below the low water mark
28288  *    and STREAMS has backenabled the ill_wq. We walk thru all the
28289  *    the drain lists and backenable the first conn in each list.
28290  * 2. The above causes STREAMS to run ip_wsrv on the conn_wq of the
28291  *    qenabled non-tcp upper layers. We start dequeing messages and call
28292  *    ip_wput for each message.
28293  */
28294 
28295 void
28296 ip_wsrv(queue_t *q)
28297 {
28298 	conn_t	*connp;
28299 	ill_t	*ill;
28300 	mblk_t	*mp;
28301 
28302 	if (q->q_next) {
28303 		ill = (ill_t *)q->q_ptr;
28304 		if (ill->ill_state_flags == 0) {
28305 			/*
28306 			 * The device flow control has opened up.
28307 			 * Walk through conn drain lists and qenable the
28308 			 * first conn in each list. This makes sense only
28309 			 * if the stream is fully plumbed and setup.
28310 			 * Hence the if check above.
28311 			 */
28312 			ip1dbg(("ip_wsrv: walking\n"));
28313 			conn_walk_drain(ill->ill_ipst);
28314 		}
28315 		return;
28316 	}
28317 
28318 	connp = Q_TO_CONN(q);
28319 	ip1dbg(("ip_wsrv: %p %p\n", (void *)q, (void *)connp));
28320 
28321 	/*
28322 	 * 1. Set conn_draining flag to signal that service is active.
28323 	 *
28324 	 * 2. ip_output determines whether it has been called from service,
28325 	 *    based on the last parameter. If it is IP_WSRV it concludes it
28326 	 *    has been called from service.
28327 	 *
28328 	 * 3. Message ordering is preserved by the following logic.
28329 	 *    i. A directly called ip_output (i.e. not thru service) will queue
28330 	 *    the message at the tail, if conn_draining is set (i.e. service
28331 	 *    is running) or if q->q_first is non-null.
28332 	 *
28333 	 *    ii. If ip_output is called from service, and if ip_output cannot
28334 	 *    putnext due to flow control, it does a putbq.
28335 	 *
28336 	 * 4. noenable the queue so that a putbq from ip_wsrv does not reenable
28337 	 *    (causing an infinite loop).
28338 	 */
28339 	ASSERT(!connp->conn_did_putbq);
28340 	while ((q->q_first != NULL) && !connp->conn_did_putbq) {
28341 		connp->conn_draining = 1;
28342 		noenable(q);
28343 		while ((mp = getq(q)) != NULL) {
28344 			ASSERT(CONN_Q(q));
28345 
28346 			ip_output(Q_TO_CONN(q), mp, q, IP_WSRV);
28347 			if (connp->conn_did_putbq) {
28348 				/* ip_wput did a putbq */
28349 				break;
28350 			}
28351 		}
28352 		/*
28353 		 * At this point, a thread coming down from top, calling
28354 		 * ip_wput, may end up queueing the message. We have not yet
28355 		 * enabled the queue, so ip_wsrv won't be called again.
28356 		 * To avoid this race, check q->q_first again (in the loop)
28357 		 * If the other thread queued the message before we call
28358 		 * enableok(), we will catch it in the q->q_first check.
28359 		 * If the other thread queues the message after we call
28360 		 * enableok(), ip_wsrv will be called again by STREAMS.
28361 		 */
28362 		connp->conn_draining = 0;
28363 		enableok(q);
28364 	}
28365 
28366 	/* Enable the next conn for draining */
28367 	conn_drain_tail(connp, B_FALSE);
28368 
28369 	connp->conn_did_putbq = 0;
28370 }
28371 
28372 /*
28373  * Walk the list of all conn's calling the function provided with the
28374  * specified argument for each.	 Note that this only walks conn's that
28375  * have been bound.
28376  * Applies to both IPv4 and IPv6.
28377  */
28378 static void
28379 conn_walk_fanout(pfv_t func, void *arg, zoneid_t zoneid, ip_stack_t *ipst)
28380 {
28381 	conn_walk_fanout_table(ipst->ips_ipcl_udp_fanout,
28382 	    ipst->ips_ipcl_udp_fanout_size,
28383 	    func, arg, zoneid);
28384 	conn_walk_fanout_table(ipst->ips_ipcl_conn_fanout,
28385 	    ipst->ips_ipcl_conn_fanout_size,
28386 	    func, arg, zoneid);
28387 	conn_walk_fanout_table(ipst->ips_ipcl_bind_fanout,
28388 	    ipst->ips_ipcl_bind_fanout_size,
28389 	    func, arg, zoneid);
28390 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout,
28391 	    IPPROTO_MAX, func, arg, zoneid);
28392 	conn_walk_fanout_table(ipst->ips_ipcl_proto_fanout_v6,
28393 	    IPPROTO_MAX, func, arg, zoneid);
28394 }
28395 
28396 /*
28397  * Flowcontrol has relieved, and STREAMS has backenabled us. For each list
28398  * of conns that need to be drained, check if drain is already in progress.
28399  * If so set the idl_repeat bit, indicating that the last conn in the list
28400  * needs to reinitiate the drain once again, for the list. If drain is not
28401  * in progress for the list, initiate the draining, by qenabling the 1st
28402  * conn in the list. The drain is self-sustaining, each qenabled conn will
28403  * in turn qenable the next conn, when it is done/blocked/closing.
28404  */
28405 static void
28406 conn_walk_drain(ip_stack_t *ipst)
28407 {
28408 	int i;
28409 	idl_t *idl;
28410 
28411 	IP_STAT(ipst, ip_conn_walk_drain);
28412 
28413 	for (i = 0; i < ipst->ips_conn_drain_list_cnt; i++) {
28414 		idl = &ipst->ips_conn_drain_list[i];
28415 		mutex_enter(&idl->idl_lock);
28416 		if (idl->idl_conn == NULL) {
28417 			mutex_exit(&idl->idl_lock);
28418 			continue;
28419 		}
28420 		/*
28421 		 * If this list is not being drained currently by
28422 		 * an ip_wsrv thread, start the process.
28423 		 */
28424 		if (idl->idl_conn_draining == NULL) {
28425 			ASSERT(idl->idl_repeat == 0);
28426 			qenable(idl->idl_conn->conn_wq);
28427 			idl->idl_conn_draining = idl->idl_conn;
28428 		} else {
28429 			idl->idl_repeat = 1;
28430 		}
28431 		mutex_exit(&idl->idl_lock);
28432 	}
28433 }
28434 
28435 /*
28436  * Walk an conn hash table of `count' buckets, calling func for each entry.
28437  */
28438 static void
28439 conn_walk_fanout_table(connf_t *connfp, uint_t count, pfv_t func, void *arg,
28440     zoneid_t zoneid)
28441 {
28442 	conn_t	*connp;
28443 
28444 	while (count-- > 0) {
28445 		mutex_enter(&connfp->connf_lock);
28446 		for (connp = connfp->connf_head; connp != NULL;
28447 		    connp = connp->conn_next) {
28448 			if (zoneid == GLOBAL_ZONEID ||
28449 			    zoneid == connp->conn_zoneid) {
28450 				CONN_INC_REF(connp);
28451 				mutex_exit(&connfp->connf_lock);
28452 				(*func)(connp, arg);
28453 				mutex_enter(&connfp->connf_lock);
28454 				CONN_DEC_REF(connp);
28455 			}
28456 		}
28457 		mutex_exit(&connfp->connf_lock);
28458 		connfp++;
28459 	}
28460 }
28461 
28462 /* conn_walk_fanout routine invoked for ip_conn_report for each conn. */
28463 static void
28464 conn_report1(conn_t *connp, void *mp)
28465 {
28466 	char	buf1[INET6_ADDRSTRLEN];
28467 	char	buf2[INET6_ADDRSTRLEN];
28468 	uint_t	print_len, buf_len;
28469 
28470 	ASSERT(connp != NULL);
28471 
28472 	buf_len = ((mblk_t *)mp)->b_datap->db_lim - ((mblk_t *)mp)->b_wptr;
28473 	if (buf_len <= 0)
28474 		return;
28475 	(void) inet_ntop(AF_INET6, &connp->conn_srcv6, buf1, sizeof (buf1));
28476 	(void) inet_ntop(AF_INET6, &connp->conn_remv6, buf2, sizeof (buf2));
28477 	print_len = snprintf((char *)((mblk_t *)mp)->b_wptr, buf_len,
28478 	    MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR MI_COL_PTRFMT_STR
28479 	    "%5d %s/%05d %s/%05d\n",
28480 	    (void *)connp, (void *)CONNP_TO_RQ(connp),
28481 	    (void *)CONNP_TO_WQ(connp), connp->conn_zoneid,
28482 	    buf1, connp->conn_lport,
28483 	    buf2, connp->conn_fport);
28484 	if (print_len < buf_len) {
28485 		((mblk_t *)mp)->b_wptr += print_len;
28486 	} else {
28487 		((mblk_t *)mp)->b_wptr += buf_len;
28488 	}
28489 }
28490 
28491 /*
28492  * Named Dispatch routine to produce a formatted report on all conns
28493  * that are listed in one of the fanout tables.
28494  * This report is accessed by using the ndd utility to "get" ND variable
28495  * "ip_conn_status".
28496  */
28497 /* ARGSUSED */
28498 static int
28499 ip_conn_report(queue_t *q, mblk_t *mp, caddr_t arg, cred_t *ioc_cr)
28500 {
28501 	conn_t *connp = Q_TO_CONN(q);
28502 
28503 	(void) mi_mpprintf(mp,
28504 	    "CONN      " MI_COL_HDRPAD_STR
28505 	    "rfq      " MI_COL_HDRPAD_STR
28506 	    "stq      " MI_COL_HDRPAD_STR
28507 	    " zone local                 remote");
28508 
28509 	/*
28510 	 * Because of the ndd constraint, at most we can have 64K buffer
28511 	 * to put in all conn info.  So to be more efficient, just
28512 	 * allocate a 64K buffer here, assuming we need that large buffer.
28513 	 * This should be OK as only privileged processes can do ndd /dev/ip.
28514 	 */
28515 	if ((mp->b_cont = allocb(ND_MAX_BUF_LEN, BPRI_HI)) == NULL) {
28516 		/* The following may work even if we cannot get a large buf. */
28517 		(void) mi_mpprintf(mp, "<< Out of buffer >>\n");
28518 		return (0);
28519 	}
28520 
28521 	conn_walk_fanout(conn_report1, mp->b_cont, connp->conn_zoneid,
28522 	    connp->conn_netstack->netstack_ip);
28523 	return (0);
28524 }
28525 
28526 /*
28527  * Determine if the ill and multicast aspects of that packets
28528  * "matches" the conn.
28529  */
28530 boolean_t
28531 conn_wantpacket(conn_t *connp, ill_t *ill, ipha_t *ipha, int fanout_flags,
28532     zoneid_t zoneid)
28533 {
28534 	ill_t *in_ill;
28535 	boolean_t found;
28536 	ipif_t *ipif;
28537 	ire_t *ire;
28538 	ipaddr_t dst, src;
28539 	ip_stack_t	*ipst = connp->conn_netstack->netstack_ip;
28540 
28541 	dst = ipha->ipha_dst;
28542 	src = ipha->ipha_src;
28543 
28544 	/*
28545 	 * conn_incoming_ill is set by IP_BOUND_IF which limits
28546 	 * unicast, broadcast and multicast reception to
28547 	 * conn_incoming_ill. conn_wantpacket itself is called
28548 	 * only for BROADCAST and multicast.
28549 	 *
28550 	 * 1) ip_rput supresses duplicate broadcasts if the ill
28551 	 *    is part of a group. Hence, we should be receiving
28552 	 *    just one copy of broadcast for the whole group.
28553 	 *    Thus, if it is part of the group the packet could
28554 	 *    come on any ill of the group and hence we need a
28555 	 *    match on the group. Otherwise, match on ill should
28556 	 *    be sufficient.
28557 	 *
28558 	 * 2) ip_rput does not suppress duplicate multicast packets.
28559 	 *    If there are two interfaces in a ill group and we have
28560 	 *    2 applications (conns) joined a multicast group G on
28561 	 *    both the interfaces, ilm_lookup_ill filter in ip_rput
28562 	 *    will give us two packets because we join G on both the
28563 	 *    interfaces rather than nominating just one interface
28564 	 *    for receiving multicast like broadcast above. So,
28565 	 *    we have to call ilg_lookup_ill to filter out duplicate
28566 	 *    copies, if ill is part of a group.
28567 	 */
28568 	in_ill = connp->conn_incoming_ill;
28569 	if (in_ill != NULL) {
28570 		if (in_ill->ill_group == NULL) {
28571 			if (in_ill != ill)
28572 				return (B_FALSE);
28573 		} else if (in_ill->ill_group != ill->ill_group) {
28574 			return (B_FALSE);
28575 		}
28576 	}
28577 
28578 	if (!CLASSD(dst)) {
28579 		if (IPCL_ZONE_MATCH(connp, zoneid))
28580 			return (B_TRUE);
28581 		/*
28582 		 * The conn is in a different zone; we need to check that this
28583 		 * broadcast address is configured in the application's zone and
28584 		 * on one ill in the group.
28585 		 */
28586 		ipif = ipif_get_next_ipif(NULL, ill);
28587 		if (ipif == NULL)
28588 			return (B_FALSE);
28589 		ire = ire_ctable_lookup(dst, 0, IRE_BROADCAST, ipif,
28590 		    connp->conn_zoneid, NULL,
28591 		    (MATCH_IRE_TYPE | MATCH_IRE_ILL_GROUP), ipst);
28592 		ipif_refrele(ipif);
28593 		if (ire != NULL) {
28594 			ire_refrele(ire);
28595 			return (B_TRUE);
28596 		} else {
28597 			return (B_FALSE);
28598 		}
28599 	}
28600 
28601 	if ((fanout_flags & IP_FF_NO_MCAST_LOOP) &&
28602 	    connp->conn_zoneid == zoneid) {
28603 		/*
28604 		 * Loopback case: the sending endpoint has IP_MULTICAST_LOOP
28605 		 * disabled, therefore we don't dispatch the multicast packet to
28606 		 * the sending zone.
28607 		 */
28608 		return (B_FALSE);
28609 	}
28610 
28611 	if (IS_LOOPBACK(ill) && connp->conn_zoneid != zoneid) {
28612 		/*
28613 		 * Multicast packet on the loopback interface: we only match
28614 		 * conns who joined the group in the specified zone.
28615 		 */
28616 		return (B_FALSE);
28617 	}
28618 
28619 	if (connp->conn_multi_router) {
28620 		/* multicast packet and multicast router socket: send up */
28621 		return (B_TRUE);
28622 	}
28623 
28624 	mutex_enter(&connp->conn_lock);
28625 	found = (ilg_lookup_ill_withsrc(connp, dst, src, ill) != NULL);
28626 	mutex_exit(&connp->conn_lock);
28627 	return (found);
28628 }
28629 
28630 /*
28631  * Finish processing of "arp_up" when AR_DLPIOP_DONE is received from arp.
28632  */
28633 /* ARGSUSED */
28634 static void
28635 ip_arp_done(ipsq_t *dummy_sq, queue_t *q, mblk_t *mp, void *dummy_arg)
28636 {
28637 	ill_t *ill = (ill_t *)q->q_ptr;
28638 	mblk_t	*mp1, *mp2;
28639 	ipif_t  *ipif;
28640 	int err = 0;
28641 	conn_t *connp = NULL;
28642 	ipsq_t	*ipsq;
28643 	arc_t	*arc;
28644 
28645 	ip1dbg(("ip_arp_done(%s)\n", ill->ill_name));
28646 
28647 	ASSERT((mp->b_wptr - mp->b_rptr) >= sizeof (arc_t));
28648 	ASSERT(((arc_t *)mp->b_rptr)->arc_cmd == AR_DLPIOP_DONE);
28649 
28650 	ASSERT(IAM_WRITER_ILL(ill));
28651 	mp2 = mp->b_cont;
28652 	mp->b_cont = NULL;
28653 
28654 	/*
28655 	 * We have now received the arp bringup completion message
28656 	 * from ARP. Mark the arp bringup as done. Also if the arp
28657 	 * stream has already started closing, send up the AR_ARP_CLOSING
28658 	 * ack now since ARP is waiting in close for this ack.
28659 	 */
28660 	mutex_enter(&ill->ill_lock);
28661 	ill->ill_arp_bringup_pending = 0;
28662 	if (ill->ill_arp_closing) {
28663 		mutex_exit(&ill->ill_lock);
28664 		/* Let's reuse the mp for sending the ack */
28665 		arc = (arc_t *)mp->b_rptr;
28666 		mp->b_wptr = mp->b_rptr + sizeof (arc_t);
28667 		arc->arc_cmd = AR_ARP_CLOSING;
28668 		qreply(q, mp);
28669 	} else {
28670 		mutex_exit(&ill->ill_lock);
28671 		freeb(mp);
28672 	}
28673 
28674 	ipsq = ill->ill_phyint->phyint_ipsq;
28675 	ipif = ipsq->ipsq_pending_ipif;
28676 	mp1 = ipsq_pending_mp_get(ipsq, &connp);
28677 	ASSERT(!((mp1 != NULL) ^ (ipif != NULL)));
28678 	if (mp1 == NULL) {
28679 		/* bringup was aborted by the user */
28680 		freemsg(mp2);
28681 		return;
28682 	}
28683 
28684 	/*
28685 	 * If an IOCTL is waiting on this (ipsq_current_ioctl != 0), then we
28686 	 * must have an associated conn_t.  Otherwise, we're bringing this
28687 	 * interface back up as part of handling an asynchronous event (e.g.,
28688 	 * physical address change).
28689 	 */
28690 	if (ipsq->ipsq_current_ioctl != 0) {
28691 		ASSERT(connp != NULL);
28692 		q = CONNP_TO_WQ(connp);
28693 	} else {
28694 		ASSERT(connp == NULL);
28695 		q = ill->ill_rq;
28696 	}
28697 
28698 	/*
28699 	 * If the DL_BIND_REQ fails, it is noted
28700 	 * in arc_name_offset.
28701 	 */
28702 	err = *((int *)mp2->b_rptr);
28703 	if (err == 0) {
28704 		if (ipif->ipif_isv6) {
28705 			if ((err = ipif_up_done_v6(ipif)) != 0)
28706 				ip0dbg(("ip_arp_done: init failed\n"));
28707 		} else {
28708 			if ((err = ipif_up_done(ipif)) != 0)
28709 				ip0dbg(("ip_arp_done: init failed\n"));
28710 		}
28711 	} else {
28712 		ip0dbg(("ip_arp_done: DL_BIND_REQ failed\n"));
28713 	}
28714 
28715 	freemsg(mp2);
28716 
28717 	if ((err == 0) && (ill->ill_up_ipifs)) {
28718 		err = ill_up_ipifs(ill, q, mp1);
28719 		if (err == EINPROGRESS)
28720 			return;
28721 	}
28722 
28723 	if (ill->ill_up_ipifs)
28724 		ill_group_cleanup(ill);
28725 
28726 	/*
28727 	 * The operation must complete without EINPROGRESS since
28728 	 * ipsq_pending_mp_get() has removed the mblk from ipsq_pending_mp.
28729 	 * Otherwise, the operation will be stuck forever in the ipsq.
28730 	 */
28731 	ASSERT(err != EINPROGRESS);
28732 	if (ipsq->ipsq_current_ioctl != 0)
28733 		ip_ioctl_finish(q, mp1, err, NO_COPYOUT, ipsq);
28734 	else
28735 		ipsq_current_finish(ipsq);
28736 }
28737 
28738 /* Allocate the private structure */
28739 static int
28740 ip_priv_alloc(void **bufp)
28741 {
28742 	void	*buf;
28743 
28744 	if ((buf = kmem_alloc(sizeof (ip_priv_t), KM_NOSLEEP)) == NULL)
28745 		return (ENOMEM);
28746 
28747 	*bufp = buf;
28748 	return (0);
28749 }
28750 
28751 /* Function to delete the private structure */
28752 void
28753 ip_priv_free(void *buf)
28754 {
28755 	ASSERT(buf != NULL);
28756 	kmem_free(buf, sizeof (ip_priv_t));
28757 }
28758 
28759 /*
28760  * The entry point for IPPF processing.
28761  * If the classifier (IPGPC_CLASSIFY) is not loaded and configured, the
28762  * routine just returns.
28763  *
28764  * When called, ip_process generates an ipp_packet_t structure
28765  * which holds the state information for this packet and invokes the
28766  * the classifier (via ipp_packet_process). The classification, depending on
28767  * configured filters, results in a list of actions for this packet. Invoking
28768  * an action may cause the packet to be dropped, in which case the resulting
28769  * mblk (*mpp) is NULL. proc indicates the callout position for
28770  * this packet and ill_index is the interface this packet on or will leave
28771  * on (inbound and outbound resp.).
28772  */
28773 void
28774 ip_process(ip_proc_t proc, mblk_t **mpp, uint32_t ill_index)
28775 {
28776 	mblk_t		*mp;
28777 	ip_priv_t	*priv;
28778 	ipp_action_id_t	aid;
28779 	int		rc = 0;
28780 	ipp_packet_t	*pp;
28781 #define	IP_CLASS	"ip"
28782 
28783 	/* If the classifier is not loaded, return  */
28784 	if ((aid = ipp_action_lookup(IPGPC_CLASSIFY)) == IPP_ACTION_INVAL) {
28785 		return;
28786 	}
28787 
28788 	mp = *mpp;
28789 	ASSERT(mp != NULL);
28790 
28791 	/* Allocate the packet structure */
28792 	rc = ipp_packet_alloc(&pp, IP_CLASS, aid);
28793 	if (rc != 0) {
28794 		*mpp = NULL;
28795 		freemsg(mp);
28796 		return;
28797 	}
28798 
28799 	/* Allocate the private structure */
28800 	rc = ip_priv_alloc((void **)&priv);
28801 	if (rc != 0) {
28802 		*mpp = NULL;
28803 		freemsg(mp);
28804 		ipp_packet_free(pp);
28805 		return;
28806 	}
28807 	priv->proc = proc;
28808 	priv->ill_index = ill_index;
28809 	ipp_packet_set_private(pp, priv, ip_priv_free);
28810 	ipp_packet_set_data(pp, mp);
28811 
28812 	/* Invoke the classifier */
28813 	rc = ipp_packet_process(&pp);
28814 	if (pp != NULL) {
28815 		mp = ipp_packet_get_data(pp);
28816 		ipp_packet_free(pp);
28817 		if (rc != 0) {
28818 			freemsg(mp);
28819 			*mpp = NULL;
28820 		}
28821 	} else {
28822 		*mpp = NULL;
28823 	}
28824 #undef	IP_CLASS
28825 }
28826 
28827 /*
28828  * Propagate a multicast group membership operation (add/drop) on
28829  * all the interfaces crossed by the related multirt routes.
28830  * The call is considered successful if the operation succeeds
28831  * on at least one interface.
28832  */
28833 static int
28834 ip_multirt_apply_membership(int (*fn)(conn_t *, boolean_t, ipaddr_t, ipaddr_t,
28835     uint_t *, mcast_record_t, ipaddr_t, mblk_t *), ire_t *ire, conn_t *connp,
28836     boolean_t checkonly, ipaddr_t group, mcast_record_t fmode, ipaddr_t src,
28837     mblk_t *first_mp)
28838 {
28839 	ire_t		*ire_gw;
28840 	irb_t		*irb;
28841 	int		error = 0;
28842 	opt_restart_t	*or;
28843 	ip_stack_t	*ipst = ire->ire_ipst;
28844 
28845 	irb = ire->ire_bucket;
28846 	ASSERT(irb != NULL);
28847 
28848 	ASSERT(DB_TYPE(first_mp) == M_CTL);
28849 
28850 	or = (opt_restart_t *)first_mp->b_rptr;
28851 	IRB_REFHOLD(irb);
28852 	for (; ire != NULL; ire = ire->ire_next) {
28853 		if ((ire->ire_flags & RTF_MULTIRT) == 0)
28854 			continue;
28855 		if (ire->ire_addr != group)
28856 			continue;
28857 
28858 		ire_gw = ire_ftable_lookup(ire->ire_gateway_addr, 0, 0,
28859 		    IRE_INTERFACE, NULL, NULL, ALL_ZONES, 0, NULL,
28860 		    MATCH_IRE_RECURSIVE | MATCH_IRE_TYPE, ipst);
28861 		/* No resolver exists for the gateway; skip this ire. */
28862 		if (ire_gw == NULL)
28863 			continue;
28864 
28865 		/*
28866 		 * This function can return EINPROGRESS. If so the operation
28867 		 * will be restarted from ip_restart_optmgmt which will
28868 		 * call ip_opt_set and option processing will restart for
28869 		 * this option. So we may end up calling 'fn' more than once.
28870 		 * This requires that 'fn' is idempotent except for the
28871 		 * return value. The operation is considered a success if
28872 		 * it succeeds at least once on any one interface.
28873 		 */
28874 		error = fn(connp, checkonly, group, ire_gw->ire_src_addr,
28875 		    NULL, fmode, src, first_mp);
28876 		if (error == 0)
28877 			or->or_private = CGTP_MCAST_SUCCESS;
28878 
28879 		if (ip_debug > 0) {
28880 			ulong_t	off;
28881 			char	*ksym;
28882 			ksym = kobj_getsymname((uintptr_t)fn, &off);
28883 			ip2dbg(("ip_multirt_apply_membership: "
28884 			    "called %s, multirt group 0x%08x via itf 0x%08x, "
28885 			    "error %d [success %u]\n",
28886 			    ksym ? ksym : "?",
28887 			    ntohl(group), ntohl(ire_gw->ire_src_addr),
28888 			    error, or->or_private));
28889 		}
28890 
28891 		ire_refrele(ire_gw);
28892 		if (error == EINPROGRESS) {
28893 			IRB_REFRELE(irb);
28894 			return (error);
28895 		}
28896 	}
28897 	IRB_REFRELE(irb);
28898 	/*
28899 	 * Consider the call as successful if we succeeded on at least
28900 	 * one interface. Otherwise, return the last encountered error.
28901 	 */
28902 	return (or->or_private == CGTP_MCAST_SUCCESS ? 0 : error);
28903 }
28904 
28905 
28906 /*
28907  * Issue a warning regarding a route crossing an interface with an
28908  * incorrect MTU. Only one message every 'ip_multirt_log_interval'
28909  * amount of time is logged.
28910  */
28911 static void
28912 ip_multirt_bad_mtu(ire_t *ire, uint32_t max_frag)
28913 {
28914 	hrtime_t	current = gethrtime();
28915 	char		buf[INET_ADDRSTRLEN];
28916 	ip_stack_t	*ipst = ire->ire_ipst;
28917 
28918 	/* Convert interval in ms to hrtime in ns */
28919 	if (ipst->ips_multirt_bad_mtu_last_time +
28920 	    ((hrtime_t)ipst->ips_ip_multirt_log_interval * (hrtime_t)1000000) <=
28921 	    current) {
28922 		cmn_err(CE_WARN, "ip: ignoring multiroute "
28923 		    "to %s, incorrect MTU %u (expected %u)\n",
28924 		    ip_dot_addr(ire->ire_addr, buf),
28925 		    ire->ire_max_frag, max_frag);
28926 
28927 		ipst->ips_multirt_bad_mtu_last_time = current;
28928 	}
28929 }
28930 
28931 
28932 /*
28933  * Get the CGTP (multirouting) filtering status.
28934  * If 0, the CGTP hooks are transparent.
28935  */
28936 /* ARGSUSED */
28937 static int
28938 ip_cgtp_filter_get(queue_t *q, mblk_t *mp, caddr_t cp, cred_t *ioc_cr)
28939 {
28940 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28941 
28942 	(void) mi_mpprintf(mp, "%d", (int)*ip_cgtp_filter_value);
28943 	return (0);
28944 }
28945 
28946 
28947 /*
28948  * Set the CGTP (multirouting) filtering status.
28949  * If the status is changed from active to transparent
28950  * or from transparent to active, forward the new status
28951  * to the filtering module (if loaded).
28952  */
28953 /* ARGSUSED */
28954 static int
28955 ip_cgtp_filter_set(queue_t *q, mblk_t *mp, char *value, caddr_t cp,
28956     cred_t *ioc_cr)
28957 {
28958 	long		new_value;
28959 	boolean_t	*ip_cgtp_filter_value = (boolean_t *)cp;
28960 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
28961 
28962 	if (secpolicy_ip_config(ioc_cr, B_FALSE) != 0)
28963 		return (EPERM);
28964 
28965 	if (ddi_strtol(value, NULL, 10, &new_value) != 0 ||
28966 	    new_value < 0 || new_value > 1) {
28967 		return (EINVAL);
28968 	}
28969 
28970 	if ((!*ip_cgtp_filter_value) && new_value) {
28971 		cmn_err(CE_NOTE, "IP: enabling CGTP filtering%s",
28972 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28973 		    " (module not loaded)" : "");
28974 	}
28975 	if (*ip_cgtp_filter_value && (!new_value)) {
28976 		cmn_err(CE_NOTE, "IP: disabling CGTP filtering%s",
28977 		    ipst->ips_ip_cgtp_filter_ops == NULL ?
28978 		    " (module not loaded)" : "");
28979 	}
28980 
28981 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
28982 		int	res;
28983 		netstackid_t stackid;
28984 
28985 		stackid = ipst->ips_netstack->netstack_stackid;
28986 		res = ipst->ips_ip_cgtp_filter_ops->cfo_change_state(stackid,
28987 		    new_value);
28988 		if (res)
28989 			return (res);
28990 	}
28991 
28992 	*ip_cgtp_filter_value = (boolean_t)new_value;
28993 
28994 	return (0);
28995 }
28996 
28997 
28998 /*
28999  * Return the expected CGTP hooks version number.
29000  */
29001 int
29002 ip_cgtp_filter_supported(void)
29003 {
29004 	return (ip_cgtp_filter_rev);
29005 }
29006 
29007 
29008 /*
29009  * CGTP hooks can be registered by invoking this function.
29010  * Checks that the version number matches.
29011  */
29012 int
29013 ip_cgtp_filter_register(netstackid_t stackid, cgtp_filter_ops_t *ops)
29014 {
29015 	netstack_t *ns;
29016 	ip_stack_t *ipst;
29017 
29018 	if (ops->cfo_filter_rev != CGTP_FILTER_REV)
29019 		return (ENOTSUP);
29020 
29021 	ns = netstack_find_by_stackid(stackid);
29022 	if (ns == NULL)
29023 		return (EINVAL);
29024 	ipst = ns->netstack_ip;
29025 	ASSERT(ipst != NULL);
29026 
29027 	if (ipst->ips_ip_cgtp_filter_ops != NULL) {
29028 		netstack_rele(ns);
29029 		return (EALREADY);
29030 	}
29031 
29032 	ipst->ips_ip_cgtp_filter_ops = ops;
29033 	netstack_rele(ns);
29034 	return (0);
29035 }
29036 
29037 /*
29038  * CGTP hooks can be unregistered by invoking this function.
29039  * Returns ENXIO if there was no registration.
29040  * Returns EBUSY if the ndd variable has not been turned off.
29041  */
29042 int
29043 ip_cgtp_filter_unregister(netstackid_t stackid)
29044 {
29045 	netstack_t *ns;
29046 	ip_stack_t *ipst;
29047 
29048 	ns = netstack_find_by_stackid(stackid);
29049 	if (ns == NULL)
29050 		return (EINVAL);
29051 	ipst = ns->netstack_ip;
29052 	ASSERT(ipst != NULL);
29053 
29054 	if (ipst->ips_ip_cgtp_filter) {
29055 		netstack_rele(ns);
29056 		return (EBUSY);
29057 	}
29058 
29059 	if (ipst->ips_ip_cgtp_filter_ops == NULL) {
29060 		netstack_rele(ns);
29061 		return (ENXIO);
29062 	}
29063 	ipst->ips_ip_cgtp_filter_ops = NULL;
29064 	netstack_rele(ns);
29065 	return (0);
29066 }
29067 
29068 /*
29069  * Check whether there is a CGTP filter registration.
29070  * Returns non-zero if there is a registration, otherwise returns zero.
29071  * Note: returns zero if bad stackid.
29072  */
29073 int
29074 ip_cgtp_filter_is_registered(netstackid_t stackid)
29075 {
29076 	netstack_t *ns;
29077 	ip_stack_t *ipst;
29078 	int ret;
29079 
29080 	ns = netstack_find_by_stackid(stackid);
29081 	if (ns == NULL)
29082 		return (0);
29083 	ipst = ns->netstack_ip;
29084 	ASSERT(ipst != NULL);
29085 
29086 	if (ipst->ips_ip_cgtp_filter_ops != NULL)
29087 		ret = 1;
29088 	else
29089 		ret = 0;
29090 
29091 	netstack_rele(ns);
29092 	return (ret);
29093 }
29094 
29095 static squeue_func_t
29096 ip_squeue_switch(int val)
29097 {
29098 	squeue_func_t rval = squeue_fill;
29099 
29100 	switch (val) {
29101 	case IP_SQUEUE_ENTER_NODRAIN:
29102 		rval = squeue_enter_nodrain;
29103 		break;
29104 	case IP_SQUEUE_ENTER:
29105 		rval = squeue_enter;
29106 		break;
29107 	default:
29108 		break;
29109 	}
29110 	return (rval);
29111 }
29112 
29113 /* ARGSUSED */
29114 static int
29115 ip_input_proc_set(queue_t *q, mblk_t *mp, char *value,
29116     caddr_t addr, cred_t *cr)
29117 {
29118 	int *v = (int *)addr;
29119 	long new_value;
29120 
29121 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29122 		return (EPERM);
29123 
29124 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29125 		return (EINVAL);
29126 
29127 	ip_input_proc = ip_squeue_switch(new_value);
29128 	*v = new_value;
29129 	return (0);
29130 }
29131 
29132 /*
29133  * Handle ndd set of variables which require PRIV_SYS_NET_CONFIG such as
29134  * ip_debug.
29135  */
29136 /* ARGSUSED */
29137 static int
29138 ip_int_set(queue_t *q, mblk_t *mp, char *value,
29139     caddr_t addr, cred_t *cr)
29140 {
29141 	int *v = (int *)addr;
29142 	long new_value;
29143 
29144 	if (secpolicy_net_config(cr, B_FALSE) != 0)
29145 		return (EPERM);
29146 
29147 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29148 		return (EINVAL);
29149 
29150 	*v = new_value;
29151 	return (0);
29152 }
29153 
29154 /*
29155  * Handle changes to ipmp_hook_emulation ndd variable.
29156  * Need to update phyint_hook_ifindex.
29157  * Also generate a nic plumb event should a new ifidex be assigned to a group.
29158  */
29159 static void
29160 ipmp_hook_emulation_changed(ip_stack_t *ipst)
29161 {
29162 	phyint_t *phyi;
29163 	phyint_t *phyi_tmp;
29164 	char *groupname;
29165 	int namelen;
29166 	ill_t	*ill;
29167 	boolean_t new_group;
29168 
29169 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29170 	/*
29171 	 * Group indicies are stored in the phyint - a common structure
29172 	 * to both IPv4 and IPv6.
29173 	 */
29174 	phyi = avl_first(&ipst->ips_phyint_g_list->phyint_list_avl_by_index);
29175 	for (; phyi != NULL;
29176 	    phyi = avl_walk(&ipst->ips_phyint_g_list->phyint_list_avl_by_index,
29177 	    phyi, AVL_AFTER)) {
29178 		/* Ignore the ones that do not have a group */
29179 		if (phyi->phyint_groupname_len == 0)
29180 			continue;
29181 
29182 		/*
29183 		 * Look for other phyint in group.
29184 		 * Clear name/namelen so the lookup doesn't find ourselves.
29185 		 */
29186 		namelen = phyi->phyint_groupname_len;
29187 		groupname = phyi->phyint_groupname;
29188 		phyi->phyint_groupname_len = 0;
29189 		phyi->phyint_groupname = NULL;
29190 
29191 		phyi_tmp = phyint_lookup_group(groupname, B_FALSE, ipst);
29192 		/* Restore */
29193 		phyi->phyint_groupname_len = namelen;
29194 		phyi->phyint_groupname = groupname;
29195 
29196 		new_group = B_FALSE;
29197 		if (ipst->ips_ipmp_hook_emulation) {
29198 			/*
29199 			 * If the group already exists and has already
29200 			 * been assigned a group ifindex, we use the existing
29201 			 * group_ifindex, otherwise we pick a new group_ifindex
29202 			 * here.
29203 			 */
29204 			if (phyi_tmp != NULL &&
29205 			    phyi_tmp->phyint_group_ifindex != 0) {
29206 				phyi->phyint_group_ifindex =
29207 				    phyi_tmp->phyint_group_ifindex;
29208 			} else {
29209 				/* XXX We need a recovery strategy here. */
29210 				if (!ip_assign_ifindex(
29211 				    &phyi->phyint_group_ifindex, ipst))
29212 					cmn_err(CE_PANIC,
29213 					    "ip_assign_ifindex() failed");
29214 				new_group = B_TRUE;
29215 			}
29216 		} else {
29217 			phyi->phyint_group_ifindex = 0;
29218 		}
29219 		if (ipst->ips_ipmp_hook_emulation)
29220 			phyi->phyint_hook_ifindex = phyi->phyint_group_ifindex;
29221 		else
29222 			phyi->phyint_hook_ifindex = phyi->phyint_ifindex;
29223 
29224 		/*
29225 		 * For IP Filter to find out the relationship between
29226 		 * names and interface indicies, we need to generate
29227 		 * a NE_PLUMB event when a new group can appear.
29228 		 * We always generate events when a new interface appears
29229 		 * (even when ipmp_hook_emulation is set) so there
29230 		 * is no need to generate NE_PLUMB events when
29231 		 * ipmp_hook_emulation is turned off.
29232 		 * And since it isn't critical for IP Filter to get
29233 		 * the NE_UNPLUMB events we skip those here.
29234 		 */
29235 		if (new_group) {
29236 			/*
29237 			 * First phyint in group - generate group PLUMB event.
29238 			 * Since we are not running inside the ipsq we do
29239 			 * the dispatch immediately.
29240 			 */
29241 			if (phyi->phyint_illv4 != NULL)
29242 				ill = phyi->phyint_illv4;
29243 			else
29244 				ill = phyi->phyint_illv6;
29245 
29246 			if (ill != NULL) {
29247 				mutex_enter(&ill->ill_lock);
29248 				ill_nic_info_plumb(ill, B_TRUE);
29249 				ill_nic_info_dispatch(ill);
29250 				mutex_exit(&ill->ill_lock);
29251 			}
29252 		}
29253 	}
29254 	rw_exit(&ipst->ips_ill_g_lock);
29255 }
29256 
29257 /* ARGSUSED */
29258 static int
29259 ipmp_hook_emulation_set(queue_t *q, mblk_t *mp, char *value,
29260     caddr_t addr, cred_t *cr)
29261 {
29262 	int *v = (int *)addr;
29263 	long new_value;
29264 	ip_stack_t	*ipst = CONNQ_TO_IPST(q);
29265 
29266 	if (ddi_strtol(value, NULL, 10, &new_value) != 0)
29267 		return (EINVAL);
29268 
29269 	if (*v != new_value) {
29270 		*v = new_value;
29271 		ipmp_hook_emulation_changed(ipst);
29272 	}
29273 	return (0);
29274 }
29275 
29276 static void *
29277 ip_kstat2_init(netstackid_t stackid, ip_stat_t *ip_statisticsp)
29278 {
29279 	kstat_t *ksp;
29280 
29281 	ip_stat_t template = {
29282 		{ "ipsec_fanout_proto", 	KSTAT_DATA_UINT64 },
29283 		{ "ip_udp_fannorm", 		KSTAT_DATA_UINT64 },
29284 		{ "ip_udp_fanmb", 		KSTAT_DATA_UINT64 },
29285 		{ "ip_udp_fanothers", 		KSTAT_DATA_UINT64 },
29286 		{ "ip_udp_fast_path", 		KSTAT_DATA_UINT64 },
29287 		{ "ip_udp_slow_path", 		KSTAT_DATA_UINT64 },
29288 		{ "ip_udp_input_err", 		KSTAT_DATA_UINT64 },
29289 		{ "ip_tcppullup", 		KSTAT_DATA_UINT64 },
29290 		{ "ip_tcpoptions", 		KSTAT_DATA_UINT64 },
29291 		{ "ip_multipkttcp", 		KSTAT_DATA_UINT64 },
29292 		{ "ip_tcp_fast_path",		KSTAT_DATA_UINT64 },
29293 		{ "ip_tcp_slow_path",		KSTAT_DATA_UINT64 },
29294 		{ "ip_tcp_input_error",		KSTAT_DATA_UINT64 },
29295 		{ "ip_db_ref",			KSTAT_DATA_UINT64 },
29296 		{ "ip_notaligned1",		KSTAT_DATA_UINT64 },
29297 		{ "ip_notaligned2",		KSTAT_DATA_UINT64 },
29298 		{ "ip_multimblk3",		KSTAT_DATA_UINT64 },
29299 		{ "ip_multimblk4",		KSTAT_DATA_UINT64 },
29300 		{ "ip_ipoptions",		KSTAT_DATA_UINT64 },
29301 		{ "ip_classify_fail",		KSTAT_DATA_UINT64 },
29302 		{ "ip_opt",			KSTAT_DATA_UINT64 },
29303 		{ "ip_udp_rput_local",		KSTAT_DATA_UINT64 },
29304 		{ "ipsec_proto_ahesp",		KSTAT_DATA_UINT64 },
29305 		{ "ip_conn_flputbq",		KSTAT_DATA_UINT64 },
29306 		{ "ip_conn_walk_drain",		KSTAT_DATA_UINT64 },
29307 		{ "ip_out_sw_cksum",		KSTAT_DATA_UINT64 },
29308 		{ "ip_in_sw_cksum",		KSTAT_DATA_UINT64 },
29309 		{ "ip_trash_ire_reclaim_calls",	KSTAT_DATA_UINT64 },
29310 		{ "ip_trash_ire_reclaim_success",	KSTAT_DATA_UINT64 },
29311 		{ "ip_ire_arp_timer_expired",	KSTAT_DATA_UINT64 },
29312 		{ "ip_ire_redirect_timer_expired",	KSTAT_DATA_UINT64 },
29313 		{ "ip_ire_pmtu_timer_expired",	KSTAT_DATA_UINT64 },
29314 		{ "ip_input_multi_squeue",	KSTAT_DATA_UINT64 },
29315 		{ "ip_tcp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29316 		{ "ip_tcp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29317 		{ "ip_tcp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29318 		{ "ip_tcp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29319 		{ "ip_udp_in_full_hw_cksum_err",	KSTAT_DATA_UINT64 },
29320 		{ "ip_udp_in_part_hw_cksum_err",	KSTAT_DATA_UINT64 },
29321 		{ "ip_udp_in_sw_cksum_err",		KSTAT_DATA_UINT64 },
29322 		{ "ip_udp_out_sw_cksum_bytes",		KSTAT_DATA_UINT64 },
29323 		{ "ip_frag_mdt_pkt_out",		KSTAT_DATA_UINT64 },
29324 		{ "ip_frag_mdt_discarded",		KSTAT_DATA_UINT64 },
29325 		{ "ip_frag_mdt_allocfail",		KSTAT_DATA_UINT64 },
29326 		{ "ip_frag_mdt_addpdescfail",		KSTAT_DATA_UINT64 },
29327 		{ "ip_frag_mdt_allocd",			KSTAT_DATA_UINT64 },
29328 	};
29329 
29330 	ksp = kstat_create_netstack("ip", 0, "ipstat", "net",
29331 	    KSTAT_TYPE_NAMED, sizeof (template) / sizeof (kstat_named_t),
29332 	    KSTAT_FLAG_VIRTUAL, stackid);
29333 
29334 	if (ksp == NULL)
29335 		return (NULL);
29336 
29337 	bcopy(&template, ip_statisticsp, sizeof (template));
29338 	ksp->ks_data = (void *)ip_statisticsp;
29339 	ksp->ks_private = (void *)(uintptr_t)stackid;
29340 
29341 	kstat_install(ksp);
29342 	return (ksp);
29343 }
29344 
29345 static void
29346 ip_kstat2_fini(netstackid_t stackid, kstat_t *ksp)
29347 {
29348 	if (ksp != NULL) {
29349 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29350 		kstat_delete_netstack(ksp, stackid);
29351 	}
29352 }
29353 
29354 static void *
29355 ip_kstat_init(netstackid_t stackid, ip_stack_t *ipst)
29356 {
29357 	kstat_t	*ksp;
29358 
29359 	ip_named_kstat_t template = {
29360 		{ "forwarding",		KSTAT_DATA_UINT32, 0 },
29361 		{ "defaultTTL",		KSTAT_DATA_UINT32, 0 },
29362 		{ "inReceives",		KSTAT_DATA_UINT64, 0 },
29363 		{ "inHdrErrors",	KSTAT_DATA_UINT32, 0 },
29364 		{ "inAddrErrors",	KSTAT_DATA_UINT32, 0 },
29365 		{ "forwDatagrams",	KSTAT_DATA_UINT64, 0 },
29366 		{ "inUnknownProtos",	KSTAT_DATA_UINT32, 0 },
29367 		{ "inDiscards",		KSTAT_DATA_UINT32, 0 },
29368 		{ "inDelivers",		KSTAT_DATA_UINT64, 0 },
29369 		{ "outRequests",	KSTAT_DATA_UINT64, 0 },
29370 		{ "outDiscards",	KSTAT_DATA_UINT32, 0 },
29371 		{ "outNoRoutes",	KSTAT_DATA_UINT32, 0 },
29372 		{ "reasmTimeout",	KSTAT_DATA_UINT32, 0 },
29373 		{ "reasmReqds",		KSTAT_DATA_UINT32, 0 },
29374 		{ "reasmOKs",		KSTAT_DATA_UINT32, 0 },
29375 		{ "reasmFails",		KSTAT_DATA_UINT32, 0 },
29376 		{ "fragOKs",		KSTAT_DATA_UINT32, 0 },
29377 		{ "fragFails",		KSTAT_DATA_UINT32, 0 },
29378 		{ "fragCreates",	KSTAT_DATA_UINT32, 0 },
29379 		{ "addrEntrySize",	KSTAT_DATA_INT32, 0 },
29380 		{ "routeEntrySize",	KSTAT_DATA_INT32, 0 },
29381 		{ "netToMediaEntrySize",	KSTAT_DATA_INT32, 0 },
29382 		{ "routingDiscards",	KSTAT_DATA_UINT32, 0 },
29383 		{ "inErrs",		KSTAT_DATA_UINT32, 0 },
29384 		{ "noPorts",		KSTAT_DATA_UINT32, 0 },
29385 		{ "inCksumErrs",	KSTAT_DATA_UINT32, 0 },
29386 		{ "reasmDuplicates",	KSTAT_DATA_UINT32, 0 },
29387 		{ "reasmPartDups",	KSTAT_DATA_UINT32, 0 },
29388 		{ "forwProhibits",	KSTAT_DATA_UINT32, 0 },
29389 		{ "udpInCksumErrs",	KSTAT_DATA_UINT32, 0 },
29390 		{ "udpInOverflows",	KSTAT_DATA_UINT32, 0 },
29391 		{ "rawipInOverflows",	KSTAT_DATA_UINT32, 0 },
29392 		{ "ipsecInSucceeded",	KSTAT_DATA_UINT32, 0 },
29393 		{ "ipsecInFailed",	KSTAT_DATA_INT32, 0 },
29394 		{ "memberEntrySize",	KSTAT_DATA_INT32, 0 },
29395 		{ "inIPv6",		KSTAT_DATA_UINT32, 0 },
29396 		{ "outIPv6",		KSTAT_DATA_UINT32, 0 },
29397 		{ "outSwitchIPv6",	KSTAT_DATA_UINT32, 0 },
29398 	};
29399 
29400 	ksp = kstat_create_netstack("ip", 0, "ip", "mib2", KSTAT_TYPE_NAMED,
29401 	    NUM_OF_FIELDS(ip_named_kstat_t), 0, stackid);
29402 	if (ksp == NULL || ksp->ks_data == NULL)
29403 		return (NULL);
29404 
29405 	template.forwarding.value.ui32 = WE_ARE_FORWARDING(ipst) ? 1:2;
29406 	template.defaultTTL.value.ui32 = (uint32_t)ipst->ips_ip_def_ttl;
29407 	template.reasmTimeout.value.ui32 = ipst->ips_ip_g_frag_timeout;
29408 	template.addrEntrySize.value.i32 = sizeof (mib2_ipAddrEntry_t);
29409 	template.routeEntrySize.value.i32 = sizeof (mib2_ipRouteEntry_t);
29410 
29411 	template.netToMediaEntrySize.value.i32 =
29412 	    sizeof (mib2_ipNetToMediaEntry_t);
29413 
29414 	template.memberEntrySize.value.i32 = sizeof (ipv6_member_t);
29415 
29416 	bcopy(&template, ksp->ks_data, sizeof (template));
29417 	ksp->ks_update = ip_kstat_update;
29418 	ksp->ks_private = (void *)(uintptr_t)stackid;
29419 
29420 	kstat_install(ksp);
29421 	return (ksp);
29422 }
29423 
29424 static void
29425 ip_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29426 {
29427 	if (ksp != NULL) {
29428 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29429 		kstat_delete_netstack(ksp, stackid);
29430 	}
29431 }
29432 
29433 static int
29434 ip_kstat_update(kstat_t *kp, int rw)
29435 {
29436 	ip_named_kstat_t *ipkp;
29437 	mib2_ipIfStatsEntry_t ipmib;
29438 	ill_walk_context_t ctx;
29439 	ill_t *ill;
29440 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29441 	netstack_t	*ns;
29442 	ip_stack_t	*ipst;
29443 
29444 	if (kp == NULL || kp->ks_data == NULL)
29445 		return (EIO);
29446 
29447 	if (rw == KSTAT_WRITE)
29448 		return (EACCES);
29449 
29450 	ns = netstack_find_by_stackid(stackid);
29451 	if (ns == NULL)
29452 		return (-1);
29453 	ipst = ns->netstack_ip;
29454 	if (ipst == NULL) {
29455 		netstack_rele(ns);
29456 		return (-1);
29457 	}
29458 	ipkp = (ip_named_kstat_t *)kp->ks_data;
29459 
29460 	bcopy(&ipst->ips_ip_mib, &ipmib, sizeof (ipmib));
29461 	rw_enter(&ipst->ips_ill_g_lock, RW_READER);
29462 	ill = ILL_START_WALK_V4(&ctx, ipst);
29463 	for (; ill != NULL; ill = ill_next(&ctx, ill))
29464 		ip_mib2_add_ip_stats(&ipmib, ill->ill_ip_mib);
29465 	rw_exit(&ipst->ips_ill_g_lock);
29466 
29467 	ipkp->forwarding.value.ui32 =		ipmib.ipIfStatsForwarding;
29468 	ipkp->defaultTTL.value.ui32 =		ipmib.ipIfStatsDefaultTTL;
29469 	ipkp->inReceives.value.ui64 =		ipmib.ipIfStatsHCInReceives;
29470 	ipkp->inHdrErrors.value.ui32 =		ipmib.ipIfStatsInHdrErrors;
29471 	ipkp->inAddrErrors.value.ui32 =		ipmib.ipIfStatsInAddrErrors;
29472 	ipkp->forwDatagrams.value.ui64 = ipmib.ipIfStatsHCOutForwDatagrams;
29473 	ipkp->inUnknownProtos.value.ui32 =	ipmib.ipIfStatsInUnknownProtos;
29474 	ipkp->inDiscards.value.ui32 =		ipmib.ipIfStatsInDiscards;
29475 	ipkp->inDelivers.value.ui64 =		ipmib.ipIfStatsHCInDelivers;
29476 	ipkp->outRequests.value.ui64 =		ipmib.ipIfStatsHCOutRequests;
29477 	ipkp->outDiscards.value.ui32 =		ipmib.ipIfStatsOutDiscards;
29478 	ipkp->outNoRoutes.value.ui32 =		ipmib.ipIfStatsOutNoRoutes;
29479 	ipkp->reasmTimeout.value.ui32 =		ipst->ips_ip_g_frag_timeout;
29480 	ipkp->reasmReqds.value.ui32 =		ipmib.ipIfStatsReasmReqds;
29481 	ipkp->reasmOKs.value.ui32 =		ipmib.ipIfStatsReasmOKs;
29482 	ipkp->reasmFails.value.ui32 =		ipmib.ipIfStatsReasmFails;
29483 	ipkp->fragOKs.value.ui32 =		ipmib.ipIfStatsOutFragOKs;
29484 	ipkp->fragFails.value.ui32 =		ipmib.ipIfStatsOutFragFails;
29485 	ipkp->fragCreates.value.ui32 =		ipmib.ipIfStatsOutFragCreates;
29486 
29487 	ipkp->routingDiscards.value.ui32 =	0;
29488 	ipkp->inErrs.value.ui32 =		ipmib.tcpIfStatsInErrs;
29489 	ipkp->noPorts.value.ui32 =		ipmib.udpIfStatsNoPorts;
29490 	ipkp->inCksumErrs.value.ui32 =		ipmib.ipIfStatsInCksumErrs;
29491 	ipkp->reasmDuplicates.value.ui32 =	ipmib.ipIfStatsReasmDuplicates;
29492 	ipkp->reasmPartDups.value.ui32 =	ipmib.ipIfStatsReasmPartDups;
29493 	ipkp->forwProhibits.value.ui32 =	ipmib.ipIfStatsForwProhibits;
29494 	ipkp->udpInCksumErrs.value.ui32 =	ipmib.udpIfStatsInCksumErrs;
29495 	ipkp->udpInOverflows.value.ui32 =	ipmib.udpIfStatsInOverflows;
29496 	ipkp->rawipInOverflows.value.ui32 =	ipmib.rawipIfStatsInOverflows;
29497 	ipkp->ipsecInSucceeded.value.ui32 =	ipmib.ipsecIfStatsInSucceeded;
29498 	ipkp->ipsecInFailed.value.i32 =		ipmib.ipsecIfStatsInFailed;
29499 
29500 	ipkp->inIPv6.value.ui32 =	ipmib.ipIfStatsInWrongIPVersion;
29501 	ipkp->outIPv6.value.ui32 =	ipmib.ipIfStatsOutWrongIPVersion;
29502 	ipkp->outSwitchIPv6.value.ui32 = ipmib.ipIfStatsOutSwitchIPVersion;
29503 
29504 	netstack_rele(ns);
29505 
29506 	return (0);
29507 }
29508 
29509 static void *
29510 icmp_kstat_init(netstackid_t stackid)
29511 {
29512 	kstat_t	*ksp;
29513 
29514 	icmp_named_kstat_t template = {
29515 		{ "inMsgs",		KSTAT_DATA_UINT32 },
29516 		{ "inErrors",		KSTAT_DATA_UINT32 },
29517 		{ "inDestUnreachs",	KSTAT_DATA_UINT32 },
29518 		{ "inTimeExcds",	KSTAT_DATA_UINT32 },
29519 		{ "inParmProbs",	KSTAT_DATA_UINT32 },
29520 		{ "inSrcQuenchs",	KSTAT_DATA_UINT32 },
29521 		{ "inRedirects",	KSTAT_DATA_UINT32 },
29522 		{ "inEchos",		KSTAT_DATA_UINT32 },
29523 		{ "inEchoReps",		KSTAT_DATA_UINT32 },
29524 		{ "inTimestamps",	KSTAT_DATA_UINT32 },
29525 		{ "inTimestampReps",	KSTAT_DATA_UINT32 },
29526 		{ "inAddrMasks",	KSTAT_DATA_UINT32 },
29527 		{ "inAddrMaskReps",	KSTAT_DATA_UINT32 },
29528 		{ "outMsgs",		KSTAT_DATA_UINT32 },
29529 		{ "outErrors",		KSTAT_DATA_UINT32 },
29530 		{ "outDestUnreachs",	KSTAT_DATA_UINT32 },
29531 		{ "outTimeExcds",	KSTAT_DATA_UINT32 },
29532 		{ "outParmProbs",	KSTAT_DATA_UINT32 },
29533 		{ "outSrcQuenchs",	KSTAT_DATA_UINT32 },
29534 		{ "outRedirects",	KSTAT_DATA_UINT32 },
29535 		{ "outEchos",		KSTAT_DATA_UINT32 },
29536 		{ "outEchoReps",	KSTAT_DATA_UINT32 },
29537 		{ "outTimestamps",	KSTAT_DATA_UINT32 },
29538 		{ "outTimestampReps",	KSTAT_DATA_UINT32 },
29539 		{ "outAddrMasks",	KSTAT_DATA_UINT32 },
29540 		{ "outAddrMaskReps",	KSTAT_DATA_UINT32 },
29541 		{ "inChksumErrs",	KSTAT_DATA_UINT32 },
29542 		{ "inUnknowns",		KSTAT_DATA_UINT32 },
29543 		{ "inFragNeeded",	KSTAT_DATA_UINT32 },
29544 		{ "outFragNeeded",	KSTAT_DATA_UINT32 },
29545 		{ "outDrops",		KSTAT_DATA_UINT32 },
29546 		{ "inOverFlows",	KSTAT_DATA_UINT32 },
29547 		{ "inBadRedirects",	KSTAT_DATA_UINT32 },
29548 	};
29549 
29550 	ksp = kstat_create_netstack("ip", 0, "icmp", "mib2", KSTAT_TYPE_NAMED,
29551 	    NUM_OF_FIELDS(icmp_named_kstat_t), 0, stackid);
29552 	if (ksp == NULL || ksp->ks_data == NULL)
29553 		return (NULL);
29554 
29555 	bcopy(&template, ksp->ks_data, sizeof (template));
29556 
29557 	ksp->ks_update = icmp_kstat_update;
29558 	ksp->ks_private = (void *)(uintptr_t)stackid;
29559 
29560 	kstat_install(ksp);
29561 	return (ksp);
29562 }
29563 
29564 static void
29565 icmp_kstat_fini(netstackid_t stackid, kstat_t *ksp)
29566 {
29567 	if (ksp != NULL) {
29568 		ASSERT(stackid == (netstackid_t)(uintptr_t)ksp->ks_private);
29569 		kstat_delete_netstack(ksp, stackid);
29570 	}
29571 }
29572 
29573 static int
29574 icmp_kstat_update(kstat_t *kp, int rw)
29575 {
29576 	icmp_named_kstat_t *icmpkp;
29577 	netstackid_t	stackid = (zoneid_t)(uintptr_t)kp->ks_private;
29578 	netstack_t	*ns;
29579 	ip_stack_t	*ipst;
29580 
29581 	if ((kp == NULL) || (kp->ks_data == NULL))
29582 		return (EIO);
29583 
29584 	if (rw == KSTAT_WRITE)
29585 		return (EACCES);
29586 
29587 	ns = netstack_find_by_stackid(stackid);
29588 	if (ns == NULL)
29589 		return (-1);
29590 	ipst = ns->netstack_ip;
29591 	if (ipst == NULL) {
29592 		netstack_rele(ns);
29593 		return (-1);
29594 	}
29595 	icmpkp = (icmp_named_kstat_t *)kp->ks_data;
29596 
29597 	icmpkp->inMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpInMsgs;
29598 	icmpkp->inErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpInErrors;
29599 	icmpkp->inDestUnreachs.value.ui32 =
29600 	    ipst->ips_icmp_mib.icmpInDestUnreachs;
29601 	icmpkp->inTimeExcds.value.ui32 =    ipst->ips_icmp_mib.icmpInTimeExcds;
29602 	icmpkp->inParmProbs.value.ui32 =    ipst->ips_icmp_mib.icmpInParmProbs;
29603 	icmpkp->inSrcQuenchs.value.ui32 =   ipst->ips_icmp_mib.icmpInSrcQuenchs;
29604 	icmpkp->inRedirects.value.ui32 =    ipst->ips_icmp_mib.icmpInRedirects;
29605 	icmpkp->inEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchos;
29606 	icmpkp->inEchoReps.value.ui32 =	    ipst->ips_icmp_mib.icmpInEchoReps;
29607 	icmpkp->inTimestamps.value.ui32 =   ipst->ips_icmp_mib.icmpInTimestamps;
29608 	icmpkp->inTimestampReps.value.ui32 =
29609 	    ipst->ips_icmp_mib.icmpInTimestampReps;
29610 	icmpkp->inAddrMasks.value.ui32 =    ipst->ips_icmp_mib.icmpInAddrMasks;
29611 	icmpkp->inAddrMaskReps.value.ui32 =
29612 	    ipst->ips_icmp_mib.icmpInAddrMaskReps;
29613 	icmpkp->outMsgs.value.ui32 =	    ipst->ips_icmp_mib.icmpOutMsgs;
29614 	icmpkp->outErrors.value.ui32 =	    ipst->ips_icmp_mib.icmpOutErrors;
29615 	icmpkp->outDestUnreachs.value.ui32 =
29616 	    ipst->ips_icmp_mib.icmpOutDestUnreachs;
29617 	icmpkp->outTimeExcds.value.ui32 =   ipst->ips_icmp_mib.icmpOutTimeExcds;
29618 	icmpkp->outParmProbs.value.ui32 =   ipst->ips_icmp_mib.icmpOutParmProbs;
29619 	icmpkp->outSrcQuenchs.value.ui32 =
29620 	    ipst->ips_icmp_mib.icmpOutSrcQuenchs;
29621 	icmpkp->outRedirects.value.ui32 =   ipst->ips_icmp_mib.icmpOutRedirects;
29622 	icmpkp->outEchos.value.ui32 =	    ipst->ips_icmp_mib.icmpOutEchos;
29623 	icmpkp->outEchoReps.value.ui32 =    ipst->ips_icmp_mib.icmpOutEchoReps;
29624 	icmpkp->outTimestamps.value.ui32 =
29625 	    ipst->ips_icmp_mib.icmpOutTimestamps;
29626 	icmpkp->outTimestampReps.value.ui32 =
29627 	    ipst->ips_icmp_mib.icmpOutTimestampReps;
29628 	icmpkp->outAddrMasks.value.ui32 =
29629 	    ipst->ips_icmp_mib.icmpOutAddrMasks;
29630 	icmpkp->outAddrMaskReps.value.ui32 =
29631 	    ipst->ips_icmp_mib.icmpOutAddrMaskReps;
29632 	icmpkp->inCksumErrs.value.ui32 =    ipst->ips_icmp_mib.icmpInCksumErrs;
29633 	icmpkp->inUnknowns.value.ui32 =	    ipst->ips_icmp_mib.icmpInUnknowns;
29634 	icmpkp->inFragNeeded.value.ui32 =   ipst->ips_icmp_mib.icmpInFragNeeded;
29635 	icmpkp->outFragNeeded.value.ui32 =
29636 	    ipst->ips_icmp_mib.icmpOutFragNeeded;
29637 	icmpkp->outDrops.value.ui32 =	    ipst->ips_icmp_mib.icmpOutDrops;
29638 	icmpkp->inOverflows.value.ui32 =    ipst->ips_icmp_mib.icmpInOverflows;
29639 	icmpkp->inBadRedirects.value.ui32 =
29640 	    ipst->ips_icmp_mib.icmpInBadRedirects;
29641 
29642 	netstack_rele(ns);
29643 	return (0);
29644 }
29645 
29646 /*
29647  * This is the fanout function for raw socket opened for SCTP.  Note
29648  * that it is called after SCTP checks that there is no socket which
29649  * wants a packet.  Then before SCTP handles this out of the blue packet,
29650  * this function is called to see if there is any raw socket for SCTP.
29651  * If there is and it is bound to the correct address, the packet will
29652  * be sent to that socket.  Note that only one raw socket can be bound to
29653  * a port.  This is assured in ipcl_sctp_hash_insert();
29654  */
29655 void
29656 ip_fanout_sctp_raw(mblk_t *mp, ill_t *recv_ill, ipha_t *ipha, boolean_t isv4,
29657     uint32_t ports, boolean_t mctl_present, uint_t flags, boolean_t ip_policy,
29658     zoneid_t zoneid)
29659 {
29660 	conn_t		*connp;
29661 	queue_t		*rq;
29662 	mblk_t		*first_mp;
29663 	boolean_t	secure;
29664 	ip6_t		*ip6h;
29665 	ip_stack_t	*ipst = recv_ill->ill_ipst;
29666 	ipsec_stack_t	*ipss = ipst->ips_netstack->netstack_ipsec;
29667 	sctp_stack_t	*sctps = ipst->ips_netstack->netstack_sctp;
29668 	boolean_t	sctp_csum_err = B_FALSE;
29669 
29670 	if (flags & IP_FF_SCTP_CSUM_ERR) {
29671 		sctp_csum_err = B_TRUE;
29672 		flags &= ~IP_FF_SCTP_CSUM_ERR;
29673 	}
29674 
29675 	first_mp = mp;
29676 	if (mctl_present) {
29677 		mp = first_mp->b_cont;
29678 		secure = ipsec_in_is_secure(first_mp);
29679 		ASSERT(mp != NULL);
29680 	} else {
29681 		secure = B_FALSE;
29682 	}
29683 	ip6h = (isv4) ? NULL : (ip6_t *)ipha;
29684 
29685 	connp = ipcl_classify_raw(mp, IPPROTO_SCTP, zoneid, ports, ipha, ipst);
29686 	if (connp == NULL) {
29687 		/*
29688 		 * Although raw sctp is not summed, OOB chunks must be.
29689 		 * Drop the packet here if the sctp checksum failed.
29690 		 */
29691 		if (sctp_csum_err) {
29692 			BUMP_MIB(&sctps->sctps_mib, sctpChecksumError);
29693 			freemsg(first_mp);
29694 			return;
29695 		}
29696 		sctp_ootb_input(first_mp, recv_ill, zoneid, mctl_present);
29697 		return;
29698 	}
29699 	rq = connp->conn_rq;
29700 	if (!canputnext(rq)) {
29701 		CONN_DEC_REF(connp);
29702 		BUMP_MIB(recv_ill->ill_ip_mib, rawipIfStatsInOverflows);
29703 		freemsg(first_mp);
29704 		return;
29705 	}
29706 	if ((isv4 ? CONN_INBOUND_POLICY_PRESENT(connp, ipss) :
29707 	    CONN_INBOUND_POLICY_PRESENT_V6(connp, ipss)) || secure) {
29708 		first_mp = ipsec_check_inbound_policy(first_mp, connp,
29709 		    (isv4 ? ipha : NULL), ip6h, mctl_present);
29710 		if (first_mp == NULL) {
29711 			BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsInDiscards);
29712 			CONN_DEC_REF(connp);
29713 			return;
29714 		}
29715 	}
29716 	/*
29717 	 * We probably should not send M_CTL message up to
29718 	 * raw socket.
29719 	 */
29720 	if (mctl_present)
29721 		freeb(first_mp);
29722 
29723 	/* Initiate IPPF processing here if needed. */
29724 	if ((isv4 && IPP_ENABLED(IPP_LOCAL_IN, ipst) && ip_policy) ||
29725 	    (!isv4 && IP6_IN_IPP(flags, ipst))) {
29726 		ip_process(IPP_LOCAL_IN, &mp,
29727 		    recv_ill->ill_phyint->phyint_ifindex);
29728 		if (mp == NULL) {
29729 			CONN_DEC_REF(connp);
29730 			return;
29731 		}
29732 	}
29733 
29734 	if (connp->conn_recvif || connp->conn_recvslla ||
29735 	    ((connp->conn_ip_recvpktinfo ||
29736 	    (!isv4 && IN6_IS_ADDR_LINKLOCAL(&ip6h->ip6_src))) &&
29737 	    (flags & IP_FF_IPINFO))) {
29738 		int in_flags = 0;
29739 
29740 		/*
29741 		 * Since sctp does not support IP_RECVPKTINFO for v4, only pass
29742 		 * IPF_RECVIF.
29743 		 */
29744 		if (connp->conn_recvif || connp->conn_ip_recvpktinfo) {
29745 			in_flags = IPF_RECVIF;
29746 		}
29747 		if (connp->conn_recvslla) {
29748 			in_flags |= IPF_RECVSLLA;
29749 		}
29750 		if (isv4) {
29751 			mp = ip_add_info(mp, recv_ill, in_flags,
29752 			    IPCL_ZONEID(connp), ipst);
29753 		} else {
29754 			mp = ip_add_info_v6(mp, recv_ill, &ip6h->ip6_dst);
29755 			if (mp == NULL) {
29756 				BUMP_MIB(recv_ill->ill_ip_mib,
29757 				    ipIfStatsInDiscards);
29758 				CONN_DEC_REF(connp);
29759 				return;
29760 			}
29761 		}
29762 	}
29763 
29764 	BUMP_MIB(recv_ill->ill_ip_mib, ipIfStatsHCInDelivers);
29765 	/*
29766 	 * We are sending the IPSEC_IN message also up. Refer
29767 	 * to comments above this function.
29768 	 * This is the SOCK_RAW, IPPROTO_SCTP case.
29769 	 */
29770 	(connp->conn_recv)(connp, mp, NULL);
29771 	CONN_DEC_REF(connp);
29772 }
29773 
29774 #define	UPDATE_IP_MIB_OB_COUNTERS(ill, len)				\
29775 {									\
29776 	BUMP_MIB((ill)->ill_ip_mib, ipIfStatsHCOutTransmits);		\
29777 	UPDATE_MIB((ill)->ill_ip_mib, ipIfStatsHCOutOctets, (len));	\
29778 }
29779 /*
29780  * This function should be called only if all packet processing
29781  * including fragmentation is complete. Callers of this function
29782  * must set mp->b_prev to one of these values:
29783  *	{0, IPP_FWD_OUT, IPP_LOCAL_OUT}
29784  * prior to handing over the mp as first argument to this function.
29785  *
29786  * If the ire passed by caller is incomplete, this function
29787  * queues the packet and if necessary, sends ARP request and bails.
29788  * If the ire passed is fully resolved, we simply prepend
29789  * the link-layer header to the packet, do ipsec hw acceleration
29790  * work if necessary, and send the packet out on the wire.
29791  *
29792  * NOTE: IPsec will only call this function with fully resolved
29793  * ires if hw acceleration is involved.
29794  * TODO list :
29795  * 	a Handle M_MULTIDATA so that
29796  *	  tcp_multisend->tcp_multisend_data can
29797  *	  call ip_xmit_v4 directly
29798  *	b Handle post-ARP work for fragments so that
29799  *	  ip_wput_frag can call this function.
29800  */
29801 ipxmit_state_t
29802 ip_xmit_v4(mblk_t *mp, ire_t *ire, ipsec_out_t *io, boolean_t flow_ctl_enabled)
29803 {
29804 	nce_t		*arpce;
29805 	queue_t		*q;
29806 	int		ill_index;
29807 	mblk_t		*nxt_mp, *first_mp;
29808 	boolean_t	xmit_drop = B_FALSE;
29809 	ip_proc_t	proc;
29810 	ill_t		*out_ill;
29811 	int		pkt_len;
29812 
29813 	arpce = ire->ire_nce;
29814 	ASSERT(arpce != NULL);
29815 
29816 	DTRACE_PROBE2(ip__xmit__v4, ire_t *, ire,  nce_t *, arpce);
29817 
29818 	mutex_enter(&arpce->nce_lock);
29819 	switch (arpce->nce_state) {
29820 	case ND_REACHABLE:
29821 		/* If there are other queued packets, queue this packet */
29822 		if (arpce->nce_qd_mp != NULL) {
29823 			if (mp != NULL)
29824 				nce_queue_mp_common(arpce, mp, B_FALSE);
29825 			mp = arpce->nce_qd_mp;
29826 		}
29827 		arpce->nce_qd_mp = NULL;
29828 		mutex_exit(&arpce->nce_lock);
29829 
29830 		/*
29831 		 * Flush the queue.  In the common case, where the
29832 		 * ARP is already resolved,  it will go through the
29833 		 * while loop only once.
29834 		 */
29835 		while (mp != NULL) {
29836 
29837 			nxt_mp = mp->b_next;
29838 			mp->b_next = NULL;
29839 			ASSERT(mp->b_datap->db_type != M_CTL);
29840 			pkt_len = ntohs(((ipha_t *)mp->b_rptr)->ipha_length);
29841 			/*
29842 			 * This info is needed for IPQOS to do COS marking
29843 			 * in ip_wput_attach_llhdr->ip_process.
29844 			 */
29845 			proc = (ip_proc_t)(uintptr_t)mp->b_prev;
29846 			mp->b_prev = NULL;
29847 
29848 			/* set up ill index for outbound qos processing */
29849 			out_ill = ire_to_ill(ire);
29850 			ill_index = out_ill->ill_phyint->phyint_ifindex;
29851 			first_mp = ip_wput_attach_llhdr(mp, ire, proc,
29852 			    ill_index);
29853 			if (first_mp == NULL) {
29854 				xmit_drop = B_TRUE;
29855 				BUMP_MIB(out_ill->ill_ip_mib,
29856 				    ipIfStatsOutDiscards);
29857 				goto next_mp;
29858 			}
29859 			/* non-ipsec hw accel case */
29860 			if (io == NULL || !io->ipsec_out_accelerated) {
29861 				/* send it */
29862 				q = ire->ire_stq;
29863 				if (proc == IPP_FWD_OUT) {
29864 					UPDATE_IB_PKT_COUNT(ire);
29865 				} else {
29866 					UPDATE_OB_PKT_COUNT(ire);
29867 				}
29868 				ire->ire_last_used_time = lbolt;
29869 
29870 				if (flow_ctl_enabled || canputnext(q)) {
29871 					if (proc == IPP_FWD_OUT) {
29872 
29873 					BUMP_MIB(out_ill->ill_ip_mib,
29874 					    ipIfStatsHCOutForwDatagrams);
29875 
29876 					}
29877 					UPDATE_IP_MIB_OB_COUNTERS(out_ill,
29878 					    pkt_len);
29879 
29880 					putnext(q, first_mp);
29881 				} else {
29882 					BUMP_MIB(out_ill->ill_ip_mib,
29883 					    ipIfStatsOutDiscards);
29884 					xmit_drop = B_TRUE;
29885 					freemsg(first_mp);
29886 				}
29887 			} else {
29888 				/*
29889 				 * Safety Pup says: make sure this
29890 				 *  is going to the right interface!
29891 				 */
29892 				ill_t *ill1 =
29893 				    (ill_t *)ire->ire_stq->q_ptr;
29894 				int ifindex =
29895 				    ill1->ill_phyint->phyint_ifindex;
29896 				if (ifindex !=
29897 				    io->ipsec_out_capab_ill_index) {
29898 					xmit_drop = B_TRUE;
29899 					freemsg(mp);
29900 				} else {
29901 					UPDATE_IP_MIB_OB_COUNTERS(ill1,
29902 					    pkt_len);
29903 					ipsec_hw_putnext(ire->ire_stq, mp);
29904 				}
29905 			}
29906 next_mp:
29907 			mp = nxt_mp;
29908 		} /* while (mp != NULL) */
29909 		if (xmit_drop)
29910 			return (SEND_FAILED);
29911 		else
29912 			return (SEND_PASSED);
29913 
29914 	case ND_INITIAL:
29915 	case ND_INCOMPLETE:
29916 
29917 		/*
29918 		 * While we do send off packets to dests that
29919 		 * use fully-resolved CGTP routes, we do not
29920 		 * handle unresolved CGTP routes.
29921 		 */
29922 		ASSERT(!(ire->ire_flags & RTF_MULTIRT));
29923 		ASSERT(io == NULL || !io->ipsec_out_accelerated);
29924 
29925 		if (mp != NULL) {
29926 			/* queue the packet */
29927 			nce_queue_mp_common(arpce, mp, B_FALSE);
29928 		}
29929 
29930 		if (arpce->nce_state == ND_INCOMPLETE) {
29931 			mutex_exit(&arpce->nce_lock);
29932 			DTRACE_PROBE3(ip__xmit__incomplete,
29933 			    (ire_t *), ire, (mblk_t *), mp,
29934 			    (ipsec_out_t *), io);
29935 			return (LOOKUP_IN_PROGRESS);
29936 		}
29937 
29938 		arpce->nce_state = ND_INCOMPLETE;
29939 		mutex_exit(&arpce->nce_lock);
29940 		/*
29941 		 * Note that ire_add() (called from ire_forward())
29942 		 * holds a ref on the ire until ARP is completed.
29943 		 */
29944 
29945 		ire_arpresolve(ire, ire_to_ill(ire));
29946 		return (LOOKUP_IN_PROGRESS);
29947 	default:
29948 		ASSERT(0);
29949 		mutex_exit(&arpce->nce_lock);
29950 		return (LLHDR_RESLV_FAILED);
29951 	}
29952 }
29953 
29954 #undef	UPDATE_IP_MIB_OB_COUNTERS
29955 
29956 /*
29957  * Return B_TRUE if the buffers differ in length or content.
29958  * This is used for comparing extension header buffers.
29959  * Note that an extension header would be declared different
29960  * even if all that changed was the next header value in that header i.e.
29961  * what really changed is the next extension header.
29962  */
29963 boolean_t
29964 ip_cmpbuf(const void *abuf, uint_t alen, boolean_t b_valid, const void *bbuf,
29965     uint_t blen)
29966 {
29967 	if (!b_valid)
29968 		blen = 0;
29969 
29970 	if (alen != blen)
29971 		return (B_TRUE);
29972 	if (alen == 0)
29973 		return (B_FALSE);	/* Both zero length */
29974 	return (bcmp(abuf, bbuf, alen));
29975 }
29976 
29977 /*
29978  * Preallocate memory for ip_savebuf(). Returns B_TRUE if ok.
29979  * Return B_FALSE if memory allocation fails - don't change any state!
29980  */
29981 boolean_t
29982 ip_allocbuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
29983     const void *src, uint_t srclen)
29984 {
29985 	void *dst;
29986 
29987 	if (!src_valid)
29988 		srclen = 0;
29989 
29990 	ASSERT(*dstlenp == 0);
29991 	if (src != NULL && srclen != 0) {
29992 		dst = mi_alloc(srclen, BPRI_MED);
29993 		if (dst == NULL)
29994 			return (B_FALSE);
29995 	} else {
29996 		dst = NULL;
29997 	}
29998 	if (*dstp != NULL)
29999 		mi_free(*dstp);
30000 	*dstp = dst;
30001 	*dstlenp = dst == NULL ? 0 : srclen;
30002 	return (B_TRUE);
30003 }
30004 
30005 /*
30006  * Replace what is in *dst, *dstlen with the source.
30007  * Assumes ip_allocbuf has already been called.
30008  */
30009 void
30010 ip_savebuf(void **dstp, uint_t *dstlenp, boolean_t src_valid,
30011     const void *src, uint_t srclen)
30012 {
30013 	if (!src_valid)
30014 		srclen = 0;
30015 
30016 	ASSERT(*dstlenp == srclen);
30017 	if (src != NULL && srclen != 0)
30018 		bcopy(src, *dstp, srclen);
30019 }
30020 
30021 /*
30022  * Free the storage pointed to by the members of an ip6_pkt_t.
30023  */
30024 void
30025 ip6_pkt_free(ip6_pkt_t *ipp)
30026 {
30027 	ASSERT(ipp->ipp_pathmtu == NULL && !(ipp->ipp_fields & IPPF_PATHMTU));
30028 
30029 	if (ipp->ipp_fields & IPPF_HOPOPTS) {
30030 		kmem_free(ipp->ipp_hopopts, ipp->ipp_hopoptslen);
30031 		ipp->ipp_hopopts = NULL;
30032 		ipp->ipp_hopoptslen = 0;
30033 	}
30034 	if (ipp->ipp_fields & IPPF_RTDSTOPTS) {
30035 		kmem_free(ipp->ipp_rtdstopts, ipp->ipp_rtdstoptslen);
30036 		ipp->ipp_rtdstopts = NULL;
30037 		ipp->ipp_rtdstoptslen = 0;
30038 	}
30039 	if (ipp->ipp_fields & IPPF_DSTOPTS) {
30040 		kmem_free(ipp->ipp_dstopts, ipp->ipp_dstoptslen);
30041 		ipp->ipp_dstopts = NULL;
30042 		ipp->ipp_dstoptslen = 0;
30043 	}
30044 	if (ipp->ipp_fields & IPPF_RTHDR) {
30045 		kmem_free(ipp->ipp_rthdr, ipp->ipp_rthdrlen);
30046 		ipp->ipp_rthdr = NULL;
30047 		ipp->ipp_rthdrlen = 0;
30048 	}
30049 	ipp->ipp_fields &= ~(IPPF_HOPOPTS | IPPF_RTDSTOPTS | IPPF_DSTOPTS |
30050 	    IPPF_RTHDR);
30051 }
30052